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/netcetera/netcetera_types.rs | crates/hyperswitch_connectors/src/connectors/netcetera/netcetera_types.rs | use std::collections::HashMap;
use common_utils::{pii::Email, types::SemanticVersion};
use hyperswitch_domain_models::router_request_types::{
authentication::MessageCategory, BrowserInformation,
};
use hyperswitch_interfaces::errors::ConnectorError;
use masking::ExposeInterface;
use serde::{Deserialize, Serialize};
use unidecode::unidecode;
use crate::utils::{AddressDetailsData as _, PhoneDetailsData as _};
#[derive(Debug, Deserialize, Serialize, Clone)]
#[serde(untagged)]
pub enum SingleOrListElement<T> {
Single(T),
List(Vec<T>),
}
impl<T> SingleOrListElement<T> {
fn get_version_checked(message_version: SemanticVersion, value: T) -> Self {
if message_version.get_major() >= 2 && message_version.get_minor() >= 3 {
Self::List(vec![value])
} else {
Self::Single(value)
}
}
}
impl<T> SingleOrListElement<T> {
pub fn new_single(value: T) -> Self {
Self::Single(value)
}
pub fn new_list(value: Vec<T>) -> Self {
Self::List(value)
}
}
#[derive(Debug, Deserialize, Serialize, Clone)]
pub enum NetceteraDeviceChannel {
#[serde(rename = "01")]
AppBased,
#[serde(rename = "02")]
Browser,
#[serde(rename = "03")]
ThreeDsRequestorInitiated,
}
impl From<api_models::payments::DeviceChannel> for NetceteraDeviceChannel {
fn from(value: api_models::payments::DeviceChannel) -> Self {
match value {
api_models::payments::DeviceChannel::App => Self::AppBased,
api_models::payments::DeviceChannel::Browser => Self::Browser,
}
}
}
#[derive(Debug, Deserialize, Serialize, Clone)]
pub enum NetceteraMessageCategory {
#[serde(rename = "01")]
PaymentAuthentication,
#[serde(rename = "02")]
NonPaymentAuthentication,
}
impl From<MessageCategory> for NetceteraMessageCategory {
fn from(value: MessageCategory) -> Self {
match value {
MessageCategory::NonPayment => Self::NonPaymentAuthentication,
MessageCategory::Payment => Self::PaymentAuthentication,
}
}
}
#[derive(Debug, Deserialize, Serialize, Clone)]
pub enum ThreeDSMethodCompletionIndicator {
/// Successfully completed
Y,
/// Did not successfully complete
N,
/// Unavailable - 3DS Method URL was not present in the PRes message data
U,
}
impl From<api_models::payments::ThreeDsCompletionIndicator> for ThreeDSMethodCompletionIndicator {
fn from(value: api_models::payments::ThreeDsCompletionIndicator) -> Self {
match value {
api_models::payments::ThreeDsCompletionIndicator::Success => Self::Y,
api_models::payments::ThreeDsCompletionIndicator::Failure => Self::N,
api_models::payments::ThreeDsCompletionIndicator::NotAvailable => Self::U,
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct ThreeDSRequestor {
#[serde(rename = "threeDSRequestorAuthenticationInd")]
pub three_ds_requestor_authentication_ind: ThreeDSRequestorAuthenticationIndicator,
/// Format of this field was changed with EMV 3DS 2.3.1 version:
/// In versions prior to 2.3.1, this field is a single object.
/// Starting from EMVCo version 2.3.1, this field is now an array of objects. Accepted value length is 1-3 elements.
///
/// This field is optional, but recommended to include.
#[serde(rename = "threeDSRequestorAuthenticationInfo")]
pub three_ds_requestor_authentication_info:
Option<SingleOrListElement<ThreeDSRequestorAuthenticationInformation>>,
#[serde(rename = "threeDSRequestorChallengeInd")]
pub three_ds_requestor_challenge_ind:
Option<SingleOrListElement<ThreeDSRequestorChallengeIndicator>>,
#[serde(rename = "threeDSRequestorPriorAuthenticationInfo")]
pub three_ds_requestor_prior_authentication_info:
Option<SingleOrListElement<ThreeDSRequestorPriorTransactionAuthenticationInformation>>,
#[serde(rename = "threeDSRequestorDecReqInd")]
pub three_ds_requestor_dec_req_ind: Option<ThreeDSRequestorDecoupledRequestIndicator>,
/// Indicates the maximum amount of time that the 3DS Requestor will wait for an ACS to provide the results
/// of a Decoupled Authentication transaction (in minutes). Valid values are between 1 and 10080.
///
/// The field is optional and if value is not present, the expected action is for the ACS to interpret it as
/// 10080 minutes (7 days).
/// Available for supporting EMV 3DS 2.2.0 and later versions.
///
/// Starting from EMV 3DS 2.3.1:
/// This field is required if threeDSRequestorDecReqInd = Y, F or B.
#[serde(rename = "threeDSRequestorDecMaxTime")]
pub three_ds_requestor_dec_max_time: Option<u32>,
/// External IP address (i.e., the device public IP address) used by the 3DS Requestor App when it connects to the
/// 3DS Requestor environment. The value length is maximum 45 characters. Accepted values are:
///
/// - IPv4 address is represented in the dotted decimal f. Refer to RFC 791.
/// - IPv6 address. Refer to RFC 4291.
///
/// This field is required when deviceChannel = 01 (APP) and unless market or regional mandate restricts sending
/// this information.
/// Available for supporting EMV 3DS 2.3.1 and later versions.
pub app_ip: Option<std::net::IpAddr>,
/// Indicate if the 3DS Requestor supports the SPC authentication.
///
/// The accepted values are:
///
/// - Y -> Supported
///
/// This field is required if deviceChannel = 02 (BRW) and it is supported by the 3DS Requestor.
/// Available for supporting EMV 3DS 2.3.1 and later versions.
#[serde(rename = "threeDSRequestorSpcSupport")]
pub three_ds_requestor_spc_support: Option<String>,
/// Reason that the SPC authentication was not completed.
/// Accepted value length is 2 characters.
///
/// The accepted values are:
///
/// - 01 -> SPC did not run or did not successfully complete
/// - 02 -> Cardholder cancels the SPC authentication
///
/// This field is required if deviceChannel = 02 (BRW) and the 3DS Requestor attempts to invoke SPC API and there is an
/// error.
/// Available for supporting EMV 3DS 2.3.1 and later versions.
pub spc_incomp_ind: Option<String>,
}
/// Indicates the type of Authentication request.
///
/// This data element provides additional information to the ACS to determine the best approach for handling an authentication request.
///
/// This value is used for App-based and Browser flows.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub enum ThreeDSRequestorAuthenticationIndicator {
#[serde(rename = "01")]
Payment,
#[serde(rename = "02")]
Recurring,
#[serde(rename = "03")]
Installment,
#[serde(rename = "04")]
AddCard,
#[serde(rename = "05")]
MaintainCard,
#[serde(rename = "06")]
CardholderVerification,
#[serde(rename = "07")]
BillingAgreement,
}
impl ThreeDSRequestor {
pub fn new(
app_ip: Option<std::net::IpAddr>,
psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>,
force_3ds_challenge: bool,
message_version: SemanticVersion,
) -> Self {
// if sca exemption is provided, we need to set the challenge indicator to NoChallengeRequestedTransactionalRiskAnalysis
let three_ds_requestor_challenge_ind = if force_3ds_challenge {
Some(SingleOrListElement::get_version_checked(
message_version,
ThreeDSRequestorChallengeIndicator::ChallengeRequestedMandate,
))
} else if let Some(common_enums::ScaExemptionType::TransactionRiskAnalysis) =
psd2_sca_exemption_type
{
Some(SingleOrListElement::get_version_checked(
message_version,
ThreeDSRequestorChallengeIndicator::NoChallengeRequestedTransactionalRiskAnalysis,
))
} else {
None
};
Self {
three_ds_requestor_authentication_ind: ThreeDSRequestorAuthenticationIndicator::Payment,
three_ds_requestor_authentication_info: None,
three_ds_requestor_challenge_ind,
three_ds_requestor_prior_authentication_info: None,
three_ds_requestor_dec_req_ind: None,
three_ds_requestor_dec_max_time: None,
app_ip,
three_ds_requestor_spc_support: None,
spc_incomp_ind: None,
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct ThreeDSRequestorAuthenticationInformation {
/// Mechanism used by the Cardholder to authenticate to the 3DS Requestor. Accepted values are:
/// - 01 -> No 3DS Requestor authentication occurred (i.e. cardholder "logged in" as guest)
/// - 02 -> Login to the cardholder account at the 3DS Requestor system using 3DS Requestor's own credentials
/// - 03 -> Login to the cardholder account at the 3DS Requestor system using federated ID
/// - 04 -> Login to the cardholder account at the 3DS Requestor system using issuer credentials
/// - 05 -> Login to the cardholder account at the 3DS Requestor system using third-party authentication
/// - 06 -> Login to the cardholder account at the 3DS Requestor system using FIDO Authenticator.
///
/// The next values are accepted as well if 3DS Server initiates authentication with EMV 3DS 2.2.0 version or greater (required protocol version can be set in ThreeDSServerAuthenticationRequest#preferredProtocolVersion field):
/// - 07 -> Login to the cardholder account at the 3DS Requestor system using FIDO Authenticator (FIDO assurance data signed).
/// - 08 -> SRC Assurance Data.
/// - Additionally, 80-99 can be used for PS-specific values, regardless of protocol version.
#[serde(rename = "threeDSReqAuthMethod")]
pub three_ds_req_auth_method: ThreeDSReqAuthMethod,
/// Date and time converted into UTC of the cardholder authentication. Field is limited to 12 characters and accepted format is YYYYMMDDHHMM
#[serde(rename = "threeDSReqAuthTimestamp")]
pub three_ds_req_auth_timestamp: String,
/// Data that documents and supports a specific authentication process. In the current version of the specification, this data element is not defined in detail, however the intention is that for each 3DS Requestor Authentication Method, this field carry data that the ACS can use to verify the authentication process.
/// For example, if the 3DS Requestor Authentication Method is:
///
/// - 03 -> then this element can carry information about the provider of the federated ID and related information
/// - 06 -> then this element can carry the FIDO attestation data (incl. the signature)
/// - 07 -> then this element can carry FIDO Attestation data with the FIDO assurance data signed.
/// - 08 -> then this element can carry the SRC assurance data.
#[serde(rename = "threeDSReqAuthData")]
pub three_ds_req_auth_data: Option<String>,
}
/// Indicates whether a challenge is requested for this transaction. For example: For 01-PA, a 3DS Requestor may have
/// concerns about the transaction, and request a challenge. For 02-NPA, a challenge may be necessary when adding a new
/// card to a wallet.
///
/// This field is optional. The accepted values are:
///
/// - 01 -> No preference
/// - 02 -> No challenge requested
/// - 03 -> Challenge requested: 3DS Requestor Preference
/// - 04 -> Challenge requested: Mandate.
/// The next values are accepted as well if 3DS Server initiates authentication with EMV 3DS 2.2.0 version
/// or greater (required protocol version can be set in
/// ThreeDSServerAuthenticationRequest#preferredProtocolVersion field):
///
/// - 05 -> No challenge requested (transactional risk analysis is already performed)
/// - 06 -> No challenge requested (Data share only)
/// - 07 -> No challenge requested (strong consumer authentication is already performed)
/// - 08 -> No challenge requested (utilise whitelist exemption if no challenge required)
/// - 09 -> Challenge requested (whitelist prompt requested if challenge required).
/// - Additionally, 80-99 can be used for PS-specific values, regardless of protocol version.
///
/// If the element is not provided, the expected action is that the ACS would interpret as 01 -> No preference.
///
/// Format of this field was changed with EMV 3DS 2.3.1 version:
/// In versions prior to 2.3.1, this field is a String.
/// Starting from EMVCo version 2.3.1, this field is now an array of objects. Accepted value length is 1-2 elements.
/// When providing two preferences, the 3DS Requestor ensures that they are in preference order and are not
/// conflicting. For example, 02 = No challenge requested and 04 = Challenge requested (Mandate).
#[derive(Serialize, Deserialize, Debug, Clone)]
pub enum ThreeDSRequestorChallengeIndicator {
#[serde(rename = "01")]
NoPreference,
#[serde(rename = "02")]
NoChallengeRequested,
#[serde(rename = "03")]
ChallengeRequested3DSRequestorPreference,
#[serde(rename = "04")]
ChallengeRequestedMandate,
#[serde(rename = "05")]
NoChallengeRequestedTransactionalRiskAnalysis,
#[serde(rename = "06")]
NoChallengeRequestedDataShareOnly,
#[serde(rename = "07")]
NoChallengeRequestedStrongConsumerAuthentication,
#[serde(rename = "08")]
NoChallengeRequestedWhitelistExemption,
#[serde(rename = "09")]
ChallengeRequestedWhitelistPrompt,
}
/// This field contains information about how the 3DS Requestor authenticated the cardholder as part of a previous 3DS transaction.
/// Format of this field was changed with EMV 3DS 2.3.1 version:
/// In versions prior to 2.3.1, this field is a single object.
/// Starting from EMVCo version 2.3.1, this field is now an array of objects. Accepted value length is 1-3 elements.
///
/// This field is optional, but recommended to include for versions prior to 2.3.1. From 2.3.1,
/// it is required for 3RI in the case of Decoupled Authentication Fallback or for SPC.
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct ThreeDSRequestorPriorTransactionAuthenticationInformation {
/// This data element provides additional information to the ACS to determine the best
/// approach for handling a request. The field is limited to 36 characters containing
/// ACS Transaction ID for a prior authenticated transaction (for example, the first
/// recurring transaction that was authenticated with the cardholder).
pub three_ds_req_prior_ref: String,
/// Mechanism used by the Cardholder to previously authenticate to the 3DS Requestor.
/// Accepted values for this field are:
/// - 01 -> Frictionless authentication occurred by ACS
/// - 02 -> Cardholder challenge occurred by ACS
/// - 03 -> AVS verified
/// - 04 -> Other issuer methods
/// - 80-99 -> PS-specific value (dependent on the payment scheme type).
pub three_ds_req_prior_auth_method: String,
/// Date and time converted into UTC of the prior authentication. Accepted date
/// format is YYYYMMDDHHMM.
pub three_ds_req_prior_auth_timestamp: String,
/// Data that documents and supports a specific authentication process. In the current
/// version of the specification this data element is not defined in detail, however
/// the intention is that for each 3DS Requestor Authentication Method, this field carry
/// data that the ACS can use to verify the authentication process. In future versions
/// of the application, these details are expected to be included. Field is limited to
/// maximum 2048 characters.
pub three_ds_req_prior_auth_data: String,
}
/// Enum indicating whether the 3DS Requestor requests the ACS to utilize Decoupled Authentication.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub enum ThreeDSRequestorDecoupledRequestIndicator {
/// Decoupled Authentication is supported and preferred if challenge is necessary.
Y,
/// Do not use Decoupled Authentication.
N,
/// Decoupled Authentication is supported and is to be used only as a fallback challenge method
/// if a challenge is necessary (Transaction Status = D in RReq).
F,
/// Decoupled Authentication is supported and can be used as a primary or fallback challenge method
/// if a challenge is necessary (Transaction Status = D in either ARes or RReq).
B,
}
#[derive(Debug, Serialize, Deserialize, Clone, strum::Display)]
pub enum SchemeId {
Visa,
Mastercard,
#[serde(rename = "JCB")]
Jcb,
#[serde(rename = "American Express")]
AmericanExpress,
Diners,
// For Cartes Bancaires and UnionPay, it is recommended to send the scheme ID
#[serde(rename = "CB")]
CartesBancaires,
UnionPay,
}
impl TryFrom<common_enums::CardNetwork> for SchemeId {
type Error = error_stack::Report<ConnectorError>;
fn try_from(network: common_enums::CardNetwork) -> Result<Self, Self::Error> {
match network {
common_enums::CardNetwork::Visa => Ok(Self::Visa),
common_enums::CardNetwork::Mastercard => Ok(Self::Mastercard),
common_enums::CardNetwork::JCB => Ok(Self::Jcb),
common_enums::CardNetwork::AmericanExpress => Ok(Self::AmericanExpress),
common_enums::CardNetwork::DinersClub => Ok(Self::Diners),
common_enums::CardNetwork::CartesBancaires => Ok(Self::CartesBancaires),
common_enums::CardNetwork::UnionPay => Ok(Self::UnionPay),
_ => Err(ConnectorError::RequestEncodingFailedWithReason(
"Invalid card network".to_string(),
))?,
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct CardholderAccount {
/// Indicates the type of account.
/// This is required if 3DS Requestor is asking Cardholder which Account Type they are using before making
/// the purchase. This field is required in some markets. Otherwise, it is optional.
pub acct_type: Option<AccountType>,
/// Expiry date of the PAN or token supplied to the 3DS Requestor by the Cardholder.
/// The field has 4 characters in a format YYMM.
///
/// The requirements of the presence of this field are DS specific.
pub card_expiry_date: Option<masking::Secret<String>>,
/// This field contains additional information about the Cardholder’s account provided by the 3DS Requestor.
///
/// The field is optional but recommended to include.
///
/// Starting from EMV 3DS 2.3.1, added new field:
/// - `ch_acc_req_id` -> The 3DS Requestor assigned account identifier of the transacting Cardholder.
/// This identifier is a unique representation of the account identifier for the 3DS Requestor and
/// is provided as a String.
pub acct_info: Option<CardHolderAccountInformation>,
/// Account number that will be used in the authorization request for payment transactions.
/// May be represented by PAN or token.
///
/// This field is required.
pub acct_number: cards::CardNumber,
/// ID for the scheme to which the Cardholder's acctNumber belongs to.
/// It will be used to identify the Scheme from the 3DS Server configuration.
///
/// This field is optional, but recommended to include.
/// It should be present when it is not one of the schemes for which scheme resolving regular expressions
/// are provided in the 3DS Server Configuration Properties. Additionally,
/// if the schemeId is present in the request and there are card ranges found by multiple schemes, the schemeId will be
/// used for proper resolving of the versioning data.
pub scheme_id: Option<SchemeId>,
/// Additional information about the account optionally provided by the 3DS Requestor.
///
/// This field is limited to 64 characters and it is optional to use.
#[serde(rename = "acctID")]
pub acct_id: Option<String>,
/// Indicates if the transaction was de-tokenized prior to being received by the ACS.
///
/// The boolean value of true is the only valid response for this field when it is present.
///
/// The field is required only if there is a de-tokenization of an Account Number.
pub pay_token_ind: Option<bool>,
/// Information about the de-tokenised Payment Token.
/// Note: Data will be formatted into a JSON object prior to being placed into the EMV Payment Token field of the message.
///
/// This field is optional.
pub pay_token_info: Option<String>,
/// Three or four-digit security code printed on the card.
/// The value is numeric and limited to 3-4 characters.
///
/// This field is required depending on the rules provided by the Directory Server.
/// Available for supporting EMV 3DS 2.3.1 and later versions.
pub card_security_code: Option<masking::Secret<String>>,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub enum AccountType {
#[serde(rename = "01")]
NotApplicable,
#[serde(rename = "02")]
Credit,
#[serde(rename = "03")]
Debit,
#[serde(rename = "80")]
Jcb,
/// 81-99 -> PS-specific value (dependent on the payment scheme type).
#[serde(untagged)]
PsSpecificValue(String),
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct CardHolderAccountInformation {
/// Length of time that the cardholder has had the account with the 3DS Requestor.
///
/// Accepted values are:
/// - `01` -> No account
/// - `02` -> Created during this transaction
/// - `03` -> Less than 30 days
/// - `04` -> Between 30 and 60 days
/// - `05` -> More than 60 days
pub ch_acc_age_ind: Option<String>,
/// Date converted into UTC that the cardholder opened the account with the 3DS Requestor.
///
/// Date format = YYYYMMDD.
pub ch_acc_date: Option<String>,
/// Length of time since the cardholder’s account information with the 3DS Requestor was
/// last changed.
///
/// Includes Billing or Shipping address, new payment account, or new user(s) added.
///
/// Accepted values are:
/// - `01` -> Changed during this transaction
/// - `02` -> Less than 30 days
/// - `03` -> 30 - 60 days
/// - `04` -> More than 60 days
pub ch_acc_change_ind: Option<String>,
/// Date converted into UTC that the cardholder’s account with the 3DS Requestor was last changed.
///
/// Including Billing or Shipping address, new payment account, or new user(s) added.
///
/// Date format = YYYYMMDD.
pub ch_acc_change: Option<String>,
/// Length of time since the cardholder’s account with the 3DS Requestor had a password change
/// or account reset.
///
/// The accepted values are:
/// - `01` -> No change
/// - `02` -> Changed during this transaction
/// - `03` -> Less than 30 days
/// - `04` -> 30 - 60 days
/// - `05` -> More than 60 days
pub ch_acc_pw_change_ind: Option<String>,
/// Date converted into UTC that cardholder’s account with the 3DS Requestor had a password
/// change or account reset.
///
/// Date format must be YYYYMMDD.
pub ch_acc_pw_change: Option<String>,
/// Indicates when the shipping address used for this transaction was first used with the
/// 3DS Requestor.
///
/// Accepted values are:
/// - `01` -> This transaction
/// - `02` -> Less than 30 days
/// - `03` -> 30 - 60 days
/// - `04` -> More than 60 days
pub ship_address_usage_ind: Option<String>,
/// Date converted into UTC when the shipping address used for this transaction was first
/// used with the 3DS Requestor.
///
/// Date format must be YYYYMMDD.
pub ship_address_usage: Option<String>,
/// Number of transactions (successful and abandoned) for this cardholder account with the
/// 3DS Requestor across all payment accounts in the previous 24 hours.
pub txn_activity_day: Option<u32>,
/// Number of transactions (successful and abandoned) for this cardholder account with the
/// 3DS Requestor across all payment accounts in the previous year.
pub txn_activity_year: Option<u32>,
/// Number of Add Card attempts in the last 24 hours.
pub provision_attempts_day: Option<u32>,
/// Number of purchases with this cardholder account during the previous six months.
pub nb_purchase_account: Option<u32>,
/// Indicates whether the 3DS Requestor has experienced suspicious activity
/// (including previous fraud) on the cardholder account.
///
/// Accepted values are:
/// - `01` -> No suspicious activity has been observed
/// - `02` -> Suspicious activity has been observed
pub suspicious_acc_activity: Option<String>,
/// Indicates if the Cardholder Name on the account is identical to the shipping Name used
/// for this transaction.
///
/// Accepted values are:
/// - `01` -> Account Name identical to shipping Name
/// - `02` -> Account Name different than shipping Name
pub ship_name_indicator: Option<String>,
/// Indicates the length of time that the payment account was enrolled in the cardholder’s
/// account with the 3DS Requester.
///
/// Accepted values are:
/// - `01` -> No account (guest check-out)
/// - `02` -> During this transaction
/// - `03` -> Less than 30 days
/// - `04` -> 30 - 60 days
/// - `05` -> More than 60 days
pub payment_acc_ind: Option<String>,
/// Date converted into UTC that the payment account was enrolled in the cardholder’s account with
/// the 3DS Requestor.
///
/// Date format must be YYYYMMDD.
pub payment_acc_age: Option<String>,
/// The 3DS Requestor assigned account identifier of the transacting Cardholder.
///
/// This identifier is a unique representation of the account identifier for the 3DS Requestor and
/// is provided as a String. Accepted value length is maximum 64 characters.
///
/// Added starting from EMV 3DS 2.3.1.
pub ch_acc_req_id: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
#[serde_with::skip_serializing_none]
pub struct Cardholder {
/// Indicates whether the Cardholder Shipping Address and Cardholder Billing Address are the same.
///
/// Accepted values:
/// - `Y` -> Shipping Address matches Billing Address
/// - `N` -> Shipping Address does not match Billing Address
///
/// If the field is not set and the shipping and billing addresses are the same, the 3DS Server will set the value to
/// `Y`. Otherwise, the value will not be changed.
///
/// This field is optional.
addr_match: Option<String>,
/// The city of the Cardholder billing address associated with the card used for this purchase.
///
/// This field is limited to a maximum of 50 characters.
///
/// This field is required unless market or regional mandate restricts sending this information.
bill_addr_city: Option<String>,
/// The country of the Cardholder billing address associated with the card used for this purchase.
///
/// This field is limited to 3 characters. This value shall be the ISO 3166-1 numeric country code, except values
/// from range 901 - 999 which are reserved by ISO.
///
/// The field is required if Cardholder Billing Address State is present and unless market or regional mandate
/// restricts sending this information.
bill_addr_country: Option<String>,
/// First line of the street address or equivalent local portion of the Cardholder billing address associated with
/// the card use for this purchase.
///
/// This field is limited to a maximum of 50 characters.
///
/// This field is required unless market or regional mandate restricts sending this information.
bill_addr_line1: Option<masking::Secret<String>>,
/// Second line of the street address or equivalent local portion of the Cardholder billing address associated with
/// the card use for this purchase.
///
/// This field is limited to a maximum of 50 characters.
///
/// This field is required unless market or regional mandate restricts sending this information.
bill_addr_line2: Option<masking::Secret<String>>,
/// Third line of the street address or equivalent local portion of the Cardholder billing address associated with
/// the card use for this purchase.
///
/// This field is limited to a maximum of 50 characters.
///
/// This field is required unless market or regional mandate restricts sending this information.
bill_addr_line3: Option<masking::Secret<String>>,
/// ZIP or other postal code of the Cardholder billing address associated with the card used for this purchase.
///
/// This field is limited to a maximum of 16 characters.
///
/// This field is required unless market or regional mandate restricts sending this information.
bill_addr_post_code: Option<masking::Secret<String>>,
/// The state or province of the Cardholder billing address associated with the card used for this purchase.
///
/// This field is limited to 3 characters. The value should be the country subdivision code defined in ISO 3166-2.
///
/// This field is required unless State is not applicable for this country and unless market or regional mandate
/// restricts sending this information.
bill_addr_state: Option<masking::Secret<String>>,
/// The email address associated with the account that is either entered by the Cardholder, or is on file with
/// the 3DS Requestor.
///
/// This field is limited to a maximum of 256 characters and shall meet requirements of Section 3.4 of
/// IETF RFC 5322.
///
/// This field is required unless market or regional mandate restricts sending this information.
email: Option<Email>,
/// The home phone provided by the Cardholder.
///
/// Refer to ITU-E.164 for additional information on format and length.
///
/// This field is required if available, unless market or regional mandate restricts sending this information.
home_phone: Option<PhoneNumber>,
/// The mobile phone provided by the Cardholder.
///
/// Refer to ITU-E.164 for additional information on format and length.
///
/// This field is required if available, unless market or regional mandate restricts sending this information.
mobile_phone: Option<PhoneNumber>,
/// The work phone provided by the Cardholder.
///
/// Refer to ITU-E.164 for additional information on format and length.
///
/// This field is required if available, unless market or regional mandate restricts sending this information.
work_phone: Option<PhoneNumber>,
/// Name of the Cardholder.
///
/// This field is limited to 2-45 characters.
///
/// This field is required unless market or regional mandate restricts sending this information.
///
/// Starting from EMV 3DS 2.3.1:
/// This field is limited to 1-45 characters.
cardholder_name: Option<masking::Secret<String>>,
/// City portion of the shipping address requested by the Cardholder.
///
/// This field is required unless shipping information is the same as billing information, or market or regional
/// mandate restricts sending this information.
ship_addr_city: Option<String>,
/// Country of the shipping address requested by the Cardholder.
///
/// This field is limited to 3 characters. This value shall be the ISO 3166-1 numeric country code, except values
/// from range 901 - 999 which are reserved by ISO.
///
/// This field is required if Cardholder Shipping Address State is present and if shipping information are not the same
/// as billing information. This field can be omitted if market or regional mandate restricts sending this information.
ship_addr_country: Option<String>,
/// First line of the street address or equivalent local portion of the shipping address associated with
/// the card use for this purchase.
///
/// This field is limited to a maximum of 50 characters.
///
/// This field is required unless shipping information is the same as billing information, or market or regional
/// mandate restricts sending this information.
| 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/netcetera/transformers.rs | crates/hyperswitch_connectors/src/connectors/netcetera/transformers.rs | use common_enums::enums;
use common_utils::{ext_traits::OptionExt as _, types::SemanticVersion};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
router_data::{ConnectorAuthType, ErrorResponse},
router_flow_types::authentication::{Authentication, PreAuthentication},
router_request_types::authentication::{
AuthNFlowType, ChallengeParams, ConnectorAuthenticationRequestData,
MessageExtensionAttribute, PreAuthNRequestData,
},
router_response_types::AuthenticationResponseData,
};
use hyperswitch_interfaces::{api::CurrencyUnit, errors::ConnectorError};
use masking::Secret;
use serde::{Deserialize, Serialize};
use super::netcetera_types;
use crate::{
types::{ConnectorAuthenticationRouterData, PreAuthNRouterData, ResponseRouterData},
utils::{get_card_details, to_connector_meta_from_secret, CardData as _},
};
//TODO: Fill the struct with respective fields
pub struct NetceteraRouterData<T> {
pub amount: i64, // The type of amount that a connector accepts, for example, String, i64, f64, etc.
pub router_data: T,
}
impl<T> TryFrom<(&CurrencyUnit, enums::Currency, i64, T)> for NetceteraRouterData<T> {
type Error = error_stack::Report<ConnectorError>;
fn try_from(
(_currency_unit, _currency, amount, item): (&CurrencyUnit, enums::Currency, i64, T),
) -> Result<Self, Self::Error> {
//Todo : use utils to convert the amount to the type of amount that a connector accepts
Ok(Self {
amount,
router_data: item,
})
}
}
impl<T> TryFrom<(i64, T)> for NetceteraRouterData<T> {
type Error = error_stack::Report<ConnectorError>;
fn try_from((amount, router_data): (i64, T)) -> Result<Self, Self::Error> {
Ok(Self {
amount,
router_data,
})
}
}
impl
TryFrom<
ResponseRouterData<
PreAuthentication,
NetceteraPreAuthenticationResponse,
PreAuthNRequestData,
AuthenticationResponseData,
>,
> for PreAuthNRouterData
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<
PreAuthentication,
NetceteraPreAuthenticationResponse,
PreAuthNRequestData,
AuthenticationResponseData,
>,
) -> Result<Self, Self::Error> {
let response = match item.response {
NetceteraPreAuthenticationResponse::Success(pre_authn_response) => {
// if card is not enrolled for 3ds, card_range will be None
let card_range = pre_authn_response.get_card_range_if_available();
let maximum_supported_3ds_version = card_range
.as_ref()
.map(|card_range| card_range.highest_common_supported_version.clone())
.unwrap_or_else(|| {
// Version "0.0.0" will be less that "2.0.0", hence we will treat this card as not eligible for 3ds authentication
SemanticVersion::new(0, 0, 0)
});
let three_ds_method_data = card_range.as_ref().and_then(|card_range| {
card_range
.three_ds_method_data_form
.as_ref()
.map(|data| data.three_ds_method_data.clone())
});
let three_ds_method_url = card_range
.as_ref()
.and_then(|card_range| card_range.get_three_ds_method_url());
Ok(AuthenticationResponseData::PreAuthNResponse {
threeds_server_transaction_id: pre_authn_response
.three_ds_server_trans_id
.clone(),
maximum_supported_3ds_version: maximum_supported_3ds_version.clone(),
connector_authentication_id: pre_authn_response.three_ds_server_trans_id,
three_ds_method_data,
three_ds_method_url,
message_version: maximum_supported_3ds_version,
connector_metadata: None,
directory_server_id: card_range
.as_ref()
.and_then(|card_range| card_range.directory_server_id.clone()),
scheme_id: card_range
.as_ref()
.map(|card_range| card_range.scheme_id.clone().to_string()),
})
}
NetceteraPreAuthenticationResponse::Failure(error_response) => Err(ErrorResponse {
code: error_response.error_details.error_code,
message: error_response.error_details.error_description,
reason: error_response.error_details.error_detail,
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
};
Ok(Self {
response,
..item.data.clone()
})
}
}
impl
TryFrom<
ResponseRouterData<
Authentication,
NetceteraAuthenticationResponse,
ConnectorAuthenticationRequestData,
AuthenticationResponseData,
>,
> for ConnectorAuthenticationRouterData
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<
Authentication,
NetceteraAuthenticationResponse,
ConnectorAuthenticationRequestData,
AuthenticationResponseData,
>,
) -> Result<Self, Self::Error> {
let response = match item.response {
NetceteraAuthenticationResponse::Success(response) => {
let authn_flow_type = match response.acs_challenge_mandated {
Some(ACSChallengeMandatedIndicator::Y) => {
AuthNFlowType::Challenge(Box::new(ChallengeParams {
acs_url: response.authentication_response.acs_url.clone(),
challenge_request: response.encoded_challenge_request,
acs_reference_number: response
.authentication_response
.acs_reference_number,
acs_trans_id: response.authentication_response.acs_trans_id,
three_dsserver_trans_id: Some(response.three_ds_server_trans_id),
acs_signed_content: response.authentication_response.acs_signed_content,
challenge_request_key: None,
}))
}
Some(ACSChallengeMandatedIndicator::N) | None => AuthNFlowType::Frictionless,
};
let challenge_code = response
.authentication_request
.as_ref()
.and_then(|req| req.three_ds_requestor_challenge_ind.as_ref())
.and_then(|ind| match ind {
ThreedsRequestorChallengeInd::Single(s) => Some(s.clone()),
ThreedsRequestorChallengeInd::Multiple(v) => v.first().cloned(),
});
let message_extension = response
.authentication_response
.message_extension
.as_ref()
.and_then(|v| match serde_json::to_value(v) {
Ok(val) => Some(Secret::new(val)),
Err(e) => {
router_env::logger::error!(
"Failed to serialize message_extension: {:?}",
e
);
None
}
});
Ok(AuthenticationResponseData::AuthNResponse {
authn_flow_type,
authentication_value: response.authentication_value,
trans_status: response.trans_status,
connector_metadata: None,
ds_trans_id: response.authentication_response.ds_trans_id,
eci: response.eci,
challenge_code,
challenge_cancel: None, // Note - challenge_cancel field is received in the RReq and updated in DB during external_authentication_incoming_webhook_flow
challenge_code_reason: response.authentication_response.trans_status_reason,
message_extension,
})
}
NetceteraAuthenticationResponse::Error(error_response) => Err(ErrorResponse {
code: error_response.error_details.error_code,
message: error_response.error_details.error_description,
reason: error_response.error_details.error_detail,
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
};
Ok(Self {
response,
..item.data.clone()
})
}
}
pub struct NetceteraAuthType {
pub(super) certificate: Secret<String>,
pub(super) private_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for NetceteraAuthType {
type Error = error_stack::Report<ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type.to_owned() {
ConnectorAuthType::CertificateAuth {
certificate,
private_key,
} => Ok(Self {
certificate,
private_key,
}),
_ => Err(ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NetceteraErrorResponse {
pub three_ds_server_trans_id: Option<String>,
pub error_details: NetceteraErrorDetails,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NetceteraErrorDetails {
/// Universally unique identifier for the transaction assigned by the 3DS Server.
#[serde(rename = "threeDSServerTransID")]
pub three_ds_server_trans_id: Option<String>,
/// Universally Unique identifier for the transaction assigned by the ACS.
#[serde(rename = "acsTransID")]
pub acs_trans_id: Option<String>,
/// Universally unique identifier for the transaction assigned by the DS.
#[serde(rename = "dsTransID")]
pub ds_trans_id: Option<String>,
/// Code indicating the type of problem identified.
pub error_code: String,
/// Code indicating the 3-D Secure component that identified the error.
pub error_component: Option<String>,
/// Text describing the problem identified.
pub error_description: String,
/// Additional detail regarding the problem identified.
pub error_detail: Option<String>,
/// Universally unique identifier for the transaction assigned by the 3DS SDK.
#[serde(rename = "sdkTransID")]
pub sdk_trans_id: Option<String>,
/// The Message Type that was identified as erroneous.
pub error_message_type: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct NetceteraMetaData {
pub mcc: Option<String>,
pub merchant_country_code: Option<String>,
pub merchant_name: Option<String>,
pub endpoint_prefix: String,
pub three_ds_requestor_name: Option<String>,
pub three_ds_requestor_id: Option<String>,
pub merchant_configuration_id: Option<String>,
}
impl TryFrom<&Option<common_utils::pii::SecretSerdeValue>> for NetceteraMetaData {
type Error = error_stack::Report<ConnectorError>;
fn try_from(
meta_data: &Option<common_utils::pii::SecretSerdeValue>,
) -> Result<Self, Self::Error> {
let metadata: Self = to_connector_meta_from_secret::<Self>(meta_data.clone())
.change_context(ConnectorError::InvalidConnectorConfig { config: "metadata" })?;
Ok(metadata)
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NetceteraPreAuthenticationRequest {
cardholder_account_number: cards::CardNumber,
scheme_id: Option<netcetera_types::SchemeId>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum NetceteraPreAuthenticationResponse {
Success(Box<NetceteraPreAuthenticationResponseData>),
Failure(Box<NetceteraErrorResponse>),
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NetceteraPreAuthenticationResponseData {
#[serde(rename = "threeDSServerTransID")]
pub three_ds_server_trans_id: String,
pub card_ranges: Vec<CardRange>,
}
impl NetceteraPreAuthenticationResponseData {
pub fn get_card_range_if_available(&self) -> Option<CardRange> {
let card_range = self
.card_ranges
.iter()
.max_by_key(|card_range| &card_range.highest_common_supported_version);
card_range.cloned()
}
}
#[derive(Debug, Deserialize, Serialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct CardRange {
pub scheme_id: netcetera_types::SchemeId,
pub directory_server_id: Option<String>,
pub acs_protocol_versions: Vec<AcsProtocolVersion>,
#[serde(rename = "threeDSMethodDataForm")]
pub three_ds_method_data_form: Option<ThreeDSMethodDataForm>,
pub highest_common_supported_version: SemanticVersion,
}
impl CardRange {
pub fn get_three_ds_method_url(&self) -> Option<String> {
self.acs_protocol_versions
.iter()
.find(|acs_protocol_version| {
acs_protocol_version.version == self.highest_common_supported_version
})
.and_then(|acs_version| acs_version.three_ds_method_url.clone())
}
}
#[derive(Debug, Deserialize, Serialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct ThreeDSMethodDataForm {
// base64 encoded value for 3ds method data collection
#[serde(rename = "threeDSMethodData")]
pub three_ds_method_data: String,
}
#[derive(Debug, Deserialize, Serialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct AcsProtocolVersion {
pub version: SemanticVersion,
#[serde(rename = "threeDSMethodURL")]
pub three_ds_method_url: Option<String>,
}
impl TryFrom<&NetceteraRouterData<&PreAuthNRouterData>> for NetceteraPreAuthenticationRequest {
type Error = error_stack::Report<ConnectorError>;
fn try_from(value: &NetceteraRouterData<&PreAuthNRouterData>) -> Result<Self, Self::Error> {
let router_data = value.router_data;
let is_cobadged_card = || {
router_data
.request
.card
.card_number
.is_cobadged_card()
.change_context(ConnectorError::RequestEncodingFailed)
.attach_printable("error while checking is_cobadged_card")
};
Ok(Self {
cardholder_account_number: router_data.request.card.card_number.clone(),
scheme_id: router_data
.request
.card
.card_network
.clone()
.map(|card_network| {
is_cobadged_card().map(|is_cobadged_card| {
is_cobadged_card
.then_some(netcetera_types::SchemeId::try_from(card_network))
})
})
.transpose()?
.flatten()
.transpose()?,
})
}
}
#[derive(Debug, Deserialize, Serialize, Clone)]
#[serde(rename_all = "camelCase")]
#[serde_with::skip_serializing_none]
pub struct NetceteraAuthenticationRequest {
/// Specifies the preferred version of 3D Secure protocol to be utilized while executing 3D Secure authentication.
/// 3DS Server initiates an authentication request with the preferred version and if this version is not supported by
/// other 3D Secure components, it falls back to the next supported version(s) and continues authentication.
///
/// If the preferred version is enforced by setting #enforcePreferredProtocolVersion flag, but this version
/// is not supported by one of the 3D Secure components, 3DS Server does not initiate an authentication and provides
/// corresponding error message to the customer.
///
/// The accepted values are:
/// - 2.1.0 -> prefer authentication with 2.1.0 version,
/// - 2.2.0 -> prefer authentication with 2.2.0 version,
/// - 2.3.1 -> prefer authentication with 2.3.1 version,
/// - latest -> prefer authentication with the latest version, the 3DS Server is certified for. 2.3.1 at this moment.
pub preferred_protocol_version: Option<SemanticVersion>,
/// Boolean flag that enforces preferred 3D Secure protocol version to be used in 3D Secure authentication.
/// The value should be set true to enforce preferred version. If value is false or not provided,
/// 3DS Server can fall back to next supported 3DS protocol version while initiating 3D Secure authentication.
///
/// For application initiated transactions (deviceChannel = '01'), the preferred protocol version must be enforced.
pub enforce_preferred_protocol_version: Option<bool>,
pub device_channel: netcetera_types::NetceteraDeviceChannel,
/// Identifies the category of the message for a specific use case. The accepted values are:
///
/// - 01 -> PA
/// - 02 -> NPA
/// - 80 - 99 -> PS Specific Values (80 -> MasterCard Identity Check Insights;
/// 85 -> MasterCard Identity Check, Production Validation PA;
/// 86 -> MasterCard Identity Check, Production Validation NPA)
pub message_category: netcetera_types::NetceteraMessageCategory,
#[serde(rename = "threeDSCompInd")]
pub three_ds_comp_ind: Option<netcetera_types::ThreeDSMethodCompletionIndicator>,
/**
* Contains the 3DS Server Transaction ID used during the previous execution of the 3DS method. Accepted value
* length is 36 characters. Accepted value is a Canonical format as defined in IETF RFC 4122. May utilise any of the
* specified versions if the output meets specified requirements.
*
* This field is required if the 3DS Requestor reuses previous 3DS Method execution with deviceChannel = 02 (BRW).
* Available for supporting EMV 3DS 2.3.1 and later versions.
*/
#[serde(rename = "threeDSMethodId")]
pub three_ds_method_id: Option<String>,
#[serde(rename = "threeDSRequestor")]
pub three_ds_requestor: Option<netcetera_types::ThreeDSRequestor>,
#[serde(rename = "threeDSServerTransID")]
pub three_ds_server_trans_id: String,
#[serde(rename = "threeDSRequestorURL")]
pub three_ds_requestor_url: Option<String>,
pub cardholder_account: netcetera_types::CardholderAccount,
pub cardholder: Option<netcetera_types::Cardholder>,
pub purchase: Option<netcetera_types::Purchase>,
pub acquirer: Option<netcetera_types::AcquirerData>,
pub merchant: Option<netcetera_types::MerchantData>,
pub broad_info: Option<String>,
pub device_render_options: Option<netcetera_types::DeviceRenderingOptionsSupported>,
pub message_extension: Option<Vec<MessageExtensionAttribute>>,
pub challenge_message_extension: Option<Vec<MessageExtensionAttribute>>,
pub browser_information: Option<netcetera_types::Browser>,
#[serde(rename = "threeRIInd")]
pub three_ri_ind: Option<String>,
pub sdk_information: Option<netcetera_types::Sdk>,
pub device: Option<String>,
pub multi_transaction: Option<String>,
pub device_id: Option<String>,
pub user_id: Option<String>,
pub payee_origin: Option<url::Url>,
}
impl TryFrom<&NetceteraRouterData<&ConnectorAuthenticationRouterData>>
for NetceteraAuthenticationRequest
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: &NetceteraRouterData<&ConnectorAuthenticationRouterData>,
) -> Result<Self, Self::Error> {
let now = common_utils::date_time::now();
let request = item.router_data.request.clone();
let pre_authn_data = request.pre_authentication_data.clone();
let ip_address = request
.browser_details
.as_ref()
.and_then(|browser| browser.ip_address);
let three_ds_requestor = netcetera_types::ThreeDSRequestor::new(
ip_address,
item.router_data.psd2_sca_exemption_type,
item.router_data.request.force_3ds_challenge,
item.router_data
.request
.pre_authentication_data
.message_version
.clone(),
);
let card = get_card_details(request.payment_method_data, "netcetera")?;
let is_cobadged_card = card
.card_number
.clone()
.is_cobadged_card()
.change_context(ConnectorError::RequestEncodingFailed)
.attach_printable("error while checking is_cobadged_card")?;
let cardholder_account = netcetera_types::CardholderAccount {
acct_type: None,
card_expiry_date: Some(card.get_expiry_date_as_yymm()?),
acct_info: None,
acct_number: card.card_number,
scheme_id: card
.card_network
.clone()
.and_then(|card_network| {
is_cobadged_card.then_some(netcetera_types::SchemeId::try_from(card_network))
})
.transpose()?,
acct_id: None,
pay_token_ind: None,
pay_token_info: None,
card_security_code: Some(card.card_cvc),
};
let currency = request
.currency
.get_required_value("currency")
.change_context(ConnectorError::MissingRequiredField {
field_name: "currency",
})?;
let purchase = netcetera_types::Purchase {
purchase_instal_data: None,
merchant_risk_indicator: None,
purchase_amount: request.amount,
purchase_currency: currency.iso_4217().to_string(),
purchase_exponent: currency.number_of_digits_after_decimal_point(),
purchase_date: Some(
common_utils::date_time::format_date(
now,
common_utils::date_time::DateFormat::YYYYMMDDHHmmss,
)
.change_context(
ConnectorError::RequestEncodingFailedWithReason(
"Failed to format Date".to_string(),
),
)?,
),
recurring_expiry: None,
recurring_frequency: None,
// 01 -> Goods and Services, hardcoding this as we serve this usecase only for now
trans_type: Some("01".to_string()),
recurring_amount: None,
recurring_currency: None,
recurring_exponent: None,
recurring_date: None,
amount_ind: None,
frequency_ind: None,
};
let acquirer_details = netcetera_types::AcquirerData {
acquirer_bin: request.pre_authentication_data.acquirer_bin,
acquirer_merchant_id: request.pre_authentication_data.acquirer_merchant_id,
acquirer_country_code: request.pre_authentication_data.acquirer_country_code,
};
let connector_meta_data: NetceteraMetaData = item
.router_data
.connector_meta_data
.clone()
.parse_value("NetceteraMetaData")
.change_context(ConnectorError::RequestEncodingFailed)?;
let merchant_data = netcetera_types::MerchantData {
merchant_configuration_id: connector_meta_data.merchant_configuration_id,
mcc: connector_meta_data.mcc,
merchant_country_code: connector_meta_data.merchant_country_code,
merchant_name: connector_meta_data.merchant_name,
notification_url: request.return_url.clone(),
three_ds_requestor_id: connector_meta_data.three_ds_requestor_id,
three_ds_requestor_name: connector_meta_data.three_ds_requestor_name,
white_list_status: None,
trust_list_status: None,
seller_info: None,
results_response_notification_url: Some(request.webhook_url),
};
let browser_information = match request.device_channel {
api_models::payments::DeviceChannel::Browser => {
request.browser_details.map(netcetera_types::Browser::from)
}
api_models::payments::DeviceChannel::App => None,
};
let sdk_information = match request.device_channel {
api_models::payments::DeviceChannel::App => {
request.sdk_information.map(netcetera_types::Sdk::from)
}
api_models::payments::DeviceChannel::Browser => None,
};
let device_render_options = match request.device_channel {
api_models::payments::DeviceChannel::App => {
Some(netcetera_types::DeviceRenderingOptionsSupported {
// hard-coded until core provides these values.
sdk_interface: netcetera_types::SdkInterface::Both,
sdk_ui_type: vec![
netcetera_types::SdkUiType::Text,
netcetera_types::SdkUiType::SingleSelect,
netcetera_types::SdkUiType::MultiSelect,
netcetera_types::SdkUiType::Oob,
netcetera_types::SdkUiType::HtmlOther,
],
})
}
api_models::payments::DeviceChannel::Browser => None,
};
Ok(Self {
preferred_protocol_version: Some(pre_authn_data.message_version),
// For Device channel App, we should enforce the preferred protocol version
enforce_preferred_protocol_version: Some(matches!(
request.device_channel,
api_models::payments::DeviceChannel::App
)),
device_channel: netcetera_types::NetceteraDeviceChannel::from(request.device_channel),
message_category: netcetera_types::NetceteraMessageCategory::from(
request.message_category,
),
three_ds_comp_ind: Some(netcetera_types::ThreeDSMethodCompletionIndicator::from(
request.threeds_method_comp_ind,
)),
three_ds_method_id: None,
three_ds_requestor: Some(three_ds_requestor),
three_ds_server_trans_id: pre_authn_data.threeds_server_transaction_id,
three_ds_requestor_url: Some(request.three_ds_requestor_url),
cardholder_account,
cardholder: Some(netcetera_types::Cardholder::try_from((
request.billing_address,
request.shipping_address,
))?),
purchase: Some(purchase),
acquirer: Some(acquirer_details),
merchant: Some(merchant_data),
broad_info: None,
device_render_options,
message_extension: None,
challenge_message_extension: None,
browser_information,
three_ri_ind: None,
sdk_information,
device: None,
multi_transaction: None,
device_id: None,
user_id: None,
payee_origin: None,
})
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum NetceteraAuthenticationResponse {
Error(NetceteraAuthenticationFailureResponse),
Success(NetceteraAuthenticationSuccessResponse),
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NetceteraAuthenticationSuccessResponse {
#[serde(rename = "threeDSServerTransID")]
pub three_ds_server_trans_id: String,
pub trans_status: common_enums::TransactionStatus,
pub authentication_value: Option<Secret<String>>,
pub eci: Option<String>,
pub acs_challenge_mandated: Option<ACSChallengeMandatedIndicator>,
pub authentication_request: Option<AuthenticationRequest>,
pub authentication_response: AuthenticationResponse,
#[serde(rename = "base64EncodedChallengeRequest")]
pub encoded_challenge_request: Option<String>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NetceteraAuthenticationFailureResponse {
pub error_details: NetceteraErrorDetails,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthenticationRequest {
#[serde(rename = "threeDSRequestorChallengeInd")]
pub three_ds_requestor_challenge_ind: Option<ThreedsRequestorChallengeInd>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ThreedsRequestorChallengeInd {
Single(String),
Multiple(Vec<String>),
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthenticationResponse {
#[serde(rename = "acsURL")]
pub acs_url: Option<url::Url>,
pub acs_reference_number: Option<String>,
#[serde(rename = "acsTransID")]
pub acs_trans_id: Option<String>,
#[serde(rename = "dsTransID")]
pub ds_trans_id: Option<String>,
pub acs_signed_content: Option<String>,
pub trans_status_reason: Option<String>,
pub message_extension: Option<serde_json::Value>,
}
#[derive(Debug, Deserialize, Serialize, Clone)]
pub enum ACSChallengeMandatedIndicator {
/// Challenge is mandated
Y,
/// Challenge is not mandated
N,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ResultsResponseData {
/// Universally unique transaction identifier assigned by the 3DS Server to identify a single transaction.
/// It has the same value as the authentication request and conforms to the format defined in IETF RFC 4122.
#[serde(rename = "threeDSServerTransID")]
pub three_ds_server_trans_id: String,
/// Indicates the status of a transaction in terms of its authentication.
///
/// Valid values:
/// - `Y`: Authentication / Account verification successful.
/// - `N`: Not authenticated / Account not verified; Transaction denied.
/// - `U`: Authentication / Account verification could not be performed; technical or other problem.
/// - `C`: A challenge is required to complete the authentication.
/// - `R`: Authentication / Account verification Rejected. Issuer is rejecting authentication/verification
/// and request that authorization not be attempted.
/// - `A`: Attempts processing performed; Not authenticated / verified, but a proof of attempt
/// authentication / verification is provided.
/// - `D`: A challenge is required to complete the authentication. Decoupled Authentication confirmed.
/// - `I`: Informational Only; 3DS Requestor challenge preference acknowledged.
pub trans_status: Option<common_enums::TransactionStatus>,
/// Payment System-specific value provided as part of the ACS registration for each supported DS.
/// Authentication Value may be used to provide proof of authentication.
pub authentication_value: Option<Secret<String>>,
/// Payment System-specific value provided by the ACS to indicate the results of the attempt to authenticate
/// the Cardholder.
pub eci: Option<String>,
/// The received Results Request from the Directory Server.
pub results_request: Option<serde_json::Value>,
/// The sent Results Response to the Directory Server.
pub results_response: Option<serde_json::Value>,
/// Optional object containing error details if any errors occurred during the process.
pub error_details: Option<NetceteraErrorDetails>,
}
| 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/mollie/transformers.rs | crates/hyperswitch_connectors/src/connectors/mollie/transformers.rs | use cards::CardNumber;
use common_enums::enums;
use common_utils::{pii::Email, request::Method, types::StringMajorUnit};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{BankDebitData, BankRedirectData, PaymentMethodData, WalletData},
router_data::{ConnectorAuthType, PaymentMethodToken, RouterData},
router_request_types::ResponseId,
router_response_types::{
ConnectorCustomerResponseData, MandateReference, PaymentsResponseData, RedirectForm,
RefundsResponseData,
},
types,
};
use hyperswitch_interfaces::errors;
use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use url::Url;
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
unimplemented_payment_method,
utils::{
get_unimplemented_payment_method_error_message, AddressDetailsData, BrowserInformationData,
CardData as CardDataUtil, CustomerData, PaymentMethodTokenizationRequestData,
PaymentsAuthorizeRequestData, PaymentsSetupMandateRequestData,
RouterData as OtherRouterData,
},
};
type Error = error_stack::Report<errors::ConnectorError>;
#[derive(Debug, Serialize)]
pub struct MollieRouterData<T> {
pub amount: StringMajorUnit,
pub router_data: T,
}
impl<T> From<(StringMajorUnit, T)> for MollieRouterData<T> {
fn from((amount, router_data): (StringMajorUnit, T)) -> Self {
Self {
amount,
router_data,
}
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MolliePaymentsRequest {
amount: Amount,
description: String,
redirect_url: String,
cancel_url: Option<String>,
webhook_url: String,
locale: Option<String>,
#[serde(flatten)]
payment_method_data: MolliePaymentMethodData,
metadata: Option<MollieMetadata>,
sequence_type: SequenceType,
customer_id: Option<String>,
capture_mode: Option<MollieCaptureMode>,
}
#[derive(Default, Debug, Serialize, Deserialize)]
pub struct Amount {
currency: enums::Currency,
value: StringMajorUnit,
}
#[derive(Debug, Serialize)]
#[serde(tag = "method")]
#[serde(rename_all = "lowercase")]
pub enum MolliePaymentMethodData {
Applepay(Box<ApplePayMethodData>),
Eps,
Giropay,
Ideal(Box<IdealMethodData>),
Paypal(Box<PaypalMethodData>),
Sofort,
Przelewy24(Box<Przelewy24MethodData>),
Bancontact,
CreditCard(Box<CreditCardMethodData>),
DirectDebit(Box<DirectDebitMethodData>),
#[serde(untagged)]
MandatePayment(Box<MandatePaymentMethodData>),
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ApplePayMethodData {
apple_pay_payment_token: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct IdealMethodData {
issuer: Option<Secret<String>>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaypalMethodData {
billing_address: Option<Address>,
shipping_address: Option<Address>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Przelewy24MethodData {
billing_email: Option<Email>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DirectDebitMethodData {
consumer_name: Option<Secret<String>>,
consumer_account: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CreditCardMethodData {
billing_address: Option<Address>,
shipping_address: Option<Address>,
card_token: Option<Secret<String>>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MandatePaymentMethodData {
mandate_id: Secret<String>,
}
#[derive(Debug, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum SequenceType {
#[default]
Oneoff,
First,
Recurring,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Address {
pub street_and_number: Secret<String>,
pub postal_code: Secret<String>,
pub city: String,
pub region: Option<Secret<String>>,
pub country: api_models::enums::CountryAlpha2,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MollieMetadata {
pub order_id: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum MollieCaptureMode {
Automatic,
Manual,
}
#[derive(Debug, Serialize)]
pub struct MollieCustomerRequest {
pub name: Option<Secret<String>>,
pub email: Option<Email>,
}
impl TryFrom<&types::ConnectorCustomerRouterData> for MollieCustomerRequest {
type Error = Error;
fn try_from(item: &types::ConnectorCustomerRouterData) -> Result<Self, Self::Error> {
Ok(Self {
name: item.request.get_optional_name(),
email: item.request.get_optional_email(),
})
}
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct MollieCustomerResponse {
pub id: String,
pub name: Option<Secret<String>>,
pub email: Option<Email>,
}
impl<F, T> TryFrom<ResponseRouterData<F, MollieCustomerResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = Error;
fn try_from(
item: ResponseRouterData<F, MollieCustomerResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
connector_customer: Some(item.response.id.clone()),
response: Ok(PaymentsResponseData::ConnectorCustomerResponse(
ConnectorCustomerResponseData::new_with_customer_id(item.response.id),
)),
..item.data
})
}
}
impl TryFrom<&MollieRouterData<&types::SetupMandateRouterData>> for MolliePaymentsRequest {
type Error = Error;
fn try_from(
item: &MollieRouterData<&types::SetupMandateRouterData>,
) -> Result<Self, Self::Error> {
let payment_method_data = match &item.router_data.request.payment_method_data {
PaymentMethodData::Card(_) => {
let pm_token = item.router_data.get_payment_method_token()?;
MolliePaymentMethodData::CreditCard(Box::new(CreditCardMethodData {
billing_address: get_address_details(
item.router_data
.get_optional_billing()
.and_then(|billing| billing.address.as_ref()),
)?,
shipping_address: get_address_details(
item.router_data
.get_optional_shipping()
.and_then(|shipping| shipping.address.as_ref()),
)?,
card_token: Some(match pm_token {
PaymentMethodToken::Token(token) => token,
PaymentMethodToken::ApplePayDecrypt(_) => Err(
unimplemented_payment_method!("Apple Pay", "Simplified", "Mollie"),
)?,
PaymentMethodToken::PazeDecrypt(_) => {
Err(unimplemented_payment_method!("Paze", "Mollie"))?
}
PaymentMethodToken::GooglePayDecrypt(_) => {
Err(unimplemented_payment_method!("Google Pay", "Mollie"))?
}
}),
}))
}
PaymentMethodData::BankRedirect(_)
| PaymentMethodData::Wallet(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::MobilePayment(_) => {
return Err(errors::ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("Mollie"),
)
.into());
}
};
Ok(Self {
amount: Amount {
currency: item.router_data.request.currency,
value: item.amount.clone(),
},
description: item.router_data.get_description()?,
redirect_url: item.router_data.request.get_router_return_url()?,
cancel_url: None,
/* webhook_url is a mandatory field. */
webhook_url: "".to_string(),
locale: None,
payment_method_data,
metadata: Some(MollieMetadata {
order_id: item.router_data.connector_request_reference_id.clone(),
}),
sequence_type: SequenceType::First,
capture_mode: None,
customer_id: Some(item.router_data.get_connector_customer_id()?),
})
}
}
impl TryFrom<&MollieRouterData<&types::PaymentsAuthorizeRouterData>> for MolliePaymentsRequest {
type Error = Error;
fn try_from(
item: &MollieRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let amount = Amount {
currency: item.router_data.request.currency,
value: item.amount.clone(),
};
let description = item.router_data.get_description()?;
let redirect_url = item.router_data.request.get_router_return_url()?;
let sequence_type = if item
.router_data
.request
.is_customer_initiated_mandate_payment()
{
SequenceType::First
} else if item.router_data.request.is_mandate_payment() {
SequenceType::Recurring
} else {
SequenceType::Oneoff
};
let capture_mode = if sequence_type == SequenceType::Oneoff {
Some(if item.router_data.request.is_auto_capture()? {
MollieCaptureMode::Automatic
} else {
MollieCaptureMode::Manual
})
} else {
None
};
let customer_id = if item.router_data.request.is_mandate_payment() {
Some(item.router_data.get_connector_customer_id()?)
} else {
None
};
let payment_method_data = match &item.router_data.request.payment_method_data {
PaymentMethodData::Card(_) => {
let pm_token = item.router_data.get_payment_method_token()?;
Ok(MolliePaymentMethodData::CreditCard(Box::new(
CreditCardMethodData {
billing_address: get_billing_details(item.router_data)?,
shipping_address: get_shipping_details(item.router_data)?,
card_token: Some(match pm_token {
PaymentMethodToken::Token(token) => token,
PaymentMethodToken::ApplePayDecrypt(_) => Err(
unimplemented_payment_method!("Apple Pay", "Simplified", "Mollie"),
)?,
PaymentMethodToken::PazeDecrypt(_) => {
Err(unimplemented_payment_method!("Paze", "Mollie"))?
}
PaymentMethodToken::GooglePayDecrypt(_) => {
Err(unimplemented_payment_method!("Google Pay", "Mollie"))?
}
}),
},
)))
}
PaymentMethodData::BankRedirect(ref redirect_data) => {
MolliePaymentMethodData::try_from((item.router_data, redirect_data))
}
PaymentMethodData::Wallet(ref wallet_data) => {
get_payment_method_for_wallet(item.router_data, wallet_data)
}
PaymentMethodData::BankDebit(ref directdebit_data) => {
MolliePaymentMethodData::try_from((directdebit_data, item.router_data))
}
PaymentMethodData::MandatePayment => Ok(MolliePaymentMethodData::MandatePayment(
Box::new(MandatePaymentMethodData {
mandate_id: item.router_data.request.get_connector_mandate_id()?.into(),
}),
)),
_ => Err(errors::ConnectorError::NotImplemented("Payment Method".to_string()).into()),
}?;
Ok(Self {
amount,
description,
redirect_url,
cancel_url: None,
/* webhook_url is a mandatory field.
But we can't support webhook in our core hence keeping it as empty string */
webhook_url: "".to_string(),
locale: None,
payment_method_data,
metadata: Some(MollieMetadata {
order_id: item.router_data.connector_request_reference_id.clone(),
}),
sequence_type,
capture_mode,
customer_id,
})
}
}
impl TryFrom<(&types::PaymentsAuthorizeRouterData, &BankRedirectData)> for MolliePaymentMethodData {
type Error = Error;
fn try_from(
(item, value): (&types::PaymentsAuthorizeRouterData, &BankRedirectData),
) -> Result<Self, Self::Error> {
match value {
BankRedirectData::Eps { .. } => Ok(Self::Eps),
BankRedirectData::Giropay { .. } => Ok(Self::Giropay),
BankRedirectData::Ideal { .. } => {
Ok(Self::Ideal(Box::new(IdealMethodData {
// To do if possible this should be from the payment request
issuer: None,
})))
}
BankRedirectData::Sofort { .. } => Ok(Self::Sofort),
BankRedirectData::Przelewy24 { .. } => {
Ok(Self::Przelewy24(Box::new(Przelewy24MethodData {
billing_email: item.get_optional_billing_email(),
})))
}
BankRedirectData::BancontactCard { .. } => Ok(Self::Bancontact),
_ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()),
}
}
}
impl TryFrom<(&BankDebitData, &types::PaymentsAuthorizeRouterData)> for MolliePaymentMethodData {
type Error = Error;
fn try_from(
(bank_debit_data, item): (&BankDebitData, &types::PaymentsAuthorizeRouterData),
) -> Result<Self, Self::Error> {
match bank_debit_data {
BankDebitData::SepaBankDebit { iban, .. } => {
Ok(Self::DirectDebit(Box::new(DirectDebitMethodData {
consumer_name: item.get_optional_billing_full_name(),
consumer_account: iban.clone(),
})))
}
_ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()),
}
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MollieCardTokenRequest {
card_holder: Secret<String>,
card_number: CardNumber,
card_cvv: Secret<String>,
card_expiry_date: Secret<String>,
locale: String,
testmode: bool,
profile_token: Secret<String>,
}
impl TryFrom<&types::TokenizationRouterData> for MollieCardTokenRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::TokenizationRouterData) -> Result<Self, Self::Error> {
match item.request.payment_method_data.clone() {
PaymentMethodData::Card(ccard) => {
let auth = MollieAuthType::try_from(&item.connector_auth_type)?;
let card_holder = item
.get_optional_billing_full_name()
.unwrap_or(Secret::new("".to_string()));
let card_number = ccard.card_number.clone();
let card_expiry_date =
ccard.get_card_expiry_month_year_2_digit_with_delimiter("/".to_owned())?;
let card_cvv = ccard.card_cvc;
let locale = item.request.get_browser_info()?.get_language()?;
let testmode =
item.test_mode
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "test_mode",
})?;
let profile_token = auth
.profile_token
.ok_or(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(Self {
card_holder,
card_number,
card_cvv,
card_expiry_date,
locale,
testmode,
profile_token,
})
}
_ => Err(errors::ConnectorError::NotImplemented(
"Payment Method".to_string(),
))?,
}
}
}
fn get_payment_method_for_wallet(
item: &types::PaymentsAuthorizeRouterData,
wallet_data: &WalletData,
) -> Result<MolliePaymentMethodData, Error> {
match wallet_data {
WalletData::PaypalRedirect { .. } => Ok(MolliePaymentMethodData::Paypal(Box::new(
PaypalMethodData {
billing_address: get_billing_details(item)?,
shipping_address: get_shipping_details(item)?,
},
))),
WalletData::ApplePay(applepay_wallet_data) => {
let apple_pay_encrypted_data = applepay_wallet_data
.payment_data
.get_encrypted_apple_pay_payment_data_mandatory()
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "Apple pay encrypted data",
})?;
Ok(MolliePaymentMethodData::Applepay(Box::new(
ApplePayMethodData {
apple_pay_payment_token: Secret::new(apple_pay_encrypted_data.to_owned()),
},
)))
}
_ => Err(errors::ConnectorError::NotImplemented("Payment Method".to_string()).into()),
}
}
fn get_shipping_details(
item: &types::PaymentsAuthorizeRouterData,
) -> Result<Option<Address>, Error> {
let shipping_address = item
.get_optional_shipping()
.and_then(|shipping| shipping.address.as_ref());
get_address_details(shipping_address)
}
fn get_billing_details(
item: &types::PaymentsAuthorizeRouterData,
) -> Result<Option<Address>, Error> {
let billing_address = item
.get_optional_billing()
.and_then(|billing| billing.address.as_ref());
get_address_details(billing_address)
}
fn get_address_details(
address: Option<&hyperswitch_domain_models::address::AddressDetails>,
) -> Result<Option<Address>, Error> {
let address_details = match address {
Some(address) => {
let street_and_number = address.get_combined_address_line()?;
let postal_code = address.get_zip()?.to_owned();
let city = address.get_city()?.to_owned();
let region = None;
let country = address.get_country()?.to_owned();
Some(Address {
street_and_number,
postal_code,
city,
region,
country,
})
}
None => None,
};
Ok(address_details)
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MolliePaymentsResponse {
pub resource: String,
pub id: String,
pub amount: Amount,
pub description: Option<String>,
pub metadata: Option<MollieMetadata>,
pub status: MolliePaymentStatus,
pub is_cancelable: Option<bool>,
pub sequence_type: Option<SequenceType>,
pub redirect_url: Option<String>,
pub webhook_url: Option<String>,
#[serde(rename = "_links")]
pub links: Links,
pub mandate_id: Option<Secret<String>>,
pub payment_id: Option<String>,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum MolliePaymentStatus {
Open,
Canceled,
#[default]
Pending,
Authorized,
Expired,
Failed,
Paid,
}
impl From<MolliePaymentStatus> for enums::AttemptStatus {
fn from(item: MolliePaymentStatus) -> Self {
match item {
MolliePaymentStatus::Paid => Self::Charged,
MolliePaymentStatus::Failed => Self::Failure,
MolliePaymentStatus::Pending => Self::Pending,
MolliePaymentStatus::Open => Self::AuthenticationPending,
MolliePaymentStatus::Canceled => Self::Voided,
MolliePaymentStatus::Authorized => Self::Authorized,
MolliePaymentStatus::Expired => Self::Failure,
}
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Link {
href: Url,
#[serde(rename = "type")]
type_: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Links {
#[serde(rename = "self")]
self_: Option<Link>,
checkout: Option<Link>,
dashboard: Option<Link>,
documentation: Option<Link>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CardDetails {
pub card_number: Secret<String>,
pub card_holder: Secret<String>,
pub card_expiry_date: Secret<String>,
pub card_cvv: Secret<String>,
}
pub struct MollieAuthType {
pub(super) api_key: Secret<String>,
pub(super) profile_token: Option<Secret<String>>,
}
impl TryFrom<&ConnectorAuthType> for MollieAuthType {
type Error = Error;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
api_key: api_key.to_owned(),
profile_token: None,
}),
ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
api_key: api_key.to_owned(),
profile_token: Some(key1.to_owned()),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType)?,
}
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MollieCardTokenResponse {
card_token: Secret<String>,
}
impl<F, T> TryFrom<ResponseRouterData<F, MollieCardTokenResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, MollieCardTokenResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: enums::AttemptStatus::Pending,
payment_method_token: Some(PaymentMethodToken::Token(item.response.card_token.clone())),
response: Ok(PaymentsResponseData::TokenizationResponse {
token: item.response.card_token.expose(),
}),
..item.data
})
}
}
impl<F, T> TryFrom<ResponseRouterData<F, MolliePaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = Error;
fn try_from(
item: ResponseRouterData<F, MolliePaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let url = item
.response
.links
.checkout
.map(|link| RedirectForm::from((link.href, Method::Get)));
let mandate_reference = item
.response
.mandate_id
.as_ref()
.map(|id| MandateReference {
connector_mandate_id: Some(id.clone().expose()),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
});
Ok(Self {
status: enums::AttemptStatus::from(item.response.status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response
.payment_id
.unwrap_or_else(|| item.response.id.clone()),
),
redirection_data: Box::new(url),
mandate_reference: Box::new(mandate_reference),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.id),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Default, Debug, Serialize)]
pub struct MollieCaptureRequest {
pub amount: Option<Amount>,
pub description: String,
}
impl TryFrom<&MollieRouterData<&types::PaymentsCaptureRouterData>> for MollieCaptureRequest {
type Error = Error;
fn try_from(
item: &MollieRouterData<&types::PaymentsCaptureRouterData>,
) -> Result<Self, Self::Error> {
Ok(Self {
amount: Some(Amount {
value: item.amount.clone(),
currency: item.router_data.request.currency,
}),
description: item.router_data.get_description()?,
})
}
}
// REFUND :
#[derive(Default, Debug, Serialize)]
pub struct MollieRefundRequest {
amount: Amount,
description: Option<String>,
metadata: Option<MollieMetadata>,
}
impl<F> TryFrom<&MollieRouterData<&types::RefundsRouterData<F>>> for MollieRefundRequest {
type Error = Error;
fn try_from(
item: &MollieRouterData<&types::RefundsRouterData<F>>,
) -> Result<Self, Self::Error> {
let amount = Amount {
currency: item.router_data.request.currency,
value: item.amount.clone(),
};
Ok(Self {
amount,
description: item.router_data.request.reason.to_owned(),
metadata: Some(MollieMetadata {
order_id: item.router_data.request.refund_id.clone(),
}),
})
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RefundResponse {
resource: String,
id: String,
amount: Amount,
settlement_id: Option<String>,
settlement_amount: Option<Amount>,
status: MollieRefundStatus,
description: Option<String>,
metadata: Option<MollieMetadata>,
payment_id: String,
#[serde(rename = "_links")]
links: Links,
}
#[derive(Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum MollieRefundStatus {
Queued,
#[default]
Pending,
Processing,
Refunded,
Failed,
Canceled,
}
impl From<MollieRefundStatus> for enums::RefundStatus {
fn from(item: MollieRefundStatus) -> Self {
match item {
MollieRefundStatus::Queued
| MollieRefundStatus::Pending
| MollieRefundStatus::Processing => Self::Pending,
MollieRefundStatus::Refunded => Self::Success,
MollieRefundStatus::Failed | MollieRefundStatus::Canceled => Self::Failure,
}
}
}
impl<T> TryFrom<RefundsResponseRouterData<T, RefundResponse>> for types::RefundsRouterData<T> {
type Error = Error;
fn try_from(item: RefundsResponseRouterData<T, RefundResponse>) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id,
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct MollieErrorResponse {
pub status: u16,
pub title: Option<String>,
pub detail: String,
pub field: Option<String>,
}
| 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/airwallex/transformers.rs | crates/hyperswitch_connectors/src/connectors/airwallex/transformers.rs | use common_enums::enums;
use common_utils::{
errors::ParsingError,
ext_traits::ValueExt,
id_type,
pii::{Email, IpAddress},
request::Method,
types::{MinorUnit, StringMajorUnit},
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{
BankRedirectData, BankTransferData, PayLaterData, PaymentMethodData, WalletData,
},
router_data::{AccessToken, ConnectorAuthType, RouterData},
router_flow_types::{
refunds::{Execute, RSync},
PSync,
},
router_request_types::{PaymentsSyncData, ResponseId},
router_response_types::{
ConnectorCustomerResponseData, MandateReference, PaymentsResponseData, RedirectForm,
RefundsResponseData,
},
types,
};
use hyperswitch_interfaces::errors;
use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
use url::Url;
use uuid::Uuid;
use crate::{
types::{CreateOrderResponseRouterData, RefundsResponseRouterData, ResponseRouterData},
utils::{
self, BrowserInformationData, CardData as _, ForeignTryFrom, PaymentsAuthorizeRequestData,
PhoneDetailsData, RouterData as _,
},
};
pub struct AirwallexAuthType {
pub x_api_key: Secret<String>,
pub x_client_id: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for AirwallexAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
if let ConnectorAuthType::BodyKey { api_key, key1 } = auth_type {
Ok(Self {
x_api_key: api_key.clone(),
x_client_id: key1.clone(),
})
} else {
Err(errors::ConnectorError::FailedToObtainAuthType)?
}
}
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct ReferrerData {
#[serde(rename = "type")]
r_type: String,
version: String,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct AirwallexIntentRequest {
// Unique ID to be sent for each transaction/operation request to the connector
request_id: String,
amount: StringMajorUnit,
currency: enums::Currency,
//ID created in merchant's order system that corresponds to this PaymentIntent.
merchant_order_id: String,
// This data is required to whitelist Hyperswitch at Airwallex.
referrer_data: ReferrerData,
order: Option<AirwallexOrderData>,
}
impl TryFrom<&AirwallexRouterData<&types::CreateOrderRouterData>> for AirwallexIntentRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &AirwallexRouterData<&types::CreateOrderRouterData>,
) -> Result<Self, Self::Error> {
let referrer_data = ReferrerData {
r_type: "hyperswitch".to_string(),
version: "1.0.0".to_string(),
};
let amount = item.amount.clone();
let currency = item.router_data.request.currency;
let order = match item.router_data.request.payment_method_data {
Some(PaymentMethodData::PayLater(_)) => Some(
item.router_data
.request
.order_details
.as_ref()
.map(|order_data| AirwallexOrderData {
products: order_data
.iter()
.map(|product| AirwallexProductData {
name: product.product_name.clone(),
quantity: product.quantity,
unit_price: product.amount,
})
.collect(),
shipping: Some(AirwallexShippingData {
first_name: item.router_data.get_optional_shipping_first_name(),
last_name: item.router_data.get_optional_shipping_last_name(),
phone_number: item.router_data.get_optional_shipping_phone_number(),
address: AirwallexPLShippingAddress {
country_code: item.router_data.get_optional_shipping_country(),
city: item.router_data.get_optional_shipping_city(),
street: item.router_data.get_optional_shipping_line1(),
postcode: item.router_data.get_optional_shipping_zip(),
},
}),
})
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "order_details",
})?,
),
_ => None,
};
Ok(Self {
request_id: Uuid::new_v4().to_string(),
amount,
currency,
merchant_order_id: item.router_data.connector_request_reference_id.clone(),
referrer_data,
order,
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct AirwallexOrderResponse {
pub status: AirwallexPaymentStatus,
pub id: String,
pub payment_consent_id: Option<Secret<String>>,
pub next_action: Option<AirwallexPaymentsNextAction>,
}
impl TryFrom<CreateOrderResponseRouterData<AirwallexOrderResponse>>
for types::CreateOrderRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: CreateOrderResponseRouterData<AirwallexOrderResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(PaymentsResponseData::PaymentsCreateOrderResponse {
order_id: item.response.id.clone(),
}),
..item.data
})
}
}
#[derive(Debug, Serialize)]
pub struct AirwallexRouterData<T> {
pub amount: StringMajorUnit,
pub router_data: T,
}
impl<T> TryFrom<(StringMajorUnit, T)> for AirwallexRouterData<T> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from((amount, router_data): (StringMajorUnit, T)) -> Result<Self, Self::Error> {
Ok(Self {
amount,
router_data,
})
}
}
#[derive(Debug, Serialize)]
pub struct AirwallexPaymentsRequest {
// Unique ID to be sent for each transaction/operation request to the connector
request_id: String,
payment_method: AirwallexPaymentMethod,
payment_method_options: Option<AirwallexPaymentOptions>,
return_url: Option<String>,
device_data: Option<DeviceData>,
payment_consent: Option<PaymentConsentData>,
customer_id: Option<String>,
payment_consent_id: Option<String>,
triggered_by: Option<TriggeredBy>,
}
#[derive(Debug, Serialize)]
pub struct PaymentConsentData {
next_triggered_by: TriggeredBy,
merchant_trigger_reason: MerchantTriggeredReason,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum MerchantTriggeredReason {
Unscheduled,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum TriggeredBy {
Merchant,
Customer,
}
#[derive(Debug, Serialize, Eq, PartialEq, Default)]
pub struct AirwallexOrderData {
products: Vec<AirwallexProductData>,
shipping: Option<AirwallexShippingData>,
}
#[derive(Debug, Serialize, Eq, PartialEq)]
pub struct AirwallexProductData {
name: String,
quantity: u16,
unit_price: MinorUnit,
}
#[derive(Debug, Serialize, Eq, PartialEq)]
pub struct AirwallexShippingData {
first_name: Option<Secret<String>>,
last_name: Option<Secret<String>>,
phone_number: Option<Secret<String>>,
address: AirwallexPLShippingAddress,
}
#[derive(Debug, Serialize, Eq, PartialEq)]
pub struct AirwallexPLShippingAddress {
country_code: Option<enums::CountryAlpha2>,
city: Option<String>,
street: Option<Secret<String>>,
postcode: Option<Secret<String>>,
}
#[derive(Debug, Serialize)]
pub struct DeviceData {
accept_header: String,
browser: Browser,
ip_address: Secret<String, IpAddress>,
language: String,
mobile: Option<Mobile>,
screen_color_depth: u8,
screen_height: u32,
screen_width: u32,
timezone: String,
}
#[derive(Debug, Serialize)]
pub struct Browser {
java_enabled: bool,
javascript_enabled: bool,
user_agent: String,
}
#[derive(Debug, Serialize)]
pub struct Mobile {
device_model: Option<String>,
os_type: Option<String>,
os_version: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum AirwallexPaymentMethod {
Card(AirwallexCard),
Wallets(AirwallexWalletData),
PayLater(AirwallexPayLaterData),
BankRedirect(AirwallexBankRedirectData),
BankTransfer(AirwallexBankTransferData),
PaymentMethodId(AirwallexPaymentMethodId),
}
#[derive(Debug, Serialize)]
pub struct AirwallexPaymentMethodId {
id: Secret<String>,
}
#[derive(Debug, Serialize)]
pub struct AirwallexCard {
card: AirwallexCardDetails,
#[serde(rename = "type")]
payment_method_type: AirwallexPaymentType,
}
#[derive(Debug, Serialize)]
pub struct AirwallexCardDetails {
expiry_month: Secret<String>,
expiry_year: Secret<String>,
number: cards::CardNumber,
cvc: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum AirwallexWalletData {
GooglePay(GooglePayData),
Paypal(PaypalData),
Skrill(SkrillData),
}
#[derive(Debug, Serialize)]
pub struct GooglePayData {
googlepay: GooglePayDetails,
#[serde(rename = "type")]
payment_method_type: AirwallexPaymentType,
}
#[derive(Debug, Serialize)]
pub struct PaypalData {
paypal: PaypalDetails,
#[serde(rename = "type")]
payment_method_type: AirwallexPaymentType,
}
#[derive(Debug, Serialize)]
pub struct SkrillData {
skrill: SkrillDetails,
#[serde(rename = "type")]
payment_method_type: AirwallexPaymentType,
}
#[derive(Debug, Serialize)]
pub struct GooglePayDetails {
encrypted_payment_token: Secret<String>,
payment_data_type: GpayPaymentDataType,
}
#[derive(Debug, Serialize)]
pub struct PaypalDetails {
shopper_name: Secret<String>,
country_code: enums::CountryAlpha2,
}
#[derive(Debug, Serialize)]
pub struct SkrillDetails {
shopper_name: Secret<String>,
shopper_email: Email,
country_code: enums::CountryAlpha2,
}
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum AirwallexPayLaterData {
Klarna(Box<KlarnaData>),
Atome(AtomeData),
}
#[derive(Debug, Serialize)]
pub struct KlarnaData {
klarna: KlarnaDetails,
#[serde(rename = "type")]
payment_method_type: AirwallexPaymentType,
}
#[derive(Debug, Serialize)]
pub struct KlarnaDetails {
country_code: enums::CountryAlpha2,
billing: Option<Billing>,
}
#[derive(Debug, Serialize)]
pub struct Billing {
date_of_birth: Option<Secret<String>>,
email: Option<Email>,
first_name: Option<Secret<String>>,
last_name: Option<Secret<String>>,
phone_number: Option<Secret<String>>,
address: Option<AddressAirwallex>,
}
#[derive(Debug, Serialize)]
pub struct AddressAirwallex {
country_code: Option<enums::CountryAlpha2>,
city: Option<String>,
street: Option<Secret<String>>,
postcode: Option<Secret<String>>,
}
#[derive(Debug, Serialize)]
pub struct AtomeData {
atome: AtomeDetails,
#[serde(rename = "type")]
payment_method_type: AirwallexPaymentType,
}
#[derive(Debug, Serialize)]
pub struct AtomeDetails {
shopper_phone: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum AirwallexBankTransferData {
IndonesianBankTransfer(IndonesianBankTransferData),
}
#[derive(Debug, Serialize)]
pub struct IndonesianBankTransferData {
bank_transfer: IndonesianBankTransferDetails,
#[serde(rename = "type")]
payment_method_type: AirwallexPaymentType,
}
#[derive(Debug, Serialize)]
pub struct IndonesianBankTransferDetails {
shopper_name: Secret<String>,
shopper_email: Email,
bank_name: common_enums::BankNames,
country_code: enums::CountryAlpha2,
}
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum AirwallexBankRedirectData {
Trustly(TrustlyData),
Blik(BlikData),
Ideal(IdealData),
}
#[derive(Debug, Serialize)]
pub struct TrustlyData {
trustly: TrustlyDetails,
#[serde(rename = "type")]
payment_method_type: AirwallexPaymentType,
}
#[derive(Debug, Serialize)]
pub struct TrustlyDetails {
shopper_name: Secret<String>,
country_code: enums::CountryAlpha2,
}
#[derive(Debug, Serialize)]
pub struct BlikData {
blik: BlikDetails,
#[serde(rename = "type")]
payment_method_type: AirwallexPaymentType,
}
#[derive(Debug, Serialize)]
pub struct BlikDetails {
shopper_name: Secret<String>,
}
#[derive(Debug, Serialize)]
pub struct IdealData {
ideal: IdealDetails,
#[serde(rename = "type")]
payment_method_type: AirwallexPaymentType,
}
#[derive(Debug, Serialize)]
pub struct IdealDetails {
bank_name: Option<common_enums::BankNames>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum AirwallexPaymentType {
Card,
Googlepay,
Paypal,
Klarna,
Atome,
Trustly,
Blik,
Ideal,
Skrill,
BankTransfer,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum GpayPaymentDataType {
EncryptedPaymentToken,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum AirwallexPaymentOptions {
Card(AirwallexCardPaymentOptions),
Klarna(AirwallexPayLaterPaymentOptions),
Atome(AirwallexPayLaterPaymentOptions),
}
#[derive(Debug, Serialize)]
pub struct AirwallexCardPaymentOptions {
auto_capture: bool,
}
#[derive(Debug, Serialize)]
pub struct AirwallexPayLaterPaymentOptions {
auto_capture: bool,
}
impl TryFrom<&AirwallexRouterData<&types::PaymentsAuthorizeRouterData>>
for AirwallexPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &AirwallexRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let mut payment_method_options = None;
let request = &item.router_data.request;
let payment_method = match request.payment_method_data.clone() {
PaymentMethodData::Card(ccard) => {
payment_method_options =
Some(AirwallexPaymentOptions::Card(AirwallexCardPaymentOptions {
auto_capture: matches!(
request.capture_method,
Some(enums::CaptureMethod::Automatic)
| Some(enums::CaptureMethod::SequentialAutomatic)
| None
),
}));
Ok(AirwallexPaymentMethod::Card(AirwallexCard {
card: AirwallexCardDetails {
number: ccard.card_number.clone(),
expiry_month: ccard.card_exp_month.clone(),
expiry_year: ccard.get_expiry_year_4_digit(),
cvc: ccard.card_cvc,
},
payment_method_type: AirwallexPaymentType::Card,
}))
}
PaymentMethodData::Wallet(ref wallet_data) => get_wallet_details(wallet_data, item),
PaymentMethodData::PayLater(ref paylater_data) => {
let paylater_options = AirwallexPayLaterPaymentOptions {
auto_capture: item.router_data.request.is_auto_capture()?,
};
payment_method_options = match paylater_data {
PayLaterData::KlarnaRedirect { .. } => {
Some(AirwallexPaymentOptions::Klarna(paylater_options))
}
PayLaterData::AtomeRedirect { .. } => {
Some(AirwallexPaymentOptions::Atome(paylater_options))
}
_ => None,
};
get_paylater_details(paylater_data, item)
}
PaymentMethodData::BankTransfer(ref banktransfer_data) => {
get_banktransfer_details(banktransfer_data, item)
}
PaymentMethodData::BankRedirect(ref bankredirect_data) => {
get_bankredirect_details(bankredirect_data, item)
}
PaymentMethodData::MandatePayment => {
let mandate_data = item
.router_data
.request
.get_connector_mandate_data()
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "connector_mandate_data",
})?;
let mandate_metadata: AirwallexMandateMetadata = mandate_data
.get_mandate_metadata()
.ok_or(errors::ConnectorError::MissingConnectorMandateMetadata)?
.clone()
.parse_value("AirwallexMandateMetadata")
.change_context(errors::ConnectorError::ParsingFailed)?;
Ok(AirwallexPaymentMethod::PaymentMethodId(
AirwallexPaymentMethodId {
id: mandate_metadata.id.ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "mandate_metadata.id",
},
)?,
},
))
}
PaymentMethodData::BankDebit(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("airwallex"),
))
}
}?;
let payment_consent = if item
.router_data
.request
.is_customer_initiated_mandate_payment()
{
Some(PaymentConsentData {
next_triggered_by: TriggeredBy::Merchant,
merchant_trigger_reason: MerchantTriggeredReason::Unscheduled,
})
} else {
None
};
let return_url = match &request.payment_method_data {
PaymentMethodData::Wallet(wallet_data) => match wallet_data {
WalletData::PaypalRedirect(_paypal_details) => {
item.router_data.request.router_return_url.clone()
}
WalletData::Skrill(_) => item.router_data.request.router_return_url.clone(),
_ => request.complete_authorize_url.clone(),
},
PaymentMethodData::BankRedirect(_bankredirect_data) => {
item.router_data.request.router_return_url.clone()
}
PaymentMethodData::PayLater(_paylater_data) => {
item.router_data.request.router_return_url.clone()
}
_ => request.complete_authorize_url.clone(),
};
let is_mandate_payment = item.router_data.request.is_mit_payment()
|| item
.router_data
.request
.is_customer_initiated_mandate_payment();
let (device_data, customer_id) = if is_mandate_payment {
let customer_id = item.router_data.get_connector_customer_id()?;
(None, Some(customer_id))
} else {
let device_data = Some(get_device_data(item.router_data)?);
(device_data, None)
};
let (payment_consent_id, triggered_by) = if item.router_data.request.is_mit_payment() {
let mandate_id = item.router_data.request.connector_mandate_id().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "connector_mandate_id",
},
)?;
(Some(mandate_id), Some(TriggeredBy::Merchant))
} else {
(None, None)
};
Ok(Self {
request_id: Uuid::new_v4().to_string(),
payment_method,
payment_method_options,
return_url,
device_data,
payment_consent,
customer_id,
payment_consent_id,
triggered_by,
})
}
}
fn get_device_data(
item: &types::PaymentsAuthorizeRouterData,
) -> Result<DeviceData, error_stack::Report<errors::ConnectorError>> {
let info = item.request.get_browser_info()?;
let browser = Browser {
java_enabled: info.get_java_enabled()?,
javascript_enabled: info.get_java_script_enabled()?,
user_agent: info.get_user_agent()?,
};
let mobile = {
let device_model = info.get_device_model().ok();
let os_type = info.get_os_type().ok();
let os_version = info.get_os_version().ok();
if device_model.is_some() || os_type.is_some() || os_version.is_some() {
Some(Mobile {
device_model,
os_type,
os_version,
})
} else {
None
}
};
Ok(DeviceData {
accept_header: info.get_accept_header()?,
browser,
ip_address: info.get_ip_address()?,
mobile,
screen_color_depth: info.get_color_depth()?,
screen_height: info.get_screen_height()?,
screen_width: info.get_screen_width()?,
timezone: info.get_time_zone()?.to_string(),
language: info.get_language()?,
})
}
fn get_banktransfer_details(
banktransfer_data: &BankTransferData,
item: &AirwallexRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<AirwallexPaymentMethod, errors::ConnectorError> {
let _bank_transfer_details = match banktransfer_data {
BankTransferData::IndonesianBankTransfer { bank_name } => {
AirwallexPaymentMethod::BankTransfer(AirwallexBankTransferData::IndonesianBankTransfer(
IndonesianBankTransferData {
bank_transfer: IndonesianBankTransferDetails {
shopper_name: item.router_data.get_billing_full_name().map_err(|_| {
errors::ConnectorError::MissingRequiredField {
field_name: "shopper_name",
}
})?,
shopper_email: item.router_data.get_billing_email().map_err(|_| {
errors::ConnectorError::MissingRequiredField {
field_name: "shopper_email",
}
})?,
bank_name: bank_name.ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "bank_name",
},
)?,
country_code: item.router_data.get_billing_country().map_err(|_| {
errors::ConnectorError::MissingRequiredField {
field_name: "country_code",
}
})?,
},
payment_method_type: AirwallexPaymentType::BankTransfer,
},
))
}
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("airwallex"),
))?,
};
let not_implemented = Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("airwallex"),
))?;
Ok(not_implemented)
}
fn get_paylater_details(
paylater_data: &PayLaterData,
item: &AirwallexRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<AirwallexPaymentMethod, errors::ConnectorError> {
let paylater_details = match paylater_data {
PayLaterData::KlarnaRedirect {} => {
AirwallexPaymentMethod::PayLater(AirwallexPayLaterData::Klarna(Box::new(KlarnaData {
klarna: KlarnaDetails {
country_code: item.router_data.get_billing_country().map_err(|_| {
errors::ConnectorError::MissingRequiredField {
field_name: "country_code",
}
})?,
billing: Some(Billing {
date_of_birth: None,
first_name: item.router_data.get_optional_billing_first_name(),
last_name: item.router_data.get_optional_billing_last_name(),
email: item.router_data.get_optional_billing_email(),
phone_number: item.router_data.get_optional_billing_phone_number(),
address: Some(AddressAirwallex {
country_code: item.router_data.get_optional_billing_country(),
city: item.router_data.get_optional_billing_city(),
street: item.router_data.get_optional_billing_line1(),
postcode: item.router_data.get_optional_billing_zip(),
}),
}),
},
payment_method_type: AirwallexPaymentType::Klarna,
})))
}
PayLaterData::AtomeRedirect {} => {
AirwallexPaymentMethod::PayLater(AirwallexPayLaterData::Atome(AtomeData {
atome: AtomeDetails {
shopper_phone: item
.router_data
.get_billing_phone()
.map_err(|_| errors::ConnectorError::MissingRequiredField {
field_name: "shopper_phone",
})?
.get_number_with_country_code()
.map_err(|_| errors::ConnectorError::MissingRequiredField {
field_name: "country_code",
})?,
},
payment_method_type: AirwallexPaymentType::Atome,
}))
}
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("airwallex"),
))?,
};
Ok(paylater_details)
}
fn get_bankredirect_details(
bankredirect_data: &BankRedirectData,
item: &AirwallexRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<AirwallexPaymentMethod, errors::ConnectorError> {
let bank_redirect_details = match bankredirect_data {
BankRedirectData::Trustly { .. } => {
AirwallexPaymentMethod::BankRedirect(AirwallexBankRedirectData::Trustly(TrustlyData {
trustly: TrustlyDetails {
shopper_name: item.router_data.get_billing_full_name().map_err(|_| {
errors::ConnectorError::MissingRequiredField {
field_name: "shopper_name",
}
})?,
country_code: item.router_data.get_billing_country().map_err(|_| {
errors::ConnectorError::MissingRequiredField {
field_name: "country_code",
}
})?,
},
payment_method_type: AirwallexPaymentType::Trustly,
}))
}
BankRedirectData::Blik { .. } => {
AirwallexPaymentMethod::BankRedirect(AirwallexBankRedirectData::Blik(BlikData {
blik: BlikDetails {
shopper_name: item.router_data.get_billing_full_name().map_err(|_| {
errors::ConnectorError::MissingRequiredField {
field_name: "shopper_name",
}
})?,
},
payment_method_type: AirwallexPaymentType::Blik,
}))
}
BankRedirectData::Ideal { .. } => {
AirwallexPaymentMethod::BankRedirect(AirwallexBankRedirectData::Ideal(IdealData {
ideal: IdealDetails { bank_name: None },
payment_method_type: AirwallexPaymentType::Ideal,
}))
}
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("airwallex"),
))?,
};
Ok(bank_redirect_details)
}
fn get_wallet_details(
wallet_data: &WalletData,
item: &AirwallexRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<AirwallexPaymentMethod, errors::ConnectorError> {
let wallet_details: AirwallexPaymentMethod = match wallet_data {
WalletData::GooglePay(gpay_details) => {
let token = gpay_details
.tokenization_data
.get_encrypted_google_pay_token()
.attach_printable("Failed to get gpay wallet token")
.map_err(|_| errors::ConnectorError::MissingRequiredField {
field_name: "gpay wallet_token",
})?;
AirwallexPaymentMethod::Wallets(AirwallexWalletData::GooglePay(GooglePayData {
googlepay: GooglePayDetails {
encrypted_payment_token: Secret::new(token.clone()),
payment_data_type: GpayPaymentDataType::EncryptedPaymentToken,
},
payment_method_type: AirwallexPaymentType::Googlepay,
}))
}
WalletData::PaypalRedirect(_paypal_details) => {
AirwallexPaymentMethod::Wallets(AirwallexWalletData::Paypal(PaypalData {
paypal: PaypalDetails {
shopper_name: item
.router_data
.request
.customer_name
.as_ref()
.cloned()
.or_else(|| item.router_data.get_billing_full_name().ok())
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "shopper_name",
})?,
country_code: item.router_data.get_billing_country().map_err(|_| {
errors::ConnectorError::MissingRequiredField {
field_name: "country_code",
}
})?,
},
payment_method_type: AirwallexPaymentType::Paypal,
}))
}
WalletData::Skrill(_skrill_details) => {
AirwallexPaymentMethod::Wallets(AirwallexWalletData::Skrill(SkrillData {
skrill: SkrillDetails {
shopper_name: item
.router_data
.request
.customer_name
.as_ref()
.cloned()
.or_else(|| item.router_data.get_billing_full_name().ok())
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "shopper_name",
})?,
shopper_email: item.router_data.get_billing_email().map_err(|_| {
errors::ConnectorError::MissingRequiredField {
field_name: "shopper_email",
}
})?,
country_code: item.router_data.get_billing_country().map_err(|_| {
errors::ConnectorError::MissingRequiredField {
field_name: "country_code",
}
})?,
},
payment_method_type: AirwallexPaymentType::Skrill,
}))
}
WalletData::AliPayQr(_)
| WalletData::AliPayRedirect(_)
| WalletData::AliPayHkRedirect(_)
| WalletData::AmazonPayRedirect(_)
| WalletData::Paysera(_)
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
| WalletData::GcashRedirect(_)
| 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/wellsfargopayout/transformers.rs | crates/hyperswitch_connectors/src/connectors/wellsfargopayout/transformers.rs | use common_enums::{AttemptStatus, RefundStatus};
use common_utils::types::StringMinorUnit;
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{ConnectorAuthType, RouterData},
router_flow_types::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RefundsResponseData},
types::{PaymentsAuthorizeRouterData, RefundsRouterData},
};
use hyperswitch_interfaces::errors::ConnectorError;
use masking::Secret;
use serde::{Deserialize, Serialize};
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::PaymentsAuthorizeRequestData as _,
};
//TODO: Fill the struct with respective fields
pub struct WellsfargopayoutRouterData<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 WellsfargopayoutRouterData<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 WellsfargopayoutPaymentsRequest {
amount: StringMinorUnit,
card: WellsfargopayoutCard,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct WellsfargopayoutCard {
number: cards::CardNumber,
expiry_month: Secret<String>,
expiry_year: Secret<String>,
cvc: Secret<String>,
complete: bool,
}
impl TryFrom<&WellsfargopayoutRouterData<&PaymentsAuthorizeRouterData>>
for WellsfargopayoutPaymentsRequest
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: &WellsfargopayoutRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(req_card) => {
let card = WellsfargopayoutCard {
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(ConnectorError::NotImplemented("Payment methods".to_string()).into()),
}
}
}
//TODO: Fill the struct with respective fields
// Auth Struct
pub struct WellsfargopayoutAuthType {
pub(super) api_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for WellsfargopayoutAuthType {
type Error = error_stack::Report<ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
api_key: api_key.to_owned(),
}),
_ => Err(ConnectorError::FailedToObtainAuthType.into()),
}
}
}
// PaymentsResponse
//TODO: Append the remaining status flags
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum WellsfargopayoutPaymentStatus {
Succeeded,
Failed,
#[default]
Processing,
}
impl From<WellsfargopayoutPaymentStatus> for AttemptStatus {
fn from(item: WellsfargopayoutPaymentStatus) -> Self {
match item {
WellsfargopayoutPaymentStatus::Succeeded => Self::Charged,
WellsfargopayoutPaymentStatus::Failed => Self::Failure,
WellsfargopayoutPaymentStatus::Processing => Self::Authorizing,
}
}
}
//TODO: Fill the struct with respective fields
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct WellsfargopayoutPaymentsResponse {
status: WellsfargopayoutPaymentStatus,
id: String,
}
impl<F, T> TryFrom<ResponseRouterData<F, WellsfargopayoutPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<F, WellsfargopayoutPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: 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 WellsfargopayoutRefundRequest {
pub amount: StringMinorUnit,
}
impl<F> TryFrom<&WellsfargopayoutRouterData<&RefundsRouterData<F>>>
for WellsfargopayoutRefundRequest
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: &WellsfargopayoutRouterData<&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 WellsfargopayoutRefundStatus {
Succeeded,
Failed,
#[default]
Processing,
}
impl From<WellsfargopayoutRefundStatus> for RefundStatus {
fn from(item: WellsfargopayoutRefundStatus) -> Self {
match item {
WellsfargopayoutRefundStatus::Succeeded => Self::Success,
WellsfargopayoutRefundStatus::Failed => Self::Failure,
WellsfargopayoutRefundStatus::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: WellsfargopayoutRefundStatus,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
//TODO: Fill the struct with respective fields
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct WellsfargopayoutErrorResponse {
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/worldpay/payout_requests.rs | crates/hyperswitch_connectors/src/connectors/worldpay/payout_requests.rs | use masking::Secret;
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct WorldpayPayoutRequest {
pub transaction_reference: String,
pub merchant: Merchant,
pub instruction: PayoutInstruction,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PayoutInstruction {
pub payout_instrument: PayoutInstrument,
pub narrative: InstructionNarrative,
pub value: PayoutValue,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct PayoutValue {
pub amount: i64,
pub currency: api_models::enums::Currency,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Merchant {
pub entity: Secret<String>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct InstructionNarrative {
pub line1: Secret<String>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum PayoutInstrument {
ApplePayDecrypt(ApplePayDecrypt),
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ApplePayDecrypt {
#[serde(rename = "type")]
pub payout_type: PayoutType,
pub dpan: cards::CardNumber,
pub card_expiry_date: PayoutExpiryDate,
#[serde(skip_serializing_if = "Option::is_none")]
pub card_holder_name: Option<Secret<String>>,
}
#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)]
pub struct PayoutExpiryDate {
pub month: Secret<i8>,
pub year: Secret<i32>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum PayoutType {
#[serde(rename = "card/networkToken+applepay")]
ApplePayDecrypt,
}
| 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/worldpay/response.rs | crates/hyperswitch_connectors/src/connectors/worldpay/response.rs | use error_stack::ResultExt;
use hyperswitch_interfaces::errors;
use masking::Secret;
use serde::{Deserialize, Serialize};
use url::Url;
use super::requests::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct WorldpayPaymentsResponse {
pub outcome: PaymentOutcome,
pub transaction_reference: Option<String>,
#[serde(flatten)]
pub other_fields: Option<WorldpayPaymentResponseFields>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum WorldpayPaymentResponseFields {
RefusedResponse(RefusedResponse),
DDCResponse(DDCResponse),
ThreeDsChallenged(ThreeDsChallengedResponse),
FraudHighRisk(FraudHighRiskResponse),
AuthorizedResponse(Box<AuthorizedResponse>),
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthorizedResponse {
pub payment_instrument: PaymentsResPaymentInstrument,
#[serde(skip_serializing_if = "Option::is_none")]
pub issuer: Option<Issuer>,
#[serde(skip_serializing_if = "Option::is_none")]
pub scheme: Option<PaymentsResponseScheme>,
#[serde(rename = "_links", skip_serializing_if = "Option::is_none")]
pub links: Option<SelfLink>,
#[serde(rename = "_actions")]
pub actions: Option<ActionLinks>,
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
pub risk_factors: Option<Vec<RiskFactorsInner>>,
pub fraud: Option<Fraud>,
/// Mandate's token
pub token: Option<MandateToken>,
/// Network transaction ID
pub scheme_reference: Option<Secret<String>>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MandateToken {
pub href: Secret<String>,
pub token_id: String,
pub token_expiry_date_time: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct FraudHighRiskResponse {
pub score: f32,
pub reason: Vec<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RefusedResponse {
pub refusal_description: String,
// Access Worldpay returns a raw response code in the refusalCode field (if enabled) containing the unmodified response code received either directly from the card scheme for Worldpay-acquired transactions, or from third party acquirers.
pub refusal_code: String,
pub risk_factors: Option<Vec<RiskFactorsInner>>,
pub fraud: Option<Fraud>,
#[serde(rename = "threeDS")]
pub three_ds: Option<ThreeDsResponse>,
pub advice: Option<Advice>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Advice {
pub code: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ThreeDsResponse {
pub outcome: String,
pub issuer_response: IssuerResponse,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ThreeDsChallengedResponse {
pub authentication: AuthenticationResponse,
pub challenge: ThreeDsChallenge,
#[serde(rename = "_actions")]
pub actions: CompleteThreeDsActionLink,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AuthenticationResponse {
pub version: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ThreeDsChallenge {
pub reference: String,
pub url: Url,
pub jwt: Secret<String>,
pub payload: Secret<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CompleteThreeDsActionLink {
#[serde(rename = "complete3dsChallenge")]
pub complete_three_ds_challenge: ActionLink,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum IssuerResponse {
Challenged,
Frictionless,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DDCResponse {
pub device_data_collection: DDCToken,
#[serde(rename = "_actions")]
pub actions: DDCActionLink,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DDCToken {
pub jwt: Secret<String>,
pub url: Url,
pub bin: Secret<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DDCActionLink {
#[serde(rename = "supply3dsDeviceData")]
supply_ddc_data: ActionLink,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum PaymentOutcome {
#[serde(alias = "authorized", alias = "Authorized")]
Authorized,
Refused,
SentForSettlement,
SentForRefund,
FraudHighRisk,
#[serde(alias = "3dsDeviceDataRequired")]
ThreeDsDeviceDataRequired,
SentForCancellation,
#[serde(alias = "3dsAuthenticationFailed")]
ThreeDsAuthenticationFailed,
SentForPartialRefund,
#[serde(alias = "3dsChallenged")]
ThreeDsChallenged,
#[serde(alias = "3dsUnavailable")]
ThreeDsUnavailable,
}
impl std::fmt::Display for PaymentOutcome {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Authorized => write!(f, "authorized"),
Self::Refused => write!(f, "refused"),
Self::SentForSettlement => write!(f, "sentForSettlement"),
Self::SentForRefund => write!(f, "sentForRefund"),
Self::FraudHighRisk => write!(f, "fraudHighRisk"),
Self::ThreeDsDeviceDataRequired => write!(f, "3dsDeviceDataRequired"),
Self::SentForCancellation => write!(f, "sentForCancellation"),
Self::ThreeDsAuthenticationFailed => write!(f, "3dsAuthenticationFailed"),
Self::SentForPartialRefund => write!(f, "sentForPartialRefund"),
Self::ThreeDsChallenged => write!(f, "3dsChallenged"),
Self::ThreeDsUnavailable => write!(f, "3dsUnavailable"),
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SelfLink {
#[serde(rename = "self")]
pub self_link: SelfLinkInner,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SelfLinkInner {
pub href: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ActionLinks {
supply_3ds_device_data: Option<ActionLink>,
settle_payment: Option<ActionLink>,
partially_settle_payment: Option<ActionLink>,
refund_payment: Option<ActionLink>,
partially_refund_payment: Option<ActionLink>,
cancel_payment: Option<ActionLink>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ActionLink {
pub href: String,
pub method: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Fraud {
pub outcome: FraudOutcome,
pub score: f32,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum FraudOutcome {
LowRisk,
HighRisk,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct WorldpayEventResponse {
pub last_event: EventType,
#[serde(rename = "_links", skip_serializing_if = "Option::is_none")]
pub links: Option<EventLinks>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum EventType {
SentForAuthorization,
#[serde(alias = "Authorized")]
Authorized,
#[serde(alias = "Sent for Settlement")]
SentForSettlement,
Settled,
SettlementFailed,
Cancelled,
Error,
Expired,
Refused,
#[serde(alias = "Sent for Refund")]
SentForRefund,
Refunded,
RefundFailed,
#[serde(other)]
Unknown,
}
#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)]
pub struct EventLinks {
#[serde(rename = "payments:events", skip_serializing_if = "Option::is_none")]
pub events: Option<String>,
}
pub fn get_resource_id<T, F>(
response: WorldpayPaymentsResponse,
connector_transaction_id: Option<String>,
transform_fn: F,
) -> Result<T, error_stack::Report<errors::ConnectorError>>
where
F: Fn(String) -> T,
{
let optional_reference_id = response
.other_fields
.as_ref()
.and_then(|other_fields| match other_fields {
WorldpayPaymentResponseFields::AuthorizedResponse(res) => res
.links
.as_ref()
.and_then(|link| link.self_link.href.rsplit_once('/').map(|(_, h)| h)),
WorldpayPaymentResponseFields::DDCResponse(res) => {
res.actions.supply_ddc_data.href.split('/').nth_back(1)
}
WorldpayPaymentResponseFields::ThreeDsChallenged(res) => res
.actions
.complete_three_ds_challenge
.href
.split('/')
.nth_back(1),
WorldpayPaymentResponseFields::FraudHighRisk(_)
| WorldpayPaymentResponseFields::RefusedResponse(_) => None,
})
.map(|href| {
urlencoding::decode(href)
.map(|s| transform_fn(s.into_owned()))
.change_context(errors::ConnectorError::ResponseHandlingFailed)
})
.transpose()?;
optional_reference_id
.or_else(|| connector_transaction_id.map(transform_fn))
.ok_or_else(|| {
errors::ConnectorError::MissingRequiredField {
field_name: "_links.self.href",
}
.into()
})
}
pub struct ResponseIdStr {
pub id: String,
}
#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Issuer {
pub authorization_code: Secret<String>,
}
impl Issuer {
pub fn new(code: String) -> Self {
Self {
authorization_code: Secret::new(code),
}
}
}
#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentsResPaymentInstrument {
#[serde(rename = "type")]
pub payment_instrument_type: String,
pub card_bin: Option<String>,
pub last_four: Option<String>,
pub expiry_date: Option<ExpiryDate>,
pub card_brand: Option<String>,
pub funding_type: Option<String>,
pub category: Option<String>,
pub issuer_name: Option<String>,
pub payment_account_reference: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RiskFactorsInner {
#[serde(rename = "type")]
pub risk_type: RiskType,
#[serde(skip_serializing_if = "Option::is_none")]
pub detail: Option<Detail>,
pub risk: Risk,
}
impl RiskFactorsInner {
pub fn new(risk_type: RiskType, risk: Risk) -> Self {
Self {
risk_type,
detail: None,
risk,
}
}
}
#[derive(
Clone, Copy, Default, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize,
)]
#[serde(rename_all = "camelCase")]
pub enum RiskType {
#[default]
Avs,
Cvc,
RiskProfile,
}
#[derive(
Clone, Copy, Default, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize,
)]
#[serde(rename_all = "lowercase")]
pub enum Detail {
#[default]
Address,
Postcode,
}
#[derive(
Clone, Copy, Default, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize,
)]
#[serde(rename_all = "camelCase")]
pub enum Risk {
#[default]
NotChecked,
NotMatched,
NotSupplied,
VerificationFailed,
}
#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)]
pub struct PaymentsResponseScheme {
pub reference: String,
}
impl PaymentsResponseScheme {
pub fn new(reference: String) -> Self {
Self { reference }
}
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct WorldpayErrorResponse {
pub error_name: String,
pub message: String,
pub validation_errors: Option<serde_json::Value>,
}
impl WorldpayErrorResponse {
pub fn default(status_code: u16) -> Self {
match status_code {
code @ 404 => Self {
error_name: format!("{code} Not found"),
message: "Resource not found".to_string(),
validation_errors: None,
},
code => Self {
error_name: code.to_string(),
message: "Unknown error".to_string(),
validation_errors: None,
},
}
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct WorldpayWebhookTransactionId {
pub event_details: EventDetails,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EventDetails {
#[serde(rename = "type")]
pub event_type: EventType,
pub transaction_reference: String,
/// Mandate's token
pub token: Option<MandateToken>,
/// Network transaction ID
pub scheme_reference: Option<Secret<String>>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct WorldpayWebhookEventType {
pub event_id: String,
pub event_timestamp: String,
pub event_details: EventDetails,
}
/// Worldpay's unique reference ID for a request
pub(super) const WP_CORRELATION_ID: &str = "WP-CorrelationId";
| 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/worldpay/payout_transformers.rs | crates/hyperswitch_connectors/src/connectors/worldpay/payout_transformers.rs | use base64::Engine;
use common_enums::enums;
use common_utils::{consts::BASE64_ENGINE, pii, types::MinorUnit};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
router_data::ConnectorAuthType, router_flow_types::payouts::PoFulfill,
router_response_types::PayoutsResponseData, types,
};
use hyperswitch_interfaces::{api, errors};
use masking::{PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use super::{payout_requests::*, payout_response::*};
use crate::{
types::PayoutsResponseRouterData,
utils::{self, CardData, RouterData as RouterDataTrait},
};
#[derive(Debug, Serialize)]
pub struct WorldpayPayoutRouterData<T> {
amount: i64,
router_data: T,
}
impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, MinorUnit, T)>
for WorldpayPayoutRouterData<T>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(_currency_unit, _currency, minor_amount, item): (
&api::CurrencyUnit,
enums::Currency,
MinorUnit,
T,
),
) -> Result<Self, Self::Error> {
Ok(Self {
amount: minor_amount.get_amount_as_i64(),
router_data: item,
})
}
}
pub struct WorldpayPayoutAuthType {
pub(super) api_key: Secret<String>,
pub(super) entity_id: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for WorldpayPayoutAuthType {
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,
} => {
let auth_key = format!("{}:{}", key1.peek(), api_key.peek());
let auth_header = format!("Basic {}", BASE64_ENGINE.encode(auth_key));
Ok(Self {
api_key: Secret::new(auth_header),
entity_id: api_secret.clone(),
})
}
_ => Err(errors::ConnectorError::FailedToObtainAuthType)?,
}
}
}
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct WorldpayPayoutConnectorMetadataObject {
pub merchant_name: Option<Secret<String>>,
}
impl TryFrom<Option<&pii::SecretSerdeValue>> for WorldpayPayoutConnectorMetadataObject {
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.cloned())
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "metadata",
})?;
Ok(metadata)
}
}
impl<F>
TryFrom<(
&WorldpayPayoutRouterData<&types::PayoutsRouterData<F>>,
&Secret<String>,
)> for WorldpayPayoutRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
req: (
&WorldpayPayoutRouterData<&types::PayoutsRouterData<F>>,
&Secret<String>,
),
) -> Result<Self, Self::Error> {
let (item, entity_id) = req;
let worldpay_connector_metadata_object: WorldpayPayoutConnectorMetadataObject =
WorldpayPayoutConnectorMetadataObject::try_from(
item.router_data.connector_meta_data.as_ref(),
)?;
let merchant_name = worldpay_connector_metadata_object.merchant_name.ok_or(
errors::ConnectorError::InvalidConnectorConfig {
config: "metadata.merchant_name",
},
)?;
Ok(Self {
transaction_reference: item.router_data.connector_request_reference_id.clone(),
merchant: Merchant {
entity: entity_id.clone(),
},
instruction: PayoutInstruction {
value: PayoutValue {
amount: item.amount,
currency: item.router_data.request.destination_currency,
},
narrative: InstructionNarrative {
line1: merchant_name,
},
payout_instrument: PayoutInstrument::try_from(
item.router_data.get_payout_method_data()?,
)?,
},
})
}
}
impl TryFrom<api_models::payouts::PayoutMethodData> for PayoutInstrument {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
payout_method_data: api_models::payouts::PayoutMethodData,
) -> Result<Self, Self::Error> {
match payout_method_data {
api_models::payouts::PayoutMethodData::Wallet(
api_models::payouts::Wallet::ApplePayDecrypt(apple_pay_decrypted_data),
) => Ok(Self::ApplePayDecrypt(ApplePayDecrypt {
payout_type: PayoutType::ApplePayDecrypt,
dpan: apple_pay_decrypted_data.dpan.clone(),
card_holder_name: apple_pay_decrypted_data.card_holder_name.clone(),
card_expiry_date: PayoutExpiryDate {
month: apple_pay_decrypted_data.get_expiry_month_as_i8()?,
year: apple_pay_decrypted_data.get_expiry_year_as_4_digit_i32()?,
},
})),
api_models::payouts::PayoutMethodData::Card(_)
| api_models::payouts::PayoutMethodData::Bank(_)
| api_models::payouts::PayoutMethodData::Wallet(_)
| api_models::payouts::PayoutMethodData::BankRedirect(_)
| api_models::payouts::PayoutMethodData::Passthrough(_) => {
Err(errors::ConnectorError::NotImplemented(
"Selected Payout Method is not implemented for Worldpay".to_string(),
)
.into())
}
}
}
}
impl From<PayoutOutcome> for enums::PayoutStatus {
fn from(item: PayoutOutcome) -> Self {
match item {
PayoutOutcome::RequestReceived => Self::Initiated,
PayoutOutcome::Error | PayoutOutcome::Refused => Self::Failed,
PayoutOutcome::QueryRequired => Self::Pending,
}
}
}
impl TryFrom<PayoutsResponseRouterData<PoFulfill, WorldpayPayoutResponse>>
for types::PayoutsRouterData<PoFulfill>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PayoutsResponseRouterData<PoFulfill, WorldpayPayoutResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(PayoutsResponseData {
status: Some(enums::PayoutStatus::from(item.response.outcome.clone())),
connector_payout_id: None,
payout_eligible: None,
should_add_next_step_to_process_tracker: false,
error_code: None,
error_message: None,
payout_connector_metadata: None,
}),
..item.data
})
}
}
| 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/worldpay/transformers.rs | crates/hyperswitch_connectors/src/connectors/worldpay/transformers.rs | use std::collections::HashMap;
use api_models::payments::{MandateIds, MandateReferenceId};
use base64::Engine;
use common_enums::enums;
use common_utils::{
consts::BASE64_ENGINE, errors::CustomResult, ext_traits::OptionExt, pii, types::MinorUnit,
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
address,
payment_method_data::{PaymentMethodData, WalletData},
router_data::{ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{Authorize, SetupMandate},
router_request_types::{
BrowserInformation, PaymentsAuthorizeData, ResponseId, SetupMandateRequestData,
},
router_response_types::{MandateReference, PaymentsResponseData, RedirectForm},
types,
};
use hyperswitch_interfaces::{api, errors};
use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use super::{requests::*, response::*};
use crate::{
types::ResponseRouterData,
utils::{
self, AddressData, ApplePay, CardData, ForeignTryFrom, PaymentsAuthorizeRequestData,
PaymentsSetupMandateRequestData, RouterData as RouterDataTrait,
},
};
#[derive(Debug, Serialize)]
pub struct WorldpayRouterData<T> {
amount: i64,
router_data: T,
}
impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, MinorUnit, T)> for WorldpayRouterData<T> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(_currency_unit, _currency, minor_amount, item): (
&api::CurrencyUnit,
enums::Currency,
MinorUnit,
T,
),
) -> Result<Self, Self::Error> {
Ok(Self {
amount: minor_amount.get_amount_as_i64(),
router_data: item,
})
}
}
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct WorldpayConnectorMetadataObject {
pub merchant_name: Option<Secret<String>>,
}
impl TryFrom<Option<&pii::SecretSerdeValue>> for WorldpayConnectorMetadataObject {
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.cloned())
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "metadata",
})?;
Ok(metadata)
}
}
fn fetch_payment_instrument(
payment_method: PaymentMethodData,
billing_address: Option<&address::Address>,
mandate_ids: Option<MandateIds>,
) -> CustomResult<PaymentInstrument, errors::ConnectorError> {
match payment_method {
PaymentMethodData::Card(card) => Ok(PaymentInstrument::Card(CardPayment {
raw_card_details: RawCardDetails {
payment_type: PaymentType::Plain,
expiry_date: ExpiryDate {
month: card.get_expiry_month_as_i8()?,
year: card.get_expiry_year_as_4_digit_i32()?,
},
card_number: card.card_number,
},
cvc: card.card_cvc,
card_holder_name: billing_address.and_then(|address| address.get_optional_full_name()),
billing_address: billing_address
.and_then(|addr| addr.address.clone())
.and_then(|address| {
match (address.line1, address.city, address.zip, address.country) {
(Some(address1), Some(city), Some(postal_code), Some(country_code)) => {
Some(BillingAddress {
address1,
address2: address.line2,
address3: address.line3,
city,
state: address.state,
postal_code,
country_code,
})
}
_ => None,
}
}),
})),
PaymentMethodData::CardDetailsForNetworkTransactionId(raw_card_details) => {
Ok(PaymentInstrument::RawCardForNTI(RawCardDetails {
payment_type: PaymentType::Plain,
expiry_date: ExpiryDate {
month: raw_card_details.get_expiry_month_as_i8()?,
year: raw_card_details.get_expiry_year_as_4_digit_i32()?,
},
card_number: raw_card_details.card_number,
}))
}
PaymentMethodData::MandatePayment => mandate_ids
.and_then(|mandate_ids| {
mandate_ids
.mandate_reference_id
.and_then(|mandate_id| match mandate_id {
MandateReferenceId::ConnectorMandateId(connector_mandate_id) => {
connector_mandate_id.get_connector_mandate_id().map(|href| {
PaymentInstrument::CardToken(CardToken {
payment_type: PaymentType::Token,
href,
cvc: None,
})
})
}
_ => None,
})
})
.ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "connector_mandate_id",
}
.into(),
),
PaymentMethodData::Wallet(wallet) => match wallet {
WalletData::GooglePay(data) => Ok(PaymentInstrument::Googlepay(WalletPayment {
payment_type: PaymentType::Encrypted,
wallet_token: Secret::new(
data.tokenization_data
.get_encrypted_google_pay_token()
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "gpay wallet_token",
})?,
),
..WalletPayment::default()
})),
WalletData::ApplePay(data) => Ok(PaymentInstrument::Applepay(WalletPayment {
payment_type: PaymentType::Encrypted,
wallet_token: data.get_applepay_decoded_payment_data()?,
..WalletPayment::default()
})),
WalletData::AliPayQr(_)
| WalletData::AliPayRedirect(_)
| WalletData::AliPayHkRedirect(_)
| WalletData::AmazonPay(_)
| WalletData::AmazonPayRedirect(_)
| WalletData::Paysera(_)
| WalletData::Skrill(_)
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
| WalletData::BluecodeRedirect {}
| WalletData::GcashRedirect(_)
| WalletData::ApplePayRedirect(_)
| WalletData::ApplePayThirdPartySdk(_)
| WalletData::DanaRedirect {}
| WalletData::GooglePayRedirect(_)
| WalletData::GooglePayThirdPartySdk(_)
| WalletData::MbWayRedirect(_)
| WalletData::MobilePayRedirect(_)
| WalletData::PaypalRedirect(_)
| WalletData::PaypalSdk(_)
| WalletData::Paze(_)
| WalletData::SamsungPay(_)
| WalletData::TwintRedirect {}
| WalletData::VippsRedirect {}
| WalletData::TouchNGoRedirect(_)
| WalletData::WeChatPayRedirect(_)
| WalletData::CashappQr(_)
| WalletData::SwishQr(_)
| WalletData::WeChatPayQr(_)
| WalletData::Mifinity(_)
| WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("worldpay"),
)
.into()),
},
PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("worldpay"),
)
.into())
}
}
}
impl TryFrom<(enums::PaymentMethod, Option<enums::PaymentMethodType>)> for PaymentMethod {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
src: (enums::PaymentMethod, Option<enums::PaymentMethodType>),
) -> Result<Self, Self::Error> {
match (src.0, src.1) {
(enums::PaymentMethod::Card, _) => Ok(Self::Card),
(enums::PaymentMethod::Wallet, pmt) => {
let pm = pmt.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "payment_method_type",
})?;
match pm {
enums::PaymentMethodType::ApplePay => Ok(Self::ApplePay),
enums::PaymentMethodType::GooglePay => Ok(Self::GooglePay),
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("worldpay"),
)
.into()),
}
}
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("worldpay"),
)
.into()),
}
}
}
// Trait to abstract common functionality between Authorize and SetupMandate
trait WorldpayPaymentsRequestData {
fn get_return_url(&self) -> Result<String, error_stack::Report<errors::ConnectorError>>;
fn get_auth_type(&self) -> &enums::AuthenticationType;
fn get_browser_info(&self) -> Option<&BrowserInformation>;
fn get_payment_method_data(&self) -> &PaymentMethodData;
fn get_setup_future_usage(&self) -> Option<enums::FutureUsage>;
fn get_off_session(&self) -> Option<bool>;
fn get_mandate_id(&self) -> Option<MandateIds>;
fn get_currency(&self) -> enums::Currency;
fn get_optional_billing_address(&self) -> Option<&address::Address>;
fn get_connector_meta_data(&self) -> Option<&pii::SecretSerdeValue>;
fn get_payment_method(&self) -> enums::PaymentMethod;
fn get_payment_method_type(&self) -> Option<enums::PaymentMethodType>;
fn get_connector_request_reference_id(&self) -> String;
fn get_is_mandate_payment(&self) -> bool;
fn get_settlement_info(&self, _amount: i64) -> Option<AutoSettlement> {
None
}
}
impl WorldpayPaymentsRequestData
for RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
{
fn get_return_url(&self) -> Result<String, error_stack::Report<errors::ConnectorError>> {
self.request.get_complete_authorize_url()
}
fn get_auth_type(&self) -> &enums::AuthenticationType {
&self.auth_type
}
fn get_browser_info(&self) -> Option<&BrowserInformation> {
self.request.browser_info.as_ref()
}
fn get_payment_method_data(&self) -> &PaymentMethodData {
&self.request.payment_method_data
}
fn get_setup_future_usage(&self) -> Option<enums::FutureUsage> {
self.request.setup_future_usage
}
fn get_off_session(&self) -> Option<bool> {
self.request.off_session
}
fn get_mandate_id(&self) -> Option<MandateIds> {
self.request.mandate_id.clone()
}
fn get_currency(&self) -> enums::Currency {
self.request.currency
}
fn get_optional_billing_address(&self) -> Option<&address::Address> {
self.get_optional_billing()
}
fn get_connector_meta_data(&self) -> Option<&pii::SecretSerdeValue> {
self.connector_meta_data.as_ref()
}
fn get_payment_method(&self) -> enums::PaymentMethod {
self.payment_method
}
fn get_payment_method_type(&self) -> Option<enums::PaymentMethodType> {
self.request.payment_method_type
}
fn get_connector_request_reference_id(&self) -> String {
self.connector_request_reference_id.clone()
}
fn get_is_mandate_payment(&self) -> bool {
true
}
}
impl WorldpayPaymentsRequestData
for RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData>
{
fn get_return_url(&self) -> Result<String, error_stack::Report<errors::ConnectorError>> {
self.request.get_complete_authorize_url()
}
fn get_auth_type(&self) -> &enums::AuthenticationType {
&self.auth_type
}
fn get_browser_info(&self) -> Option<&BrowserInformation> {
self.request.browser_info.as_ref()
}
fn get_payment_method_data(&self) -> &PaymentMethodData {
&self.request.payment_method_data
}
fn get_setup_future_usage(&self) -> Option<enums::FutureUsage> {
self.request.setup_future_usage
}
fn get_off_session(&self) -> Option<bool> {
self.request.off_session
}
fn get_mandate_id(&self) -> Option<MandateIds> {
self.request.mandate_id.clone()
}
fn get_currency(&self) -> enums::Currency {
self.request.currency
}
fn get_optional_billing_address(&self) -> Option<&address::Address> {
self.get_optional_billing()
}
fn get_connector_meta_data(&self) -> Option<&pii::SecretSerdeValue> {
self.connector_meta_data.as_ref()
}
fn get_payment_method(&self) -> enums::PaymentMethod {
self.payment_method
}
fn get_payment_method_type(&self) -> Option<enums::PaymentMethodType> {
self.request.payment_method_type
}
fn get_connector_request_reference_id(&self) -> String {
self.connector_request_reference_id.clone()
}
fn get_is_mandate_payment(&self) -> bool {
self.request.is_mandate_payment()
}
fn get_settlement_info(&self, amount: i64) -> Option<AutoSettlement> {
match (self.request.capture_method.unwrap_or_default(), amount) {
(_, 0) => None,
(enums::CaptureMethod::Automatic, _)
| (enums::CaptureMethod::SequentialAutomatic, _) => Some(AutoSettlement { auto: true }),
(enums::CaptureMethod::Manual, _) | (enums::CaptureMethod::ManualMultiple, _) => {
Some(AutoSettlement { auto: false })
}
_ => None,
}
}
}
// Dangling helper function to create ThreeDS request
fn create_three_ds_request<T: WorldpayPaymentsRequestData>(
router_data: &T,
is_mandate_payment: bool,
) -> Result<Option<ThreeDSRequest>, error_stack::Report<errors::ConnectorError>> {
match (
router_data.get_auth_type(),
router_data.get_payment_method_data(),
) {
// 3DS for NTI flow
(_, PaymentMethodData::CardDetailsForNetworkTransactionId(_)) => Ok(None),
// 3DS for regular payments
(enums::AuthenticationType::ThreeDs, _) => {
let browser_info = router_data.get_browser_info().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "browser_info",
},
)?;
let accept_header = browser_info
.accept_header
.clone()
.get_required_value("accept_header")
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "accept_header",
})?;
let user_agent_header = browser_info
.user_agent
.clone()
.get_required_value("user_agent")
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "user_agent",
})?;
Ok(Some(ThreeDSRequest {
three_ds_type: THREE_DS_TYPE.to_string(),
mode: THREE_DS_MODE.to_string(),
device_data: ThreeDSRequestDeviceData {
accept_header,
user_agent_header,
browser_language: browser_info.language.clone(),
browser_screen_width: browser_info.screen_width,
browser_screen_height: browser_info.screen_height,
browser_color_depth: browser_info.color_depth.map(|depth| depth.to_string()),
time_zone: browser_info.time_zone.map(|tz| tz.to_string()),
browser_java_enabled: browser_info.java_enabled,
browser_javascript_enabled: browser_info.java_script_enabled,
channel: Some(ThreeDSRequestChannel::Browser),
},
challenge: ThreeDSRequestChallenge {
return_url: router_data.get_return_url()?,
preference: if is_mandate_payment {
Some(ThreeDsPreference::ChallengeMandated)
} else {
None
},
},
}))
}
// Non 3DS
_ => Ok(None),
}
}
// Dangling helper function to determine token and agreement settings
fn get_token_and_agreement(
payment_method_data: &PaymentMethodData,
setup_future_usage: Option<enums::FutureUsage>,
off_session: Option<bool>,
mandate_ids: Option<MandateIds>,
) -> (Option<TokenCreation>, Option<CustomerAgreement>) {
match (payment_method_data, setup_future_usage, off_session) {
// CIT
(PaymentMethodData::Card(_), Some(enums::FutureUsage::OffSession), _) => (
Some(TokenCreation {
token_type: TokenCreationType::Worldpay,
}),
Some(CustomerAgreement {
agreement_type: CustomerAgreementType::Subscription,
stored_card_usage: Some(StoredCardUsageType::First),
scheme_reference: None,
}),
),
// MIT
(PaymentMethodData::Card(_), _, Some(true)) => (
None,
Some(CustomerAgreement {
agreement_type: CustomerAgreementType::Subscription,
stored_card_usage: Some(StoredCardUsageType::Subsequent),
scheme_reference: None,
}),
),
// NTI with raw card data
(PaymentMethodData::CardDetailsForNetworkTransactionId(_), _, _) => (
None,
mandate_ids.and_then(|mandate_ids| {
mandate_ids
.mandate_reference_id
.and_then(|mandate_id| match mandate_id {
MandateReferenceId::NetworkMandateId(network_transaction_id) => {
Some(CustomerAgreement {
agreement_type: CustomerAgreementType::Unscheduled,
scheme_reference: Some(network_transaction_id.into()),
stored_card_usage: None,
})
}
_ => None,
})
}),
),
_ => (None, None),
}
}
// Implementation for WorldpayPaymentsRequest using abstracted request
impl<T: WorldpayPaymentsRequestData> TryFrom<(&WorldpayRouterData<&T>, &Secret<String>)>
for WorldpayPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(req: (&WorldpayRouterData<&T>, &Secret<String>)) -> Result<Self, Self::Error> {
let (item, entity_id) = req;
let worldpay_connector_metadata_object: WorldpayConnectorMetadataObject =
WorldpayConnectorMetadataObject::try_from(item.router_data.get_connector_meta_data())?;
let merchant_name = worldpay_connector_metadata_object.merchant_name.ok_or(
errors::ConnectorError::InvalidConnectorConfig {
config: "metadata.merchant_name",
},
)?;
let is_mandate_payment = item.router_data.get_is_mandate_payment();
let three_ds = create_three_ds_request(item.router_data, is_mandate_payment)?;
let (token_creation, customer_agreement) = get_token_and_agreement(
item.router_data.get_payment_method_data(),
item.router_data.get_setup_future_usage(),
item.router_data.get_off_session(),
item.router_data.get_mandate_id(),
);
Ok(Self {
instruction: Instruction {
settlement: item.router_data.get_settlement_info(item.amount),
method: PaymentMethod::try_from((
item.router_data.get_payment_method(),
item.router_data.get_payment_method_type(),
))?,
payment_instrument: fetch_payment_instrument(
item.router_data.get_payment_method_data().clone(),
item.router_data.get_optional_billing_address(),
item.router_data.get_mandate_id(),
)?,
narrative: InstructionNarrative {
line1: merchant_name.expose(),
},
value: PaymentValue {
amount: item.amount,
currency: item.router_data.get_currency(),
},
debt_repayment: None,
three_ds,
token_creation,
customer_agreement,
},
merchant: Merchant {
entity: entity_id.clone(),
..Default::default()
},
transaction_reference: item.router_data.get_connector_request_reference_id(),
customer: None,
})
}
}
pub struct WorldpayAuthType {
pub(super) api_key: Secret<String>,
pub(super) entity_id: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for WorldpayAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
// TODO: Remove this later, kept purely for backwards compatibility
ConnectorAuthType::BodyKey { api_key, key1 } => {
let auth_key = format!("{}:{}", key1.peek(), api_key.peek());
let auth_header = format!("Basic {}", BASE64_ENGINE.encode(auth_key));
Ok(Self {
api_key: Secret::new(auth_header),
entity_id: Secret::new("default".to_string()),
})
}
ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} => {
let auth_key = format!("{}:{}", key1.peek(), api_key.peek());
let auth_header = format!("Basic {}", BASE64_ENGINE.encode(auth_key));
Ok(Self {
api_key: Secret::new(auth_header),
entity_id: api_secret.clone(),
})
}
_ => Err(errors::ConnectorError::FailedToObtainAuthType)?,
}
}
}
impl From<PaymentOutcome> for enums::AttemptStatus {
fn from(item: PaymentOutcome) -> Self {
match item {
PaymentOutcome::Authorized => Self::Authorized,
PaymentOutcome::SentForSettlement => Self::Charged,
PaymentOutcome::ThreeDsDeviceDataRequired => Self::DeviceDataCollectionPending,
PaymentOutcome::ThreeDsAuthenticationFailed => Self::AuthenticationFailed,
PaymentOutcome::ThreeDsChallenged => Self::AuthenticationPending,
PaymentOutcome::SentForCancellation => Self::VoidInitiated,
PaymentOutcome::SentForPartialRefund | PaymentOutcome::SentForRefund => {
Self::AutoRefunded
}
PaymentOutcome::Refused | PaymentOutcome::FraudHighRisk => Self::Failure,
PaymentOutcome::ThreeDsUnavailable => Self::AuthenticationFailed,
}
}
}
impl From<PaymentOutcome> for enums::RefundStatus {
fn from(item: PaymentOutcome) -> Self {
match item {
PaymentOutcome::SentForPartialRefund | PaymentOutcome::SentForRefund => Self::Success,
PaymentOutcome::Refused
| PaymentOutcome::FraudHighRisk
| PaymentOutcome::Authorized
| PaymentOutcome::SentForSettlement
| PaymentOutcome::ThreeDsDeviceDataRequired
| PaymentOutcome::ThreeDsAuthenticationFailed
| PaymentOutcome::ThreeDsChallenged
| PaymentOutcome::SentForCancellation
| PaymentOutcome::ThreeDsUnavailable => Self::Failure,
}
}
}
impl From<&EventType> for enums::AttemptStatus {
fn from(value: &EventType) -> Self {
match value {
EventType::SentForAuthorization => Self::Authorizing,
EventType::SentForSettlement => Self::Charged,
EventType::Settled => Self::Charged,
EventType::Authorized => Self::Authorized,
EventType::Refused
| EventType::SettlementFailed
| EventType::Expired
| EventType::Cancelled
| EventType::Error => Self::Failure,
EventType::SentForRefund
| EventType::RefundFailed
| EventType::Refunded
| EventType::Unknown => Self::Pending,
}
}
}
impl From<EventType> for enums::RefundStatus {
fn from(value: EventType) -> Self {
match value {
EventType::Refunded | EventType::SentForRefund => Self::Success,
EventType::RefundFailed => Self::Failure,
EventType::Authorized
| EventType::Cancelled
| EventType::Settled
| EventType::Refused
| EventType::Error
| EventType::SentForSettlement
| EventType::SentForAuthorization
| EventType::SettlementFailed
| EventType::Expired
| EventType::Unknown => Self::Pending,
}
}
}
impl<F, T>
ForeignTryFrom<(
ResponseRouterData<F, WorldpayPaymentsResponse, T, PaymentsResponseData>,
Option<String>,
i64,
)> for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(
item: (
ResponseRouterData<F, WorldpayPaymentsResponse, T, PaymentsResponseData>,
Option<String>,
i64,
),
) -> Result<Self, Self::Error> {
let (router_data, optional_correlation_id, amount) = item;
let (description, redirection_data, mandate_reference, network_txn_id, error) = router_data
.response
.other_fields
.as_ref()
.map(|other_fields| match other_fields {
WorldpayPaymentResponseFields::AuthorizedResponse(res) => (
res.description.clone(),
None,
res.token.as_ref().map(|mandate_token| MandateReference {
connector_mandate_id: Some(mandate_token.href.clone().expose()),
payment_method_id: Some(mandate_token.token_id.clone()),
mandate_metadata: None,
connector_mandate_request_reference_id: None,
}),
res.scheme_reference.clone(),
None,
),
WorldpayPaymentResponseFields::DDCResponse(res) => (
None,
Some(RedirectForm::WorldpayDDCForm {
endpoint: res.device_data_collection.url.clone(),
method: common_utils::request::Method::Post,
collection_id: Some("SessionId".to_string()),
form_fields: HashMap::from([
(
"Bin".to_string(),
res.device_data_collection.bin.clone().expose(),
),
(
"JWT".to_string(),
res.device_data_collection.jwt.clone().expose(),
),
]),
}),
None,
None,
None,
),
WorldpayPaymentResponseFields::ThreeDsChallenged(res) => (
None,
Some(RedirectForm::Form {
endpoint: res.challenge.url.to_string(),
method: common_utils::request::Method::Post,
form_fields: HashMap::from([(
"JWT".to_string(),
res.challenge.jwt.clone().expose(),
)]),
}),
None,
None,
None,
),
WorldpayPaymentResponseFields::RefusedResponse(res) => (
None,
None,
None,
None,
Some((
res.refusal_code.clone(),
res.refusal_description.clone(),
res.advice
.as_ref()
.and_then(|advice_code| advice_code.code.clone()),
)),
),
WorldpayPaymentResponseFields::FraudHighRisk(_) => (None, None, None, None, None),
})
.unwrap_or((None, None, None, None, None));
let worldpay_status = router_data.response.outcome.clone();
let optional_error_message = match worldpay_status {
PaymentOutcome::ThreeDsAuthenticationFailed => {
Some("3DS authentication failed from issuer".to_string())
}
PaymentOutcome::ThreeDsUnavailable => {
Some("3DS authentication unavailable from issuer".to_string())
}
PaymentOutcome::FraudHighRisk => Some("Transaction marked as high risk".to_string()),
_ => None,
};
let status = if amount == 0 && worldpay_status == PaymentOutcome::Authorized {
enums::AttemptStatus::Charged
} else {
enums::AttemptStatus::from(worldpay_status.clone())
};
let response = match (optional_error_message, error) {
(None, None) => Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::foreign_try_from((
router_data.response,
optional_correlation_id.clone(),
))?,
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(mandate_reference),
connector_metadata: None,
network_txn_id: network_txn_id.map(|id| id.expose()),
connector_response_reference_id: optional_correlation_id.clone(),
incremental_authorization_allowed: None,
charges: None,
}),
(Some(reason), _) => Err(ErrorResponse {
code: worldpay_status.to_string(),
message: reason.clone(),
reason: Some(reason),
status_code: router_data.http_code,
attempt_status: Some(status),
connector_transaction_id: optional_correlation_id,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
(_, Some((code, message, advice_code))) => Err(ErrorResponse {
code: code.clone(),
message: message.clone(),
reason: Some(message.clone()),
status_code: router_data.http_code,
attempt_status: Some(status),
connector_transaction_id: optional_correlation_id,
network_advice_code: advice_code,
| 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/worldpay/payout_response.rs | crates/hyperswitch_connectors/src/connectors/worldpay/payout_response.rs | use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct WorldpayPayoutResponse {
pub outcome: PayoutOutcome,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum PayoutOutcome {
RequestReceived,
Refused,
Error,
QueryRequired,
}
| 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/worldpay/requests.rs | crates/hyperswitch_connectors/src/connectors/worldpay/requests.rs | use masking::Secret;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct WorldpayPaymentsRequest {
pub transaction_reference: String,
pub merchant: Merchant,
pub instruction: Instruction,
#[serde(skip_serializing_if = "Option::is_none")]
pub customer: Option<Customer>,
}
#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Merchant {
pub entity: Secret<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub mcc: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub payment_facilitator: Option<PaymentFacilitator>,
}
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Instruction {
#[serde(skip_serializing_if = "Option::is_none")]
pub settlement: Option<AutoSettlement>,
pub method: PaymentMethod,
pub payment_instrument: PaymentInstrument,
pub narrative: InstructionNarrative,
pub value: PaymentValue,
#[serde(skip_serializing_if = "Option::is_none")]
pub debt_repayment: Option<bool>,
#[serde(rename = "threeDS", skip_serializing_if = "Option::is_none")]
pub three_ds: Option<ThreeDSRequest>,
/// For setting up mandates
pub token_creation: Option<TokenCreation>,
/// For specifying CIT vs MIT
pub customer_agreement: Option<CustomerAgreement>,
}
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct TokenCreation {
#[serde(rename = "type")]
pub token_type: TokenCreationType,
}
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum TokenCreationType {
Worldpay,
}
#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CustomerAgreement {
#[serde(rename = "type")]
pub agreement_type: CustomerAgreementType,
pub stored_card_usage: Option<StoredCardUsageType>,
#[serde(skip_serializing_if = "Option::is_none")]
pub scheme_reference: Option<Secret<String>>,
}
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum CustomerAgreementType {
Subscription,
Unscheduled,
}
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum StoredCardUsageType {
First,
Subsequent,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum PaymentInstrument {
Card(CardPayment),
CardToken(CardToken),
RawCardForNTI(RawCardDetails),
Googlepay(WalletPayment),
Applepay(WalletPayment),
}
#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CardPayment {
#[serde(flatten)]
pub raw_card_details: RawCardDetails,
pub cvc: Secret<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub card_holder_name: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub billing_address: Option<BillingAddress>,
}
#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RawCardDetails {
#[serde(rename = "type")]
pub payment_type: PaymentType,
pub card_number: cards::CardNumber,
pub expiry_date: ExpiryDate,
}
#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CardToken {
#[serde(rename = "type")]
pub payment_type: PaymentType,
pub href: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub cvc: Option<Secret<String>>,
}
#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct WalletPayment {
#[serde(rename = "type")]
pub payment_type: PaymentType,
pub wallet_token: Secret<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub billing_address: Option<BillingAddress>,
}
#[derive(
Clone, Copy, Debug, Eq, Default, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize,
)]
#[serde(rename_all = "lowercase")]
pub enum PaymentType {
#[default]
Plain,
Token,
Encrypted,
Checkout,
}
#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)]
pub struct ExpiryDate {
pub month: Secret<i8>,
pub year: Secret<i32>,
}
#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BillingAddress {
pub address1: Secret<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub address2: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub address3: Option<Secret<String>>,
pub city: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub state: Option<Secret<String>>,
pub postal_code: Secret<String>,
pub country_code: common_enums::CountryAlpha2,
}
#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Customer {
#[serde(skip_serializing_if = "Option::is_none")]
pub risk_profile: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub authentication: Option<CustomerAuthentication>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum CustomerAuthentication {
ThreeDS(ThreeDS),
Token(NetworkToken),
}
#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ThreeDS {
#[serde(skip_serializing_if = "Option::is_none")]
pub authentication_value: Option<Secret<String>>,
pub version: ThreeDSVersion,
#[serde(skip_serializing_if = "Option::is_none")]
pub transaction_id: Option<String>,
pub eci: String,
#[serde(rename = "type")]
pub auth_type: CustomerAuthType,
}
#[derive(
Clone, Copy, Default, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize,
)]
pub enum ThreeDSVersion {
#[default]
#[serde(rename = "1")]
One,
#[serde(rename = "2")]
Two,
}
#[derive(
Clone, Copy, Default, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize,
)]
pub enum CustomerAuthType {
#[serde(rename = "3DS")]
#[default]
Variant3Ds,
#[serde(rename = "card/networkToken")]
NetworkToken,
}
#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NetworkToken {
#[serde(rename = "type")]
pub auth_type: CustomerAuthType,
pub authentication_value: Secret<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub eci: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AutoSettlement {
pub auto: bool,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ThreeDSRequest {
#[serde(rename = "type")]
pub three_ds_type: String,
pub mode: String,
pub device_data: ThreeDSRequestDeviceData,
pub challenge: ThreeDSRequestChallenge,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ThreeDSRequestDeviceData {
pub accept_header: String,
pub user_agent_header: String,
pub browser_language: Option<String>,
pub browser_screen_width: Option<u32>,
pub browser_screen_height: Option<u32>,
pub browser_color_depth: Option<String>,
pub time_zone: Option<String>,
pub browser_java_enabled: Option<bool>,
pub browser_javascript_enabled: Option<bool>,
pub channel: Option<ThreeDSRequestChannel>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ThreeDSRequestChannel {
Browser,
Native,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ThreeDSRequestChallenge {
pub return_url: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub preference: Option<ThreeDsPreference>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum ThreeDsPreference {
ChallengeMandated,
}
#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum PaymentMethod {
#[default]
Card,
ApplePay,
GooglePay,
}
#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct InstructionNarrative {
pub line1: String,
}
#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)]
pub struct PaymentValue {
pub amount: i64,
pub currency: api_models::enums::Currency,
}
#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentFacilitator {
pub pf_id: Secret<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub iso_id: Option<Secret<String>>,
pub sub_merchant: SubMerchant,
}
#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SubMerchant {
pub city: String,
pub name: Secret<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub state: Option<String>,
pub postal_code: Secret<String>,
pub merchant_id: Secret<String>,
pub country_code: String,
pub street: Secret<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub tax_id: Option<String>,
}
#[derive(Default, Debug, Serialize)]
pub struct WorldpayPartialRequest {
pub value: PaymentValue,
pub reference: String,
}
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct WorldpayCompleteAuthorizationRequest {
#[serde(skip_serializing_if = "Option::is_none")]
pub collection_reference: Option<String>,
}
pub(super) const THREE_DS_MODE: &str = "always";
pub(super) const THREE_DS_TYPE: &str = "integrated";
| 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/nordea/responses.rs | crates/hyperswitch_connectors/src/connectors/nordea/responses.rs | use common_enums::CountryAlpha2;
use common_utils::types::StringMajorUnit;
use masking::Secret;
use serde::{Deserialize, Serialize};
use super::requests::{
CreditorAccount, DebitorAccount, InstructedAmount, PaymentsUrgency, RecurringInformation,
ThirdPartyMessages,
};
// OAuth token response structure
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct NordeaOAuthExchangeResponse {
pub access_token: Option<Secret<String>>,
pub expires_in: Option<i64>,
pub refresh_token: Option<Secret<String>>,
pub token_type: Option<String>,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "PascalCase")]
pub enum NordeaPaymentStatus {
#[default]
PendingConfirmation,
PendingSecondConfirmation,
PendingUserApproval,
OnHold,
Confirmed,
Rejected,
Paid,
InsufficientFunds,
LimitExceeded,
UserApprovalFailed,
UserApprovalTimeout,
UserApprovalCancelled,
Unknown,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct NordeaGroupHeader {
/// Response creation time. Format: date-time.
pub creation_date_time: Option<String>,
/// HTTP code for response. Format: int32.
pub http_code: Option<i32>,
/// Original request id for correlation purposes
pub message_identification: Option<String>,
/// Details of paginated response
pub message_pagination: Option<MessagePagination>,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct NordeaResponseLinks {
/// Describes the nature of the link, e.g. 'details' for a link to the detailed information of a listed resource.
pub rel: Option<String>,
/// Relative path to the linked resource
pub href: Option<String>,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum FeesType {
Additional,
Standard,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct TransactionFee {
/// Monetary amount
pub amount: InstructedAmount,
pub description: Option<String>,
pub excluded_from_total_fee: Option<bool>,
pub percentage: Option<bool>,
#[serde(rename = "type")]
pub fees_type: Option<FeesType>,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct BankFee {
/// Example 'domestic_transaction' only for DK domestic payments
#[serde(rename = "_type")]
pub bank_fee_type: Option<String>,
/// Country code according to ISO Alpha-2
pub country_code: Option<CountryAlpha2>,
/// Currency code according to ISO 4217
pub currency_code: Option<api_models::enums::Currency>,
/// Value of the fee.
pub value: Option<StringMajorUnit>,
pub fees: Option<Vec<TransactionFee>>,
/// Monetary amount
pub total_fee_amount: InstructedAmount,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum ChargeBearer {
Shar,
Debt,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct ExchangeRate {
pub base_currency: Option<api_models::enums::Currency>,
pub exchange_currency: Option<api_models::enums::Currency>,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct MessagePagination {
/// Resource listing may return a continuationKey if there's more results available.
/// Request may be retried with the continuationKey, but otherwise same parameters, in order to get more results.
pub continuation_key: Option<String>,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct NordeaPaymentsInitiateResponseData {
/// Unique payment identifier assigned for new payment
#[serde(rename = "_id")]
pub payment_id: String,
/// HATEOAS inspired links: 'rel' and 'href'. Context specific link (only GET supported)
#[serde(rename = "_links")]
pub links: Option<Vec<NordeaResponseLinks>>,
/// Marked as required field in the docs, but connector does not send amount in payment_response.amount
pub amount: Option<StringMajorUnit>,
/// Bearer of charges. shar = The Debtor (sender of the payment) will pay all fees charged by the sending bank.
/// The Creditor (recipient of the payment) will pay all fees charged by the receiving bank.
/// debt = The Debtor (sender of the payment) will bear all of the payment transaction fees.
/// The creditor (beneficiary) will receive the full amount of the payment.
pub charge_bearer: Option<ChargeBearer>,
/// Creditor of the payment
#[serde(rename = "creditor")]
pub creditor_account: CreditorAccount,
pub currency: Option<api_models::enums::Currency>,
/// Debtor of the payment
#[serde(rename = "debtor")]
pub debitor_account: Option<DebitorAccount>,
/// Timestamp of payment creation. ISO 8601 format yyyy-mm-ddThh:mm:ss.fffZ. Format:date-time.
pub entry_date_time: Option<String>,
/// Unique identification as assigned by a partner to identify the payment.
pub external_id: Option<String>,
/// An amount the bank will charge for executing the payment
pub fee: Option<BankFee>,
pub indicative_exchange_rate: Option<ExchangeRate>,
/// It is mentioned as `number`. It can be an integer or a decimal number.
pub rate: Option<f32>,
/// Monetary amount
pub instructed_amount: Option<InstructedAmount>,
/// Indication of cross border payment to own account
pub is_own_account_transfer: Option<bool>,
/// OTP Challenge
pub otp_challenge: Option<String>,
/// Status of the payment
pub payment_status: NordeaPaymentStatus,
/// Planned execution date will indicate the day the payment will be finalized. If the payment has been pushed due to cut-off, it will be indicated in planned execution date. Format:date.
pub planned_execution_date: Option<String>,
/// Recurring information
pub recurring: Option<RecurringInformation>,
/// Choose a preferred execution date (or leave blank for today's date).
/// This should be a valid bank day, and depending on the country the date will either be pushed to the next valid bank day,
/// or return an error if a non-banking day date was supplied (all dates accepted in sandbox).
/// SEPA: max +5 years from yesterday, Domestic: max. +1 year from yesterday. NB: Not supported for Own transfer Non-Recurring Norway.
/// Format:date.
pub requested_execution_date: Option<String>,
/// Timestamp of payment creation. ISO 8601 format yyyy-mm-ddThh:mm:ss.fffZ Format:date-time.
pub timestamp: Option<String>,
/// Additional messages for third parties
pub tpp_messages: Option<Vec<ThirdPartyMessages>>,
pub transaction_fee: Option<Vec<BankFee>>,
/// Currency that the cross border payment will be transferred in.
/// This field is only supported for cross border payments for DK.
/// If this field is not supplied then the payment will use the currency specified for the currency field of instructed_amount.
pub transfer_currency: Option<api_models::enums::Currency>,
/// Urgency of the payment. NB: This field is supported for DK Domestic ('standard' and 'express') and NO Domestic bank transfer payments ('standard' and 'express').
/// Use 'express' for Straksbetaling (Instant payment).
/// All other payment types ignore this input.
/// For further details on urgencies and cut-offs, refer to the Nordea website.
/// Value 'sameday' is marked as deprecated and will be removed in the future.
pub urgency: Option<PaymentsUrgency>,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct NordeaPaymentsInitiateResponse {
/// Payment information
#[serde(rename = "response")]
pub payments_response: Option<NordeaPaymentsInitiateResponseData>,
/// External response header
pub group_header: Option<NordeaGroupHeader>,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct NordeaPaymentsConfirmErrorObject {
/// Error message
pub error: Option<String>,
/// Description of the error
pub error_description: Option<String>,
/// Payment id of the payment, the error is associated with
pub payment_id: Option<String>,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct NordeaPaymentsResponseWrapper {
pub payments: Vec<NordeaPaymentsInitiateResponseData>,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct NordeaPaymentsConfirmResponse {
/// HATEOAS inspired links: 'rel' and 'href'
#[serde(rename = "_links")]
pub links: Option<Vec<NordeaResponseLinks>>,
/// Error description
pub errors: Option<Vec<NordeaPaymentsConfirmErrorObject>>,
/// External response header
pub group_header: Option<NordeaGroupHeader>,
/// OTP Challenge
pub otp_challenge: Option<String>,
#[serde(rename = "response")]
pub nordea_payments_response: Option<NordeaPaymentsResponseWrapper>,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct NordeaOriginalRequest {
/// Original request url
#[serde(rename = "url")]
pub nordea_url: Option<String>,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct NordeaFailures {
/// Failure code
pub code: Option<String>,
/// Failure description
pub description: Option<String>,
/// JSON path of the failing element if applicable
pub path: Option<String>,
/// Type of the validation error, e.g. NotNull
#[serde(rename = "type")]
pub failure_type: Option<String>,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct NordeaErrorBody {
// Serde JSON because connector returns an `(item)` object in failures array object
/// More details on the occurred error: Validation error
#[serde(rename = "failures")]
pub nordea_failures: Option<Vec<NordeaFailures>>,
/// Original request information
#[serde(rename = "request")]
pub nordea_request: Option<NordeaOriginalRequest>,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct NordeaErrorResponse {
/// Error response body
pub error: Option<NordeaErrorBody>,
/// External response header
pub group_header: Option<NordeaGroupHeader>,
#[serde(rename = "httpCode")]
pub http_code: Option<String>,
#[serde(rename = "moreInformation")]
pub more_information: Option<String>,
}
// Nordea does not support refunds in Private APIs. Only Corporate APIs support Refunds
| 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/nordea/transformers.rs | crates/hyperswitch_connectors/src/connectors/nordea/transformers.rs | use std::collections::HashMap;
use common_utils::{pii, request::Method, types::StringMajorUnit};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{BankDebitData, PaymentMethodData},
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{Authorize, PreProcessing},
router_request_types::{PaymentsAuthorizeData, PaymentsPreProcessingData, ResponseId},
router_response_types::{PaymentsResponseData, RedirectForm},
types::{
self, AccessTokenAuthenticationRouterData, CreateOrderRouterData,
PaymentsAuthorizeRouterData, PaymentsPreProcessingRouterData, PaymentsSyncRouterData,
},
};
use hyperswitch_interfaces::errors;
use masking::Secret;
use rand::distributions::DistString;
use serde::{Deserialize, Deserializer, Serialize};
use crate::{
connectors::nordea::{
requests::{
AccessScope, AccountNumber, AccountType, CreditorAccount, CreditorBank, DebitorAccount,
GrantType, NordeaOAuthExchangeRequest, NordeaOAuthRequest,
NordeaPaymentsConfirmRequest, NordeaPaymentsRequest, NordeaRouterData, PaymentsUrgency,
},
responses::{
NordeaErrorBody, NordeaFailures, NordeaOAuthExchangeResponse, NordeaPaymentStatus,
NordeaPaymentsConfirmResponse, NordeaPaymentsInitiateResponse,
},
},
types::{
CreateOrderResponseRouterData, PaymentsPreprocessingResponseRouterData,
PaymentsSyncResponseRouterData, ResponseRouterData,
},
utils::{self, get_unimplemented_payment_method_error_message, RouterData as _},
};
type Error = error_stack::Report<errors::ConnectorError>;
impl<T> From<(StringMajorUnit, T)> for NordeaRouterData<T> {
fn from((amount, item): (StringMajorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
// Auth Struct
#[derive(Debug)]
pub struct NordeaAuthType {
pub(super) client_id: Secret<String>,
pub(super) client_secret: Secret<String>,
/// PEM format private key for eIDAS signing
/// Should be base64 encoded
pub(super) eidas_private_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for NordeaAuthType {
type Error = Error;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} => Ok(Self {
client_id: key1.to_owned(),
client_secret: api_key.to_owned(),
eidas_private_key: api_secret.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct NordeaConnectorMetadataObject {
/// Account number of the beneficiary (merchant)
pub destination_account_number: Secret<String>,
/// Account type (example: IBAN, BBAN_SE, BBAN_DK, BBAN_NO, BGNR, PGNR, GIRO_DK, BBAN_OTHER)
pub account_type: String,
/// Name of the beneficiary (merchant)
pub merchant_name: Secret<String>,
}
impl TryFrom<&Option<pii::SecretSerdeValue>> for NordeaConnectorMetadataObject {
type Error = Error;
fn try_from(meta_data: &Option<pii::SecretSerdeValue>) -> Result<Self, Self::Error> {
let metadata: Self = utils::to_connector_meta_from_secret::<Self>(meta_data.clone())
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "merchant_connector_account.metadata",
})?;
Ok(metadata)
}
}
impl TryFrom<&AccessTokenAuthenticationRouterData> for NordeaOAuthRequest {
type Error = Error;
fn try_from(item: &AccessTokenAuthenticationRouterData) -> Result<Self, Self::Error> {
let country = item.get_billing_country()?;
// Set refresh_token maximum expiry duration to 180 days (259200 / 60 = 180)
// Minimum is 1 minute
let duration = Some(259200);
let maximum_transaction_history = Some(18);
let redirect_uri = "https://hyperswitch.io".to_string();
let scope = [
AccessScope::AccountsBasic,
AccessScope::AccountsDetails,
AccessScope::AccountsBalances,
AccessScope::AccountsTransactions,
AccessScope::PaymentsMultiple,
]
.to_vec();
let state = rand::distributions::Alphanumeric.sample_string(&mut rand::thread_rng(), 15);
Ok(Self {
country,
duration,
maximum_transaction_history,
redirect_uri,
scope,
state: state.into(),
})
}
}
impl TryFrom<&types::RefreshTokenRouterData> for NordeaOAuthExchangeRequest {
type Error = Error;
fn try_from(item: &types::RefreshTokenRouterData) -> Result<Self, Self::Error> {
let code = item
.request
.authentication_token
.as_ref()
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "authorization_code",
})?
.code
.clone();
let grant_type = GrantType::AuthorizationCode;
let redirect_uri = Some("https://hyperswitch.io".to_string());
Ok(Self {
code: Some(code),
grant_type,
redirect_uri,
refresh_token: None, // We're not using refresh_token to generate new access_token
})
}
}
impl<F, T> TryFrom<ResponseRouterData<F, NordeaOAuthExchangeResponse, T, AccessToken>>
for RouterData<F, T, AccessToken>
{
type Error = Error;
fn try_from(
item: ResponseRouterData<F, NordeaOAuthExchangeResponse, T, AccessToken>,
) -> Result<Self, Self::Error> {
let access_token =
item.response
.access_token
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "access_token",
})?;
let expires_in = item.response.expires_in.unwrap_or(3600); // Default to 1 hour if not provided
Ok(Self {
status: common_enums::AttemptStatus::AuthenticationSuccessful,
response: Ok(AccessToken {
token: access_token.clone(),
expires: expires_in,
}),
..item.data
})
}
}
impl TryFrom<&str> for AccountType {
type Error = Error;
fn try_from(value: &str) -> Result<Self, Self::Error> {
match value.to_uppercase().as_str() {
"IBAN" => Ok(Self::Iban),
"BBAN_SE" => Ok(Self::BbanSe),
"BBAN_DK" => Ok(Self::BbanDk),
"BBAN_NO" => Ok(Self::BbanNo),
"BGNR" => Ok(Self::Bgnr),
"PGNR" => Ok(Self::Pgnr),
"GIRO_DK" => Ok(Self::GiroDk),
"BBAN_OTHER" => Ok(Self::BbanOther),
_ => Err(errors::ConnectorError::InvalidConnectorConfig {
config: "account_type",
}
.into()),
}
}
}
impl<'de> Deserialize<'de> for PaymentsUrgency {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let s = String::deserialize(deserializer)?.to_lowercase();
match s.as_str() {
"standard" => Ok(Self::Standard),
"express" => Ok(Self::Express),
"sameday" => Ok(Self::Sameday),
_ => Err(serde::de::Error::unknown_variant(
&s,
&["standard", "express", "sameday"],
)),
}
}
}
fn get_creditor_account_from_metadata(
router_data: &PaymentsPreProcessingRouterData,
) -> Result<CreditorAccount, Error> {
let metadata: NordeaConnectorMetadataObject =
utils::to_connector_meta_from_secret(router_data.connector_meta_data.clone())
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "merchant_connector_account.metadata",
})?;
let creditor_account = CreditorAccount {
account: AccountNumber {
account_type: AccountType::try_from(metadata.account_type.as_str())
.unwrap_or(AccountType::Iban),
currency: router_data.request.currency,
value: metadata.destination_account_number,
},
country: router_data.get_optional_billing_country(),
// Merchant is the beneficiary in this case
name: Some(metadata.merchant_name),
message: router_data
.description
.as_ref()
.map(|desc| desc.chars().take(20).collect::<String>()),
bank: Some(CreditorBank {
address: None,
bank_code: None,
bank_name: None,
business_identifier_code: None,
country: router_data.get_billing_country()?,
}),
creditor_address: None,
// Either Reference or Message must be supplied in the request
reference: None,
};
Ok(creditor_account)
}
fn get_creditor_account_from_metadata_for_create_order(
router_data: &CreateOrderRouterData,
) -> Result<CreditorAccount, Error> {
let metadata: NordeaConnectorMetadataObject =
utils::to_connector_meta_from_secret(router_data.connector_meta_data.clone())
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "merchant_connector_account.metadata",
})?;
let creditor_account = CreditorAccount {
account: AccountNumber {
account_type: AccountType::try_from(metadata.account_type.as_str())
.unwrap_or(AccountType::Iban),
currency: Some(router_data.request.currency),
value: metadata.destination_account_number,
},
country: router_data.get_optional_billing_country(),
// Merchant is the beneficiary in this case
name: Some(metadata.merchant_name),
message: router_data
.description
.as_ref()
.map(|desc| desc.chars().take(20).collect::<String>()),
bank: Some(CreditorBank {
address: None,
bank_code: None,
bank_name: None,
business_identifier_code: None,
country: router_data.get_billing_country()?,
}),
creditor_address: None,
// Either Reference or Message must be supplied in the request
reference: None,
};
Ok(creditor_account)
}
impl TryFrom<&NordeaRouterData<&CreateOrderRouterData>> for NordeaPaymentsRequest {
type Error = Error;
fn try_from(item: &NordeaRouterData<&CreateOrderRouterData>) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
Some(PaymentMethodData::BankDebit(bank_debit_data)) => match bank_debit_data {
BankDebitData::SepaBankDebit { iban, .. } => {
let creditor_account =
get_creditor_account_from_metadata_for_create_order(item.router_data)?;
let debitor_account = DebitorAccount {
account: AccountNumber {
account_type: AccountType::Iban,
currency: Some(item.router_data.request.currency),
value: iban,
},
message: item
.router_data
.description
.as_ref()
.map(|desc| desc.chars().take(20).collect::<String>()),
};
let instructed_amount = super::requests::InstructedAmount {
amount: item.amount.clone(),
currency: item.router_data.request.currency,
};
Ok(Self {
creditor_account,
debitor_account,
end_to_end_identification: None,
external_id: Some(item.router_data.connector_request_reference_id.clone()),
instructed_amount,
recurring: None,
request_availability_of_funds: None,
requested_execution_date: None,
tpp_messages: None,
urgency: None,
})
}
BankDebitData::AchBankDebit { .. }
| BankDebitData::BacsBankDebit { .. }
| BankDebitData::BecsBankDebit { .. }
| BankDebitData::SepaGuarenteedBankDebit { .. } => {
Err(errors::ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("Nordea"),
)
.into())
}
},
Some(PaymentMethodData::CardRedirect(_))
| Some(PaymentMethodData::CardDetailsForNetworkTransactionId(_))
| Some(PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_))
| Some(PaymentMethodData::Wallet(_))
| Some(PaymentMethodData::PayLater(_))
| Some(PaymentMethodData::BankRedirect(_))
| Some(PaymentMethodData::BankTransfer(_))
| Some(PaymentMethodData::Crypto(_))
| Some(PaymentMethodData::MandatePayment)
| Some(PaymentMethodData::Reward)
| Some(PaymentMethodData::RealTimePayment(_))
| Some(PaymentMethodData::MobilePayment(_))
| Some(PaymentMethodData::Upi(_))
| Some(PaymentMethodData::Voucher(_))
| Some(PaymentMethodData::GiftCard(_))
| Some(PaymentMethodData::OpenBanking(_))
| Some(PaymentMethodData::CardToken(_))
| Some(PaymentMethodData::NetworkToken(_))
| Some(PaymentMethodData::Card(_))
| None => {
Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into())
}
}
}
}
impl TryFrom<&NordeaRouterData<&PaymentsPreProcessingRouterData>> for NordeaPaymentsRequest {
type Error = Error;
fn try_from(
item: &NordeaRouterData<&PaymentsPreProcessingRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
Some(PaymentMethodData::BankDebit(bank_debit_data)) => match bank_debit_data {
BankDebitData::SepaBankDebit { iban, .. } => {
let creditor_account = get_creditor_account_from_metadata(item.router_data)?;
let debitor_account = DebitorAccount {
account: AccountNumber {
account_type: AccountType::Iban,
currency: item.router_data.request.currency,
value: iban,
},
message: item
.router_data
.description
.as_ref()
.map(|desc| desc.chars().take(20).collect::<String>()),
};
let instructed_amount = super::requests::InstructedAmount {
amount: item.amount.clone(),
currency: item.router_data.request.currency.ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "amount",
},
)?,
};
Ok(Self {
creditor_account,
debitor_account,
end_to_end_identification: None,
external_id: Some(item.router_data.connector_request_reference_id.clone()),
instructed_amount,
recurring: None,
request_availability_of_funds: None,
requested_execution_date: None,
tpp_messages: None,
urgency: None,
})
}
BankDebitData::AchBankDebit { .. }
| BankDebitData::BacsBankDebit { .. }
| BankDebitData::BecsBankDebit { .. }
| BankDebitData::SepaGuarenteedBankDebit { .. } => {
Err(errors::ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("Nordea"),
)
.into())
}
},
Some(PaymentMethodData::CardRedirect(_))
| Some(PaymentMethodData::CardDetailsForNetworkTransactionId(_))
| Some(PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_))
| Some(PaymentMethodData::Wallet(_))
| Some(PaymentMethodData::PayLater(_))
| Some(PaymentMethodData::BankRedirect(_))
| Some(PaymentMethodData::BankTransfer(_))
| Some(PaymentMethodData::Crypto(_))
| Some(PaymentMethodData::MandatePayment)
| Some(PaymentMethodData::Reward)
| Some(PaymentMethodData::RealTimePayment(_))
| Some(PaymentMethodData::MobilePayment(_))
| Some(PaymentMethodData::Upi(_))
| Some(PaymentMethodData::Voucher(_))
| Some(PaymentMethodData::GiftCard(_))
| Some(PaymentMethodData::OpenBanking(_))
| Some(PaymentMethodData::CardToken(_))
| Some(PaymentMethodData::NetworkToken(_))
| Some(PaymentMethodData::Card(_))
| None => {
Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into())
}
}
}
}
impl TryFrom<&NordeaRouterData<&PaymentsAuthorizeRouterData>> for NordeaPaymentsConfirmRequest {
type Error = Error;
fn try_from(
item: &NordeaRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let payment_ids = match &item.router_data.response {
Ok(response_data) => response_data
.get_connector_transaction_id()
.map_err(|_| errors::ConnectorError::MissingConnectorTransactionID)?,
Err(_) => return Err(errors::ConnectorError::ResponseDeserializationFailed.into()),
};
Ok(Self {
authentication_method: None,
language: None,
payments_ids: vec![payment_ids],
redirect_url: None,
state: None,
})
}
}
impl From<NordeaPaymentStatus> for common_enums::AttemptStatus {
fn from(item: NordeaPaymentStatus) -> Self {
match item {
NordeaPaymentStatus::Confirmed | NordeaPaymentStatus::Paid => Self::Charged,
NordeaPaymentStatus::PendingConfirmation
| NordeaPaymentStatus::PendingSecondConfirmation => Self::ConfirmationAwaited,
NordeaPaymentStatus::PendingUserApproval => Self::AuthenticationPending,
NordeaPaymentStatus::OnHold | NordeaPaymentStatus::Unknown => Self::Pending,
NordeaPaymentStatus::Rejected
| NordeaPaymentStatus::InsufficientFunds
| NordeaPaymentStatus::LimitExceeded
| NordeaPaymentStatus::UserApprovalFailed
| NordeaPaymentStatus::UserApprovalTimeout
| NordeaPaymentStatus::UserApprovalCancelled => Self::Failure,
}
}
}
pub fn get_error_data(error_response: Option<&NordeaErrorBody>) -> Option<&NordeaFailures> {
error_response
.and_then(|error| error.nordea_failures.as_ref())
.and_then(|failures| failures.first())
}
// Helper function to convert NordeaPaymentsInitiateResponse to common response data
fn convert_nordea_payment_response(
response: &NordeaPaymentsInitiateResponse,
) -> Result<(PaymentsResponseData, common_enums::AttemptStatus), Error> {
let payment_response = response
.payments_response
.as_ref()
.ok_or(errors::ConnectorError::ResponseHandlingFailed)?;
let resource_id = ResponseId::ConnectorTransactionId(payment_response.payment_id.clone());
let response_data = PaymentsResponseData::TransactionResponse {
resource_id,
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: payment_response.external_id.clone(),
incremental_authorization_allowed: None,
charges: None,
};
let status = common_enums::AttemptStatus::from(payment_response.payment_status.clone());
Ok((response_data, status))
}
impl TryFrom<PaymentsPreprocessingResponseRouterData<NordeaPaymentsInitiateResponse>>
for RouterData<PreProcessing, PaymentsPreProcessingData, PaymentsResponseData>
{
type Error = Error;
fn try_from(
item: PaymentsPreprocessingResponseRouterData<NordeaPaymentsInitiateResponse>,
) -> Result<Self, Self::Error> {
let (response, status) = convert_nordea_payment_response(&item.response)?;
Ok(Self {
status,
response: Ok(response),
..item.data
})
}
}
impl TryFrom<CreateOrderResponseRouterData<NordeaPaymentsInitiateResponse>>
for CreateOrderRouterData
{
type Error = Error;
fn try_from(
item: CreateOrderResponseRouterData<NordeaPaymentsInitiateResponse>,
) -> Result<Self, Self::Error> {
let (response, status) = convert_nordea_payment_response(&item.response)?;
Ok(Self {
status,
response: Ok(response),
..item.data
})
}
}
impl
TryFrom<
ResponseRouterData<
Authorize,
NordeaPaymentsConfirmResponse,
PaymentsAuthorizeData,
PaymentsResponseData,
>,
> for RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData>
{
type Error = Error;
fn try_from(
item: ResponseRouterData<
Authorize,
NordeaPaymentsConfirmResponse,
PaymentsAuthorizeData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
// First check if there are any errors in the response
if let Some(errors) = &item.response.errors {
if !errors.is_empty() {
// Get the first error for the error response
let first_error = errors
.first()
.ok_or(errors::ConnectorError::ResponseHandlingFailed)?;
return Ok(Self {
status: common_enums::AttemptStatus::Failure,
response: Err(ErrorResponse {
code: first_error
.error
.clone()
.unwrap_or_else(|| "UNKNOWN_ERROR".to_string()),
message: first_error
.error_description
.clone()
.unwrap_or_else(|| "Payment confirmation failed".to_string()),
reason: first_error.error_description.clone(),
status_code: item.http_code,
attempt_status: Some(common_enums::AttemptStatus::Failure),
connector_transaction_id: first_error.payment_id.clone(),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
});
}
}
// If no errors, proceed with normal response handling
// Check if there's a redirect link at the top level only
let redirection_data = item
.response
.links
.as_ref()
.and_then(|links| {
links.iter().find(|link| {
link.rel
.as_ref()
.map(|rel| rel == "signing")
.unwrap_or(false)
})
})
.and_then(|link| link.href.clone())
.map(|redirect_url| RedirectForm::Form {
endpoint: redirect_url,
method: Method::Get,
form_fields: HashMap::new(),
});
let (response, status) = match &item.response.nordea_payments_response {
Some(payment_response_wrapper) => {
// Get the first payment from the payments array
let payment = payment_response_wrapper
.payments
.first()
.ok_or(errors::ConnectorError::ResponseHandlingFailed)?;
let resource_id = ResponseId::ConnectorTransactionId(payment.payment_id.clone());
let response = Ok(PaymentsResponseData::TransactionResponse {
resource_id,
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: payment.external_id.clone(),
incremental_authorization_allowed: None,
charges: None,
});
let status = common_enums::AttemptStatus::from(payment.payment_status.clone());
(response, status)
}
None => {
// No payment response, but we might still have a redirect link
if let Some(redirect) = redirection_data {
let response = Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(Some(redirect)),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
});
(response, common_enums::AttemptStatus::AuthenticationPending)
} else {
return Err(errors::ConnectorError::ResponseHandlingFailed.into());
}
}
};
Ok(Self {
status,
response,
..item.data
})
}
}
impl TryFrom<PaymentsSyncResponseRouterData<NordeaPaymentsInitiateResponse>>
for PaymentsSyncRouterData
{
type Error = Error;
fn try_from(
item: PaymentsSyncResponseRouterData<NordeaPaymentsInitiateResponse>,
) -> Result<Self, Self::Error> {
let (response, status) = convert_nordea_payment_response(&item.response)?;
Ok(Self {
status,
response: Ok(response),
..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/nordea/requests.rs | crates/hyperswitch_connectors/src/connectors/nordea/requests.rs | use common_utils::types::StringMajorUnit;
use masking::Secret;
use serde::{Deserialize, Serialize};
pub struct NordeaRouterData<T> {
pub amount: StringMajorUnit,
pub router_data: T,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct NordeaOAuthRequest {
/// Country is a mandatory parameter with possible values FI, DK, NO or SE
pub country: api_models::enums::CountryAlpha2,
/// Duration of access authorization in minutes. range: 1 to 259200 minutes (180 days).
/// Duration should be left empty if the request includes PAYMENTS_SINGLE_SCA scope.
#[serde(skip_serializing_if = "Option::is_none")]
pub duration: Option<i32>,
/// Maximum transaction history in months. Optional if ACCOUNTS_TRANSACTIONS scope is requested. Default=2 months. range: 1 to 18 months
#[serde(rename = "max_tx_history")]
#[serde(skip_serializing_if = "Option::is_none")]
pub maximum_transaction_history: Option<i32>,
/// Redirect URI you used when this application was registered with Nordea.
pub redirect_uri: String,
pub scope: Vec<AccessScope>,
/// The OAuth2 state parameter. This is a nonce and should be used to prevent CSRF attacks.
pub state: Secret<String>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "snake_case")]
pub enum GrantType {
AuthorizationCode,
RefreshToken,
}
// To be passed in query parameters for OAuth scopes
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum AccessScope {
AccountsBasic,
AccountsBalances,
AccountsDetails,
AccountsTransactions,
PaymentsMultiple,
PaymentsSingleSca,
CardsInformation,
CardsTransactions,
}
#[derive(Debug, Clone, Serialize)]
pub struct NordeaOAuthExchangeRequest {
/// authorization_code flow
#[serde(skip_serializing_if = "Option::is_none")]
pub code: Option<Secret<String>>,
pub grant_type: GrantType,
#[serde(skip_serializing_if = "Option::is_none")]
pub redirect_uri: Option<String>,
/// refresh_token flow
#[serde(skip_serializing_if = "Option::is_none")]
pub refresh_token: Option<Secret<String>>,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum AccountType {
/// International bank account number
Iban,
/// National bank account number of Sweden
BbanSe,
/// National bank account number of Denmark
BbanDk,
/// National bank account number of Norway
BbanNo,
/// Bankgiro number
Bgnr,
/// Plusgiro number
Pgnr,
/// Creditor number (Giro) Denmark
GiroDk,
/// Any bank account number without any check-digit validations
BbanOther,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct AccountNumber {
/// Type of account number
#[serde(rename = "_type")]
pub account_type: AccountType,
/// Currency of the account (Mandatory for debtor, Optional for creditor)
#[serde(skip_serializing_if = "Option::is_none")]
pub currency: Option<api_models::enums::Currency>,
/// Actual account number
pub value: Secret<String>,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct CreditorAccountReference {
/// RF or Invoice for FI Sepa payments, OCR for NO Kid payments and 01, 04, 15, 71, 73 or 75 for Danish Transfer Form payments.
#[serde(rename = "_type")]
pub creditor_reference_type: String,
/// Actual reference number
#[serde(skip_serializing_if = "Option::is_none")]
pub value: Option<String>,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct NordeaAddress {
/// First line of the address. e.g. Street address
pub line1: Option<Secret<String>>,
/// Second line of the address (optional). e.g. Postal address
pub line2: Option<Secret<String>>,
/// Third line of the address (optional). e.g. Country
pub line3: Option<Secret<String>>,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct CreditorBank {
/// Address
pub address: Option<NordeaAddress>,
/// Bank code
pub bank_code: Option<String>,
/// Business identifier code (BIC) of the creditor bank.
/// This information is required, if the creditor account number is not in IBAN format.
#[serde(rename = "bic")]
pub business_identifier_code: Option<Secret<String>>,
/// Country of the creditor bank. Only ISO 3166 alpha-2 codes are used.
pub country: api_models::enums::CountryAlpha2,
/// Name of the creditor bank.
#[serde(rename = "name")]
pub bank_name: Option<String>,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct CreditorAccount {
/// Account number
pub account: AccountNumber,
/// Creditor bank information.
pub bank: Option<CreditorBank>,
/// Country of the creditor
pub country: Option<api_models::enums::CountryAlpha2>,
/// Address
pub creditor_address: Option<NordeaAddress>,
/// Message for the creditor to appear on their transaction.
/// Max length: FI SEPA:140; SE:12; PGNR:25; BGNR:150; DK: 40 (Instant/Express: 140); NO: 140
#[serde(skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
/// Name of the creditor.
/// Max length: FI SEPA: 30; SE: 35; DK: Not use (Mandatory for Instant/Express payments: 70);
/// NO: 30 (mandatory for Straksbetaling/Express payments).
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<Secret<String>>,
/// Creditor reference number.
/// Either Reference or Message has to be passed in the Request
pub reference: Option<CreditorAccountReference>,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct DebitorAccount {
/// Account number
pub account: AccountNumber,
/// Own message to be on the debtor's transaction.
/// Max length 20. NB: This field is not supported for SEPA and Norwegian payments and will be ignored.
#[serde(skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct InstructedAmount {
/// Monetary amount of the payment. Max (digits+decimals): FI SEPA: (9+2); SE:(11+2); DK:(7+2); NO:(7+2)
pub amount: StringMajorUnit,
/// Currency code according to ISO 4217.
/// NB: Possible value depends on the type of the payment.
/// For domestic payment it should be same as debtor local currency,
/// for SEPA it must be EUR,
/// for cross border it can be Currency code according to ISO 4217.
pub currency: api_models::enums::Currency,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum RecurrenceType {
Daily,
Weekly,
Biweekly,
MonthlySameDay,
MonthlyEom,
QuartelySameDay,
QuartelyEom,
SemiAnnuallySameDay,
SemiAnnuallyEom,
TriAnnuallySameDay,
YearlySameDay,
YearlyEom,
EveryMinuteSandboxOnly,
}
#[derive(Debug, Serialize, PartialEq)]
#[serde(rename_all = "snake_case")]
#[allow(dead_code)] // This is an optional field and not having it is fine
pub enum FundsAvailabilityRequest {
True,
False,
}
#[derive(Debug, Serialize, PartialEq, Clone)]
pub enum PaymentsUrgency {
Standard,
Express,
Sameday,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct RecurringInformation {
/// Number of occurrences. Not applicable for NO (use end_date instead). Format: int32.
#[serde(skip_serializing_if = "Option::is_none")]
pub count: Option<i32>,
/// Date on which the recurrence will end. Format: YYYY-MM-DD. Applicable only for Norway. Format: date
#[serde(skip_serializing_if = "Option::is_none")]
pub end_date: Option<String>,
/// Repeats every interval
#[serde(skip_serializing_if = "Option::is_none")]
pub recurrence_type: Option<RecurrenceType>,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum TppCategory {
Error,
Warning,
Info,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum TppCode {
Ds0a,
Narr,
Am21,
Am04,
Tm01,
Am12,
Rc06,
Rc07,
Rc04,
Ag06,
Bg06,
Be22,
Be20,
Ff06,
Be19,
Am03,
Am11,
Ch04,
Dt01,
Ch03,
Ff08,
Ac10,
Ac02,
Ag08,
Rr09,
Rc11,
Ff10,
Rr10,
Ff05,
Ch15,
Ff04,
Ac11,
Ac03,
Ac13,
Ac14,
Ac05,
Ac06,
Rr07,
Dt03,
Am13,
Ds24,
Fr01,
Am02,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct ThirdPartyMessages {
/// Category of the TPP message, INFO is further information, WARNING is something can be fixed, ERROR possibly non fixable issue
#[serde(skip_serializing_if = "Option::is_none")]
pub category: Option<TppCategory>,
/// Additional code that is combined with the text
#[serde(skip_serializing_if = "Option::is_none")]
pub code: Option<TppCode>,
/// Additional explaining text to the TPP
#[serde(skip_serializing_if = "Option::is_none")]
pub text: Option<String>,
}
#[derive(Debug, Serialize, PartialEq)]
pub struct NordeaPaymentsRequest {
/// Creditor of the payment
#[serde(rename = "creditor")]
pub creditor_account: CreditorAccount,
/// Debtor of the payment
#[serde(rename = "debtor")]
pub debitor_account: DebitorAccount,
/// Free text reference that can be provided by the PSU.
/// This identification is passed on throughout the entire end-to-end chain.
/// Only in scope for Nordea Business DK.
#[serde(skip_serializing_if = "Option::is_none")]
pub end_to_end_identification: Option<String>,
/// Unique identification as assigned by a partner to identify the payment.
#[serde(skip_serializing_if = "Option::is_none")]
pub external_id: Option<String>,
/// Monetary amount
pub instructed_amount: InstructedAmount,
/// Recurring information
#[serde(skip_serializing_if = "Option::is_none")]
pub recurring: Option<RecurringInformation>,
/// Use as an indicator that the supplied payment (amount, currency and debtor account)
/// should be used to check whether the funds are available for further processing - at this moment.
#[serde(skip_serializing_if = "Option::is_none")]
pub request_availability_of_funds: Option<FundsAvailabilityRequest>,
/// Choose a preferred execution date (or leave blank for today's date).
/// This should be a valid bank day, and depending on the country the date will either be
/// pushed to the next valid bank day, or return an error if a non-banking day date was
/// supplied (all dates accepted in sandbox). SEPA: max +5 years from yesterday,
/// Domestic: max. +1 year from yesterday. NB: Not supported for Own transfer Non-Recurring Norway.
/// Format:date.
#[serde(skip_serializing_if = "Option::is_none")]
pub requested_execution_date: Option<String>,
/// Additional messages for third parties
#[serde(rename = "tpp_messages")]
#[serde(skip_serializing_if = "Option::is_none")]
pub tpp_messages: Option<Vec<ThirdPartyMessages>>,
/// Urgency of the payment. NB: This field is supported for
/// DK Domestic ('standard' and 'express')
/// NO Domestic bank transfer payments ('standard'). Use 'express' for Straksbetaling (Instant payment).
/// FI Sepa ('standard' and 'express') All other payment types ignore this input.
/// For further details on urgencies and cut-offs, refer to the Nordea website. Value 'sameday' is marked as deprecated and will be removed in the future.
#[serde(skip_serializing_if = "Option::is_none")]
pub urgency: Option<PaymentsUrgency>,
}
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum NordeaAuthenticationMethod {
Mta,
#[serde(rename = "CCALC (Deprecated)")]
Ccalc,
Qrt,
CardRdr,
BankidSe,
QrtSe,
BankidNo,
BankidmNo,
MtaNo,
#[serde(rename = "NEMID_2F")]
Nemid2f,
Mitid,
MtaDk,
QrtDk,
}
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
#[serde(rename_all = "snake_case")]
pub enum NordeaConfirmLanguage {
Fi,
Da,
Sv,
En,
No,
}
#[derive(Debug, Serialize, PartialEq)]
pub struct NordeaPaymentsConfirmRequest {
/// Authentication method to use for the signing of payment.
#[serde(skip_serializing_if = "Option::is_none")]
pub authentication_method: Option<NordeaAuthenticationMethod>,
/// Language of the signing page that will be displayed to client, ISO639-1 and 639-2, default=en
#[serde(skip_serializing_if = "Option::is_none")]
pub language: Option<NordeaConfirmLanguage>,
pub payments_ids: Vec<String>,
pub redirect_url: Option<String>,
pub state: 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/adyen/transformers.rs | crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs | use std::{ops::Deref, str::FromStr};
#[cfg(feature = "payouts")]
use api_models::payouts::{self, PayoutMethodData};
use api_models::{
enums,
payments::{self, PollConfig, QrCodeInformation, VoucherNextStepData},
};
use cards::{CardNumber, NetworkToken};
use common_enums::enums as storage_enums;
#[cfg(feature = "payouts")]
use common_utils::ext_traits::OptionExt;
use common_utils::{
errors::{CustomResult, ParsingError},
ext_traits::{Encode, ValueExt},
pii::Email,
request::Method,
types::{MinorUnit, SemanticVersion},
};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
payment_method_data::{
BankDebitData, BankRedirectData, BankTransferData, Card, CardRedirectData, GiftCardData,
NetworkTokenData, PayLaterData, PaymentMethodData, VoucherData, WalletData,
},
router_data::{
ConnectorAuthType, ConnectorResponseData, ErrorResponse, ExtendedAuthorizationResponseData,
PaymentMethodBalance, PaymentMethodToken, RouterData,
},
router_flow_types::GiftCardBalanceCheck,
router_request_types::{
GiftCardBalanceCheckRequestData, ResponseId, SubmitEvidenceRequestData,
},
router_response_types::{
AcceptDisputeResponse, DefendDisputeResponse, GiftCardBalanceCheckResponseData,
MandateReference, PaymentsResponseData, RedirectForm, RefundsResponseData,
SubmitEvidenceResponse,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsExtendAuthorizationRouterData, PaymentsGiftCardBalanceCheckRouterData,
PaymentsPreProcessingRouterData, RefundsRouterData,
},
};
#[cfg(feature = "payouts")]
use hyperswitch_domain_models::{
router_response_types::PayoutsResponseData, types::PayoutsRouterData,
};
use hyperswitch_interfaces::{
consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE},
errors,
};
use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use time::{Duration, OffsetDateTime, PrimitiveDateTime};
use url::Url;
#[cfg(feature = "payouts")]
use crate::{types::PayoutsResponseRouterData, utils::PayoutsData};
use crate::{
types::{
AcceptDisputeRouterData, DefendDisputeRouterData, PaymentsCancelResponseRouterData,
PaymentsCaptureResponseRouterData, PaymentsExtendAuthorizationResponseRouterData,
PaymentsPreprocessingResponseRouterData, RefundsResponseRouterData, ResponseRouterData,
SubmitEvidenceRouterData,
},
utils::{
self, is_manual_capture, missing_field_err, AddressDetailsData, BrowserInformationData,
CardData, ForeignTryFrom, NetworkTokenData as UtilsNetworkTokenData,
PaymentsAuthorizeRequestData, PhoneDetailsData, RouterData as OtherRouterData,
},
};
type Error = error_stack::Report<errors::ConnectorError>;
#[derive(Debug, Serialize)]
pub struct AdyenRouterData<T> {
pub amount: MinorUnit,
pub router_data: T,
}
impl<T> TryFrom<(MinorUnit, T)> for AdyenRouterData<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, Default, Serialize, Deserialize)]
pub struct AdyenConnectorMetadataObject {
pub endpoint_prefix: Option<String>,
}
impl TryFrom<&Option<common_utils::pii::SecretSerdeValue>> for AdyenConnectorMetadataObject {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
meta_data: &Option<common_utils::pii::SecretSerdeValue>,
) -> Result<Self, Self::Error> {
match meta_data {
Some(metadata) => utils::to_connector_meta_from_secret::<Self>(Some(metadata.clone()))
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "metadata",
}),
None => Ok(Self::default()),
}
}
}
// Adyen Types Definition
// Payments Request and Response Types
#[derive(Default, Debug, Serialize, Deserialize)]
pub enum AdyenShopperInteraction {
#[default]
Ecommerce,
#[serde(rename = "ContAuth")]
ContinuedAuthentication,
Moto,
#[serde(rename = "POS")]
Pos,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub enum AdyenRecurringModel {
UnscheduledCardOnFile,
CardOnFile,
}
#[derive(Clone, Default, Debug, Serialize, Deserialize)]
pub enum AuthType {
#[default]
PreAuth,
}
#[serde_with::skip_serializing_none]
#[derive(Clone, Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AdditionalData {
authorisation_type: Option<AuthType>,
manual_capture: Option<String>,
execute_three_d: Option<String>,
pub recurring_processing_model: Option<AdyenRecurringModel>,
/// Enable recurring details in dashboard to receive this ID, https://docs.adyen.com/online-payments/tokenization/create-and-use-tokens#test-and-go-live
#[serde(rename = "recurring.recurringDetailReference")]
recurring_detail_reference: Option<Secret<String>>,
#[serde(rename = "recurring.shopperReference")]
recurring_shopper_reference: Option<String>,
network_tx_reference: Option<Secret<String>>,
#[cfg(feature = "payouts")]
payout_eligible: Option<PayoutEligibility>,
funds_availability: Option<String>,
refusal_reason_raw: Option<String>,
refusal_code_raw: Option<String>,
merchant_advice_code: Option<String>,
#[serde(flatten)]
riskdata: Option<RiskData>,
sca_exemption: Option<AdyenExemptionValues>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum AdyenExemptionValues {
LowValue,
SecureCorporate,
TrustedBeneficiary,
TransactionRiskAnalysis,
}
fn to_adyen_exemption(data: &enums::ExemptionIndicator) -> Option<AdyenExemptionValues> {
match data {
enums::ExemptionIndicator::LowValue => Some(AdyenExemptionValues::LowValue),
enums::ExemptionIndicator::SecureCorporatePayment => {
Some(AdyenExemptionValues::SecureCorporate)
}
enums::ExemptionIndicator::TrustedListing => Some(AdyenExemptionValues::TrustedBeneficiary),
enums::ExemptionIndicator::TransactionRiskAssessment => {
Some(AdyenExemptionValues::TransactionRiskAnalysis)
}
_ => None,
}
}
#[serde_with::skip_serializing_none]
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ShopperName {
first_name: Option<Secret<String>>,
last_name: Option<Secret<String>>,
}
#[serde_with::skip_serializing_none]
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Address {
city: String,
country: enums::CountryAlpha2,
house_number_or_name: Secret<String>,
postal_code: Secret<String>,
state_or_province: Option<Secret<String>>,
street: Option<Secret<String>>,
}
#[serde_with::skip_serializing_none]
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct LineItem {
amount_excluding_tax: Option<MinorUnit>,
amount_including_tax: Option<MinorUnit>,
description: Option<String>,
id: Option<String>,
tax_amount: Option<MinorUnit>,
quantity: Option<u16>,
}
#[serde_with::skip_serializing_none]
#[derive(Clone, Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RiskData {
#[serde(rename = "riskdata.basket.item1.itemID")]
item_i_d: Option<String>,
#[serde(rename = "riskdata.basket.item1.productTitle")]
product_title: Option<String>,
#[serde(rename = "riskdata.basket.item1.amountPerItem")]
amount_per_item: Option<String>,
#[serde(rename = "riskdata.basket.item1.currency")]
currency: Option<String>,
#[serde(rename = "riskdata.basket.item1.upc")]
upc: Option<String>,
#[serde(rename = "riskdata.basket.item1.brand")]
brand: Option<String>,
#[serde(rename = "riskdata.basket.item1.manufacturer")]
manufacturer: Option<String>,
#[serde(rename = "riskdata.basket.item1.category")]
category: Option<String>,
#[serde(rename = "riskdata.basket.item1.quantity")]
quantity: Option<String>,
#[serde(rename = "riskdata.basket.item1.color")]
color: Option<String>,
#[serde(rename = "riskdata.basket.item1.size")]
size: Option<String>,
#[serde(rename = "riskdata.deviceCountry")]
device_country: Option<String>,
#[serde(rename = "riskdata.houseNumberorName")]
house_numberor_name: Option<String>,
#[serde(rename = "riskdata.accountCreationDate")]
account_creation_date: Option<String>,
#[serde(rename = "riskdata.affiliateChannel")]
affiliate_channel: Option<String>,
#[serde(rename = "riskdata.avgOrderValue")]
avg_order_value: Option<String>,
#[serde(rename = "riskdata.deliveryMethod")]
delivery_method: Option<String>,
#[serde(rename = "riskdata.emailName")]
email_name: Option<String>,
#[serde(rename = "riskdata.emailDomain")]
email_domain: Option<String>,
#[serde(rename = "riskdata.lastOrderDate")]
last_order_date: Option<String>,
#[serde(rename = "riskdata.merchantReference")]
merchant_reference: Option<String>,
#[serde(rename = "riskdata.paymentMethod")]
payment_method: Option<String>,
#[serde(rename = "riskdata.promotionName")]
promotion_name: Option<String>,
#[serde(rename = "riskdata.secondaryPhoneNumber")]
secondary_phone_number: Option<String>,
#[serde(rename = "riskdata.timefromLogintoOrder")]
timefrom_loginto_order: Option<String>,
#[serde(rename = "riskdata.totalSessionTime")]
total_session_time: Option<String>,
#[serde(rename = "riskdata.totalAuthorizedAmountInLast30Days")]
total_authorized_amount_in_last30_days: Option<String>,
#[serde(rename = "riskdata.totalOrderQuantity")]
total_order_quantity: Option<String>,
#[serde(rename = "riskdata.totalLifetimeValue")]
total_lifetime_value: Option<String>,
#[serde(rename = "riskdata.visitsMonth")]
visits_month: Option<String>,
#[serde(rename = "riskdata.visitsWeek")]
visits_week: Option<String>,
#[serde(rename = "riskdata.visitsYear")]
visits_year: Option<String>,
#[serde(rename = "riskdata.shipToName")]
ship_to_name: Option<String>,
#[serde(rename = "riskdata.first8charactersofAddressLine1Zip")]
first8charactersof_address_line1_zip: Option<String>,
#[serde(rename = "riskdata.affiliateOrder")]
affiliate_order: Option<bool>,
}
#[serde_with::skip_serializing_none]
#[derive(Clone, Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ApplicationInfo {
external_platform: Option<ExternalPlatform>,
merchant_application: Option<MerchantApplication>,
}
#[serde_with::skip_serializing_none]
#[derive(Clone, Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ExternalPlatform {
name: Option<String>,
version: Option<String>,
integrator: Option<String>,
}
#[serde_with::skip_serializing_none]
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MerchantApplication {
name: Option<String>,
version: Option<String>,
}
#[serde_with::skip_serializing_none]
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AdyenPaymentRequest<'a> {
amount: Amount,
merchant_account: Secret<String>,
payment_method: PaymentMethod<'a>,
mpi_data: Option<AdyenMpiData>,
reference: String,
return_url: String,
browser_info: Option<AdyenBrowserInfo>,
shopper_interaction: AdyenShopperInteraction,
recurring_processing_model: Option<AdyenRecurringModel>,
additional_data: Option<AdditionalData>,
shopper_reference: Option<String>,
store_payment_method: Option<bool>,
shopper_name: Option<ShopperName>,
#[serde(rename = "shopperIP")]
shopper_ip: Option<Secret<String, common_utils::pii::IpAddress>>,
shopper_locale: Option<String>,
shopper_email: Option<Email>,
shopper_statement: Option<String>,
social_security_number: Option<Secret<String>>,
telephone_number: Option<Secret<String>>,
billing_address: Option<Address>,
delivery_address: Option<Address>,
country_code: Option<enums::CountryAlpha2>,
line_items: Option<Vec<LineItem>>,
channel: Option<Channel>,
merchant_order_reference: Option<String>,
splits: Option<Vec<AdyenSplitData>>,
/// metadata.store
store: Option<String>,
device_fingerprint: Option<Secret<String>>,
#[serde(with = "common_utils::custom_serde::iso8601::option")]
session_validity: Option<PrimitiveDateTime>,
metadata: Option<serde_json::Value>,
platform_chargeback_logic: Option<AdyenPlatformChargeBackLogicMetadata>,
application_info: Option<ApplicationInfo>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct AdyenSplitData {
amount: Option<Amount>,
#[serde(rename = "type")]
split_type: common_enums::AdyenSplitType,
account: Option<String>,
reference: String,
description: Option<String>,
}
#[serde_with::skip_serializing_none]
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct AdyenMpiData {
directory_response: common_enums::TransactionStatus,
authentication_response: common_enums::TransactionStatus,
cavv: Option<Secret<String>>,
token_authentication_verification_value: Option<Secret<String>>,
eci: Option<String>,
#[serde(rename = "dsTransID")]
ds_trans_id: Option<String>,
#[serde(rename = "threeDSVersion")]
three_ds_version: Option<SemanticVersion>,
challenge_cancel: Option<String>,
risk_score: Option<String>,
cavv_algorithm: Option<enums::CavvAlgorithm>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct AdyenBrowserInfo {
user_agent: String,
accept_header: String,
language: String,
color_depth: u8,
screen_height: u32,
screen_width: u32,
time_zone_offset: i32,
java_enabled: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum AdyenStatus {
AuthenticationFinished,
AuthenticationNotRequired,
Authorised,
Cancelled,
ChallengeShopper,
Error,
Pending,
Received,
RedirectShopper,
Refused,
PresentToShopper,
#[cfg(feature = "payouts")]
#[serde(rename = "[payout-confirm-received]")]
PayoutConfirmReceived,
#[cfg(feature = "payouts")]
#[serde(rename = "[payout-decline-received]")]
PayoutDeclineReceived,
#[cfg(feature = "payouts")]
#[serde(rename = "[payout-submit-received]")]
PayoutSubmitReceived,
}
#[derive(Debug, Clone, Serialize)]
pub enum Channel {
Web,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AdyenBalanceRequest<'a> {
pub payment_method: AdyenPaymentMethod<'a>,
pub merchant_account: Secret<String>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AdyenBalanceResponse {
pub psp_reference: String,
pub balance: Amount,
}
/// This implementation will be used only in Authorize, Automatic capture flow.
/// It is also being used in Psync flow, However Psync will be called only after create payment call that too in redirect flow.
fn get_adyen_payment_status(
is_manual_capture: bool,
adyen_status: AdyenStatus,
pmt: Option<common_enums::PaymentMethodType>,
) -> storage_enums::AttemptStatus {
match adyen_status {
AdyenStatus::AuthenticationFinished => {
storage_enums::AttemptStatus::AuthenticationSuccessful
}
AdyenStatus::AuthenticationNotRequired | AdyenStatus::Received => {
storage_enums::AttemptStatus::Pending
}
AdyenStatus::Authorised => match is_manual_capture {
true => storage_enums::AttemptStatus::Authorized,
// In case of Automatic capture Authorized is the final status of the payment
false => storage_enums::AttemptStatus::Charged,
},
AdyenStatus::Cancelled => storage_enums::AttemptStatus::Voided,
AdyenStatus::ChallengeShopper
| AdyenStatus::RedirectShopper
| AdyenStatus::PresentToShopper => storage_enums::AttemptStatus::AuthenticationPending,
AdyenStatus::Error | AdyenStatus::Refused => storage_enums::AttemptStatus::Failure,
AdyenStatus::Pending => match pmt {
Some(common_enums::PaymentMethodType::Pix) => {
storage_enums::AttemptStatus::AuthenticationPending
}
_ => storage_enums::AttemptStatus::Pending,
},
#[cfg(feature = "payouts")]
AdyenStatus::PayoutConfirmReceived => storage_enums::AttemptStatus::Started,
#[cfg(feature = "payouts")]
AdyenStatus::PayoutSubmitReceived => storage_enums::AttemptStatus::Pending,
#[cfg(feature = "payouts")]
AdyenStatus::PayoutDeclineReceived => storage_enums::AttemptStatus::Voided,
}
}
impl ForeignTryFrom<(bool, AdyenWebhookStatus)> for storage_enums::AttemptStatus {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(
(is_manual_capture, adyen_webhook_status): (bool, AdyenWebhookStatus),
) -> Result<Self, Self::Error> {
match adyen_webhook_status {
AdyenWebhookStatus::Authorised | AdyenWebhookStatus::AdjustedAuthorization => {
match is_manual_capture {
true => Ok(Self::Authorized),
// In case of Automatic capture Authorized is the final status of the payment
false => Ok(Self::Charged),
}
}
AdyenWebhookStatus::AuthorisationFailed
| AdyenWebhookStatus::AdjustAuthorizationFailed => Ok(Self::Failure),
AdyenWebhookStatus::Cancelled => Ok(Self::Voided),
AdyenWebhookStatus::CancelFailed => Ok(Self::VoidFailed),
AdyenWebhookStatus::Captured => Ok(Self::Charged),
AdyenWebhookStatus::CaptureFailed => Ok(Self::CaptureFailed),
AdyenWebhookStatus::Expired => Ok(Self::Expired),
//If Unexpected Event is received, need to understand how it reached this point
//Webhooks with Payment Events only should try to conume this resource object.
AdyenWebhookStatus::UnexpectedEvent | AdyenWebhookStatus::Reversed => {
Err(report!(errors::ConnectorError::WebhookBodyDecodingFailed))
}
}
}
}
#[derive(Debug, Serialize, Deserialize, Eq, PartialEq)]
pub struct AdyenRedirectRequest {
pub details: AdyenRedirectRequestTypes,
}
#[derive(Debug, Clone, Serialize, serde::Deserialize, Eq, PartialEq)]
#[serde(untagged)]
pub enum AdyenRedirectRequestTypes {
AdyenRedirection(AdyenRedirection),
AdyenThreeDS(AdyenThreeDS),
AdyenRefusal(AdyenRefusal),
}
#[derive(Debug, Clone, Serialize, serde::Deserialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct AdyenRefusal {
pub payload: String,
#[serde(rename = "type")]
pub type_of_redirection_result: Option<String>,
pub result_code: Option<String>,
}
#[derive(Debug, Clone, Serialize, serde::Deserialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct AdyenRedirection {
pub redirect_result: String,
#[serde(rename = "type")]
pub type_of_redirection_result: Option<String>,
pub result_code: Option<String>,
}
#[derive(Debug, Clone, Serialize, serde::Deserialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct AdyenThreeDS {
#[serde(rename = "threeDSResult")]
pub three_ds_result: String,
#[serde(rename = "type")]
pub type_of_redirection_result: Option<String>,
pub result_code: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(untagged)]
pub enum AdyenPaymentResponse {
Response(Box<AdyenResponse>),
PresentToShopper(Box<PresentToShopperResponse>),
QrCodeResponse(Box<QrCodeResponseResponse>),
RedirectionResponse(Box<RedirectionResponse>),
RedirectionErrorResponse(Box<RedirectionErrorResponse>),
WebhookResponse(Box<AdyenWebhookResponse>),
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AdyenResponse {
psp_reference: String,
result_code: AdyenStatus,
amount: Option<Amount>,
merchant_reference: String,
refusal_reason: Option<String>,
refusal_reason_code: Option<String>,
additional_data: Option<AdditionalData>,
splits: Option<Vec<AdyenSplitData>>,
store: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum AdyenWebhookStatus {
Authorised,
AuthorisationFailed,
Cancelled,
CancelFailed,
Captured,
CaptureFailed,
Reversed,
UnexpectedEvent,
Expired,
AdjustedAuthorization,
AdjustAuthorizationFailed,
}
//Creating custom struct which can be consumed in Psync Handler triggered from Webhooks
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AdyenWebhookResponse {
transaction_id: String,
payment_reference: Option<String>,
status: AdyenWebhookStatus,
amount: Option<Amount>,
merchant_reference_id: String,
refusal_reason: Option<String>,
refusal_reason_code: Option<String>,
event_code: WebhookEventCode,
#[serde(with = "common_utils::custom_serde::iso8601::option")]
event_date: Option<PrimitiveDateTime>,
// Raw acquirer refusal code
refusal_code_raw: Option<String>,
// Raw acquirer refusal reason
refusal_reason_raw: Option<String>,
recurring_detail_reference: Option<Secret<String>>,
recurring_shopper_reference: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RedirectionErrorResponse {
result_code: AdyenStatus,
refusal_reason: Option<String>,
psp_reference: Option<String>,
merchant_reference: Option<String>,
additional_data: Option<AdditionalData>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RedirectionResponse {
result_code: AdyenStatus,
action: AdyenRedirectAction,
amount: Option<Amount>,
refusal_reason: Option<String>,
refusal_reason_code: Option<String>,
psp_reference: Option<String>,
merchant_reference: Option<String>,
store: Option<String>,
splits: Option<Vec<AdyenSplitData>>,
additional_data: Option<AdditionalData>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PresentToShopperResponse {
psp_reference: Option<String>,
result_code: AdyenStatus,
action: AdyenPtsAction,
amount: Option<Amount>,
refusal_reason: Option<String>,
refusal_reason_code: Option<String>,
merchant_reference: Option<String>,
store: Option<String>,
splits: Option<Vec<AdyenSplitData>>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct QrCodeResponseResponse {
result_code: AdyenStatus,
action: AdyenQrCodeAction,
amount: Option<Amount>,
refusal_reason: Option<String>,
refusal_reason_code: Option<String>,
additional_data: Option<QrCodeAdditionalData>,
psp_reference: Option<String>,
merchant_reference: Option<String>,
store: Option<String>,
splits: Option<Vec<AdyenSplitData>>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AdyenQrCodeAction {
payment_method_type: PaymentType,
#[serde(rename = "type")]
type_of_response: ActionType,
#[serde(rename = "url")]
qr_code_url: Option<Url>,
qr_code_data: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QrCodeAdditionalData {
#[serde(rename = "pix.expirationDate")]
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pix_expiration_date: Option<PrimitiveDateTime>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AdyenPtsAction {
reference: String,
download_url: Option<Url>,
payment_method_type: PaymentType,
#[serde(rename = "expiresAt")]
#[serde(
default,
with = "common_utils::custom_serde::iso8601::option_without_timezone"
)]
expires_at: Option<PrimitiveDateTime>,
initial_amount: Option<Amount>,
pass_creation_token: Option<String>,
total_amount: Option<Amount>,
#[serde(rename = "type")]
type_of_response: ActionType,
instructions_url: Option<Url>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AdyenRedirectAction {
payment_method_type: PaymentType,
url: Option<Url>,
method: Option<Method>,
#[serde(rename = "type")]
type_of_response: ActionType,
data: Option<std::collections::HashMap<String, String>>,
payment_data: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ActionType {
Redirect,
Await,
#[serde(rename = "qrCode")]
QrCode,
Voucher,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct Amount {
pub currency: storage_enums::Currency,
pub value: MinorUnit,
}
#[derive(Debug, Clone, Serialize)]
#[serde(untagged)]
pub enum PaymentMethod<'a> {
AdyenPaymentMethod(Box<AdyenPaymentMethod<'a>>),
AdyenMandatePaymentMethod(Box<AdyenMandate>),
}
#[derive(Debug, Clone, Serialize)]
#[serde(tag = "type")]
#[serde(rename_all = "lowercase")]
pub enum AdyenPaymentMethod<'a> {
#[serde(rename = "affirm")]
AdyenAffirm,
#[serde(rename = "scheme")]
AdyenCard(Box<AdyenCard>),
#[serde(rename = "klarna")]
AdyenKlarna,
#[serde(rename = "paypal")]
AdyenPaypal,
#[serde(rename = "networkToken")]
AdyenPaze(Box<AdyenPazeData>),
#[serde(rename = "afterpaytouch")]
AfterPay,
#[serde(rename = "alma")]
AlmaPayLater,
AliPay,
#[serde(rename = "alipay_hk")]
AliPayHk,
ApplePay(Box<AdyenApplePay>),
ApplePayDecrypt(Box<AdyenApplePayDecryptData>),
Atome,
#[serde(rename = "scheme")]
BancontactCard(Box<AdyenCard>),
Bizum,
Blik(Box<BlikRedirectionData>),
#[serde(rename = "boletobancario")]
BoletoBancario,
#[serde(rename = "clearpay")]
ClearPay,
#[serde(rename = "dana")]
Dana,
Eps(Box<BankRedirectionWithIssuer<'a>>),
#[serde(rename = "gcash")]
Gcash(Box<GcashData>),
#[serde(rename = "googlepay")]
Gpay(Box<AdyenGPay>),
#[serde(rename = "gopay_wallet")]
GoPay(Box<GoPayData>),
Ideal,
#[serde(rename = "kakaopay")]
Kakaopay(Box<KakaoPayData>),
Mbway(Box<MbwayData>),
MobilePay,
#[serde(rename = "momo_wallet")]
Momo(Box<MomoData>),
#[serde(rename = "momo_atm")]
MomoAtm,
#[serde(rename = "touchngo")]
TouchNGo(Box<TouchNGoData>),
#[serde(rename = "onlineBanking_CZ")]
OnlineBankingCzechRepublic(Box<OnlineBankingCzechRepublicData>),
#[serde(rename = "ebanking_FI")]
OnlineBankingFinland,
#[serde(rename = "onlineBanking_PL")]
OnlineBankingPoland(Box<OnlineBankingPolandData>),
#[serde(rename = "onlineBanking_SK")]
OnlineBankingSlovakia(Box<OnlineBankingSlovakiaData>),
#[serde(rename = "molpay_ebanking_fpx_MY")]
OnlineBankingFpx(Box<OnlineBankingFpxData>),
#[serde(rename = "molpay_ebanking_TH")]
OnlineBankingThailand(Box<OnlineBankingThailandData>),
#[serde(rename = "paybybank")]
OpenBankingUK(Box<OpenBankingUKData>),
#[serde(rename = "oxxo")]
Oxxo,
#[serde(rename = "paysafecard")]
PaySafeCard,
#[serde(rename = "paybright")]
PayBright,
#[serde(rename = "doku_permata_lite_atm")]
PermataBankTransfer(Box<DokuBankData>),
#[serde(rename = "trustly")]
Trustly,
#[serde(rename = "walley")]
Walley,
#[serde(rename = "wechatpayWeb")]
WeChatPayWeb,
#[serde(rename = "ach")]
AchDirectDebit(Box<AchDirectDebitData>),
#[serde(rename = "sepadirectdebit")]
SepaDirectDebit(Box<SepaDirectDebitData>),
#[serde(rename = "directdebit_GB")]
BacsDirectDebit(Box<BacsDirectDebitData>),
SamsungPay(Box<SamsungPayPmData>),
#[serde(rename = "doku_bca_va")]
BcaBankTransfer(Box<DokuBankData>),
#[serde(rename = "doku_bni_va")]
BniVa(Box<DokuBankData>),
#[serde(rename = "doku_bri_va")]
BriVa(Box<DokuBankData>),
#[serde(rename = "doku_cimb_va")]
CimbVa(Box<DokuBankData>),
#[serde(rename = "doku_danamon_va")]
DanamonVa(Box<DokuBankData>),
#[serde(rename = "doku_mandiri_va")]
MandiriVa(Box<DokuBankData>),
#[serde(rename = "twint")]
Twint,
#[serde(rename = "vipps")]
Vipps,
#[serde(rename = "doku_indomaret")]
Indomaret(Box<DokuBankData>),
#[serde(rename = "doku_alfamart")]
Alfamart(Box<DokuBankData>),
#[serde(rename = "givex")]
PaymentMethodBalance(Box<BalancePmData>),
#[serde(rename = "giftcard")]
AdyenGiftCard(Box<AdyenGiftCardData>),
#[serde(rename = "swish")]
Swish,
#[serde(rename = "benefit")]
Benefit,
#[serde(rename = "knet")]
Knet,
#[serde(rename = "econtext_seven_eleven")]
SevenEleven(Box<JCSVoucherData>),
#[serde(rename = "econtext_stores")]
JapaneseConvenienceStores(Box<JCSVoucherData>),
Pix,
#[serde(rename = "networkToken")]
NetworkToken(Box<AdyenNetworkTokenData>),
}
#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct JCSVoucherData {
first_name: Secret<String>,
last_name: Option<Secret<String>>,
shopper_email: Email,
telephone_number: Secret<String>,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BalancePmData {
number: Secret<String>,
cvc: Secret<String>,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AdyenGiftCardData {
brand: GiftCardBrand,
number: Secret<String>,
cvc: Secret<String>,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AchDirectDebitData {
bank_account_number: Secret<String>,
bank_location_id: Secret<String>,
owner_name: Secret<String>,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SepaDirectDebitData {
#[serde(rename = "sepa.ownerName")]
owner_name: Secret<String>,
#[serde(rename = "sepa.ibanNumber")]
iban_number: Secret<String>,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BacsDirectDebitData {
bank_account_number: Secret<String>,
bank_location_id: Secret<String>,
holder_name: Secret<String>,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MbwayData {
telephone_number: Secret<String>,
}
#[derive(Debug, Clone, Serialize)]
pub struct SamsungPayPmData {
#[serde(rename = "samsungPayToken")]
samsung_pay_token: Secret<String>,
}
#[derive(Debug, Clone, Serialize)]
pub struct OnlineBankingCzechRepublicData {
issuer: OnlineBankingCzechRepublicBanks,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum OnlineBankingCzechRepublicBanks {
KB,
CS,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum AdyenPlatformChargeBackBehaviour {
#[serde(alias = "deduct_from_liable_account")]
DeductFromLiableAccount,
#[serde(alias = "deduct_from_one_balance_account")]
DeductFromOneBalanceAccount,
#[serde(alias = "deduct_according_to_split_ratio")]
DeductAccordingToSplitRatio,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AdyenPlatformChargeBackLogicMetadata {
pub behavior: Option<AdyenPlatformChargeBackBehaviour>,
#[serde(alias = "target_account")]
pub target_account: Option<Secret<String>>,
#[serde(alias = "cost_allocation_account")]
pub cost_allocation_account: Option<Secret<String>>,
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
struct AdyenMetadata {
#[serde(alias = "device_fingerprint")]
pub device_fingerprint: Option<Secret<String>>,
pub store: Option<String>,
#[serde(alias = "platform_chargeback_logic")]
pub platform_chargeback_logic: Option<AdyenPlatformChargeBackLogicMetadata>,
}
fn filter_adyen_metadata(metadata: serde_json::Value) -> serde_json::Value {
| 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/coinbase/transformers.rs | crates/hyperswitch_connectors/src/connectors/coinbase/transformers.rs | use std::collections::HashMap;
use common_enums::enums;
use common_utils::{pii, request::Method, types::StringMajorUnit};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
router_data::{ConnectorAuthType, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RedirectForm},
types::{self, PaymentsAuthorizeRouterData},
};
use hyperswitch_interfaces::errors;
use masking::Secret;
use serde::{Deserialize, Serialize};
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{
self, AddressDetailsData, PaymentsAuthorizeRequestData, RouterData as OtherRouterData,
},
};
#[derive(Debug, Serialize)]
pub struct CoinbaseRouterData<T> {
amount: StringMajorUnit,
router_data: T,
}
impl<T> From<(StringMajorUnit, T)> for CoinbaseRouterData<T> {
fn from((amount, item): (StringMajorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
#[derive(Debug, Default, Eq, PartialEq, Serialize)]
pub struct LocalPrice {
pub amount: StringMajorUnit,
pub currency: String,
}
#[derive(Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
pub struct Metadata {
pub customer_id: Option<String>,
pub customer_name: Option<Secret<String>>,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct CoinbasePaymentsRequest {
pub name: Option<Secret<String>>,
pub description: Option<String>,
pub pricing_type: String,
pub local_price: LocalPrice,
pub redirect_url: String,
pub cancel_url: String,
}
impl TryFrom<&CoinbaseRouterData<&PaymentsAuthorizeRouterData>> for CoinbasePaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &CoinbaseRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
get_crypto_specific_payment_data(item)
}
}
// Auth Struct
pub struct CoinbaseAuthType {
pub(super) api_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for CoinbaseAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(_auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
if let ConnectorAuthType::HeaderKey { api_key } = _auth_type {
Ok(Self {
api_key: api_key.to_owned(),
})
} else {
Err(errors::ConnectorError::FailedToObtainAuthType.into())
}
}
}
// PaymentsResponse
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "UPPERCASE")]
pub enum CoinbasePaymentStatus {
New,
#[default]
Pending,
Completed,
Expired,
Unresolved,
Resolved,
Canceled,
#[serde(rename = "PENDING REFUND")]
PendingRefund,
Refunded,
}
impl From<CoinbasePaymentStatus> for enums::AttemptStatus {
fn from(item: CoinbasePaymentStatus) -> Self {
match item {
CoinbasePaymentStatus::Completed | CoinbasePaymentStatus::Resolved => Self::Charged,
CoinbasePaymentStatus::Expired => Self::Failure,
CoinbasePaymentStatus::New => Self::AuthenticationPending,
CoinbasePaymentStatus::Unresolved => Self::Unresolved,
CoinbasePaymentStatus::Canceled => Self::Voided,
_ => Self::Pending,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, strum::Display)]
#[serde(rename_all = "UPPERCASE")]
#[strum(serialize_all = "UPPERCASE")]
pub enum UnResolvedContext {
Underpaid,
Overpaid,
Delayed,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Timeline {
status: CoinbasePaymentStatus,
context: Option<UnResolvedContext>,
time: String,
pub payment: Option<TimelinePayment>,
}
#[derive(Default, Debug, Serialize, Deserialize)]
pub struct CoinbasePaymentsResponse {
// status: CoinbasePaymentStatus,
// id: String,
data: CoinbasePaymentResponseData,
}
impl<F, T> TryFrom<ResponseRouterData<F, CoinbasePaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, CoinbasePaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let form_fields = HashMap::new();
let redirection_data = RedirectForm::Form {
endpoint: item.response.data.hosted_url.to_string(),
method: Method::Get,
form_fields,
};
let timeline = item
.response
.data
.timeline
.last()
.ok_or(errors::ConnectorError::ResponseHandlingFailed)?
.clone();
let connector_id = ResponseId::ConnectorTransactionId(item.response.data.id.clone());
let attempt_status = timeline.status.clone();
let response_data = timeline.context.map_or(
Ok(PaymentsResponseData::TransactionResponse {
resource_id: connector_id.clone(),
redirection_data: Box::new(Some(redirection_data)),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.data.id.clone()),
incremental_authorization_allowed: None,
charges: None,
}),
|context| {
Ok(PaymentsResponseData::TransactionUnresolvedResponse{
resource_id: connector_id,
reason: Some(api_models::enums::UnresolvedResponseReason {
code: context.to_string(),
message: "Please check the transaction in coinbase dashboard and resolve manually"
.to_string(),
}),
connector_response_reference_id: Some(item.response.data.id),
})
},
);
Ok(Self {
status: enums::AttemptStatus::from(attempt_status),
response: response_data,
..item.data
})
}
}
// REFUND :
// Type definition for RefundRequest
#[derive(Default, Debug, Serialize)]
pub struct CoinbaseRefundRequest {}
impl<F> TryFrom<&types::RefundsRouterData<F>> for CoinbaseRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(_item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> {
Err(errors::ConnectorError::NotImplemented("try_from RefundsRouterData".to_string()).into())
}
}
// Type definition for Refund Response
#[allow(dead_code)]
#[derive(Debug, Serialize, Default, Deserialize, Clone)]
pub enum RefundStatus {
Succeeded,
Failed,
#[default]
Processing,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Succeeded => Self::Success,
RefundStatus::Failed => Self::Failure,
RefundStatus::Processing => Self::Pending,
}
}
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct RefundResponse {}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>>
for types::RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
_item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Err(errors::ConnectorError::NotImplemented(
"try_from RefundsResponseRouterData".to_string(),
)
.into())
}
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for types::RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
_item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
Err(errors::ConnectorError::NotImplemented(
"try_from RefundsResponseRouterData".to_string(),
)
.into())
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct CoinbaseErrorData {
#[serde(rename = "type")]
pub error_type: String,
pub message: String,
pub code: Option<String>,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct CoinbaseErrorResponse {
pub error: CoinbaseErrorData,
}
#[derive(Default, Debug, Deserialize, PartialEq)]
pub struct CoinbaseConnectorMeta {
pub pricing_type: String,
}
impl TryFrom<&Option<pii::SecretSerdeValue>> for CoinbaseConnectorMeta {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(meta_data: &Option<pii::SecretSerdeValue>) -> Result<Self, Self::Error> {
utils::to_connector_meta_from_secret(meta_data.clone())
.change_context(errors::ConnectorError::InvalidConnectorConfig { config: "metadata" })
}
}
fn get_crypto_specific_payment_data(
item: &CoinbaseRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<CoinbasePaymentsRequest, error_stack::Report<errors::ConnectorError>> {
let billing_address = item
.router_data
.get_billing()
.ok()
.and_then(|billing_address| billing_address.address.as_ref());
let name =
billing_address.and_then(|add| add.get_first_name().ok().map(|name| name.to_owned()));
let description = item.router_data.get_description().ok();
let connector_meta = CoinbaseConnectorMeta::try_from(&item.router_data.connector_meta_data)
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "Merchant connector account metadata",
})?;
let pricing_type = connector_meta.pricing_type;
let local_price = get_local_price(item);
let redirect_url = item.router_data.request.get_router_return_url()?;
let cancel_url = item.router_data.request.get_router_return_url()?;
Ok(CoinbasePaymentsRequest {
name,
description,
pricing_type,
local_price,
redirect_url,
cancel_url,
})
}
fn get_local_price(item: &CoinbaseRouterData<&PaymentsAuthorizeRouterData>) -> LocalPrice {
LocalPrice {
amount: item.amount.clone(),
currency: item.router_data.request.currency.to_string(),
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct CoinbaseWebhookDetails {
pub attempt_number: i64,
pub event: Event,
pub id: String,
pub scheduled_for: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Event {
pub api_version: String,
pub created_at: String,
pub data: CoinbasePaymentResponseData,
pub id: String,
pub resource: String,
#[serde(rename = "type")]
pub event_type: WebhookEventType,
}
#[derive(Debug, Serialize, Deserialize)]
pub enum WebhookEventType {
#[serde(rename = "charge:confirmed")]
Confirmed,
#[serde(rename = "charge:created")]
Created,
#[serde(rename = "charge:pending")]
Pending,
#[serde(rename = "charge:failed")]
Failed,
#[serde(rename = "charge:resolved")]
Resolved,
#[serde(other)]
Unknown,
}
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct Redirects {
cancel_url: Option<String>,
success_url: Option<String>,
will_redirect_after_success: bool,
}
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct CoinbasePaymentResponseData {
pub id: String,
pub code: String,
pub name: Option<Secret<String>>,
pub utxo: Option<bool>,
pub pricing: HashMap<String, OverpaymentAbsoluteThreshold>,
pub fee_rate: Option<f64>,
pub logo_url: Option<String>,
pub metadata: Option<Metadata>,
pub payments: Vec<PaymentElement>,
pub resource: Option<String>,
pub timeline: Vec<Timeline>,
pub pwcb_only: bool,
pub created_at: String,
pub expires_at: String,
pub hosted_url: String,
pub brand_color: String,
pub description: Option<String>,
pub confirmed_at: Option<String>,
pub fees_settled: Option<bool>,
pub pricing_type: String,
pub redirects: Redirects,
pub support_email: pii::Email,
pub brand_logo_url: String,
pub offchain_eligible: Option<bool>,
pub organization_name: String,
pub payment_threshold: Option<PaymentThreshold>,
pub coinbase_managed_merchant: Option<bool>,
}
#[derive(Debug, Serialize, Default, Deserialize)]
pub struct PaymentThreshold {
pub overpayment_absolute_threshold: OverpaymentAbsoluteThreshold,
pub overpayment_relative_threshold: String,
pub underpayment_absolute_threshold: OverpaymentAbsoluteThreshold,
pub underpayment_relative_threshold: String,
}
#[derive(Debug, Clone, Serialize, Default, Deserialize, PartialEq, Eq)]
pub struct OverpaymentAbsoluteThreshold {
pub amount: StringMajorUnit,
pub currency: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct PaymentElement {
pub net: CoinbaseProcessingFee,
pub block: Block,
pub value: CoinbaseProcessingFee,
pub status: String,
pub network: String,
pub deposited: Deposited,
pub payment_id: String,
pub detected_at: String,
pub transaction_id: String,
pub coinbase_processing_fee: CoinbaseProcessingFee,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Block {
pub hash: Option<String>,
pub height: Option<i64>,
pub confirmations: Option<i64>,
pub confirmations_required: Option<i64>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct CoinbaseProcessingFee {
pub local: Option<OverpaymentAbsoluteThreshold>,
pub crypto: OverpaymentAbsoluteThreshold,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Deposited {
pub amount: Amount,
pub status: String,
pub destination: String,
pub exchange_rate: Option<serde_json::Value>,
pub autoconversion_status: String,
pub autoconversion_enabled: bool,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Amount {
pub net: CoinbaseProcessingFee,
pub gross: CoinbaseProcessingFee,
pub coinbase_fee: CoinbaseProcessingFee,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct TimelinePayment {
pub value: OverpaymentAbsoluteThreshold,
pub network: String,
pub transaction_id: String,
}
| 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/zift/transformers.rs | crates/hyperswitch_connectors/src/connectors/zift/transformers.rs | use api_models::payments::AdditionalPaymentData;
use common_enums::enums;
use common_utils::types::StringMinorUnit;
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{refunds::Execute, PSync},
router_request_types::{
PaymentsAuthorizeData, PaymentsSyncData, ResponseId, SetupMandateRequestData,
},
router_response_types::{MandateReference, PaymentsResponseData, RefundsResponseData},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsSyncRouterData, RefundsRouterData, SetupMandateRouterData,
},
};
use hyperswitch_interfaces::{
consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE},
errors,
};
use masking::Secret;
use serde::{Deserialize, Serialize};
use crate::{
types::{
PaymentsCancelResponseRouterData, PaymentsCaptureResponseRouterData,
RefundsResponseRouterData, ResponseRouterData,
},
utils::{AdditionalCardInfo, CardData, PaymentsAuthorizeRequestData, RouterData as _},
};
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ZiftAuthType {
user_name: Secret<String>,
password: Secret<String>,
account_id: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for ZiftAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
if let ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} = auth_type
{
Ok(Self {
user_name: api_key.to_owned(),
password: api_secret.to_owned(),
account_id: key1.to_owned(),
})
} else {
Err(errors::ConnectorError::FailedToObtainAuthType.into())
}
}
}
pub struct ZiftRouterData<T> {
pub amount: StringMinorUnit,
pub router_data: T,
}
impl<T> From<(StringMinorUnit, T)> for ZiftRouterData<T> {
fn from((amount, item): (StringMinorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum RequestType {
Sale,
#[serde(rename = "sale-auth")]
Auth,
Capture,
Refund,
Find,
Void,
#[serde(rename = "account-verification")]
AccountVerification,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum PaymentRequestType {
Sale,
#[serde(rename = "sale-auth")]
Auth,
Capture,
}
#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq)]
pub enum AccountType {
#[serde(rename = "R")]
PaymentCard,
#[serde(rename = "S")]
Savings,
#[serde(rename = "C")]
Checking,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum TransactionIndustryType {
#[serde(rename = "DM")]
CardNotPresent,
#[serde(rename = "RE")]
CardPresent,
#[serde(rename = "RS")]
Restaurant,
#[serde(rename = "LD")]
Lodging,
#[serde(rename = "PT")]
Petroleum,
#[serde(rename = "EC")]
Ecommerce,
}
#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq)]
pub enum HolderType {
#[serde(rename = "P")]
Personal,
#[serde(rename = "O")]
Organizational,
}
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum ZiftPaymentsRequest {
Card(ZiftCardPaymentRequest),
Mandate(ZiftMandatePaymentRequest),
ExternalThreeDs(ZiftExternalThreeDsPaymentRequest),
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ZiftCardPaymentRequest {
request_type: RequestType,
#[serde(flatten)]
auth: ZiftAuthType,
account_type: AccountType,
account_number: cards::CardNumber,
account_accessory: Secret<String>,
transaction_code: String,
csc: Secret<String>,
transaction_industry_type: TransactionIndustryType,
transaction_category_code: TransactionCategoryCode,
holder_name: Secret<String>,
holder_type: HolderType,
amount: StringMinorUnit,
//Billing address fields are intentionally not passed to Zift.As confirmed by the Zift connector team, billing-related parameters must not be sent in payment or mandate requests. Passing billing address details was causing transaction failures in production. To ensure successful processing and alignment with Zift’s API expectations, all billing address fields have been removed.
}
// Mandate payment (MIT - Merchant Initiated)
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ZiftMandatePaymentRequest {
request_type: RequestType,
#[serde(flatten)]
auth: ZiftAuthType,
account_type: AccountType,
token: Secret<String>,
account_accessory: Secret<String>,
// NO csc for MIT payments
transaction_industry_type: TransactionIndustryType,
transaction_category_code: TransactionCategoryCode,
holder_name: Secret<String>,
holder_type: HolderType,
amount: StringMinorUnit,
transaction_mode_type: TransactionModeType,
transaction_code: String,
// Required for MIT
transaction_category_type: TransactionCategoryType,
sequence_number: i32,
//Billing address fields are intentionally not passed to Zift.As confirmed by the Zift connector team, billing-related parameters must not be sent in payment or mandate requests. Passing billing address details was causing transaction failures in production. To ensure successful processing and alignment with Zift’s API expectations, all billing address fields have been removed.
}
// External 3DS payment request
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ZiftExternalThreeDsPaymentRequest {
request_type: RequestType,
#[serde(flatten)]
auth: ZiftAuthType,
account_type: AccountType,
account_number: cards::CardNumber,
account_accessory: Secret<String>,
transaction_industry_type: TransactionIndustryType,
transaction_category_code: TransactionCategoryCode,
holder_name: Secret<String>,
holder_type: HolderType,
transaction_code: String,
amount: StringMinorUnit,
// 3DS authentication fields
authentication_status: AuthenticationStatus,
#[serde(skip_serializing_if = "Option::is_none")]
authentication_code: Option<Secret<String>>,
authentication_verification_value: Secret<String>,
#[serde(skip_serializing_if = "Option::is_none")]
authentication_version: Option<Secret<String>>,
}
#[derive(Debug, Serialize)]
pub enum AuthenticationStatus {
#[serde(rename = "Y")]
Success,
#[serde(rename = "A")]
Attempted,
#[serde(rename = "U")]
Unavailable,
}
impl TryFrom<&hyperswitch_domain_models::router_request_types::AuthenticationData>
for AuthenticationStatus
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
auth_data: &hyperswitch_domain_models::router_request_types::AuthenticationData,
) -> Result<Self, Self::Error> {
// Map authentication status based on trans_status field
let authentication_status = match auth_data.transaction_status {
Some(common_enums::TransactionStatus::Success) => Self::Success,
Some(common_enums::TransactionStatus::NotVerified) => Self::Attempted,
Some(common_enums::TransactionStatus::VerificationNotPerformed)
| Some(common_enums::TransactionStatus::Rejected)
| Some(common_enums::TransactionStatus::InformationOnly)
| Some(common_enums::TransactionStatus::Failure)
| Some(common_enums::TransactionStatus::ChallengeRequired)
| Some(common_enums::TransactionStatus::ChallengeRequiredDecoupledAuthentication)
| None => Self::Unavailable,
};
Ok(authentication_status)
}
}
#[derive(Debug, Serialize)]
pub enum TransactionModeType {
#[serde(rename = "P")]
CardPresent,
#[serde(rename = "N")]
CardNotPresent,
}
#[derive(Debug, Serialize)]
pub enum TransactionCategoryType {
#[serde(rename = "R")]
Recurring,
#[serde(rename = "I")]
Installment,
#[serde(rename = "B")]
BillPayment,
}
#[derive(Debug, Serialize)]
pub enum TransactionCategoryCode {
#[serde(rename = "EC")]
Ecommerce,
}
impl TryFrom<&ZiftRouterData<&PaymentsAuthorizeRouterData>> for ZiftPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &ZiftRouterData<&PaymentsAuthorizeRouterData>) -> Result<Self, Self::Error> {
let auth = ZiftAuthType::try_from(&item.router_data.connector_auth_type)?;
let request_type = if item.router_data.request.is_auto_capture()? {
RequestType::Sale
} else {
RequestType::Auth
};
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(card) => {
if item.router_data.is_three_ds()
&& item.router_data.request.authentication_data.is_none()
{
Err(errors::ConnectorError::NotSupported {
message: "3DS flow".to_string(),
connector: "Zift",
}
.into())
}
// Check if this is an external 3DS payment - both is_three_ds() and authentication_data must be present
else if item.router_data.is_three_ds()
&& item.router_data.request.authentication_data.is_some()
{
// Handle external 3DS authentication
let auth_data = item
.router_data
.request
.authentication_data
.as_ref()
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "authentication_data",
})?;
let authentication_status = AuthenticationStatus::try_from(auth_data)?;
let external_3ds_request = ZiftExternalThreeDsPaymentRequest {
request_type,
auth,
account_number: card.card_number.clone(),
account_accessory: card.get_expiry_date_as_mmyy()?,
transaction_industry_type: TransactionIndustryType::Ecommerce,
transaction_category_code: TransactionCategoryCode::Ecommerce,
holder_name: item.router_data.get_billing_full_name()?,
amount: item.amount.to_owned(),
account_type: AccountType::PaymentCard,
holder_type: HolderType::Personal,
authentication_status,
authentication_code: auth_data.ds_trans_id.clone().map(Secret::new),
authentication_verification_value: auth_data.cavv.clone(),
authentication_version: auth_data
.message_version
.as_ref()
.map(|v| Secret::new(v.to_string())),
transaction_code: item.router_data.connector_request_reference_id.clone(),
};
Ok(Self::ExternalThreeDs(external_3ds_request))
} else {
let card_request = ZiftCardPaymentRequest {
request_type,
auth,
account_number: card.card_number.clone(),
account_accessory: card.get_expiry_date_as_mmyy()?,
transaction_industry_type: TransactionIndustryType::Ecommerce,
transaction_category_code: TransactionCategoryCode::Ecommerce,
holder_name: item.router_data.get_billing_full_name()?,
amount: item.amount.to_owned(),
account_type: AccountType::PaymentCard,
holder_type: HolderType::Personal,
csc: card.card_cvc,
transaction_code: item.router_data.connector_request_reference_id.clone(),
};
Ok(Self::Card(card_request))
}
}
PaymentMethodData::MandatePayment => {
let additional_card_details = match item
.router_data
.request
.additional_payment_method_data
.clone()
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "additional_payment_method_data",
})? {
AdditionalPaymentData::Card(card) => *card,
_ => Err(errors::ConnectorError::NotSupported {
message: "Payment Method Not Supported".to_string(),
connector: "Zift",
})?,
};
let mandate_request = ZiftMandatePaymentRequest {
request_type,
auth,
account_type: AccountType::PaymentCard,
token: Secret::new(item.router_data.request.connector_mandate_id().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "connector_mandate_id",
},
)?),
account_accessory: additional_card_details.get_expiry_date_as_mmyy()?,
transaction_industry_type: TransactionIndustryType::Ecommerce,
transaction_category_code: TransactionCategoryCode::Ecommerce,
holder_name: additional_card_details.get_card_holder_name()?,
holder_type: HolderType::Personal,
amount: item.amount.to_owned(),
transaction_mode_type: TransactionModeType::CardNotPresent,
transaction_category_type: TransactionCategoryType::Recurring,
sequence_number: 2, // Its required for MIT
transaction_code: item.router_data.connector_request_reference_id.clone(),
};
Ok(Self::Mandate(mandate_request))
}
_ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()),
}
}
}
pub trait ResponseCodeExt {
fn is_pending(&self) -> bool;
fn is_approved(&self) -> bool;
fn is_failed(&self) -> bool;
}
impl ResponseCodeExt for String {
fn is_pending(&self) -> bool {
self == "X02"
}
fn is_approved(&self) -> bool {
self.starts_with('A')
}
fn is_failed(&self) -> bool {
!(self.is_approved() || self.is_pending())
}
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ZiftErrorResponse {
pub response_code: String,
pub response_message: String,
pub failure_code: String,
pub failure_message: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ZiftAuthPaymentsResponse {
pub response_code: String,
pub response_message: String,
pub transaction_id: Option<i64>,
pub transaction_code: Option<String>,
pub token: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ZiftCaptureResponse {
pub response_code: String,
pub response_message: String,
}
impl TryFrom<PaymentsCaptureResponseRouterData<ZiftCaptureResponse>> for PaymentsCaptureRouterData {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsCaptureResponseRouterData<ZiftCaptureResponse>,
) -> Result<Self, Self::Error> {
let capture_response = &item.response;
match capture_response.response_code.is_approved() {
true => Ok(Self {
status: common_enums::AttemptStatus::Charged,
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
}),
false => Ok(Self {
status: common_enums::AttemptStatus::CaptureFailed,
response: Err(ErrorResponse {
code: capture_response.response_code.clone(),
message: capture_response.response_message.clone(),
reason: Some(capture_response.response_message.clone()),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
}),
}
}
}
impl<F>
TryFrom<
ResponseRouterData<
F,
ZiftAuthPaymentsResponse,
PaymentsAuthorizeData,
PaymentsResponseData,
>,
> for RouterData<F, PaymentsAuthorizeData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
ZiftAuthPaymentsResponse,
PaymentsAuthorizeData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let status = if item.response.response_code.is_approved() {
if item.data.request.is_auto_capture()? {
common_enums::AttemptStatus::Charged
} else {
common_enums::AttemptStatus::Authorized
}
} else if item.response.response_code.is_pending() {
common_enums::AttemptStatus::Pending
} else {
common_enums::AttemptStatus::Failure
};
if status != common_enums::AttemptStatus::Failure {
let mandate_reference: Box<Option<MandateReference>> =
if item.data.request.is_customer_initiated_mandate_payment() {
Box::new(item.response.token.clone().map(|token| MandateReference {
connector_mandate_id: Some(token),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
}))
} else {
Box::new(None)
};
let transaction_id = item.response.transaction_id.ok_or_else(|| {
errors::ConnectorError::MissingRequiredField {
field_name: "transaction_id",
}
})?;
Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(transaction_id.to_string()),
redirection_data: Box::new(None),
mandate_reference,
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: item.response.transaction_code.clone(),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
} else {
Ok(Self {
status: common_enums::AttemptStatus::Failure,
response: Err(ErrorResponse {
code: item.response.response_code.clone(),
message: item.response.response_message.clone(),
reason: Some(item.response.response_message.clone()),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: item.response.transaction_id.map(|id| id.to_string()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
})
}
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ZiftRefundRequest {
request_type: RequestType,
#[serde(flatten)]
auth: ZiftAuthType,
transaction_id: String,
amount: StringMinorUnit,
transaction_code: String,
}
impl<F> TryFrom<&ZiftRouterData<&RefundsRouterData<F>>> for ZiftRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &ZiftRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
let auth = ZiftAuthType::try_from(&item.router_data.connector_auth_type)?;
Ok(Self {
request_type: RequestType::Refund,
auth,
transaction_id: item.router_data.request.connector_transaction_id.clone(),
amount: item.amount.to_owned(),
transaction_code: item.router_data.request.refund_id.clone(),
})
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RefundResponse {
transaction_id: Option<String>,
response_code: String,
response_message: Option<String>,
transaction_code: Option<String>,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
let refund_response = &item.response;
let refund_status = if refund_response.response_code.is_approved() {
enums::RefundStatus::Success
} else if refund_response.response_code.is_pending() {
enums::RefundStatus::Pending
} else {
enums::RefundStatus::Failure
};
let response = if refund_response.response_code.is_approved() {
Ok(RefundsResponseData {
connector_refund_id: item
.response
.transaction_id
.clone()
.or(item.response.transaction_code.clone())
.ok_or(errors::ConnectorError::MissingConnectorRefundID)?,
refund_status,
})
} else {
Err(ErrorResponse {
code: refund_response.response_code.clone(),
message: refund_response
.response_message
.clone()
.unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()),
reason: refund_response.response_message.clone(),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
};
Ok(Self {
response,
..item.data
})
}
}
// impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> {
// type Error = error_stack::Report<errors::ConnectorError>;
// fn try_from(
// item: RefundsResponseRouterData<RSync, RefundResponse>,
// ) -> Result<Self, Self::Error> {
// Ok(Self {
// response: Ok(RefundsResponseData {
// connector_refund_id: item.response.transaction_id.to_string(),
// refund_status: enums::RefundStatus::from(item.response.response_code),
// }),
// ..item.data
// })
// }
// }
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum TransactionStatus {
#[serde(rename = "N")]
Pending,
#[serde(rename = "P")]
Processed,
#[serde(rename = "C")]
Cancelled,
#[serde(rename = "R")]
InRebill,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ZiftSyncRequest {
request_type: RequestType,
#[serde(flatten)]
auth: ZiftAuthType,
transaction_id: i64,
}
impl TryFrom<&PaymentsSyncRouterData> for ZiftSyncRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsSyncRouterData) -> Result<Self, Self::Error> {
let auth = ZiftAuthType::try_from(&item.connector_auth_type)?;
let transaction_id = item
.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
Ok(Self {
request_type: RequestType::Find,
auth,
transaction_id: transaction_id
.parse::<i64>()
.map_err(|_| errors::ConnectorError::ResponseDeserializationFailed)?,
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ZiftSyncResponse {
pub transaction_status: TransactionStatus,
pub transaction_type: PaymentRequestType,
pub response_message: Option<String>,
pub response_code: Option<String>,
}
impl TryFrom<ResponseRouterData<PSync, ZiftSyncResponse, PaymentsSyncData, PaymentsResponseData>>
for RouterData<PSync, PaymentsSyncData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<PSync, ZiftSyncResponse, PaymentsSyncData, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let attempt_status = match item.response.transaction_type {
// Sale transactions
PaymentRequestType::Sale => match item.response.transaction_status {
TransactionStatus::Processed => common_enums::AttemptStatus::Charged,
TransactionStatus::Pending | TransactionStatus::InRebill => {
common_enums::AttemptStatus::Pending
}
TransactionStatus::Cancelled => common_enums::AttemptStatus::Failure,
},
// Auth transactions (sale-auth)
PaymentRequestType::Auth => match item.response.transaction_status {
TransactionStatus::Processed => common_enums::AttemptStatus::Authorized,
TransactionStatus::Pending | TransactionStatus::InRebill => {
common_enums::AttemptStatus::Pending
}
TransactionStatus::Cancelled => common_enums::AttemptStatus::Failure,
},
// Capture transactions
PaymentRequestType::Capture => match item.response.transaction_status {
TransactionStatus::Processed => common_enums::AttemptStatus::Charged,
TransactionStatus::Pending | TransactionStatus::InRebill => {
common_enums::AttemptStatus::CaptureInitiated
}
TransactionStatus::Cancelled => common_enums::AttemptStatus::CaptureFailed,
},
};
let response = if attempt_status == common_enums::AttemptStatus::Failure {
Err(ErrorResponse {
code: item
.response
.response_code
.clone()
.unwrap_or_else(|| NO_ERROR_CODE.to_string()),
message: item
.response
.response_message
.clone()
.unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()),
reason: item.response.response_message,
status_code: item.http_code,
attempt_status: Some(attempt_status),
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
})
};
Ok(Self {
status: attempt_status,
response,
..item.data
})
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ZiftCaptureRequest {
request_type: RequestType,
#[serde(flatten)]
auth: ZiftAuthType,
transaction_id: i64,
amount: StringMinorUnit,
}
impl TryFrom<&ZiftRouterData<&PaymentsCaptureRouterData>> for ZiftCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &ZiftRouterData<&PaymentsCaptureRouterData>) -> Result<Self, Self::Error> {
let auth = ZiftAuthType::try_from(&item.router_data.connector_auth_type)?;
Ok(Self {
request_type: RequestType::Capture,
auth,
transaction_id: item
.router_data
.request
.connector_transaction_id
.parse::<i64>()
.map_err(|_| errors::ConnectorError::ResponseDeserializationFailed)?,
amount: item.amount.to_owned(),
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ZiftCancelRequest {
request_type: RequestType,
#[serde(flatten)]
auth: ZiftAuthType,
transaction_id: i64,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ZiftVoidResponse {
pub response_code: String,
pub response_message: String,
}
impl TryFrom<&PaymentsCancelRouterData> for ZiftCancelRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> {
let auth = ZiftAuthType::try_from(&item.connector_auth_type)?;
Ok(Self {
request_type: RequestType::Void,
auth,
transaction_id: item
.request
.connector_transaction_id
.parse::<i64>()
.map_err(|_| errors::ConnectorError::ResponseDeserializationFailed)?,
})
}
}
impl TryFrom<PaymentsCancelResponseRouterData<ZiftVoidResponse>> for PaymentsCancelRouterData {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsCancelResponseRouterData<ZiftVoidResponse>,
) -> Result<Self, Self::Error> {
let void_response = &item.response;
let response = if void_response.response_code.is_approved() {
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,
})
} else {
Err(ErrorResponse {
code: void_response.response_code.to_string(),
message: void_response.response_message.clone(),
reason: Some(void_response.response_message.clone()),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: 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/chargebee/transformers.rs | crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs | #[cfg(all(feature = "revenue_recovery", feature = "v2"))]
use std::str::FromStr;
use api_models::subscription as api;
use common_enums::{connector_enums, enums};
use common_utils::{
errors::CustomResult,
ext_traits::ByteSliceExt,
id_type::{CustomerId, InvoiceId, SubscriptionId},
pii::{self, Email},
types::MinorUnit,
};
use error_stack::ResultExt;
#[cfg(all(feature = "revenue_recovery", feature = "v2"))]
use hyperswitch_domain_models::revenue_recovery;
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{ConnectorAuthType, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::{subscriptions::SubscriptionAutoCollection, ResponseId},
router_response_types::{
revenue_recovery::InvoiceRecordBackResponse,
subscriptions::{
self, GetSubscriptionEstimateResponse, GetSubscriptionItemPricesResponse,
GetSubscriptionItemsResponse, SubscriptionCancelResponse, SubscriptionCreateResponse,
SubscriptionInvoiceData, SubscriptionLineItem, SubscriptionPauseResponse,
SubscriptionResumeResponse, SubscriptionStatus,
},
ConnectorCustomerResponseData, PaymentsResponseData, RefundsResponseData,
},
types::{
GetSubscriptionEstimateRouterData, InvoiceRecordBackRouterData,
PaymentsAuthorizeRouterData, RefundsRouterData, SubscriptionCancelRouterData,
SubscriptionPauseRouterData, SubscriptionResumeRouterData,
},
};
use hyperswitch_interfaces::errors;
use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
use crate::{
convert_connector_response_to_domain_response,
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{self, PaymentsAuthorizeRequestData, RouterData as OtherRouterData},
};
// SubscriptionCreate structures
#[derive(Debug, Serialize)]
pub struct ChargebeeSubscriptionCreateRequest {
#[serde(rename = "id")]
pub subscription_id: SubscriptionId,
#[serde(rename = "subscription_items[item_price_id][0]")]
pub item_price_id: String,
#[serde(rename = "subscription_items[quantity][0]")]
pub quantity: Option<u32>,
#[serde(rename = "billing_address[line1]")]
pub billing_address_line1: Option<Secret<String>>,
#[serde(rename = "billing_address[city]")]
pub billing_address_city: Option<String>,
#[serde(rename = "billing_address[state]")]
pub billing_address_state: Option<Secret<String>>,
#[serde(rename = "billing_address[zip]")]
pub billing_address_zip: Option<Secret<String>>,
#[serde(rename = "billing_address[country]")]
pub billing_address_country: Option<common_enums::CountryAlpha2>,
pub auto_collection: ChargebeeAutoCollection,
}
#[derive(Debug, Deserialize, Serialize, Clone)]
#[serde(rename_all = "snake_case")]
pub enum ChargebeeAutoCollection {
On,
Off,
}
impl From<SubscriptionAutoCollection> for ChargebeeAutoCollection {
fn from(auto_collection: SubscriptionAutoCollection) -> Self {
match auto_collection {
SubscriptionAutoCollection::On => Self::On,
SubscriptionAutoCollection::Off => Self::Off,
}
}
}
impl TryFrom<&ChargebeeRouterData<&hyperswitch_domain_models::types::SubscriptionCreateRouterData>>
for ChargebeeSubscriptionCreateRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &ChargebeeRouterData<&hyperswitch_domain_models::types::SubscriptionCreateRouterData>,
) -> Result<Self, Self::Error> {
let req = &item.router_data.request;
let first_item =
req.subscription_items
.first()
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "subscription_items",
})?;
Ok(Self {
subscription_id: req.subscription_id.clone(),
item_price_id: first_item.item_price_id.clone(),
quantity: first_item.quantity,
billing_address_line1: item.router_data.get_optional_billing_line1(),
billing_address_city: item.router_data.get_optional_billing_city(),
billing_address_state: item.router_data.get_optional_billing_state(),
billing_address_zip: item.router_data.get_optional_billing_zip(),
billing_address_country: item.router_data.get_optional_billing_country(),
auto_collection: req.auto_collection.clone().into(),
})
}
}
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct ChargebeeSubscriptionCreateResponse {
pub subscription: ChargebeeSubscriptionDetails,
pub invoice: Option<ChargebeeInvoiceData>,
}
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct ChargebeeSubscriptionDetails {
pub id: SubscriptionId,
pub status: ChargebeeSubscriptionStatus,
pub customer_id: CustomerId,
pub currency_code: enums::Currency,
pub total_dues: Option<MinorUnit>,
#[serde(default, with = "common_utils::custom_serde::timestamp::option")]
pub next_billing_at: Option<PrimitiveDateTime>,
#[serde(default, with = "common_utils::custom_serde::timestamp::option")]
pub created_at: Option<PrimitiveDateTime>,
#[serde(default, with = "common_utils::custom_serde::timestamp::option")]
pub pause_date: Option<PrimitiveDateTime>,
#[serde(default, with = "common_utils::custom_serde::timestamp::option")]
cancelled_at: Option<PrimitiveDateTime>,
}
#[derive(Debug, Deserialize, Serialize, Clone)]
#[serde(rename_all = "snake_case")]
pub enum ChargebeeSubscriptionStatus {
Future,
#[serde(rename = "in_trial")]
InTrial,
Active,
#[serde(rename = "non_renewing")]
NonRenewing,
Paused,
Cancelled,
Transferred,
}
impl From<ChargebeeSubscriptionStatus> for SubscriptionStatus {
fn from(status: ChargebeeSubscriptionStatus) -> Self {
match status {
ChargebeeSubscriptionStatus::Future => Self::Pending,
ChargebeeSubscriptionStatus::InTrial => Self::Trial,
ChargebeeSubscriptionStatus::Active => Self::Active,
ChargebeeSubscriptionStatus::NonRenewing => Self::Onetime,
ChargebeeSubscriptionStatus::Paused => Self::Paused,
ChargebeeSubscriptionStatus::Cancelled => Self::Cancelled,
ChargebeeSubscriptionStatus::Transferred => Self::Cancelled,
}
}
}
convert_connector_response_to_domain_response!(
ChargebeeSubscriptionCreateResponse,
SubscriptionCreateResponse,
|item: ResponseRouterData<_, ChargebeeSubscriptionCreateResponse, _, _>| {
let subscription = &item.response.subscription;
Ok(Self {
response: Ok(SubscriptionCreateResponse {
subscription_id: subscription.id.clone(),
status: subscription.status.clone().into(),
customer_id: subscription.customer_id.clone(),
currency_code: subscription.currency_code,
total_amount: subscription.total_dues.unwrap_or(MinorUnit::new(0)),
next_billing_at: subscription.next_billing_at,
created_at: subscription.created_at,
invoice_details: item.response.invoice.map(SubscriptionInvoiceData::from),
}),
..item.data
})
}
);
//TODO: Fill the struct with respective fields
pub struct ChargebeeRouterData<T> {
pub amount: MinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc.
pub router_data: T,
}
impl<T> From<(MinorUnit, T)> for ChargebeeRouterData<T> {
fn from((amount, item): (MinorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
//TODO: Fill the struct with respective fields
#[derive(Default, Debug, Serialize, PartialEq)]
pub struct ChargebeePaymentsRequest {
amount: MinorUnit,
card: ChargebeeCard,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct ChargebeeCard {
number: cards::CardNumber,
expiry_month: Secret<String>,
expiry_year: Secret<String>,
cvc: Secret<String>,
complete: bool,
}
impl TryFrom<&ChargebeeRouterData<&PaymentsAuthorizeRouterData>> for ChargebeePaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &ChargebeeRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(req_card) => {
let card = ChargebeeCard {
number: req_card.card_number,
expiry_month: req_card.card_exp_month,
expiry_year: req_card.card_exp_year,
cvc: req_card.card_cvc,
complete: item.router_data.request.is_auto_capture()?,
};
Ok(Self {
amount: item.amount,
card,
})
}
_ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()),
}
}
}
// Auth Struct
pub struct ChargebeeAuthType {
pub(super) full_access_key_v1: Secret<String>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct ChargebeeMetadata {
pub(super) site: Secret<String>,
}
impl TryFrom<&Option<pii::SecretSerdeValue>> for ChargebeeMetadata {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(meta_data: &Option<pii::SecretSerdeValue>) -> Result<Self, Self::Error> {
let metadata: Self = utils::to_connector_meta_from_secret::<Self>(meta_data.clone())
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "metadata",
})?;
Ok(metadata)
}
}
impl TryFrom<&ConnectorAuthType> for ChargebeeAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
full_access_key_v1: api_key.clone(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
// PaymentsResponse
//TODO: Append the remaining status flags
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum ChargebeePaymentStatus {
Succeeded,
Failed,
#[default]
Processing,
}
impl From<ChargebeePaymentStatus> for common_enums::AttemptStatus {
fn from(item: ChargebeePaymentStatus) -> Self {
match item {
ChargebeePaymentStatus::Succeeded => Self::Charged,
ChargebeePaymentStatus::Failed => Self::Failure,
ChargebeePaymentStatus::Processing => Self::Authorizing,
}
}
}
//TODO: Fill the struct with respective fields
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ChargebeePaymentsResponse {
status: ChargebeePaymentStatus,
id: String,
}
convert_connector_response_to_domain_response!(
ChargebeePaymentsResponse,
PaymentsResponseData,
|item: ResponseRouterData<_, ChargebeePaymentsResponse, _, _>| {
Ok(Self {
status: common_enums::AttemptStatus::from(item.response.status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
);
//TODO: Fill the struct with respective fields
// REFUND :
// Type definition for RefundRequest
#[derive(Default, Debug, Serialize)]
pub struct ChargebeeRefundRequest {
pub amount: MinorUnit,
}
impl<F> TryFrom<&ChargebeeRouterData<&RefundsRouterData<F>>> for ChargebeeRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &ChargebeeRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.amount.to_owned(),
})
}
}
// Type definition for Refund Response
#[allow(dead_code)]
#[derive(Debug, Serialize, Default, Deserialize, Clone)]
pub enum RefundStatus {
Succeeded,
Failed,
#[default]
Processing,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Succeeded => Self::Success,
RefundStatus::Failed => Self::Failure,
RefundStatus::Processing => Self::Pending,
//TODO: Review mapping
}
}
}
//TODO: Fill the struct with respective fields
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct RefundResponse {
id: String,
status: RefundStatus,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct ChargebeeErrorResponse {
pub api_error_code: String,
pub message: String,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct ChargebeeWebhookBody {
pub content: ChargebeeWebhookContent,
pub event_type: ChargebeeEventType,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct ChargebeeInvoiceBody {
pub content: ChargebeeInvoiceContent,
pub event_type: ChargebeeEventType,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct ChargebeeInvoiceContent {
pub invoice: ChargebeeInvoiceData,
pub subscription: Option<ChargebeeSubscriptionData>,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct ChargebeeWebhookContent {
pub transaction: ChargebeeTransactionData,
pub invoice: ChargebeeInvoiceData,
pub customer: Option<ChargebeeCustomer>,
pub subscription: Option<ChargebeeSubscriptionData>,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct ChargebeeSubscriptionData {
#[serde(default, with = "common_utils::custom_serde::timestamp::option")]
pub current_term_start: Option<PrimitiveDateTime>,
#[serde(default, with = "common_utils::custom_serde::timestamp::option")]
pub next_billing_at: Option<PrimitiveDateTime>,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "snake_case")]
pub enum ChargebeeEventType {
PaymentSucceeded,
PaymentFailed,
InvoiceDeleted,
InvoiceGenerated,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct ChargebeeInvoiceData {
// invoice id
pub id: InvoiceId,
pub total: MinorUnit,
pub currency_code: enums::Currency,
pub status: Option<ChargebeeInvoiceStatus>,
pub billing_address: Option<ChargebeeInvoiceBillingAddress>,
pub linked_payments: Option<Vec<ChargebeeInvoicePayments>>,
pub customer_id: CustomerId,
pub subscription_id: SubscriptionId,
pub first_invoice: Option<bool>,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct ChargebeeInvoicePayments {
pub txn_status: Option<String>,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct ChargebeeTransactionData {
id_at_gateway: Option<String>,
status: ChargebeeTranasactionStatus,
error_code: Option<String>,
error_text: Option<String>,
gateway_account_id: String,
currency_code: enums::Currency,
amount: MinorUnit,
#[serde(default, with = "common_utils::custom_serde::timestamp::option")]
date: Option<PrimitiveDateTime>,
payment_method: ChargebeeTransactionPaymentMethod,
payment_method_details: String,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "snake_case")]
pub enum ChargebeeTransactionPaymentMethod {
Card,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct ChargebeePaymentMethodDetails {
card: ChargebeeCardDetails,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct ChargebeeCardDetails {
funding_type: ChargebeeFundingType,
brand: common_enums::CardNetwork,
iin: String,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "snake_case")]
pub enum ChargebeeFundingType {
Credit,
Debit,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "snake_case")]
pub enum ChargebeeTranasactionStatus {
// Waiting for response from the payment gateway.
InProgress,
// The transaction is successful.
Success,
// Transaction failed.
Failure,
// No response received while trying to charge the card.
Timeout,
// Indicates that a successful payment transaction has failed now due to a late failure notification from the payment gateway,
// typically caused by issues like insufficient funds or a closed bank account.
LateFailure,
// Connection with Gateway got terminated abruptly. So, status of this transaction needs to be resolved manually
NeedsAttention,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct ChargebeeCustomer {
pub payment_method: ChargebeePaymentMethod,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct ChargebeeInvoiceBillingAddress {
pub line1: Option<Secret<String>>,
pub line2: Option<Secret<String>>,
pub line3: Option<Secret<String>>,
pub state: Option<Secret<String>>,
pub country: Option<enums::CountryAlpha2>,
pub zip: Option<Secret<String>>,
pub city: Option<String>,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct ChargebeePaymentMethod {
pub reference_id: String,
pub gateway: ChargebeeGateway,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "snake_case")]
pub enum ChargebeeGateway {
Stripe,
Braintree,
}
impl ChargebeeWebhookBody {
pub fn get_webhook_object_from_body(body: &[u8]) -> CustomResult<Self, errors::ConnectorError> {
let webhook_body = body
.parse_struct::<Self>("ChargebeeWebhookBody")
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
Ok(webhook_body)
}
}
impl ChargebeeInvoiceBody {
pub fn get_invoice_webhook_data_from_body(
body: &[u8],
) -> CustomResult<Self, errors::ConnectorError> {
let webhook_body = body
.parse_struct::<Self>("ChargebeeInvoiceBody")
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
Ok(webhook_body)
}
}
// Structure to extract MIT payment data from invoice_generated webhook
#[derive(Debug, Clone)]
pub struct ChargebeeMitPaymentData {
pub invoice_id: InvoiceId,
pub amount_due: MinorUnit,
pub currency_code: enums::Currency,
pub status: Option<ChargebeeInvoiceStatus>,
pub customer_id: CustomerId,
pub subscription_id: SubscriptionId,
pub first_invoice: bool,
}
impl TryFrom<ChargebeeInvoiceBody> for ChargebeeMitPaymentData {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(webhook_body: ChargebeeInvoiceBody) -> Result<Self, Self::Error> {
let invoice = webhook_body.content.invoice;
Ok(Self {
invoice_id: invoice.id,
amount_due: invoice.total,
currency_code: invoice.currency_code,
status: invoice.status,
customer_id: invoice.customer_id,
subscription_id: invoice.subscription_id,
first_invoice: invoice.first_invoice.unwrap_or(false),
})
}
}
pub struct ChargebeeMandateDetails {
pub customer_id: String,
pub mandate_id: String,
}
impl ChargebeeCustomer {
// the logic to find connector customer id & mandate id is different for different gateways, reference : https://apidocs.chargebee.com/docs/api/customers?prod_cat_ver=2#customer_payment_method_reference_id .
pub fn find_connector_ids(&self) -> Result<ChargebeeMandateDetails, errors::ConnectorError> {
match self.payment_method.gateway {
ChargebeeGateway::Stripe | ChargebeeGateway::Braintree => {
let mut parts = self.payment_method.reference_id.split('/');
let customer_id = parts
.next()
.ok_or(errors::ConnectorError::WebhookBodyDecodingFailed)?
.to_string();
let mandate_id = parts
.next_back()
.ok_or(errors::ConnectorError::WebhookBodyDecodingFailed)?
.to_string();
Ok(ChargebeeMandateDetails {
customer_id,
mandate_id,
})
}
}
}
}
#[cfg(all(feature = "revenue_recovery", feature = "v2"))]
impl TryFrom<ChargebeeWebhookBody> for revenue_recovery::RevenueRecoveryAttemptData {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: ChargebeeWebhookBody) -> Result<Self, Self::Error> {
let amount = item.content.transaction.amount;
let currency = item.content.transaction.currency_code.to_owned();
let merchant_reference_id = common_utils::id_type::PaymentReferenceId::from_str(
item.content.invoice.id.get_string_repr(),
)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
let connector_transaction_id = item
.content
.transaction
.id_at_gateway
.map(common_utils::types::ConnectorTransactionId::TxnId);
let error_code = item.content.transaction.error_code.clone();
let error_message = item.content.transaction.error_text.clone();
let connector_mandate_details = item
.content
.customer
.as_ref()
.map(|customer| customer.find_connector_ids())
.transpose()?
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "connector_mandate_details",
})?;
let connector_account_reference_id = item.content.transaction.gateway_account_id.clone();
let transaction_created_at = item.content.transaction.date;
let status = enums::AttemptStatus::from(item.content.transaction.status);
let payment_method_type =
enums::PaymentMethod::from(item.content.transaction.payment_method);
let payment_method_details: ChargebeePaymentMethodDetails =
serde_json::from_str(&item.content.transaction.payment_method_details)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
let payment_method_sub_type =
enums::PaymentMethodType::from(payment_method_details.card.funding_type);
// Chargebee retry count will always be less than u16 always. Chargebee can have maximum 12 retry attempts
#[allow(clippy::as_conversions)]
let retry_count = item
.content
.invoice
.linked_payments
.map(|linked_payments| linked_payments.len() as u16);
let invoice_next_billing_time = item
.content
.subscription
.as_ref()
.and_then(|subscription| subscription.next_billing_at);
let invoice_billing_started_at_time = item
.content
.subscription
.as_ref()
.and_then(|subscription| subscription.current_term_start);
Ok(Self {
amount,
currency,
merchant_reference_id,
connector_transaction_id,
error_code,
error_message,
processor_payment_method_token: connector_mandate_details.mandate_id,
connector_customer_id: connector_mandate_details.customer_id,
connector_account_reference_id,
transaction_created_at,
status,
payment_method_type,
payment_method_sub_type,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
retry_count,
invoice_next_billing_time,
invoice_billing_started_at_time,
// This field is none because it is specific to stripebilling.
charge_id: None,
// Need to populate these card info field
card_info: api_models::payments::AdditionalCardInfo {
card_network: Some(payment_method_details.card.brand),
card_isin: Some(payment_method_details.card.iin),
card_issuer: None,
card_type: None,
card_issuing_country: None,
card_issuing_country_code: None,
bank_code: None,
last4: None,
card_extended_bin: None,
card_exp_month: None,
card_exp_year: None,
card_holder_name: None,
payment_checks: None,
authentication_data: None,
is_regulated: None,
signature_network: None,
},
})
}
}
impl From<ChargebeeTranasactionStatus> for enums::AttemptStatus {
fn from(status: ChargebeeTranasactionStatus) -> Self {
match status {
ChargebeeTranasactionStatus::InProgress
| ChargebeeTranasactionStatus::NeedsAttention => Self::Pending,
ChargebeeTranasactionStatus::Success => Self::Charged,
ChargebeeTranasactionStatus::Failure
| ChargebeeTranasactionStatus::Timeout
| ChargebeeTranasactionStatus::LateFailure => Self::Failure,
}
}
}
impl From<ChargebeeTransactionPaymentMethod> for enums::PaymentMethod {
fn from(payment_method: ChargebeeTransactionPaymentMethod) -> Self {
match payment_method {
ChargebeeTransactionPaymentMethod::Card => Self::Card,
}
}
}
impl From<ChargebeeFundingType> for enums::PaymentMethodType {
fn from(funding_type: ChargebeeFundingType) -> Self {
match funding_type {
ChargebeeFundingType::Credit => Self::Credit,
ChargebeeFundingType::Debit => Self::Debit,
}
}
}
#[cfg(all(feature = "revenue_recovery", feature = "v2"))]
impl From<ChargebeeEventType> for api_models::webhooks::IncomingWebhookEvent {
fn from(event: ChargebeeEventType) -> Self {
match event {
ChargebeeEventType::PaymentSucceeded => Self::RecoveryPaymentSuccess,
ChargebeeEventType::PaymentFailed => Self::RecoveryPaymentFailure,
ChargebeeEventType::InvoiceDeleted => Self::RecoveryInvoiceCancel,
ChargebeeEventType::InvoiceGenerated => Self::InvoiceGenerated,
}
}
}
#[cfg(feature = "v1")]
impl From<ChargebeeEventType> for api_models::webhooks::IncomingWebhookEvent {
fn from(event: ChargebeeEventType) -> Self {
match event {
ChargebeeEventType::PaymentSucceeded => Self::PaymentIntentSuccess,
ChargebeeEventType::PaymentFailed => Self::PaymentIntentFailure,
ChargebeeEventType::InvoiceDeleted => Self::EventNotSupported,
ChargebeeEventType::InvoiceGenerated => Self::InvoiceGenerated,
}
}
}
#[cfg(all(feature = "revenue_recovery", feature = "v2"))]
impl TryFrom<ChargebeeInvoiceBody> for revenue_recovery::RevenueRecoveryInvoiceData {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: ChargebeeInvoiceBody) -> Result<Self, Self::Error> {
let merchant_reference_id = common_utils::id_type::PaymentReferenceId::from_str(
item.content.invoice.id.get_string_repr(),
)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
// The retry count will never exceed u16 limit in a billing connector. It can have maximum of 12 in case of charge bee so its ok to suppress this
#[allow(clippy::as_conversions)]
let retry_count = item
.content
.invoice
.linked_payments
.as_ref()
.map(|linked_payments| linked_payments.len() as u16);
let invoice_next_billing_time = item
.content
.subscription
.as_ref()
.and_then(|subscription| subscription.next_billing_at);
let billing_started_at = item
.content
.subscription
.as_ref()
.and_then(|subscription| subscription.current_term_start);
Ok(Self {
amount: item.content.invoice.total,
currency: item.content.invoice.currency_code,
merchant_reference_id,
billing_address: Some(api_models::payments::Address::from(item.content.invoice)),
retry_count,
next_billing_at: invoice_next_billing_time,
billing_started_at,
metadata: None,
// TODO! This field should be handled for billing connnector integrations
enable_partial_authorization: None,
})
}
}
impl From<ChargebeeInvoiceData> for api_models::payments::Address {
fn from(item: ChargebeeInvoiceData) -> Self {
Self {
address: item
.billing_address
.map(api_models::payments::AddressDetails::from),
phone: None,
email: None,
}
}
}
impl From<ChargebeeInvoiceBillingAddress> for api_models::payments::AddressDetails {
fn from(item: ChargebeeInvoiceBillingAddress) -> Self {
Self {
city: item.city,
country: item.country,
state: item.state,
zip: item.zip,
line1: item.line1,
line2: item.line2,
line3: item.line3,
first_name: None,
last_name: None,
origin_zip: None,
}
}
}
#[derive(Debug, Serialize)]
pub struct ChargebeeRecordPaymentRequest {
#[serde(rename = "transaction[amount]")]
pub amount: MinorUnit,
#[serde(rename = "transaction[payment_method]")]
pub payment_method: ChargebeeRecordPaymentMethod,
#[serde(rename = "transaction[id_at_gateway]")]
pub connector_payment_id: Option<String>,
#[serde(rename = "transaction[status]")]
pub status: ChargebeeRecordStatus,
}
#[derive(Debug, Serialize, Clone, Copy)]
#[serde(rename_all = "snake_case")]
pub enum ChargebeeRecordPaymentMethod {
Other,
}
#[derive(Debug, Serialize, Clone, Copy)]
#[serde(rename_all = "snake_case")]
pub enum ChargebeeRecordStatus {
Success,
Failure,
}
impl TryFrom<&ChargebeeRouterData<&InvoiceRecordBackRouterData>> for ChargebeeRecordPaymentRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &ChargebeeRouterData<&InvoiceRecordBackRouterData>,
) -> Result<Self, Self::Error> {
let req = &item.router_data.request;
Ok(Self {
amount: req.amount,
payment_method: ChargebeeRecordPaymentMethod::Other,
connector_payment_id: req
.connector_transaction_id
.as_ref()
.map(|connector_payment_id| connector_payment_id.get_id().to_string()),
status: ChargebeeRecordStatus::try_from(req.attempt_status)?,
})
}
}
impl TryFrom<enums::AttemptStatus> for ChargebeeRecordStatus {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(status: enums::AttemptStatus) -> Result<Self, Self::Error> {
match status {
enums::AttemptStatus::Charged
| enums::AttemptStatus::PartialCharged
| 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/payjustnow/transformers.rs | crates/hyperswitch_connectors/src/connectors/payjustnow/transformers.rs | use common_enums::enums;
use common_utils::{pii, request::Method, types::MinorUnit};
use hyperswitch_domain_models::{
router_data::{ConnectorAuthType, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsSyncRouterData,
RefundsRouterData,
},
};
use hyperswitch_interfaces::errors;
use masking::Secret;
use serde::{Deserialize, Serialize};
use crate::{
types::{self, RefundsResponseRouterData},
utils::{PaymentsAuthorizeRequestData, PaymentsSyncRequestData, RouterData as _},
};
const NO_REFUND_REASON: &str = "No reason provided";
//TODO: Fill the struct with respective fields
pub struct PayjustnowRouterData<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 PayjustnowRouterData<T> {
fn from((amount, item): (MinorUnit, T)) -> Self {
//Todo : use utils to convert the amount to the type of amount that a connector accepts
Self {
amount,
router_data: item,
}
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PayjustnowPaymentsRequest {
#[serde(skip_serializing_if = "Option::is_none")]
request_id: Option<String>,
payjustnow: PayjustnowRequest,
checkout_total_cents: MinorUnit,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PayjustnowRequest {
merchant_order_reference: String,
order_amount_cents: MinorUnit,
#[serde(skip_serializing_if = "Option::is_none")]
order_items: Option<Vec<OrderItem>>,
#[serde(skip_serializing_if = "Option::is_none")]
customer: Option<Customer>,
#[serde(skip_serializing_if = "Option::is_none")]
billing_address: Option<Address>,
#[serde(skip_serializing_if = "Option::is_none")]
shipping_address: Option<Address>,
confirm_redirect_url: String,
cancel_redirect_url: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct OrderItem {
name: String,
sku: String,
quantity: u32,
price_cents: MinorUnit,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Customer {
#[serde(skip_serializing_if = "Option::is_none")]
first_name: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
last_name: Option<Secret<String>>,
email: pii::Email,
#[serde(skip_serializing_if = "Option::is_none")]
phone_number: Option<Secret<String>>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Address {
#[serde(skip_serializing_if = "Option::is_none")]
address_line1: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
address_line2: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
city: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
province: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
postal_code: Option<Secret<String>>,
}
impl Address {
fn is_empty(&self) -> bool {
self.address_line1.is_none()
&& self.address_line2.is_none()
&& self.city.is_none()
&& self.province.is_none()
&& self.postal_code.is_none()
}
}
impl TryFrom<&PayjustnowRouterData<&PaymentsAuthorizeRouterData>> for PayjustnowPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &PayjustnowRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let router_data = item.router_data;
let order_items = router_data
.request
.order_details
.as_ref()
.map(|order_details| {
order_details
.iter()
.map(|order| {
Ok(OrderItem {
name: order.product_name.clone(),
sku: order.product_id.clone().unwrap_or_default(),
quantity: u32::from(order.quantity),
price_cents: order.amount,
})
})
.collect::<Result<Vec<OrderItem>, errors::ConnectorError>>()
})
.transpose()?;
let customer = router_data
.get_optional_billing_email()
.or_else(|| item.router_data.request.email.clone())
.map(|email| Customer {
first_name: router_data.get_optional_billing_first_name(),
last_name: router_data.get_optional_billing_last_name(),
email,
phone_number: router_data.get_optional_billing_phone_number(),
});
let billing_address = {
let addr = Address {
address_line1: router_data.get_optional_billing_line1(),
address_line2: router_data.get_optional_billing_line2(),
city: router_data.get_optional_billing_city(),
province: router_data.get_optional_billing_state(),
postal_code: item.router_data.get_optional_billing_zip(),
};
if addr.is_empty() {
None
} else {
Some(addr)
}
};
let shipping_address = {
let addr = Address {
address_line1: item.router_data.get_optional_shipping_line1(),
address_line2: item.router_data.get_optional_shipping_line2(),
city: item.router_data.get_optional_shipping_city(),
province: item.router_data.get_optional_shipping_state(),
postal_code: item.router_data.get_optional_shipping_zip(),
};
if addr.is_empty() {
None
} else {
Some(addr)
}
};
let router_return_url = item.router_data.request.get_router_return_url()?;
let payjustnow_request = PayjustnowRequest {
merchant_order_reference: item
.router_data
.request
.merchant_order_reference_id
.clone()
.unwrap_or(item.router_data.payment_id.clone()),
order_amount_cents: item.amount,
order_items,
customer,
billing_address,
shipping_address,
confirm_redirect_url: router_return_url.clone(),
cancel_redirect_url: router_return_url,
};
Ok(Self {
request_id: Some(item.router_data.connector_request_reference_id.clone()),
payjustnow: payjustnow_request,
checkout_total_cents: item.amount,
})
}
}
//TODO: Fill the struct with respective fields
// Auth Struct
pub struct PayjustnowAuthType {
pub(super) merchant_account_id: Secret<String>,
pub(super) signing_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for PayjustnowAuthType {
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 {
signing_key: api_key.to_owned(),
merchant_account_id: key1.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
// PaymentsResponse
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct PayjustnowPaymentsResponse {
payment_url: String,
checkout_token: String,
}
impl<F, T>
TryFrom<types::ResponseRouterData<F, PayjustnowPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: types::ResponseRouterData<F, PayjustnowPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let redirection_data = url::Url::parse(&item.response.payment_url.clone())
.ok()
.map(|url| RedirectForm::from((url, Method::Get)));
Ok(Self {
status: enums::AttemptStatus::AuthenticationPending,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.checkout_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, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PayjustnowSyncRequest {
checkout_token: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PayjustnowCancelRequest {
checkout_token: String,
}
impl TryFrom<&PaymentsCancelRouterData> for PayjustnowCancelRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> {
Ok(Self {
checkout_token: item.request.connector_transaction_id.clone(),
})
}
}
impl TryFrom<&PaymentsSyncRouterData> for PayjustnowSyncRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsSyncRouterData) -> Result<Self, Self::Error> {
let checkout_token = item.request.get_connector_transaction_id()?;
Ok(Self { checkout_token })
}
}
impl TryFrom<&RefundsRouterData<RSync>> for PayjustnowSyncRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &RefundsRouterData<RSync>) -> Result<Self, Self::Error> {
Ok(Self {
checkout_token: item.request.connector_transaction_id.clone(),
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PayjustnowCheckoutStatus {
PendingOrder,
PendingPayment,
PaidPendingCallback,
Paid,
CancelledByMerchant,
CancelledByConsumer,
Expired,
}
impl From<PayjustnowCheckoutStatus> for enums::AttemptStatus {
fn from(item: PayjustnowCheckoutStatus) -> Self {
match item {
PayjustnowCheckoutStatus::Paid | PayjustnowCheckoutStatus::PaidPendingCallback => {
Self::Charged
}
PayjustnowCheckoutStatus::PendingOrder | PayjustnowCheckoutStatus::PendingPayment => {
Self::AuthenticationPending
}
PayjustnowCheckoutStatus::CancelledByMerchant
| PayjustnowCheckoutStatus::CancelledByConsumer => Self::Voided,
PayjustnowCheckoutStatus::Expired => Self::Failure,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PayjustnowSyncResponse {
checkout_token: String,
payment_url: Option<String>,
checkout_payment_status: PayjustnowCheckoutStatus,
payment_reference: Option<i64>,
}
impl<F, T> TryFrom<types::ResponseRouterData<F, PayjustnowSyncResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: types::ResponseRouterData<F, PayjustnowSyncResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let status = enums::AttemptStatus::from(item.response.checkout_payment_status);
let redirection_data = item.response.payment_url.and_then(|url_string| {
url::Url::parse(&url_string)
.ok()
.map(|url| RedirectForm::from((url, Method::Get)))
});
Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.checkout_token),
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: item
.response
.payment_reference
.map(|id| id.to_string()),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
//TODO: Fill the struct with respective fields
// REFUND :
// Type definition for RefundRequest
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PayjustnowRefundRequest {
request_id: Option<String>,
checkout_token: String,
merchant_refund_reference: String,
refund_amount_cents: MinorUnit,
refund_description: String,
}
impl<F> TryFrom<&RefundsRouterData<F>> for PayjustnowRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &RefundsRouterData<F>) -> Result<Self, Self::Error> {
Ok(Self {
request_id: Some(item.connector_request_reference_id.clone()),
checkout_token: item.request.connector_transaction_id.clone(),
merchant_refund_reference: item.request.refund_id.clone(),
refund_amount_cents: item.request.minor_refund_amount,
refund_description: item
.request
.reason
.clone()
.unwrap_or(NO_REFUND_REASON.to_string()),
})
}
}
// Type definition for Refund Response
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum RefundStatus {
Success,
Failed,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Success => Self::Success,
RefundStatus::Failed => Self::Failure,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PayjustnowRefundResponse {
request_id: String,
refunded_amount_cents: MinorUnit,
refund_status: RefundStatus,
refund_status_at: String,
refund_status_description: String,
}
impl TryFrom<RefundsResponseRouterData<Execute, PayjustnowRefundResponse>>
for RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, PayjustnowRefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.request_id,
refund_status: enums::RefundStatus::from(item.response.refund_status),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, PayjustnowRefundResponse>>
for RefundsRouterData<RSync>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, PayjustnowRefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.request_id,
refund_status: enums::RefundStatus::from(item.response.refund_status),
}),
..item.data
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PayjustnowRsyncStatus {
FullyRefunded,
PartiallyRefunded,
PaidPendingCallback,
Paid,
}
impl From<PayjustnowRsyncStatus> for enums::RefundStatus {
fn from(item: PayjustnowRsyncStatus) -> Self {
match item {
PayjustnowRsyncStatus::FullyRefunded | PayjustnowRsyncStatus::PartiallyRefunded => {
Self::Success
}
PayjustnowRsyncStatus::Paid | PayjustnowRsyncStatus::PaidPendingCallback => {
Self::Failure
}
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PayjustnowRsyncResponse {
request_id: String,
checkout_payment_status: PayjustnowRsyncStatus,
}
impl TryFrom<RefundsResponseRouterData<RSync, PayjustnowRsyncResponse>>
for RefundsRouterData<RSync>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, PayjustnowRsyncResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.request_id.clone(),
refund_status: enums::RefundStatus::from(item.response.checkout_payment_status),
}),
..item.data
})
}
}
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct PayjustnowError {
pub message: String,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum PayjustnowErrorResponse {
Structured(PayjustnowError),
Message(String),
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PayjustnowWebhookStatus {
PaidPendingCallback,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PayjustnowWebhookDetails {
pub checkout_token: String,
pub checkout_payment_status: PayjustnowWebhookStatus,
}
| 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/aci/transformers.rs | crates/hyperswitch_connectors/src/connectors/aci/transformers.rs | use std::str::FromStr;
use cards::NetworkToken;
use common_enums::enums;
use common_utils::{id_type, pii::Email, request::Method, types::StringMajorUnit};
use error_stack::report;
use hyperswitch_domain_models::{
payment_method_data::{
BankRedirectData, Card, NetworkTokenData, PayLaterData, PaymentMethodData, WalletData,
},
router_data::{ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::SetupMandate,
router_request_types::{
PaymentsAuthorizeData, PaymentsCancelData, PaymentsSyncData, ResponseId,
SetupMandateRequestData,
},
router_response_types::{
MandateReference, PaymentsResponseData, RedirectForm, RefundsResponseData,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
RefundsRouterData,
},
};
use hyperswitch_interfaces::errors;
use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use url::Url;
use super::aci_result_codes::{FAILURE_CODES, PENDING_CODES, SUCCESSFUL_CODES};
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{
self, CardData, NetworkTokenData as NetworkTokenDataTrait, PaymentsAuthorizeRequestData,
PhoneDetailsData, RouterData as _,
},
};
type Error = error_stack::Report<errors::ConnectorError>;
trait GetCaptureMethod {
fn get_capture_method(&self) -> Option<enums::CaptureMethod>;
}
impl GetCaptureMethod for PaymentsAuthorizeData {
fn get_capture_method(&self) -> Option<enums::CaptureMethod> {
self.capture_method
}
}
impl GetCaptureMethod for PaymentsSyncData {
fn get_capture_method(&self) -> Option<enums::CaptureMethod> {
self.capture_method
}
}
impl GetCaptureMethod for PaymentsCancelData {
fn get_capture_method(&self) -> Option<enums::CaptureMethod> {
None
}
}
#[derive(Debug, Serialize)]
pub struct AciRouterData<T> {
pub amount: StringMajorUnit,
pub router_data: T,
}
impl<T> From<(StringMajorUnit, T)> for AciRouterData<T> {
fn from((amount, item): (StringMajorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
pub struct AciAuthType {
pub api_key: Secret<String>,
pub entity_id: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for AciAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &ConnectorAuthType) -> Result<Self, Self::Error> {
if let ConnectorAuthType::BodyKey { api_key, key1 } = item {
Ok(Self {
api_key: api_key.to_owned(),
entity_id: key1.to_owned(),
})
} else {
Err(errors::ConnectorError::FailedToObtainAuthType)?
}
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum AciRecurringType {
Initial,
Repeated,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AciPaymentsRequest {
#[serde(flatten)]
pub txn_details: TransactionDetails,
#[serde(flatten)]
pub payment_method: PaymentDetails,
#[serde(flatten)]
pub instruction: Option<Instruction>,
pub shopper_result_url: Option<String>,
#[serde(rename = "customParameters[3DS2_enrolled]")]
pub three_ds_two_enrolled: Option<bool>,
pub recurring_type: Option<AciRecurringType>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TransactionDetails {
pub entity_id: Secret<String>,
pub amount: StringMajorUnit,
pub currency: String,
pub payment_type: AciPaymentType,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AciCancelRequest {
pub entity_id: Secret<String>,
pub payment_type: AciPaymentType,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AciMandateRequest {
pub entity_id: Secret<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub payment_brand: Option<PaymentBrand>,
#[serde(flatten)]
pub payment_details: PaymentDetails,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AciMandateResponse {
pub id: String,
pub result: ResultCode,
pub build_number: String,
pub timestamp: String,
}
#[derive(Debug, Clone, Serialize)]
#[serde(untagged)]
pub enum PaymentDetails {
#[serde(rename = "card")]
AciCard(Box<CardDetails>),
BankRedirect(Box<BankRedirectionPMData>),
Wallet(Box<WalletPMData>),
Klarna,
Mandate,
AciNetworkToken(Box<AciNetworkTokenData>),
}
impl TryFrom<(&WalletData, &PaymentsAuthorizeRouterData)> for PaymentDetails {
type Error = Error;
fn try_from(value: (&WalletData, &PaymentsAuthorizeRouterData)) -> Result<Self, Self::Error> {
let (wallet_data, item) = value;
let payment_data = match wallet_data {
WalletData::MbWayRedirect(_) => {
let phone_details = item.get_billing_phone()?;
Self::Wallet(Box::new(WalletPMData {
payment_brand: PaymentBrand::Mbway,
account_id: Some(phone_details.get_number_with_hash_country_code()?),
}))
}
WalletData::AliPayRedirect { .. } => Self::Wallet(Box::new(WalletPMData {
payment_brand: PaymentBrand::AliPay,
account_id: None,
})),
WalletData::AliPayHkRedirect(_)
| WalletData::AmazonPayRedirect(_)
| WalletData::Paysera(_)
| WalletData::Skrill(_)
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
| WalletData::GcashRedirect(_)
| WalletData::AmazonPay(_)
| WalletData::ApplePay(_)
| WalletData::ApplePayThirdPartySdk(_)
| WalletData::DanaRedirect { .. }
| WalletData::GooglePay(_)
| WalletData::BluecodeRedirect {}
| WalletData::GooglePayThirdPartySdk(_)
| WalletData::MobilePayRedirect(_)
| WalletData::PaypalRedirect(_)
| WalletData::PaypalSdk(_)
| WalletData::Paze(_)
| WalletData::SamsungPay(_)
| WalletData::TwintRedirect { .. }
| WalletData::VippsRedirect { .. }
| WalletData::TouchNGoRedirect(_)
| WalletData::WeChatPayRedirect(_)
| WalletData::WeChatPayQr(_)
| WalletData::CashappQr(_)
| WalletData::SwishQr(_)
| WalletData::AliPayQr(_)
| WalletData::ApplePayRedirect(_)
| WalletData::GooglePayRedirect(_)
| WalletData::Mifinity(_)
| WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented(
"Payment method".to_string(),
))?,
};
Ok(payment_data)
}
}
impl
TryFrom<(
&AciRouterData<&PaymentsAuthorizeRouterData>,
&BankRedirectData,
)> for PaymentDetails
{
type Error = Error;
fn try_from(
value: (
&AciRouterData<&PaymentsAuthorizeRouterData>,
&BankRedirectData,
),
) -> Result<Self, Self::Error> {
let (item, bank_redirect_data) = value;
let payment_data = match bank_redirect_data {
BankRedirectData::Eps { .. } => Self::BankRedirect(Box::new(BankRedirectionPMData {
payment_brand: PaymentBrand::Eps,
bank_account_country: Some(item.router_data.get_billing_country()?),
bank_account_bank_name: None,
bank_account_bic: None,
bank_account_iban: None,
billing_country: None,
merchant_customer_id: None,
merchant_transaction_id: None,
customer_email: None,
})),
BankRedirectData::Eft { .. } => Self::BankRedirect(Box::new(BankRedirectionPMData {
payment_brand: PaymentBrand::Eft,
bank_account_country: Some(item.router_data.get_billing_country()?),
bank_account_bank_name: None,
bank_account_bic: None,
bank_account_iban: None,
billing_country: None,
merchant_customer_id: None,
merchant_transaction_id: None,
customer_email: None,
})),
BankRedirectData::Giropay {
bank_account_bic,
bank_account_iban,
..
} => Self::BankRedirect(Box::new(BankRedirectionPMData {
payment_brand: PaymentBrand::Giropay,
bank_account_country: Some(item.router_data.get_billing_country()?),
bank_account_bank_name: None,
bank_account_bic: bank_account_bic.clone(),
bank_account_iban: bank_account_iban.clone(),
billing_country: None,
merchant_customer_id: None,
merchant_transaction_id: None,
customer_email: None,
})),
BankRedirectData::Ideal { bank_name, .. } => {
Self::BankRedirect(Box::new(BankRedirectionPMData {
payment_brand: PaymentBrand::Ideal,
bank_account_country: Some(item.router_data.get_billing_country()?),
bank_account_bank_name: Some(bank_name.ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "ideal.bank_name",
},
)?),
bank_account_bic: None,
bank_account_iban: None,
billing_country: None,
merchant_customer_id: None,
merchant_transaction_id: None,
customer_email: None,
}))
}
BankRedirectData::Sofort { .. } => {
Self::BankRedirect(Box::new(BankRedirectionPMData {
payment_brand: PaymentBrand::Sofortueberweisung,
bank_account_country: Some(item.router_data.get_billing_country()?),
bank_account_bank_name: None,
bank_account_bic: None,
bank_account_iban: None,
billing_country: None,
merchant_customer_id: None,
merchant_transaction_id: None,
customer_email: None,
}))
}
BankRedirectData::Przelewy24 { .. } => {
Self::BankRedirect(Box::new(BankRedirectionPMData {
payment_brand: PaymentBrand::Przelewy,
bank_account_country: None,
bank_account_bank_name: None,
bank_account_bic: None,
bank_account_iban: None,
billing_country: None,
merchant_customer_id: None,
merchant_transaction_id: None,
customer_email: Some(item.router_data.get_billing_email()?),
}))
}
BankRedirectData::Interac { .. } => {
Self::BankRedirect(Box::new(BankRedirectionPMData {
payment_brand: PaymentBrand::InteracOnline,
bank_account_country: Some(item.router_data.get_billing_country()?),
bank_account_bank_name: None,
bank_account_bic: None,
bank_account_iban: None,
billing_country: None,
merchant_customer_id: None,
merchant_transaction_id: None,
customer_email: Some(item.router_data.get_billing_email()?),
}))
}
BankRedirectData::Trustly { .. } => {
Self::BankRedirect(Box::new(BankRedirectionPMData {
payment_brand: PaymentBrand::Trustly,
bank_account_country: None,
bank_account_bank_name: None,
bank_account_bic: None,
bank_account_iban: None,
billing_country: Some(item.router_data.get_billing_country()?),
merchant_customer_id: Some(Secret::new(item.router_data.get_customer_id()?)),
merchant_transaction_id: Some(Secret::new(
item.router_data.connector_request_reference_id.clone(),
)),
customer_email: None,
}))
}
BankRedirectData::Bizum { .. }
| BankRedirectData::Blik { .. }
| BankRedirectData::BancontactCard { .. }
| BankRedirectData::OnlineBankingCzechRepublic { .. }
| BankRedirectData::OnlineBankingFinland { .. }
| BankRedirectData::OnlineBankingFpx { .. }
| BankRedirectData::OnlineBankingPoland { .. }
| BankRedirectData::OnlineBankingSlovakia { .. }
| BankRedirectData::OnlineBankingThailand { .. }
| BankRedirectData::LocalBankRedirect {}
| BankRedirectData::OpenBankingUk { .. }
| BankRedirectData::OpenBanking { .. } => Err(errors::ConnectorError::NotImplemented(
"Payment method".to_string(),
))?,
};
Ok(payment_data)
}
}
fn get_aci_payment_brand(
card_network: Option<common_enums::CardNetwork>,
is_network_token_flow: bool,
) -> Result<PaymentBrand, Error> {
match card_network {
Some(common_enums::CardNetwork::Visa) => Ok(PaymentBrand::Visa),
Some(common_enums::CardNetwork::Mastercard) => Ok(PaymentBrand::Mastercard),
Some(common_enums::CardNetwork::AmericanExpress) => Ok(PaymentBrand::AmericanExpress),
Some(common_enums::CardNetwork::JCB) => Ok(PaymentBrand::Jcb),
Some(common_enums::CardNetwork::DinersClub) => Ok(PaymentBrand::DinersClub),
Some(common_enums::CardNetwork::Discover) => Ok(PaymentBrand::Discover),
Some(common_enums::CardNetwork::UnionPay) => Ok(PaymentBrand::UnionPay),
Some(common_enums::CardNetwork::Maestro) => Ok(PaymentBrand::Maestro),
Some(unsupported_network) => Err(errors::ConnectorError::NotSupported {
message: format!("Card network {unsupported_network} is not supported by ACI"),
connector: "ACI",
})?,
None => {
if is_network_token_flow {
Ok(PaymentBrand::Visa)
} else {
Err(errors::ConnectorError::MissingRequiredField {
field_name: "card.card_network",
}
.into())
}
}
}
}
impl TryFrom<(Card, Option<Secret<String>>)> for PaymentDetails {
type Error = Error;
fn try_from(
(card_data, card_holder_name): (Card, Option<Secret<String>>),
) -> Result<Self, Self::Error> {
let card_expiry_year = card_data.get_expiry_year_4_digit();
let payment_brand = get_aci_payment_brand(card_data.card_network, false).ok();
Ok(Self::AciCard(Box::new(CardDetails {
card_number: card_data.card_number,
card_holder: card_holder_name.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "card_holder_name",
})?,
card_expiry_month: card_data.card_exp_month.clone(),
card_expiry_year,
card_cvv: card_data.card_cvc,
payment_brand,
})))
}
}
impl
TryFrom<(
&AciRouterData<&PaymentsAuthorizeRouterData>,
&NetworkTokenData,
)> for PaymentDetails
{
type Error = Error;
fn try_from(
value: (
&AciRouterData<&PaymentsAuthorizeRouterData>,
&NetworkTokenData,
),
) -> Result<Self, Self::Error> {
let (_item, network_token_data) = value;
let token_number = network_token_data.get_network_token();
let payment_brand = get_aci_payment_brand(network_token_data.card_network.clone(), true)?;
let aci_network_token_data = AciNetworkTokenData {
token_type: AciTokenAccountType::Network,
token_number,
token_expiry_month: network_token_data.get_network_token_expiry_month(),
token_expiry_year: network_token_data.get_expiry_year_4_digit(),
token_cryptogram: Some(
network_token_data
.get_cryptogram()
.clone()
.unwrap_or_default(),
),
payment_brand,
};
Ok(Self::AciNetworkToken(Box::new(aci_network_token_data)))
}
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum AciTokenAccountType {
Network,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AciNetworkTokenData {
#[serde(rename = "tokenAccount.type")]
pub token_type: AciTokenAccountType,
#[serde(rename = "tokenAccount.number")]
pub token_number: NetworkToken,
#[serde(rename = "tokenAccount.expiryMonth")]
pub token_expiry_month: Secret<String>,
#[serde(rename = "tokenAccount.expiryYear")]
pub token_expiry_year: Secret<String>,
#[serde(rename = "tokenAccount.cryptogram")]
pub token_cryptogram: Option<Secret<String>>,
#[serde(rename = "paymentBrand")]
pub payment_brand: PaymentBrand,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BankRedirectionPMData {
payment_brand: PaymentBrand,
#[serde(rename = "bankAccount.country")]
bank_account_country: Option<api_models::enums::CountryAlpha2>,
#[serde(rename = "bankAccount.bankName")]
bank_account_bank_name: Option<common_enums::BankNames>,
#[serde(rename = "bankAccount.bic")]
bank_account_bic: Option<Secret<String>>,
#[serde(rename = "bankAccount.iban")]
bank_account_iban: Option<Secret<String>>,
#[serde(rename = "billing.country")]
billing_country: Option<api_models::enums::CountryAlpha2>,
#[serde(rename = "customer.email")]
customer_email: Option<Email>,
#[serde(rename = "customer.merchantCustomerId")]
merchant_customer_id: Option<Secret<id_type::CustomerId>>,
merchant_transaction_id: Option<Secret<String>>,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct WalletPMData {
payment_brand: PaymentBrand,
#[serde(rename = "virtualAccount.accountId")]
account_id: Option<Secret<String>>,
}
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PaymentBrand {
Eps,
Eft,
Ideal,
Giropay,
Sofortueberweisung,
InteracOnline,
Przelewy,
Trustly,
Mbway,
#[serde(rename = "ALIPAY")]
AliPay,
// Card network brands
#[serde(rename = "VISA")]
Visa,
#[serde(rename = "MASTER")]
Mastercard,
#[serde(rename = "AMEX")]
AmericanExpress,
#[serde(rename = "JCB")]
Jcb,
#[serde(rename = "DINERS")]
DinersClub,
#[serde(rename = "DISCOVER")]
Discover,
#[serde(rename = "UNIONPAY")]
UnionPay,
#[serde(rename = "MAESTRO")]
Maestro,
}
#[derive(Debug, Clone, Eq, PartialEq, Serialize)]
pub struct CardDetails {
#[serde(rename = "card.number")]
pub card_number: cards::CardNumber,
#[serde(rename = "card.holder")]
pub card_holder: Secret<String>,
#[serde(rename = "card.expiryMonth")]
pub card_expiry_month: Secret<String>,
#[serde(rename = "card.expiryYear")]
pub card_expiry_year: Secret<String>,
#[serde(rename = "card.cvv")]
pub card_cvv: Secret<String>,
#[serde(rename = "paymentBrand")]
#[serde(skip_serializing_if = "Option::is_none")]
pub payment_brand: Option<PaymentBrand>,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum InstructionMode {
Initial,
Repeated,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum InstructionType {
Unscheduled,
}
#[derive(Debug, Clone, Serialize)]
pub enum InstructionSource {
#[serde(rename = "CIT")]
CardholderInitiatedTransaction,
#[serde(rename = "MIT")]
MerchantInitiatedTransaction,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Instruction {
#[serde(rename = "standingInstruction.mode")]
mode: InstructionMode,
#[serde(rename = "standingInstruction.type")]
transaction_type: InstructionType,
#[serde(rename = "standingInstruction.source")]
source: InstructionSource,
create_registration: Option<bool>,
}
#[derive(Debug, Clone, Eq, PartialEq, Serialize)]
pub struct BankDetails {
#[serde(rename = "bankAccount.holder")]
pub account_holder: Secret<String>,
}
#[allow(dead_code)]
#[derive(Debug, Default, Clone, Eq, PartialEq, Serialize, Deserialize)]
pub enum AciPaymentType {
#[serde(rename = "PA")]
Preauthorization,
#[default]
#[serde(rename = "DB")]
Debit,
#[serde(rename = "CD")]
Credit,
#[serde(rename = "CP")]
Capture,
#[serde(rename = "RV")]
Reversal,
#[serde(rename = "RF")]
Refund,
}
impl TryFrom<&AciRouterData<&PaymentsAuthorizeRouterData>> for AciPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &AciRouterData<&PaymentsAuthorizeRouterData>) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(ref card_data) => Self::try_from((item, card_data)),
PaymentMethodData::NetworkToken(ref network_token_data) => {
Self::try_from((item, network_token_data))
}
PaymentMethodData::Wallet(ref wallet_data) => Self::try_from((item, wallet_data)),
PaymentMethodData::PayLater(ref pay_later_data) => {
Self::try_from((item, pay_later_data))
}
PaymentMethodData::BankRedirect(ref bank_redirect_data) => {
Self::try_from((item, bank_redirect_data))
}
PaymentMethodData::MandatePayment => {
let mandate_id = item.router_data.request.mandate_id.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "mandate_id",
},
)?;
Self::try_from((item, mandate_id))
}
PaymentMethodData::Crypto(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Aci"),
))?
}
}
}
}
impl TryFrom<(&AciRouterData<&PaymentsAuthorizeRouterData>, &WalletData)> for AciPaymentsRequest {
type Error = Error;
fn try_from(
value: (&AciRouterData<&PaymentsAuthorizeRouterData>, &WalletData),
) -> Result<Self, Self::Error> {
let (item, wallet_data) = value;
let txn_details = get_transaction_details(item)?;
let payment_method = PaymentDetails::try_from((wallet_data, item.router_data))?;
Ok(Self {
txn_details,
payment_method,
instruction: None,
shopper_result_url: item.router_data.request.router_return_url.clone(),
three_ds_two_enrolled: None,
recurring_type: None,
})
}
}
impl
TryFrom<(
&AciRouterData<&PaymentsAuthorizeRouterData>,
&BankRedirectData,
)> for AciPaymentsRequest
{
type Error = Error;
fn try_from(
value: (
&AciRouterData<&PaymentsAuthorizeRouterData>,
&BankRedirectData,
),
) -> Result<Self, Self::Error> {
let (item, bank_redirect_data) = value;
let txn_details = get_transaction_details(item)?;
let payment_method = PaymentDetails::try_from((item, bank_redirect_data))?;
Ok(Self {
txn_details,
payment_method,
instruction: None,
shopper_result_url: item.router_data.request.router_return_url.clone(),
three_ds_two_enrolled: None,
recurring_type: None,
})
}
}
impl TryFrom<(&AciRouterData<&PaymentsAuthorizeRouterData>, &PayLaterData)> for AciPaymentsRequest {
type Error = Error;
fn try_from(
value: (&AciRouterData<&PaymentsAuthorizeRouterData>, &PayLaterData),
) -> Result<Self, Self::Error> {
let (item, _pay_later_data) = value;
let txn_details = get_transaction_details(item)?;
let payment_method = PaymentDetails::Klarna;
Ok(Self {
txn_details,
payment_method,
instruction: None,
shopper_result_url: item.router_data.request.router_return_url.clone(),
three_ds_two_enrolled: None,
recurring_type: None,
})
}
}
impl TryFrom<(&AciRouterData<&PaymentsAuthorizeRouterData>, &Card)> for AciPaymentsRequest {
type Error = Error;
fn try_from(
value: (&AciRouterData<&PaymentsAuthorizeRouterData>, &Card),
) -> Result<Self, Self::Error> {
let (item, card_data) = value;
let card_holder_name = item.router_data.get_optional_billing_full_name();
let txn_details = get_transaction_details(item)?;
let payment_method = PaymentDetails::try_from((card_data.clone(), card_holder_name))?;
let instruction = get_instruction_details(item);
let recurring_type = get_recurring_type(item);
let three_ds_two_enrolled = item
.router_data
.is_three_ds()
.then_some(item.router_data.request.enrolled_for_3ds);
Ok(Self {
txn_details,
payment_method,
instruction,
shopper_result_url: item.router_data.request.router_return_url.clone(),
three_ds_two_enrolled,
recurring_type,
})
}
}
impl
TryFrom<(
&AciRouterData<&PaymentsAuthorizeRouterData>,
&NetworkTokenData,
)> for AciPaymentsRequest
{
type Error = Error;
fn try_from(
value: (
&AciRouterData<&PaymentsAuthorizeRouterData>,
&NetworkTokenData,
),
) -> Result<Self, Self::Error> {
let (item, network_token_data) = value;
let txn_details = get_transaction_details(item)?;
let payment_method = PaymentDetails::try_from((item, network_token_data))?;
let instruction = get_instruction_details(item);
Ok(Self {
txn_details,
payment_method,
instruction,
shopper_result_url: item.router_data.request.router_return_url.clone(),
three_ds_two_enrolled: None,
recurring_type: None,
})
}
}
impl
TryFrom<(
&AciRouterData<&PaymentsAuthorizeRouterData>,
api_models::payments::MandateIds,
)> for AciPaymentsRequest
{
type Error = Error;
fn try_from(
value: (
&AciRouterData<&PaymentsAuthorizeRouterData>,
api_models::payments::MandateIds,
),
) -> Result<Self, Self::Error> {
let (item, _mandate_data) = value;
let instruction = get_instruction_details(item);
let txn_details = get_transaction_details(item)?;
let recurring_type = get_recurring_type(item);
Ok(Self {
txn_details,
payment_method: PaymentDetails::Mandate,
instruction,
shopper_result_url: item.router_data.request.router_return_url.clone(),
three_ds_two_enrolled: None,
recurring_type,
})
}
}
fn get_transaction_details(
item: &AciRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<TransactionDetails, error_stack::Report<errors::ConnectorError>> {
let auth = AciAuthType::try_from(&item.router_data.connector_auth_type)?;
let payment_type = if item.router_data.request.is_auto_capture()? {
AciPaymentType::Debit
} else {
AciPaymentType::Preauthorization
};
Ok(TransactionDetails {
entity_id: auth.entity_id,
amount: item.amount.to_owned(),
currency: item.router_data.request.currency.to_string(),
payment_type,
})
}
fn get_instruction_details(
item: &AciRouterData<&PaymentsAuthorizeRouterData>,
) -> Option<Instruction> {
if item.router_data.request.customer_acceptance.is_some()
&& item.router_data.request.setup_future_usage == Some(enums::FutureUsage::OffSession)
{
return Some(Instruction {
mode: InstructionMode::Initial,
transaction_type: InstructionType::Unscheduled,
source: InstructionSource::CardholderInitiatedTransaction,
create_registration: Some(true),
});
} else if item.router_data.request.mandate_id.is_some() {
return Some(Instruction {
mode: InstructionMode::Repeated,
transaction_type: InstructionType::Unscheduled,
source: InstructionSource::MerchantInitiatedTransaction,
create_registration: None,
});
}
None
}
fn get_recurring_type(
item: &AciRouterData<&PaymentsAuthorizeRouterData>,
) -> Option<AciRecurringType> {
if item.router_data.request.mandate_id.is_some() {
Some(AciRecurringType::Repeated)
} else if item.router_data.request.customer_acceptance.is_some()
&& item.router_data.request.setup_future_usage == Some(enums::FutureUsage::OffSession)
{
Some(AciRecurringType::Initial)
} else {
None
}
}
impl TryFrom<&PaymentsCancelRouterData> for AciCancelRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> {
let auth = AciAuthType::try_from(&item.connector_auth_type)?;
let aci_payment_request = Self {
entity_id: auth.entity_id,
payment_type: AciPaymentType::Reversal,
};
Ok(aci_payment_request)
}
}
impl TryFrom<&RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>>
for AciMandateRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let auth = AciAuthType::try_from(&item.connector_auth_type)?;
let (payment_brand, payment_details) = match &item.request.payment_method_data {
PaymentMethodData::Card(card_data) => {
let brand = get_aci_payment_brand(card_data.card_network.clone(), false).ok();
match brand.as_ref() {
Some(PaymentBrand::Visa)
| Some(PaymentBrand::Mastercard)
| Some(PaymentBrand::AmericanExpress) => (),
Some(_) => {
return Err(errors::ConnectorError::NotSupported {
message: "Payment method not supported for mandate setup".to_string(),
connector: "ACI",
}
.into());
}
None => (),
};
let details = PaymentDetails::AciCard(Box::new(CardDetails {
card_number: card_data.card_number.clone(),
card_expiry_month: card_data.card_exp_month.clone(),
card_expiry_year: card_data.get_expiry_year_4_digit(),
card_cvv: card_data.card_cvc.clone(),
card_holder: card_data.card_holder_name.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "card_holder_name",
},
)?,
| 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/aci/aci_result_codes.rs | crates/hyperswitch_connectors/src/connectors/aci/aci_result_codes.rs | pub(super) const FAILURE_CODES: [&str; 502] = [
"100.370.100",
"100.370.110",
"100.370.111",
"100.380.100",
"100.380.101",
"100.380.110",
"100.380.201",
"100.380.305",
"100.380.306",
"100.380.401",
"100.380.501",
"100.395.502",
"100.396.101",
"100.400.000",
"100.400.001",
"100.400.002",
"100.400.005",
"100.400.007",
"100.400.020",
"100.400.021",
"100.400.030",
"100.400.039",
"100.400.040",
"100.400.041",
"100.400.042",
"100.400.043",
"100.400.044",
"100.400.045",
"100.400.051",
"100.400.060",
"100.400.061",
"100.400.063",
"100.400.064",
"100.400.065",
"100.400.071",
"100.400.080",
"100.400.081",
"100.400.083",
"100.400.084",
"100.400.085",
"100.400.086",
"100.400.087",
"100.400.091",
"100.400.100",
"100.400.120",
"100.400.121",
"100.400.122",
"100.400.123",
"100.400.130",
"100.400.139",
"100.400.140",
"100.400.141",
"100.400.142",
"100.400.143",
"100.400.144",
"100.400.145",
"100.400.146",
"100.400.147",
"100.400.148",
"100.400.149",
"100.400.150",
"100.400.151",
"100.400.152",
"100.400.241",
"100.400.242",
"100.400.243",
"100.400.260",
"100.400.300",
"100.400.301",
"100.400.302",
"100.400.303",
"100.400.304",
"100.400.305",
"100.400.306",
"100.400.307",
"100.400.308",
"100.400.309",
"100.400.310",
"100.400.311",
"100.400.312",
"100.400.313",
"100.400.314",
"100.400.315",
"100.400.316",
"100.400.317",
"100.400.318",
"100.400.319",
"100.400.320",
"100.400.321",
"100.400.322",
"100.400.323",
"100.400.324",
"100.400.325",
"100.400.326",
"100.400.327",
"100.400.328",
"800.400.100",
"800.400.101",
"800.400.102",
"800.400.103",
"800.400.104",
"800.400.105",
"800.400.110",
"800.400.150",
"800.400.151",
"100.380.401",
"100.390.101",
"100.390.102",
"100.390.103",
"100.390.104",
"100.390.105",
"100.390.106",
"100.390.107",
"100.390.108",
"100.390.109",
"100.390.110",
"100.390.111",
"100.390.112",
"100.390.113",
"100.390.114",
"100.390.115",
"100.390.116",
"100.390.117",
"100.390.118",
"800.400.200",
"100.100.701",
"800.200.159",
"800.200.160",
"800.200.165",
"800.200.202",
"800.200.208",
"800.200.220",
"800.300.101",
"800.300.102",
"800.300.200",
"800.300.301",
"800.300.302",
"800.300.401",
"800.300.500",
"800.300.501",
"800.310.200",
"800.310.210",
"800.310.211",
"800.110.100",
"800.120.100",
"800.120.101",
"800.120.102",
"800.120.103",
"800.120.200",
"800.120.201",
"800.120.202",
"800.120.203",
"800.120.300",
"800.120.401",
"800.130.100",
"800.140.100",
"800.140.101",
"800.140.110",
"800.140.111",
"800.140.112",
"800.140.113",
"800.150.100",
"800.160.100",
"800.160.110",
"800.160.120",
"800.160.130",
"500.100.201",
"500.100.202",
"500.100.203",
"500.100.301",
"500.100.302",
"500.100.303",
"500.100.304",
"500.100.401",
"500.100.402",
"500.100.403",
"500.200.101",
"600.200.100",
"600.200.200",
"600.200.201",
"600.200.202",
"600.200.300",
"600.200.310",
"600.200.400",
"600.200.500",
"600.200.501",
"600.200.600",
"600.200.700",
"600.200.800",
"600.200.810",
"600.300.101",
"600.300.200",
"600.300.210",
"600.300.211",
"800.121.100",
"800.121.200",
"100.150.100",
"100.150.101",
"100.150.200",
"100.150.201",
"100.150.202",
"100.150.203",
"100.150.204",
"100.150.205",
"100.150.300",
"100.350.100",
"100.350.101",
"100.350.200",
"100.350.201",
"100.350.301",
"100.350.302",
"100.350.303",
"100.350.310",
"100.350.311",
"100.350.312",
"100.350.313",
"100.350.314",
"100.350.315",
"100.350.316",
"100.350.400",
"100.350.500",
"100.350.601",
"100.350.602",
"100.250.100",
"100.250.105",
"100.250.106",
"100.250.107",
"100.250.110",
"100.250.111",
"100.250.120",
"100.250.121",
"100.250.122",
"100.250.123",
"100.250.124",
"100.250.125",
"100.250.250",
"100.360.201",
"100.360.300",
"100.360.303",
"100.360.400",
"700.100.100",
"700.100.200",
"700.100.300",
"700.100.400",
"700.100.500",
"700.100.600",
"700.100.700",
"700.100.701",
"700.100.710",
"700.300.100",
"700.300.200",
"700.300.300",
"700.300.400",
"700.300.500",
"700.300.600",
"700.300.700",
"700.300.800",
"700.400.000",
"700.400.100",
"700.400.101",
"700.400.200",
"700.400.300",
"700.400.400",
"700.400.402",
"700.400.410",
"700.400.411",
"700.400.420",
"700.400.510",
"700.400.520",
"700.400.530",
"700.400.540",
"700.400.550",
"700.400.560",
"700.400.561",
"700.400.562",
"700.400.565",
"700.400.570",
"700.400.580",
"700.400.590",
"700.400.600",
"700.400.700",
"700.450.001",
"700.500.001",
"700.500.002",
"700.500.003",
"700.500.004",
"100.300.101",
"100.300.200",
"100.300.300",
"100.300.400",
"100.300.401",
"100.300.402",
"100.300.501",
"100.300.600",
"100.300.601",
"100.300.700",
"100.300.701",
"100.370.100",
"100.370.101",
"100.370.102",
"100.370.110",
"100.370.111",
"100.370.121",
"100.370.122",
"100.370.123",
"100.370.124",
"100.370.125",
"100.370.131",
"100.370.132",
"100.500.101",
"100.500.201",
"100.500.301",
"100.500.302",
"100.500.303",
"100.500.304",
"100.600.500",
"100.900.500",
"200.100.101",
"200.100.102",
"200.100.103",
"200.100.150",
"200.100.151",
"200.100.199",
"200.100.201",
"200.100.300",
"200.100.301",
"200.100.302",
"200.100.401",
"200.100.402",
"200.100.403",
"200.100.404",
"200.100.501",
"200.100.502",
"200.100.503",
"200.100.504",
"200.100.601",
"200.100.602",
"200.100.603",
"200.200.106",
"200.300.403",
"200.300.404",
"200.300.405",
"200.300.406",
"200.300.407",
"800.900.100",
"800.900.101",
"800.900.200",
"800.900.201",
"800.900.300",
"800.900.301",
"800.900.302",
"800.900.303",
"800.900.399",
"800.900.401",
"800.900.450",
"100.800.100",
"100.800.101",
"100.800.102",
"100.800.200",
"100.800.201",
"100.800.202",
"100.800.300",
"100.800.301",
"100.800.302",
"100.800.400",
"100.800.401",
"100.800.500",
"100.800.501",
"100.700.100",
"100.700.101",
"100.700.200",
"100.700.201",
"100.700.300",
"100.700.400",
"100.700.500",
"100.700.800",
"100.700.801",
"100.700.802",
"100.700.810",
"100.900.100",
"100.900.101",
"100.900.105",
"100.900.200",
"100.900.300",
"100.900.301",
"100.900.400",
"100.900.401",
"100.900.450",
"100.900.500",
"100.100.100",
"100.100.101",
"100.100.104",
"100.100.200",
"100.100.201",
"100.100.300",
"100.100.301",
"100.100.303",
"100.100.304",
"100.100.305",
"100.100.400",
"100.100.401",
"100.100.402",
"100.100.500",
"100.100.501",
"100.100.600",
"100.100.601",
"100.100.650",
"100.100.651",
"100.100.700",
"100.100.701",
"100.200.100",
"100.200.103",
"100.200.104",
"100.200.200",
"100.210.101",
"100.210.102",
"100.211.101",
"100.211.102",
"100.211.103",
"100.211.104",
"100.211.105",
"100.211.106",
"100.212.101",
"100.212.102",
"100.212.103",
"100.550.300",
"100.550.301",
"100.550.303",
"100.550.310",
"100.550.311",
"100.550.312",
"100.550.400",
"100.550.401",
"100.550.601",
"100.550.603",
"100.550.605",
"100.550.701",
"100.550.702",
"100.380.101",
"100.380.201",
"100.380.305",
"100.380.306",
"800.100.100",
"800.100.150",
"800.100.151",
"800.100.152",
"800.100.153",
"800.100.154",
"800.100.155",
"800.100.156",
"800.100.157",
"800.100.158",
"800.100.159",
"800.100.160",
"800.100.161",
"800.100.162",
"800.100.163",
"800.100.164",
"800.100.165",
"800.100.166",
"800.100.167",
"800.100.168",
"800.100.169",
"800.100.170",
"800.100.171",
"800.100.172",
"800.100.173",
"800.100.174",
"800.100.175",
"800.100.176",
"800.100.177",
"800.100.178",
"800.100.179",
"800.100.190",
"800.100.191",
"800.100.192",
"800.100.195",
"800.100.196",
"800.100.197",
"800.100.198",
"800.100.199",
"800.100.200",
"800.100.201",
"800.100.202",
"800.100.203",
"800.100.204",
"800.100.205",
"800.100.206",
"800.100.207",
"800.100.208",
"800.100.402",
"800.100.403",
"800.100.500",
"800.100.501",
"800.700.100",
"800.700.101",
"800.700.201",
"800.700.500",
"800.800.102",
"800.800.202",
"800.800.302",
"100.390.100",
];
pub(super) const SUCCESSFUL_CODES: [&str; 16] = [
"000.000.000",
"000.000.100",
"000.100.105",
"000.100.106",
"000.100.110",
"000.100.111",
"000.100.112",
"000.300.000",
"000.300.100",
"000.300.101",
"000.300.102",
"000.300.103",
"000.310.100",
"000.310.101",
"000.310.110",
"000.600.000",
];
pub(super) const PENDING_CODES: [&str; 26] = [
"000.400.000",
"000.400.010",
"000.400.020",
"000.400.040",
"000.400.050",
"000.400.060",
"000.400.070",
"000.400.080",
"000.400.081",
"000.400.082",
"000.400.090",
"000.400.091",
"000.400.100",
"000.400.110",
"000.200.000",
"000.200.001",
"000.200.100",
"000.200.101",
"000.200.102",
"000.200.103",
"000.200.200",
"000.200.201",
"100.400.500",
"800.400.500",
"800.400.501",
"800.400.502",
];
| 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/rapyd/transformers.rs | crates/hyperswitch_connectors/src/connectors/rapyd/transformers.rs | use common_enums::enums;
use common_utils::{
ext_traits::OptionExt,
request::Method,
types::{FloatMajorUnit, MinorUnit},
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{PaymentMethodData, WalletData},
router_data::{ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
types,
};
use hyperswitch_interfaces::{consts::NO_ERROR_CODE, errors};
use masking::Secret;
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
use url::Url;
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{PaymentsAuthorizeRequestData, RouterData as _},
};
#[derive(Debug, Serialize)]
pub struct RapydRouterData<T> {
pub amount: FloatMajorUnit,
pub router_data: T,
}
impl<T> From<(FloatMajorUnit, T)> for RapydRouterData<T> {
fn from((amount, router_data): (FloatMajorUnit, T)) -> Self {
Self {
amount,
router_data,
}
}
}
#[derive(Default, Debug, Serialize)]
pub struct RapydPaymentsRequest {
pub amount: FloatMajorUnit,
pub currency: enums::Currency,
pub payment_method: PaymentMethod,
pub payment_method_options: Option<PaymentMethodOptions>,
pub merchant_reference_id: Option<String>,
pub capture: Option<bool>,
pub description: Option<String>,
pub complete_payment_url: Option<String>,
pub error_payment_url: Option<String>,
}
#[derive(Default, Debug, Serialize)]
pub struct PaymentMethodOptions {
#[serde(rename = "3d_required")]
pub three_ds: bool,
}
#[derive(Default, Debug, Serialize)]
pub struct PaymentMethod {
#[serde(rename = "type")]
pub pm_type: String,
pub fields: Option<PaymentFields>,
pub address: Option<Address>,
pub digital_wallet: Option<RapydWallet>,
}
#[derive(Default, Debug, Serialize)]
pub struct PaymentFields {
pub number: cards::CardNumber,
pub expiration_month: Secret<String>,
pub expiration_year: Secret<String>,
pub name: Secret<String>,
pub cvv: Secret<String>,
}
#[derive(Default, Debug, Serialize)]
pub struct Address {
name: Secret<String>,
line_1: Secret<String>,
line_2: Option<Secret<String>>,
line_3: Option<Secret<String>>,
city: Option<String>,
state: Option<Secret<String>>,
country: Option<String>,
zip: Option<Secret<String>>,
phone_number: Option<Secret<String>>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RapydWallet {
#[serde(rename = "type")]
payment_type: String,
#[serde(rename = "details")]
token: Option<Secret<String>>,
}
impl TryFrom<&RapydRouterData<&types::PaymentsAuthorizeRouterData>> for RapydPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &RapydRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let (capture, payment_method_options) = match item.router_data.payment_method {
enums::PaymentMethod::Card => {
let three_ds_enabled = matches!(
item.router_data.auth_type,
enums::AuthenticationType::ThreeDs
);
let payment_method_options = PaymentMethodOptions {
three_ds: three_ds_enabled,
};
(
Some(matches!(
item.router_data.request.capture_method,
Some(enums::CaptureMethod::Automatic)
| Some(enums::CaptureMethod::SequentialAutomatic)
| None
)),
Some(payment_method_options),
)
}
_ => (None, None),
};
let payment_method = match item.router_data.request.payment_method_data {
PaymentMethodData::Card(ref ccard) => {
Some(PaymentMethod {
pm_type: "in_amex_card".to_owned(), //[#369] Map payment method type based on country
fields: Some(PaymentFields {
number: ccard.card_number.to_owned(),
expiration_month: ccard.card_exp_month.to_owned(),
expiration_year: ccard.card_exp_year.to_owned(),
name: item
.router_data
.get_optional_billing_full_name()
.to_owned()
.unwrap_or(Secret::new("".to_string())),
cvv: ccard.card_cvc.to_owned(),
}),
address: None,
digital_wallet: None,
})
}
PaymentMethodData::Wallet(ref wallet_data) => {
let digital_wallet = match wallet_data {
WalletData::GooglePay(data) => Some(RapydWallet {
payment_type: "google_pay".to_string(),
token: Some(Secret::new(
data.tokenization_data
.get_encrypted_google_pay_token()
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "gpay wallet_token",
})?
.to_owned(),
)),
}),
WalletData::ApplePay(data) => {
let apple_pay_encrypted_data = data
.payment_data
.get_encrypted_apple_pay_payment_data_mandatory()
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "Apple pay encrypted data",
})?;
Some(RapydWallet {
payment_type: "apple_pay".to_string(),
token: Some(Secret::new(apple_pay_encrypted_data.to_string())),
})
}
_ => None,
};
Some(PaymentMethod {
pm_type: "by_visa_card".to_string(), //[#369]
fields: None,
address: None,
digital_wallet,
})
}
_ => None,
}
.get_required_value("payment_method not implemented")
.change_context(errors::ConnectorError::NotImplemented(
"payment_method".to_owned(),
))?;
let return_url = item.router_data.request.get_router_return_url()?;
Ok(Self {
amount: item.amount,
currency: item.router_data.request.currency,
payment_method,
capture,
payment_method_options,
merchant_reference_id: Some(item.router_data.connector_request_reference_id.clone()),
description: None,
error_payment_url: Some(return_url.clone()),
complete_payment_url: Some(return_url),
})
}
}
#[derive(Debug, Deserialize)]
pub struct RapydAuthType {
pub access_key: Secret<String>,
pub secret_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for RapydAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
if let ConnectorAuthType::BodyKey { api_key, key1 } = auth_type {
Ok(Self {
access_key: api_key.to_owned(),
secret_key: key1.to_owned(),
})
} else {
Err(errors::ConnectorError::FailedToObtainAuthType)?
}
}
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[allow(clippy::upper_case_acronyms)]
pub enum RapydPaymentStatus {
#[serde(rename = "ACT")]
Active,
#[serde(rename = "CAN")]
CanceledByClientOrBank,
#[serde(rename = "CLO")]
Closed,
#[serde(rename = "ERR")]
Error,
#[serde(rename = "EXP")]
Expired,
#[serde(rename = "REV")]
ReversedByRapyd,
#[default]
#[serde(rename = "NEW")]
New,
}
fn get_status(status: RapydPaymentStatus, next_action: NextAction) -> enums::AttemptStatus {
match (status, next_action) {
(RapydPaymentStatus::Closed, _) => enums::AttemptStatus::Charged,
(
RapydPaymentStatus::Active,
NextAction::ThreedsVerification | NextAction::PendingConfirmation,
) => enums::AttemptStatus::AuthenticationPending,
(RapydPaymentStatus::Active, NextAction::PendingCapture | NextAction::NotApplicable) => {
enums::AttemptStatus::Authorized
}
(
RapydPaymentStatus::CanceledByClientOrBank
| RapydPaymentStatus::Expired
| RapydPaymentStatus::ReversedByRapyd,
_,
) => enums::AttemptStatus::Voided,
(RapydPaymentStatus::Error, _) => enums::AttemptStatus::Failure,
(RapydPaymentStatus::New, _) => enums::AttemptStatus::Authorizing,
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct RapydPaymentsResponse {
pub status: Status,
pub data: Option<ResponseData>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Status {
pub error_code: String,
pub status: Option<String>,
pub message: Option<String>,
pub response_code: Option<String>,
pub operation_id: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum NextAction {
#[serde(rename = "3d_verification")]
ThreedsVerification,
#[serde(rename = "pending_capture")]
PendingCapture,
#[serde(rename = "not_applicable")]
NotApplicable,
#[serde(rename = "pending_confirmation")]
PendingConfirmation,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ResponseData {
pub id: String,
pub amount: i64,
pub status: RapydPaymentStatus,
pub next_action: NextAction,
pub redirect_url: Option<String>,
pub original_amount: Option<i64>,
pub is_partial: Option<bool>,
pub currency_code: Option<enums::Currency>,
pub country_code: Option<String>,
pub captured: Option<bool>,
pub transaction_id: String,
pub merchant_reference_id: Option<String>,
pub paid: Option<bool>,
pub failure_code: Option<String>,
pub failure_message: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct DisputeResponseData {
pub id: String,
pub amount: MinorUnit,
pub currency: api_models::enums::Currency,
pub token: String,
pub dispute_reason_description: String,
#[serde(default, with = "common_utils::custom_serde::timestamp::option")]
pub due_date: Option<PrimitiveDateTime>,
pub status: RapydWebhookDisputeStatus,
#[serde(default, with = "common_utils::custom_serde::timestamp::option")]
pub created_at: Option<PrimitiveDateTime>,
#[serde(default, with = "common_utils::custom_serde::timestamp::option")]
pub updated_at: Option<PrimitiveDateTime>,
pub original_transaction_id: String,
}
#[derive(Default, Debug, Serialize)]
pub struct RapydRefundRequest {
pub payment: String,
pub amount: Option<FloatMajorUnit>,
pub currency: Option<enums::Currency>,
}
impl<F> TryFrom<&RapydRouterData<&types::RefundsRouterData<F>>> for RapydRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &RapydRouterData<&types::RefundsRouterData<F>>) -> Result<Self, Self::Error> {
Ok(Self {
payment: item
.router_data
.request
.connector_transaction_id
.to_string(),
amount: Some(item.amount),
currency: Some(item.router_data.request.currency),
})
}
}
#[allow(dead_code)]
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
pub enum RefundStatus {
Completed,
Error,
Rejected,
#[default]
Pending,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Completed => Self::Success,
RefundStatus::Error | RefundStatus::Rejected => Self::Failure,
RefundStatus::Pending => Self::Pending,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RefundResponse {
pub status: Status,
pub data: Option<RefundResponseData>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct RefundResponseData {
//Some field related to foreign exchange and split payment can be added as and when implemented
pub id: String,
pub payment: String,
pub amount: i64,
pub currency: enums::Currency,
pub status: RefundStatus,
pub created_at: Option<i64>,
pub failure_reason: Option<String>,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>>
for types::RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
let (connector_refund_id, refund_status) = match item.response.data {
Some(data) => (data.id, enums::RefundStatus::from(data.status)),
None => (
item.response.status.error_code,
enums::RefundStatus::Failure,
),
};
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id,
refund_status,
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for types::RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
let (connector_refund_id, refund_status) = match item.response.data {
Some(data) => (data.id, enums::RefundStatus::from(data.status)),
None => (
item.response.status.error_code,
enums::RefundStatus::Failure,
),
};
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id,
refund_status,
}),
..item.data
})
}
}
#[derive(Debug, Serialize, Clone)]
pub struct CaptureRequest {
amount: Option<FloatMajorUnit>,
receipt_email: Option<Secret<String>>,
statement_descriptor: Option<String>,
}
impl TryFrom<&RapydRouterData<&types::PaymentsCaptureRouterData>> for CaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &RapydRouterData<&types::PaymentsCaptureRouterData>,
) -> Result<Self, Self::Error> {
Ok(Self {
amount: Some(item.amount),
receipt_email: None,
statement_descriptor: None,
})
}
}
impl<F, T> TryFrom<ResponseRouterData<F, RapydPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, RapydPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let (status, response) = match &item.response.data {
Some(data) => {
let attempt_status =
get_status(data.status.to_owned(), data.next_action.to_owned());
match attempt_status {
enums::AttemptStatus::Failure => (
enums::AttemptStatus::Failure,
Err(ErrorResponse {
code: data
.failure_code
.to_owned()
.unwrap_or(item.response.status.error_code),
status_code: item.http_code,
message: item.response.status.status.unwrap_or_default(),
reason: data.failure_message.to_owned(),
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
),
_ => {
let redirection_url = data
.redirect_url
.as_ref()
.filter(|redirect_str| !redirect_str.is_empty())
.map(|url| {
Url::parse(url).change_context(
errors::ConnectorError::FailedToObtainIntegrationUrl,
)
})
.transpose()?;
let redirection_data =
redirection_url.map(|url| RedirectForm::from((url, Method::Get)));
(
attempt_status,
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(data.id.to_owned()), //transaction_id is also the field but this id is used to initiate a refund
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: data
.merchant_reference_id
.to_owned(),
incremental_authorization_allowed: None,
charges: None,
}),
)
}
}
}
None => (
enums::AttemptStatus::Failure,
Err(ErrorResponse {
code: item.response.status.error_code,
status_code: item.http_code,
message: item.response.status.status.unwrap_or_default(),
reason: item.response.status.message,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
),
};
Ok(Self {
status,
response,
..item.data
})
}
}
#[derive(Debug, Deserialize)]
pub struct RapydIncomingWebhook {
pub id: String,
#[serde(rename = "type")]
pub webhook_type: RapydWebhookObjectEventType,
pub data: WebhookData,
pub trigger_operation_id: Option<String>,
pub status: String,
pub created_at: i64,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum RapydWebhookObjectEventType {
PaymentCompleted,
PaymentCaptured,
PaymentFailed,
RefundCompleted,
PaymentRefundRejected,
PaymentRefundFailed,
PaymentDisputeCreated,
PaymentDisputeUpdated,
#[serde(other)]
Unknown,
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, strum::Display)]
pub enum RapydWebhookDisputeStatus {
#[serde(rename = "ACT")]
Active,
#[serde(rename = "RVW")]
Review,
#[serde(rename = "LOS")]
Lose,
#[serde(rename = "WIN")]
Win,
#[serde(other)]
Unknown,
}
impl From<RapydWebhookDisputeStatus> for api_models::webhooks::IncomingWebhookEvent {
fn from(value: RapydWebhookDisputeStatus) -> Self {
match value {
RapydWebhookDisputeStatus::Active => Self::DisputeOpened,
RapydWebhookDisputeStatus::Review => Self::DisputeChallenged,
RapydWebhookDisputeStatus::Lose => Self::DisputeLost,
RapydWebhookDisputeStatus::Win => Self::DisputeWon,
RapydWebhookDisputeStatus::Unknown => Self::EventNotSupported,
}
}
}
#[derive(Debug, Deserialize)]
#[serde(untagged)]
pub enum WebhookData {
Payment(ResponseData),
Refund(RefundResponseData),
Dispute(DisputeResponseData),
}
impl From<ResponseData> for RapydPaymentsResponse {
fn from(value: ResponseData) -> Self {
Self {
status: Status {
error_code: NO_ERROR_CODE.to_owned(),
status: None,
message: None,
response_code: None,
operation_id: None,
},
data: Some(value),
}
}
}
impl From<RefundResponseData> for RefundResponse {
fn from(value: RefundResponseData) -> Self {
Self {
status: Status {
error_code: NO_ERROR_CODE.to_owned(),
status: None,
message: None,
response_code: None,
operation_id: None,
},
data: Some(value),
}
}
}
| 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/klarna/transformers.rs | crates/hyperswitch_connectors/src/connectors/klarna/transformers.rs | use api_models::payments::{KlarnaSessionTokenResponse, SessionToken};
use common_enums::enums;
use common_utils::{pii, types::MinorUnit};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
payment_method_data::{PayLaterData, PaymentMethodData},
router_data::{
AdditionalPaymentMethodConnectorResponse, ConnectorAuthType, ConnectorResponseData,
KlarnaSdkResponse, RouterData,
},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
types,
};
use hyperswitch_interfaces::errors;
use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
types::{
PaymentsCaptureResponseRouterData, PaymentsResponseRouterData,
PaymentsSessionResponseRouterData, RefundsResponseRouterData, ResponseRouterData,
},
utils::{self, AddressData, AddressDetailsData, PaymentsAuthorizeRequestData, RouterData as _},
};
#[derive(Debug, Serialize)]
pub struct KlarnaRouterData<T> {
amount: MinorUnit,
router_data: T,
}
impl<T> From<(MinorUnit, T)> for KlarnaRouterData<T> {
fn from((amount, router_data): (MinorUnit, T)) -> Self {
Self {
amount,
router_data,
}
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct KlarnaConnectorMetadataObject {
pub klarna_region: Option<KlarnaEndpoint>,
}
#[derive(Debug, Serialize, Deserialize)]
pub enum KlarnaEndpoint {
Europe,
NorthAmerica,
Oceania,
}
impl From<KlarnaEndpoint> for String {
fn from(endpoint: KlarnaEndpoint) -> Self {
Self::from(match endpoint {
KlarnaEndpoint::Europe => "",
KlarnaEndpoint::NorthAmerica => "-na",
KlarnaEndpoint::Oceania => "-oc",
})
}
}
impl TryFrom<&Option<pii::SecretSerdeValue>> for KlarnaConnectorMetadataObject {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(meta_data: &Option<pii::SecretSerdeValue>) -> Result<Self, Self::Error> {
let metadata: Self = utils::to_connector_meta_from_secret::<Self>(meta_data.clone())
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "metadata",
})?;
Ok(metadata)
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum PaymentMethodSpecifics {
KlarnaCheckout(KlarnaCheckoutRequestData),
KlarnaSdk,
}
#[derive(Default, Debug, Serialize, Deserialize)]
pub struct MerchantURLs {
terms: String,
checkout: String,
confirmation: String,
push: String,
}
#[derive(Default, Debug, Serialize, Deserialize)]
pub struct KlarnaCheckoutRequestData {
merchant_urls: MerchantURLs,
options: CheckoutOptions,
}
#[derive(Default, Debug, Deserialize, Serialize)]
pub struct KlarnaPaymentsRequest {
order_lines: Vec<OrderLines>,
order_amount: MinorUnit,
purchase_country: enums::CountryAlpha2,
purchase_currency: enums::Currency,
merchant_reference1: Option<String>,
merchant_reference2: Option<String>,
shipping_address: Option<KlarnaShippingAddress>,
auto_capture: Option<bool>,
order_tax_amount: Option<MinorUnit>,
#[serde(flatten)]
payment_method_specifics: Option<PaymentMethodSpecifics>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum KlarnaAuthResponse {
KlarnaPaymentsAuthResponse(PaymentsResponse),
KlarnaCheckoutAuthResponse(CheckoutResponse),
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct PaymentsResponse {
order_id: String,
fraud_status: KlarnaFraudStatus,
authorized_payment_method: Option<AuthorizedPaymentMethod>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct CheckoutResponse {
order_id: String,
status: KlarnaCheckoutStatus,
html_snippet: String,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct AuthorizedPaymentMethod {
#[serde(rename = "type")]
payment_type: String,
}
impl From<AuthorizedPaymentMethod> for AdditionalPaymentMethodConnectorResponse {
fn from(item: AuthorizedPaymentMethod) -> Self {
Self::PayLater {
klarna_sdk: Some(KlarnaSdkResponse {
payment_type: Some(item.payment_type),
}),
}
}
}
#[derive(Debug, Serialize)]
pub struct KlarnaSessionRequest {
intent: KlarnaSessionIntent,
purchase_country: enums::CountryAlpha2,
purchase_currency: enums::Currency,
order_amount: MinorUnit,
order_lines: Vec<OrderLines>,
shipping_address: Option<KlarnaShippingAddress>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct KlarnaShippingAddress {
city: String,
country: enums::CountryAlpha2,
email: pii::Email,
given_name: Secret<String>,
family_name: Secret<String>,
phone: Secret<String>,
postal_code: Secret<String>,
region: Secret<String>,
street_address: Secret<String>,
street_address2: Option<Secret<String>>,
}
#[derive(Default, Debug, Serialize, Deserialize)]
pub struct CheckoutOptions {
auto_capture: bool,
}
#[derive(Deserialize, Serialize, Debug)]
pub struct KlarnaSessionResponse {
pub client_token: Secret<String>,
pub session_id: String,
}
impl TryFrom<&KlarnaRouterData<&types::PaymentsSessionRouterData>> for KlarnaSessionRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &KlarnaRouterData<&types::PaymentsSessionRouterData>,
) -> Result<Self, Self::Error> {
let request = &item.router_data.request;
match request.order_details.clone() {
Some(order_details) => Ok(Self {
intent: KlarnaSessionIntent::Buy,
purchase_country: request.country.ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "billing.address.country",
},
)?,
purchase_currency: request.currency,
order_amount: item.amount,
order_lines: order_details
.iter()
.map(|data| OrderLines {
name: data.product_name.clone(),
quantity: data.quantity,
unit_price: data.amount,
total_amount: data.amount * data.quantity,
total_tax_amount: None,
tax_rate: None,
})
.collect(),
shipping_address: get_address_info(item.router_data.get_optional_shipping())
.transpose()?,
}),
None => Err(report!(errors::ConnectorError::MissingRequiredField {
field_name: "order_details",
})),
}
}
}
impl TryFrom<PaymentsSessionResponseRouterData<KlarnaSessionResponse>>
for types::PaymentsSessionRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsSessionResponseRouterData<KlarnaSessionResponse>,
) -> Result<Self, Self::Error> {
let response = &item.response;
Ok(Self {
response: Ok(PaymentsResponseData::SessionResponse {
session_token: SessionToken::Klarna(Box::new(KlarnaSessionTokenResponse {
session_token: response.client_token.clone().expose(),
session_id: response.session_id.clone(),
})),
}),
..item.data
})
}
}
impl TryFrom<&KlarnaRouterData<&types::PaymentsAuthorizeRouterData>> for KlarnaPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &KlarnaRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let request = &item.router_data.request;
let payment_method_data = request.payment_method_data.clone();
let return_url = item.router_data.request.get_router_return_url()?;
let webhook_url = item.router_data.request.get_webhook_url()?;
match payment_method_data {
PaymentMethodData::PayLater(PayLaterData::KlarnaSdk { .. }) => {
match request.order_details.clone() {
Some(order_details) => Ok(Self {
purchase_country: item.router_data.get_billing_country()?,
purchase_currency: request.currency,
order_amount: item.amount,
order_lines: order_details
.iter()
.map(|data| OrderLines {
name: data.product_name.clone(),
quantity: data.quantity,
unit_price: data.amount,
total_amount: data.amount * data.quantity,
total_tax_amount: None,
tax_rate: None,
})
.collect(),
merchant_reference1: Some(
item.router_data.connector_request_reference_id.clone(),
),
merchant_reference2: item
.router_data
.request
.merchant_order_reference_id
.clone(),
auto_capture: Some(request.is_auto_capture()?),
shipping_address: get_address_info(
item.router_data.get_optional_shipping(),
)
.transpose()?,
order_tax_amount: None,
payment_method_specifics: None,
}),
None => Err(report!(errors::ConnectorError::MissingRequiredField {
field_name: "order_details"
})),
}
}
PaymentMethodData::PayLater(PayLaterData::KlarnaRedirect {}) => {
match request.order_details.clone() {
Some(order_details) => Ok(Self {
purchase_country: item.router_data.get_billing_country()?,
purchase_currency: request.currency,
order_amount: item.amount
- request.order_tax_amount.unwrap_or(MinorUnit::zero()),
order_tax_amount: request.order_tax_amount,
order_lines: order_details
.iter()
.map(|data| OrderLines {
name: data.product_name.clone(),
quantity: data.quantity,
unit_price: data.amount,
total_amount: data.amount * data.quantity,
total_tax_amount: data.total_tax_amount,
tax_rate: data.tax_rate,
})
.collect(),
payment_method_specifics: Some(PaymentMethodSpecifics::KlarnaCheckout(
KlarnaCheckoutRequestData {
merchant_urls: MerchantURLs {
terms: return_url.clone(),
checkout: return_url.clone(),
confirmation: return_url,
push: webhook_url,
},
options: CheckoutOptions {
auto_capture: request.is_auto_capture()?,
},
},
)),
shipping_address: get_address_info(
item.router_data.get_optional_shipping(),
)
.transpose()?,
merchant_reference1: Some(
item.router_data.connector_request_reference_id.clone(),
),
merchant_reference2: item
.router_data
.request
.merchant_order_reference_id
.clone(),
auto_capture: None,
}),
None => Err(report!(errors::ConnectorError::MissingRequiredField {
field_name: "order_details"
})),
}
}
_ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()),
}
}
}
fn get_address_info(
address: Option<&hyperswitch_domain_models::address::Address>,
) -> Option<Result<KlarnaShippingAddress, error_stack::Report<errors::ConnectorError>>> {
address.and_then(|add| {
add.address.as_ref().map(
|address_details| -> Result<KlarnaShippingAddress, error_stack::Report<errors::ConnectorError>> {
Ok(KlarnaShippingAddress {
city: address_details.get_city()?.to_owned(),
country: address_details.get_country()?.to_owned(),
email: add.get_email()?.to_owned(),
postal_code: address_details.get_zip()?.to_owned(),
region: address_details.to_state_code()?.to_owned(),
street_address: address_details.get_line1()?.to_owned(),
street_address2: address_details.get_optional_line2(),
given_name: address_details.get_first_name()?.to_owned(),
family_name: address_details.get_last_name()?.to_owned(),
phone: add.get_phone_with_country_code()?.to_owned(),
})
},
)
})
}
impl TryFrom<PaymentsResponseRouterData<KlarnaAuthResponse>>
for types::PaymentsAuthorizeRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: PaymentsResponseRouterData<KlarnaAuthResponse>) -> Result<Self, Self::Error> {
match item.response {
KlarnaAuthResponse::KlarnaPaymentsAuthResponse(ref response) => {
let connector_response =
response
.authorized_payment_method
.as_ref()
.map(|authorized_payment_method| {
ConnectorResponseData::with_additional_payment_method_data(
AdditionalPaymentMethodConnectorResponse::from(
authorized_payment_method.clone(),
),
)
});
Ok(Self {
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(response.order_id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(response.order_id.clone()),
incremental_authorization_allowed: None,
charges: None,
}),
status: get_fraud_status(
response.fraud_status.clone(),
item.data.request.is_auto_capture()?,
),
connector_response,
..item.data
})
}
KlarnaAuthResponse::KlarnaCheckoutAuthResponse(ref response) => Ok(Self {
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(response.order_id.clone()),
redirection_data: Box::new(Some(RedirectForm::Html {
html_data: response.html_snippet.clone(),
})),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(response.order_id.clone()),
incremental_authorization_allowed: None,
charges: None,
}),
status: get_checkout_status(
response.status.clone(),
item.data.request.is_auto_capture()?,
),
connector_response: None,
..item.data
}),
}
}
}
#[derive(Default, Debug, Serialize, Deserialize)]
pub struct OrderLines {
name: String,
quantity: u16,
unit_price: MinorUnit,
total_amount: MinorUnit,
total_tax_amount: Option<MinorUnit>,
tax_rate: Option<f64>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
#[allow(dead_code)]
pub enum KlarnaSessionIntent {
Buy,
Tokenize,
BuyAndTokenize,
}
pub struct KlarnaAuthType {
pub username: Secret<String>,
pub password: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for KlarnaAuthType {
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 {
username: key1.to_owned(),
password: api_key.to_owned(),
})
} else {
Err(errors::ConnectorError::FailedToObtainAuthType.into())
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum KlarnaFraudStatus {
Accepted,
Pending,
Rejected,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum KlarnaCheckoutStatus {
CheckoutComplete,
CheckoutIncomplete,
}
fn get_fraud_status(
klarna_status: KlarnaFraudStatus,
is_auto_capture: bool,
) -> common_enums::AttemptStatus {
match klarna_status {
KlarnaFraudStatus::Accepted => {
if is_auto_capture {
common_enums::AttemptStatus::Charged
} else {
common_enums::AttemptStatus::Authorized
}
}
KlarnaFraudStatus::Pending => common_enums::AttemptStatus::Pending,
KlarnaFraudStatus::Rejected => common_enums::AttemptStatus::Failure,
}
}
fn get_checkout_status(
klarna_status: KlarnaCheckoutStatus,
is_auto_capture: bool,
) -> common_enums::AttemptStatus {
match klarna_status {
KlarnaCheckoutStatus::CheckoutIncomplete => {
if is_auto_capture {
common_enums::AttemptStatus::AuthenticationPending
} else {
common_enums::AttemptStatus::Authorized
}
}
KlarnaCheckoutStatus::CheckoutComplete => common_enums::AttemptStatus::Charged,
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum KlarnaPsyncResponse {
KlarnaSDKPsyncResponse(KlarnaSDKSyncResponse),
KlarnaCheckoutPSyncResponse(KlarnaCheckoutSyncResponse),
}
#[derive(Debug, Serialize, Deserialize)]
pub struct KlarnaSDKSyncResponse {
pub order_id: String,
pub status: KlarnaPaymentStatus,
pub klarna_reference: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct KlarnaCheckoutSyncResponse {
pub order_id: String,
pub status: KlarnaCheckoutStatus,
pub options: CheckoutOptions,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum KlarnaPaymentStatus {
Authorized,
PartCaptured,
Captured,
Cancelled,
Expired,
Closed,
}
impl From<KlarnaPaymentStatus> for enums::AttemptStatus {
fn from(item: KlarnaPaymentStatus) -> Self {
match item {
KlarnaPaymentStatus::Authorized => Self::Authorized,
KlarnaPaymentStatus::PartCaptured => Self::PartialCharged,
KlarnaPaymentStatus::Captured => Self::Charged,
KlarnaPaymentStatus::Cancelled => Self::Voided,
KlarnaPaymentStatus::Expired | KlarnaPaymentStatus::Closed => Self::Failure,
}
}
}
impl<F, T> TryFrom<ResponseRouterData<F, KlarnaPsyncResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, KlarnaPsyncResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
match item.response {
KlarnaPsyncResponse::KlarnaSDKPsyncResponse(response) => Ok(Self {
status: enums::AttemptStatus::from(response.status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(response.order_id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: response
.klarna_reference
.or(Some(response.order_id.clone())),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
}),
KlarnaPsyncResponse::KlarnaCheckoutPSyncResponse(response) => Ok(Self {
status: get_checkout_status(response.status.clone(), response.options.auto_capture),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(response.order_id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(response.order_id.clone()),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
}),
}
}
}
#[derive(Debug, Serialize)]
pub struct KlarnaCaptureRequest {
captured_amount: MinorUnit,
reference: Option<String>,
}
impl TryFrom<&KlarnaRouterData<&types::PaymentsCaptureRouterData>> for KlarnaCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &KlarnaRouterData<&types::PaymentsCaptureRouterData>,
) -> Result<Self, Self::Error> {
let reference = Some(item.router_data.connector_request_reference_id.clone());
Ok(Self {
reference,
captured_amount: item.amount.to_owned(),
})
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct KlarnaMeta {
capture_id: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct KlarnaCaptureResponse {
pub capture_id: Option<String>,
}
impl TryFrom<PaymentsCaptureResponseRouterData<KlarnaCaptureResponse>>
for types::PaymentsCaptureRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsCaptureResponseRouterData<KlarnaCaptureResponse>,
) -> Result<Self, Self::Error> {
let connector_meta = serde_json::json!(KlarnaMeta {
capture_id: item.response.capture_id,
});
// https://docs.klarna.com/api/ordermanagement/#operation/captureOrder
// If 201 status code, then order is captured, other status codes are handled by the error handler
let status = if item.http_code == 201 {
enums::AttemptStatus::Charged
} else {
item.data.status
};
let resource_id = item.data.request.connector_transaction_id.clone();
Ok(Self {
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(resource_id),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: Some(connector_meta),
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
status,
..item.data
})
}
}
#[derive(Default, Debug, Serialize)]
pub struct KlarnaRefundRequest {
refunded_amount: MinorUnit,
reference: Option<String>,
}
impl<F> TryFrom<&KlarnaRouterData<&types::RefundsRouterData<F>>> for KlarnaRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &KlarnaRouterData<&types::RefundsRouterData<F>>,
) -> Result<Self, Self::Error> {
let request = &item.router_data.request;
Ok(Self {
refunded_amount: item.amount,
reference: Some(request.refund_id.clone()),
})
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct KlarnaRefundResponse {
pub refund_id: String,
}
impl TryFrom<RefundsResponseRouterData<Execute, KlarnaRefundResponse>>
for types::RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, KlarnaRefundResponse>,
) -> Result<Self, Self::Error> {
// https://docs.klarna.com/api/ordermanagement/#operation/refundOrder
// If 201 status code, then Refund is Successful, other status codes are handled by the error handler
let status = if item.http_code == 201 {
enums::RefundStatus::Pending
} else {
enums::RefundStatus::Failure
};
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.refund_id,
refund_status: status,
}),
..item.data
})
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct KlarnaRefundSyncResponse {
pub refund_id: String,
}
impl TryFrom<RefundsResponseRouterData<RSync, KlarnaRefundSyncResponse>>
for types::RefundsRouterData<RSync>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, KlarnaRefundSyncResponse>,
) -> Result<Self, Self::Error> {
// https://docs.klarna.com/api/ordermanagement/#operation/get
// If 200 status code, then Refund is Successful, other status codes are handled by the error handler
let status = if item.http_code == 200 {
enums::RefundStatus::Success
} else {
enums::RefundStatus::Failure
};
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.refund_id,
refund_status: status,
}),
..item.data
})
}
}
#[derive(Deserialize, Serialize, Debug)]
pub struct KlarnaErrorResponse {
pub error_code: String,
pub error_messages: Option<Vec<String>>,
pub 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/thunes/transformers.rs | crates/hyperswitch_connectors/src/connectors/thunes/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 ThunesRouterData<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 ThunesRouterData<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 ThunesPaymentsRequest {
amount: StringMinorUnit,
card: ThunesCard,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct ThunesCard {
number: cards::CardNumber,
expiry_month: Secret<String>,
expiry_year: Secret<String>,
cvc: Secret<String>,
complete: bool,
}
impl TryFrom<&ThunesRouterData<&PaymentsAuthorizeRouterData>> for ThunesPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &ThunesRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(req_card) => {
let card = ThunesCard {
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 methods".to_string()).into()),
}
}
}
//TODO: Fill the struct with respective fields
// Auth Struct
pub struct ThunesAuthType {
pub(super) api_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for ThunesAuthType {
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 ThunesPaymentStatus {
Succeeded,
Failed,
#[default]
Processing,
}
impl From<ThunesPaymentStatus> for common_enums::AttemptStatus {
fn from(item: ThunesPaymentStatus) -> Self {
match item {
ThunesPaymentStatus::Succeeded => Self::Charged,
ThunesPaymentStatus::Failed => Self::Failure,
ThunesPaymentStatus::Processing => Self::Authorizing,
}
}
}
//TODO: Fill the struct with respective fields
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ThunesPaymentsResponse {
status: ThunesPaymentStatus,
id: String,
}
impl<F, T> TryFrom<ResponseRouterData<F, ThunesPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, ThunesPaymentsResponse, 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 ThunesRefundRequest {
pub amount: StringMinorUnit,
}
impl<F> TryFrom<&ThunesRouterData<&RefundsRouterData<F>>> for ThunesRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &ThunesRouterData<&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 ThunesErrorResponse {
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/sift/transformers.rs | crates/hyperswitch_connectors/src/connectors/sift/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 SiftRouterData<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 SiftRouterData<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 SiftPaymentsRequest {
amount: StringMinorUnit,
card: SiftCard,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct SiftCard {
number: cards::CardNumber,
expiry_month: Secret<String>,
expiry_year: Secret<String>,
cvc: Secret<String>,
complete: bool,
}
impl TryFrom<&SiftRouterData<&PaymentsAuthorizeRouterData>> for SiftPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &SiftRouterData<&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 SiftAuthType {
pub(super) api_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for SiftAuthType {
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 SiftPaymentStatus {
Succeeded,
Failed,
#[default]
Processing,
}
impl From<SiftPaymentStatus> for common_enums::AttemptStatus {
fn from(item: SiftPaymentStatus) -> Self {
match item {
SiftPaymentStatus::Succeeded => Self::Charged,
SiftPaymentStatus::Failed => Self::Failure,
SiftPaymentStatus::Processing => Self::Authorizing,
}
}
}
//TODO: Fill the struct with respective fields
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct SiftPaymentsResponse {
status: SiftPaymentStatus,
id: String,
}
impl<F, T> TryFrom<ResponseRouterData<F, SiftPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, SiftPaymentsResponse, 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 SiftRefundRequest {
pub amount: StringMinorUnit,
}
impl<F> TryFrom<&SiftRouterData<&RefundsRouterData<F>>> for SiftRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &SiftRouterData<&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 SiftErrorResponse {
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/coingate/transformers.rs | crates/hyperswitch_connectors/src/connectors/coingate/transformers.rs | use std::collections::HashMap;
use common_enums::{enums, Currency};
use common_utils::{ext_traits::OptionExt, pii, request::Method, types::StringMajorUnit};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{ConnectorAuthType, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
types::{PaymentsAuthorizeRouterData, PaymentsSyncRouterData, RefundsRouterData},
};
use hyperswitch_interfaces::errors;
use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
types::{PaymentsSyncResponseRouterData, RefundsResponseRouterData, ResponseRouterData},
utils::{self, PaymentsAuthorizeRequestData},
};
pub struct CoingateRouterData<T> {
pub amount: StringMajorUnit,
pub router_data: T,
}
impl<T> From<(StringMajorUnit, T)> for CoingateRouterData<T> {
fn from((amount, item): (StringMajorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct CoingateConnectorMetadataObject {
pub currency_id: i32,
pub platform_id: i32,
pub ledger_account_id: Secret<String>,
}
impl TryFrom<&Option<pii::SecretSerdeValue>> for CoingateConnectorMetadataObject {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(meta_data: &Option<pii::SecretSerdeValue>) -> Result<Self, Self::Error> {
let metadata: Self = utils::to_connector_meta_from_secret::<Self>(meta_data.clone())
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "metadata",
})?;
Ok(metadata)
}
}
#[derive(Default, Debug, Serialize, PartialEq)]
pub struct CoingatePaymentsRequest {
price_amount: StringMajorUnit,
price_currency: Currency,
receive_currency: String,
callback_url: String,
success_url: Option<String>,
cancel_url: Option<String>,
title: String,
token: Secret<String>,
}
impl TryFrom<&CoingateRouterData<&PaymentsAuthorizeRouterData>> for CoingatePaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &CoingateRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let auth = CoingateAuthType::try_from(&item.router_data.connector_auth_type)?;
Ok(match item.router_data.request.payment_method_data {
PaymentMethodData::Crypto(_) => Ok(Self {
price_amount: item.amount.clone(),
price_currency: item.router_data.request.currency,
receive_currency: "DO_NOT_CONVERT".to_string(),
callback_url: item.router_data.request.get_webhook_url()?,
success_url: item.router_data.request.router_return_url.clone(),
cancel_url: item.router_data.request.router_return_url.clone(),
title: item.router_data.connector_request_reference_id.clone(),
token: auth.merchant_token,
}),
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Coingate"),
)),
}?)
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct CoingateSyncResponse {
status: CoingatePaymentStatus,
id: i64,
}
impl TryFrom<PaymentsSyncResponseRouterData<CoingateSyncResponse>> for PaymentsSyncRouterData {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsSyncResponseRouterData<CoingateSyncResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: enums::AttemptStatus::from(item.response.status.clone()),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.to_string()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
pub struct CoingateAuthType {
pub(super) api_key: Secret<String>,
pub(super) merchant_token: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for CoingateAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
api_key: api_key.to_owned(),
merchant_token: key1.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum CoingatePaymentStatus {
New,
Pending,
Confirming,
Paid,
Invalid,
Expired,
Canceled,
}
impl From<CoingatePaymentStatus> for common_enums::AttemptStatus {
fn from(item: CoingatePaymentStatus) -> Self {
match item {
CoingatePaymentStatus::Paid => Self::Charged,
CoingatePaymentStatus::Canceled
| CoingatePaymentStatus::Expired
| CoingatePaymentStatus::Invalid => Self::Failure,
CoingatePaymentStatus::Confirming | CoingatePaymentStatus::New => {
Self::AuthenticationPending
}
CoingatePaymentStatus::Pending => Self::Pending,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct CoingatePaymentsResponse {
status: CoingatePaymentStatus,
id: i64,
payment_url: Option<String>,
order_id: Option<String>,
}
impl<F, T> TryFrom<ResponseRouterData<F, CoingatePaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, CoingatePaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: enums::AttemptStatus::from(item.response.status.clone()),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.to_string()),
redirection_data: Box::new(Some(RedirectForm::Form {
endpoint: item.response.payment_url.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "payment_url",
},
)?,
method: Method::Get,
form_fields: HashMap::new(),
})),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: item.response.order_id.clone(),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Default, Debug, Serialize)]
pub struct CoingateRefundRequest {
pub amount: StringMajorUnit,
pub address: Secret<String>,
pub currency_id: i32,
pub platform_id: i32,
pub reason: String,
pub email: pii::Email,
pub ledger_account_id: Secret<String>,
}
impl<F> TryFrom<&CoingateRouterData<&RefundsRouterData<F>>> for CoingateRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &CoingateRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
let metadata: CoingateConnectorMetadataObject =
utils::to_connector_meta_from_secret(item.router_data.connector_meta_data.clone())
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "merchant_connector_account.metadata",
})?;
let refund_metadata = item
.router_data
.request
.refund_connector_metadata
.as_ref()
.get_required_value("refund_connector_metadata")
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "refund_connector_metadata",
})?
.clone()
.expose();
let address: Secret<String> = serde_json::from_value::<Secret<String>>(
refund_metadata.get("address").cloned().ok_or_else(|| {
errors::ConnectorError::MissingRequiredField {
field_name: "address",
}
})?,
)
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "address",
})?;
let email: pii::Email = serde_json::from_value::<pii::Email>(
refund_metadata.get("email").cloned().ok_or_else(|| {
errors::ConnectorError::MissingRequiredField {
field_name: "email",
}
})?,
)
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "email",
})?;
Ok(Self {
amount: item.amount.clone(),
address,
currency_id: metadata.currency_id,
platform_id: metadata.platform_id,
reason: item.router_data.request.reason.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "refund.reason",
},
)?,
email,
ledger_account_id: metadata.ledger_account_id,
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct CoingateRefundResponse {
pub status: CoingateRefundStatus,
pub id: i64,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum CoingateRefundStatus {
Pending,
Completed,
Rejected,
Processing,
}
impl TryFrom<RefundsResponseRouterData<Execute, CoingateRefundResponse>>
for RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, CoingateRefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, CoingateRefundResponse>>
for RefundsRouterData<RSync>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, CoingateRefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
impl From<CoingateRefundStatus> for common_enums::RefundStatus {
fn from(item: CoingateRefundStatus) -> Self {
match item {
CoingateRefundStatus::Pending => Self::Pending,
CoingateRefundStatus::Completed => Self::Success,
CoingateRefundStatus::Rejected => Self::Failure,
CoingateRefundStatus::Processing => Self::Pending,
}
}
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct CoingateErrorResponse {
pub message: String,
pub reason: String,
pub errors: Option<Vec<String>>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct CoingateWebhookBody {
pub token: Secret<String>,
pub status: CoingatePaymentStatus,
pub id: i64,
}
| 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/prophetpay/transformers.rs | crates/hyperswitch_connectors/src/connectors/prophetpay/transformers.rs | use std::collections::HashMap;
use common_enums::enums;
use common_utils::{
consts::{PROPHETPAY_REDIRECT_URL, PROPHETPAY_TOKEN},
errors::CustomResult,
request::Method,
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{CardRedirectData, PaymentMethodData},
router_data::{ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::refunds::Execute,
router_request_types::{CompleteAuthorizeData, CompleteAuthorizeRedirectResponse, ResponseId},
router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
types,
};
use hyperswitch_interfaces::{api, consts::NO_ERROR_CODE, errors};
use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use url::Url;
use crate::{
types::{PaymentsResponseRouterData, RefundsResponseRouterData, ResponseRouterData},
utils::{self, to_connector_meta},
};
pub struct ProphetpayRouterData<T> {
pub amount: f64,
pub router_data: T,
}
impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for ProphetpayRouterData<T> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(currency_unit, currency, amount, item): (&api::CurrencyUnit, enums::Currency, i64, T),
) -> Result<Self, Self::Error> {
let amount = utils::get_amount_as_f64(currency_unit, amount, currency)?;
Ok(Self {
amount,
router_data: item,
})
}
}
pub struct ProphetpayAuthType {
pub(super) user_name: Secret<String>,
pub(super) password: Secret<String>,
pub(super) profile_id: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for ProphetpayAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} => Ok(Self {
user_name: api_key.to_owned(),
password: key1.to_owned(),
profile_id: api_secret.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "PascalCase")]
pub struct ProphetpayTokenRequest {
ref_info: String,
profile: Secret<String>,
entry_method: i8,
token_type: i8,
card_entry_context: i8,
}
#[derive(Debug, Clone)]
pub enum ProphetpayEntryMethod {
ManualEntry,
CardSwipe,
}
impl ProphetpayEntryMethod {
fn get_entry_method(&self) -> i8 {
match self {
Self::ManualEntry => 1,
Self::CardSwipe => 2,
}
}
}
#[derive(Debug, Clone)]
#[repr(i8)]
pub enum ProphetpayTokenType {
Normal,
SaleTab,
TemporarySave,
}
impl ProphetpayTokenType {
fn get_token_type(&self) -> i8 {
match self {
Self::Normal => 0,
Self::SaleTab => 1,
Self::TemporarySave => 2,
}
}
}
#[derive(Debug, Clone)]
#[repr(i8)]
pub enum ProphetpayCardContext {
NotApplicable,
WebConsumerInitiated,
}
impl ProphetpayCardContext {
fn get_card_context(&self) -> i8 {
match self {
Self::NotApplicable => 0,
Self::WebConsumerInitiated => 5,
}
}
}
impl TryFrom<&ProphetpayRouterData<&types::PaymentsAuthorizeRouterData>>
for ProphetpayTokenRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &ProphetpayRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
if item.router_data.request.currency == api_models::enums::Currency::USD {
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::CardRedirect(CardRedirectData::CardRedirect {}) => {
let auth_data =
ProphetpayAuthType::try_from(&item.router_data.connector_auth_type)?;
Ok(Self {
ref_info: item.router_data.connector_request_reference_id.to_owned(),
profile: auth_data.profile_id,
entry_method: ProphetpayEntryMethod::get_entry_method(
&ProphetpayEntryMethod::ManualEntry,
),
token_type: ProphetpayTokenType::get_token_type(
&ProphetpayTokenType::SaleTab,
),
card_entry_context: ProphetpayCardContext::get_card_context(
&ProphetpayCardContext::WebConsumerInitiated,
),
})
}
_ => Err(
errors::ConnectorError::NotImplemented("Payment methods".to_string()).into(),
),
}
} else {
Err(errors::ConnectorError::CurrencyNotSupported {
message: item.router_data.request.currency.to_string(),
connector: "Prophetpay",
}
.into())
}
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ProphetpayTokenResponse {
hosted_tokenize_id: Secret<String>,
}
impl TryFrom<PaymentsResponseRouterData<ProphetpayTokenResponse>>
for types::PaymentsAuthorizeRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsResponseRouterData<ProphetpayTokenResponse>,
) -> Result<Self, Self::Error> {
let url_data = format!(
"{}{}",
PROPHETPAY_REDIRECT_URL,
item.response.hosted_tokenize_id.expose()
);
let redirect_url = Url::parse(url_data.as_str())
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
let redirection_data = get_redirect_url_form(
redirect_url,
item.data.request.complete_authorize_url.clone(),
)
.ok();
Ok(Self {
status: enums::AttemptStatus::AuthenticationPending,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
fn get_redirect_url_form(
mut redirect_url: Url,
complete_auth_url: Option<String>,
) -> CustomResult<RedirectForm, errors::ConnectorError> {
let mut form_fields = HashMap::<String, String>::new();
form_fields.insert(
String::from("redirectUrl"),
complete_auth_url.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "complete_auth_url",
})?,
);
// Do not include query params in the endpoint
redirect_url.set_query(None);
Ok(RedirectForm::Form {
endpoint: redirect_url.to_string(),
method: Method::Get,
form_fields,
})
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ProphetpayCompleteRequest {
amount: f64,
ref_info: String,
inquiry_reference: String,
profile: Secret<String>,
action_type: i8,
card_token: Secret<String>,
}
impl TryFrom<&ProphetpayRouterData<&types::PaymentsCompleteAuthorizeRouterData>>
for ProphetpayCompleteRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &ProphetpayRouterData<&types::PaymentsCompleteAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let auth_data = ProphetpayAuthType::try_from(&item.router_data.connector_auth_type)?;
let card_token = Secret::new(get_card_token(
item.router_data.request.redirect_response.clone(),
)?);
Ok(Self {
amount: item.amount.to_owned(),
ref_info: item.router_data.connector_request_reference_id.to_owned(),
inquiry_reference: item.router_data.connector_request_reference_id.clone(),
profile: auth_data.profile_id,
action_type: ProphetpayActionType::get_action_type(&ProphetpayActionType::Charge),
card_token,
})
}
}
fn get_card_token(
response: Option<CompleteAuthorizeRedirectResponse>,
) -> CustomResult<String, errors::ConnectorError> {
let res = response.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "redirect_response",
})?;
let queries_params = res
.params
.map(|param| {
let mut queries = HashMap::<String, String>::new();
let values = param.peek().split('&').collect::<Vec<&str>>();
for value in values {
let pair = value.split('=').collect::<Vec<&str>>();
queries.insert(
pair.first()
.ok_or(errors::ConnectorError::ResponseDeserializationFailed)?
.to_string(),
pair.get(1)
.ok_or(errors::ConnectorError::ResponseDeserializationFailed)?
.to_string(),
);
}
Ok::<_, errors::ConnectorError>(queries)
})
.transpose()?
.ok_or(errors::ConnectorError::ResponseDeserializationFailed)?;
for (key, val) in queries_params {
if key.as_str() == PROPHETPAY_TOKEN {
return Ok(val);
}
}
Err(errors::ConnectorError::MissingRequiredField {
field_name: "card_token",
}
.into())
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ProphetpaySyncRequest {
transaction_id: String,
ref_info: String,
inquiry_reference: String,
profile: Secret<String>,
action_type: i8,
}
#[derive(Debug, Clone)]
pub enum ProphetpayActionType {
Charge,
Refund,
Inquiry,
}
impl ProphetpayActionType {
fn get_action_type(&self) -> i8 {
match self {
Self::Charge => 1,
Self::Refund => 3,
Self::Inquiry => 7,
}
}
}
impl TryFrom<&types::PaymentsSyncRouterData> for ProphetpaySyncRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::PaymentsSyncRouterData) -> Result<Self, Self::Error> {
let auth_data = ProphetpayAuthType::try_from(&item.connector_auth_type)?;
let transaction_id = item
.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
Ok(Self {
transaction_id,
ref_info: item.connector_request_reference_id.to_owned(),
inquiry_reference: item.connector_request_reference_id.clone(),
profile: auth_data.profile_id,
action_type: ProphetpayActionType::get_action_type(&ProphetpayActionType::Inquiry),
})
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ProphetpayCompleteAuthResponse {
pub success: bool,
pub response_text: String,
#[serde(rename = "transactionID")]
pub transaction_id: String,
pub response_code: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProphetpayCardTokenData {
card_token: Secret<String>,
}
impl<F>
TryFrom<
ResponseRouterData<
F,
ProphetpayCompleteAuthResponse,
CompleteAuthorizeData,
PaymentsResponseData,
>,
> for RouterData<F, CompleteAuthorizeData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
ProphetpayCompleteAuthResponse,
CompleteAuthorizeData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
if item.response.success {
let card_token = get_card_token(item.data.request.redirect_response.clone())?;
let card_token_data = ProphetpayCardTokenData {
card_token: Secret::from(card_token),
};
let connector_metadata = serde_json::to_value(card_token_data).ok();
Ok(Self {
status: enums::AttemptStatus::Charged,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.transaction_id),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
} else {
Ok(Self {
status: enums::AttemptStatus::Failure,
response: Err(ErrorResponse {
code: item.response.response_code,
message: item.response.response_text.clone(),
reason: Some(item.response.response_text),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
})
}
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ProphetpaySyncResponse {
success: bool,
pub response_text: String,
#[serde(rename = "transactionID")]
pub transaction_id: String,
}
impl<F, T> TryFrom<ResponseRouterData<F, ProphetpaySyncResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, ProphetpaySyncResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
if item.response.success {
Ok(Self {
status: enums::AttemptStatus::Charged,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.transaction_id),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
} else {
Ok(Self {
status: enums::AttemptStatus::Failure,
response: Err(ErrorResponse {
code: NO_ERROR_CODE.to_string(),
message: item.response.response_text.clone(),
reason: Some(item.response.response_text),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
})
}
}
}
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ProphetpayVoidResponse {
pub success: bool,
pub response_text: String,
#[serde(rename = "transactionID")]
pub transaction_id: String,
}
impl<F, T> TryFrom<ResponseRouterData<F, ProphetpayVoidResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, ProphetpayVoidResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
if item.response.success {
Ok(Self {
status: enums::AttemptStatus::Voided,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.transaction_id),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
} else {
Ok(Self {
status: enums::AttemptStatus::VoidFailed,
response: Err(ErrorResponse {
code: NO_ERROR_CODE.to_string(),
message: item.response.response_text.clone(),
reason: Some(item.response.response_text),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
})
}
}
}
#[derive(Default, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ProphetpayVoidRequest {
pub transaction_id: String,
pub profile: Secret<String>,
pub ref_info: String,
pub inquiry_reference: String,
pub action_type: i8,
}
impl TryFrom<&types::PaymentsCancelRouterData> for ProphetpayVoidRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::PaymentsCancelRouterData) -> Result<Self, Self::Error> {
let auth_data = ProphetpayAuthType::try_from(&item.connector_auth_type)?;
let transaction_id = item.request.connector_transaction_id.to_owned();
Ok(Self {
transaction_id,
ref_info: item.connector_request_reference_id.to_owned(),
inquiry_reference: item.connector_request_reference_id.clone(),
profile: auth_data.profile_id,
action_type: ProphetpayActionType::get_action_type(&ProphetpayActionType::Inquiry),
})
}
}
#[derive(Default, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ProphetpayRefundRequest {
pub amount: f64,
pub card_token: Secret<String>,
pub transaction_id: String,
pub profile: Secret<String>,
pub ref_info: String,
pub inquiry_reference: String,
pub action_type: i8,
}
impl<F> TryFrom<&ProphetpayRouterData<&types::RefundsRouterData<F>>> for ProphetpayRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &ProphetpayRouterData<&types::RefundsRouterData<F>>,
) -> Result<Self, Self::Error> {
if item.router_data.request.payment_amount == item.router_data.request.refund_amount {
let auth_data = ProphetpayAuthType::try_from(&item.router_data.connector_auth_type)?;
let transaction_id = item.router_data.request.connector_transaction_id.to_owned();
let card_token_data: ProphetpayCardTokenData =
to_connector_meta(item.router_data.request.connector_metadata.clone())?;
Ok(Self {
transaction_id,
amount: item.amount.to_owned(),
card_token: card_token_data.card_token,
profile: auth_data.profile_id,
ref_info: item.router_data.request.refund_id.to_owned(),
inquiry_reference: item.router_data.request.refund_id.clone(),
action_type: ProphetpayActionType::get_action_type(&ProphetpayActionType::Refund),
})
} else {
Err(errors::ConnectorError::NotImplemented("Partial Refund".to_string()).into())
}
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ProphetpayRefundResponse {
pub success: bool,
pub response_text: String,
pub tran_seq_number: Option<String>,
}
impl TryFrom<RefundsResponseRouterData<Execute, ProphetpayRefundResponse>>
for types::RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, ProphetpayRefundResponse>,
) -> Result<Self, Self::Error> {
if item.response.success {
Ok(Self {
response: Ok(RefundsResponseData {
// no refund id is generated, tranSeqNumber is kept for future usage
connector_refund_id: item.response.tran_seq_number.ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "tran_seq_number",
},
)?,
refund_status: enums::RefundStatus::Success,
}),
..item.data
})
} else {
Ok(Self {
status: enums::AttemptStatus::Failure,
response: Err(ErrorResponse {
code: NO_ERROR_CODE.to_string(),
message: item.response.response_text.clone(),
reason: Some(item.response.response_text),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
})
}
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ProphetpayRefundSyncResponse {
pub success: bool,
pub response_text: String,
}
impl<T> TryFrom<RefundsResponseRouterData<T, ProphetpayRefundSyncResponse>>
for types::RefundsRouterData<T>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<T, ProphetpayRefundSyncResponse>,
) -> Result<Self, Self::Error> {
if item.response.success {
Ok(Self {
response: Ok(RefundsResponseData {
// no refund id is generated, rather transaction id is used for referring to status in refund also
connector_refund_id: item.data.request.connector_transaction_id.clone(),
refund_status: enums::RefundStatus::Success,
}),
..item.data
})
} else {
Ok(Self {
status: enums::AttemptStatus::Failure,
response: Err(ErrorResponse {
code: NO_ERROR_CODE.to_string(),
message: item.response.response_text.clone(),
reason: Some(item.response.response_text),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
})
}
}
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ProphetpayRefundSyncRequest {
transaction_id: String,
inquiry_reference: String,
ref_info: String,
profile: Secret<String>,
action_type: i8,
}
impl TryFrom<&types::RefundSyncRouterData> for ProphetpayRefundSyncRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::RefundSyncRouterData) -> Result<Self, Self::Error> {
let auth_data = ProphetpayAuthType::try_from(&item.connector_auth_type)?;
Ok(Self {
transaction_id: item.request.connector_transaction_id.clone(),
ref_info: item.connector_request_reference_id.to_owned(),
inquiry_reference: item.connector_request_reference_id.clone(),
profile: auth_data.profile_id,
action_type: ProphetpayActionType::get_action_type(&ProphetpayActionType::Inquiry),
})
}
}
| 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/cybersource/transformers.rs | crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs | use api_models::payments;
#[cfg(feature = "payouts")]
use api_models::payouts::PayoutMethodData;
use base64::Engine;
use cards::NetworkToken;
use common_enums::{enums, FutureUsage};
use common_types::payments::{ApplePayPredecryptData, GPayPredecryptData};
use common_utils::{
consts, date_time,
ext_traits::{OptionExt, ValueExt},
pii,
types::{SemanticVersion, StringMajorUnit},
};
use error_stack::ResultExt;
#[cfg(feature = "payouts")]
use hyperswitch_domain_models::{
address::{AddressDetails, PhoneDetails},
router_flow_types::PoFulfill,
router_response_types::PayoutsResponseData,
types::PayoutsRouterData,
};
use hyperswitch_domain_models::{
payment_method_data::{
ApplePayWalletData, GooglePayWalletData, NetworkTokenData, PaymentMethodData,
SamsungPayWalletData, WalletData,
},
router_data::{
AdditionalPaymentMethodConnectorResponse, ConnectorAuthType, ConnectorResponseData,
ErrorResponse, PaymentMethodToken, RouterData,
},
router_flow_types::{
payments::Authorize,
refunds::{Execute, RSync},
SetupMandate,
},
router_request_types::{
authentication::MessageExtensionAttribute, CompleteAuthorizeData, PaymentsAuthenticateData,
PaymentsAuthorizeData, PaymentsPostAuthenticateData, PaymentsPreAuthenticateData,
ResponseId, SetupMandateRequestData,
},
router_response_types::{
MandateReference, PaymentsResponseData, RedirectForm, RefundsResponseData,
},
types::{
PaymentsAuthenticateRouterData, PaymentsAuthorizeRouterData, PaymentsCancelRouterData,
PaymentsCaptureRouterData, PaymentsCompleteAuthorizeRouterData,
PaymentsIncrementalAuthorizationRouterData, PaymentsPostAuthenticateRouterData,
PaymentsPreAuthenticateRouterData, PaymentsPreProcessingRouterData, PaymentsSyncRouterData,
RefundsRouterData, SetupMandateRouterData,
},
};
use hyperswitch_interfaces::{api, errors};
use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use utils::ForeignTryFrom;
#[cfg(feature = "payouts")]
use crate::types::PayoutsResponseRouterData;
#[cfg(feature = "payouts")]
use crate::utils::PayoutsData;
use crate::{
constants,
types::{
PaymentsCancelResponseRouterData, PaymentsCaptureResponseRouterData,
PaymentsPreprocessingResponseRouterData, PaymentsResponseRouterData,
PaymentsSyncResponseRouterData, RefundsResponseRouterData, ResponseRouterData,
},
unimplemented_payment_method,
utils::{
self, AddressDetailsData, CardData, CardIssuer, NetworkTokenData as _,
PaymentsAuthorizeRequestData, PaymentsCompleteAuthorizeRequestData,
PaymentsPreProcessingRequestData, PaymentsSetupMandateRequestData, PaymentsSyncRequestData,
RecurringMandateData, RouterData as OtherRouterData,
},
};
#[derive(Debug, Serialize)]
pub struct CybersourceRouterData<T> {
pub amount: StringMajorUnit,
pub router_data: T,
}
impl<T> From<(StringMajorUnit, T)> for CybersourceRouterData<T> {
fn from((amount, router_data): (StringMajorUnit, T)) -> Self {
Self {
amount,
router_data,
}
}
}
impl From<CardIssuer> for String {
fn from(card_issuer: CardIssuer) -> Self {
let card_type = match card_issuer {
CardIssuer::AmericanExpress => "003",
CardIssuer::Master => "002",
//"042" is the type code for Masetro Cards(International). For Maestro Cards(UK-Domestic) the mapping should be "024"
CardIssuer::Maestro => "042",
CardIssuer::Visa => "001",
CardIssuer::Discover => "004",
CardIssuer::DinersClub => "005",
CardIssuer::CarteBlanche => "006",
CardIssuer::JCB => "007",
CardIssuer::CartesBancaires => "036",
CardIssuer::UnionPay => "062",
};
card_type.to_string()
}
}
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct CybersourceConnectorMetadataObject {
pub disable_avs: Option<bool>,
pub disable_cvn: Option<bool>,
}
impl TryFrom<&Option<pii::SecretSerdeValue>> for CybersourceConnectorMetadataObject {
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)
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CybersourceZeroMandateRequest {
processing_information: ProcessingInformation,
payment_information: PaymentInformation,
order_information: OrderInformationWithBill,
client_reference_information: ClientReferenceInformation,
}
impl TryFrom<&SetupMandateRouterData> for CybersourceZeroMandateRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &SetupMandateRouterData) -> Result<Self, Self::Error> {
let email = item.get_billing_email().or(item.request.get_email())?;
let bill_to = build_bill_to(item.get_optional_billing(), email)?;
let order_information = OrderInformationWithBill {
amount_details: Amount {
total_amount: StringMajorUnit::zero(),
currency: item.request.currency,
},
bill_to: Some(bill_to),
};
let connector_merchant_config =
CybersourceConnectorMetadataObject::try_from(&item.connector_meta_data)?;
let skip_psp_tokenization = matches!(
item.request.tokenization,
Some(common_enums::Tokenization::SkipPsp)
);
let (action_list, action_token_types, authorization_options) = if skip_psp_tokenization {
(
None,
None,
Some(CybersourceAuthorizationOptions {
initiator: Some(CybersourcePaymentInitiator {
initiator_type: Some(CybersourcePaymentInitiatorTypes::Customer),
credential_stored_on_file: Some(false),
stored_credential_used: None,
}),
merchant_initiated_transaction: None,
ignore_avs_result: connector_merchant_config.disable_avs,
ignore_cv_result: connector_merchant_config.disable_cvn,
}),
)
} else {
(
Some(vec![CybersourceActionsList::TokenCreate]),
Some(vec![
CybersourceActionsTokenType::PaymentInstrument,
CybersourceActionsTokenType::Customer,
]),
Some(CybersourceAuthorizationOptions {
initiator: Some(CybersourcePaymentInitiator {
initiator_type: Some(CybersourcePaymentInitiatorTypes::Customer),
credential_stored_on_file: Some(true),
stored_credential_used: None,
}),
merchant_initiated_transaction: None,
ignore_avs_result: connector_merchant_config.disable_avs,
ignore_cv_result: connector_merchant_config.disable_cvn,
}),
)
};
let client_reference_information = ClientReferenceInformation {
code: Some(item.connector_request_reference_id.clone()),
};
let (payment_information, solution) = match item.request.payment_method_data.clone() {
PaymentMethodData::Card(ccard) => {
let card_type = match ccard
.card_network
.clone()
.and_then(get_cybersource_card_type)
{
Some(card_network) => Some(card_network.to_string()),
None => ccard.get_card_issuer().ok().map(String::from),
};
(
PaymentInformation::Cards(Box::new(CardPaymentInformation {
card: Card {
number: ccard.card_number,
expiration_month: ccard.card_exp_month,
expiration_year: ccard.card_exp_year,
security_code: Some(ccard.card_cvc),
card_type,
type_selection_indicator: Some("1".to_owned()),
},
})),
None,
)
}
PaymentMethodData::Wallet(wallet_data) => match wallet_data {
WalletData::ApplePay(apple_pay_data) => match item.payment_method_token.clone() {
Some(payment_method_token) => match payment_method_token {
PaymentMethodToken::ApplePayDecrypt(decrypt_data) => {
let expiration_month = decrypt_data.get_expiry_month().change_context(
errors::ConnectorError::InvalidDataFormat {
field_name: "expiration_month",
},
)?;
let expiration_year = decrypt_data.get_four_digit_expiry_year();
(
PaymentInformation::ApplePay(Box::new(
ApplePayPaymentInformation {
tokenized_card: TokenizedCard {
number: decrypt_data.application_primary_account_number,
cryptogram: Some(
decrypt_data.payment_data.online_payment_cryptogram,
),
transaction_type: TransactionType::InApp,
expiration_year,
expiration_month,
},
},
)),
Some(PaymentSolution::ApplePay),
)
}
PaymentMethodToken::Token(_) => Err(unimplemented_payment_method!(
"Apple Pay",
"Manual",
"Cybersource"
))?,
PaymentMethodToken::PazeDecrypt(_) => {
Err(unimplemented_payment_method!("Paze", "Cybersource"))?
}
PaymentMethodToken::GooglePayDecrypt(_) => {
Err(unimplemented_payment_method!("Google Pay", "Cybersource"))?
}
},
None => {
let apple_pay_encrypted_data = apple_pay_data
.payment_data
.get_encrypted_apple_pay_payment_data_mandatory()
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "Apple pay encrypted data",
})?;
(
PaymentInformation::ApplePayToken(Box::new(
ApplePayTokenPaymentInformation {
fluid_data: FluidData {
value: Secret::from(apple_pay_encrypted_data.clone()),
descriptor: Some(FLUID_DATA_DESCRIPTOR.to_string()),
},
tokenized_card: ApplePayTokenizedCard {
transaction_type: TransactionType::InApp,
},
},
)),
Some(PaymentSolution::ApplePay),
)
}
},
WalletData::GooglePay(google_pay_data) => (
PaymentInformation::GooglePayToken(Box::new(
GooglePayTokenPaymentInformation {
fluid_data: FluidData {
value: Secret::from(
consts::BASE64_ENGINE.encode(
google_pay_data
.tokenization_data
.get_encrypted_google_pay_token()
.change_context(
errors::ConnectorError::MissingRequiredField {
field_name: "gpay wallet_token",
},
)?,
),
),
descriptor: None,
},
tokenized_card: GooglePayTokenizedCard {
transaction_type: TransactionType::InApp,
},
},
)),
Some(PaymentSolution::GooglePay),
),
WalletData::SamsungPay(samsung_pay_data) => (
(get_samsung_pay_payment_information(&samsung_pay_data)
.attach_printable("Failed to get samsung pay payment information")?),
Some(PaymentSolution::SamsungPay),
),
WalletData::AliPayQr(_)
| WalletData::AliPayRedirect(_)
| WalletData::AliPayHkRedirect(_)
| WalletData::AmazonPayRedirect(_)
| WalletData::Paysera(_)
| WalletData::Skrill(_)
| WalletData::BluecodeRedirect {}
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
| WalletData::GcashRedirect(_)
| WalletData::ApplePayRedirect(_)
| WalletData::ApplePayThirdPartySdk(_)
| WalletData::DanaRedirect {}
| WalletData::GooglePayRedirect(_)
| WalletData::GooglePayThirdPartySdk(_)
| WalletData::MbWayRedirect(_)
| WalletData::MobilePayRedirect(_)
| WalletData::PaypalRedirect(_)
| WalletData::PaypalSdk(_)
| WalletData::Paze(_)
| WalletData::AmazonPay(_)
| WalletData::TwintRedirect {}
| WalletData::VippsRedirect {}
| WalletData::TouchNGoRedirect(_)
| WalletData::WeChatPayRedirect(_)
| WalletData::WeChatPayQr(_)
| WalletData::CashappQr(_)
| WalletData::SwishQr(_)
| WalletData::Mifinity(_)
| WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Cybersource"),
))?,
},
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::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Cybersource"),
))?
}
};
let processing_information = ProcessingInformation {
capture: Some(false),
capture_options: None,
action_list,
action_token_types,
authorization_options,
commerce_indicator: String::from("internet"),
payment_solution: solution.map(String::from),
};
Ok(Self {
processing_information,
payment_information,
order_information,
client_reference_information,
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CybersourcePaymentsRequest {
processing_information: ProcessingInformation,
payment_information: PaymentInformation,
order_information: OrderInformationWithBill,
client_reference_information: ClientReferenceInformation,
#[serde(skip_serializing_if = "Option::is_none")]
consumer_authentication_information: Option<CybersourceConsumerAuthInformation>,
#[serde(skip_serializing_if = "Option::is_none")]
merchant_defined_information: Option<Vec<MerchantDefinedInformation>>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ProcessingInformation {
action_list: Option<Vec<CybersourceActionsList>>,
action_token_types: Option<Vec<CybersourceActionsTokenType>>,
authorization_options: Option<CybersourceAuthorizationOptions>,
commerce_indicator: String,
capture: Option<bool>,
capture_options: Option<CaptureOptions>,
payment_solution: Option<String>,
}
#[derive(Debug, Serialize)]
pub enum CybersourceParesStatus {
#[serde(rename = "Y")]
AuthenticationSuccessful,
#[serde(rename = "A")]
AuthenticationAttempted,
#[serde(rename = "N")]
AuthenticationFailed,
#[serde(rename = "U")]
AuthenticationNotCompleted,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CybersourceConsumerAuthInformation {
ucaf_collection_indicator: Option<String>,
cavv: Option<Secret<String>>,
ucaf_authentication_data: Option<Secret<String>>,
xid: Option<String>,
directory_server_transaction_id: Option<Secret<String>>,
specification_version: Option<SemanticVersion>,
/// This field specifies the 3ds version
pa_specification_version: Option<SemanticVersion>,
/// Verification response enrollment status.
///
/// This field is supported only on Asia, Middle East, and Africa Gateway.
///
/// For external authentication, this field will always be "Y"
veres_enrolled: Option<String>,
/// Raw electronic commerce indicator (ECI)
eci_raw: Option<String>,
/// This field is supported only on Asia, Middle East, and Africa Gateway
/// Also needed for Credit Mutuel-CIC in France and Mastercard Identity Check transactions
/// This field is only applicable for Mastercard and Visa Transactions
pares_status: Option<CybersourceParesStatus>,
//This field is used to send the authentication date in yyyyMMDDHHMMSS format
authentication_date: Option<String>,
/// This field indicates the 3D Secure transaction flow. It is only supported for secure transactions in France.
/// The possible values are - CH (Challenge), FD (Frictionless with delegation), FR (Frictionless)
effective_authentication_type: Option<EffectiveAuthenticationType>,
/// This field indicates the authentication type or challenge presented to the cardholder at checkout.
challenge_code: Option<String>,
/// This field indicates the reason for payer authentication response status. It is only supported for secure transactions in France.
signed_pares_status_reason: Option<String>,
/// This field indicates the reason why strong authentication was cancelled. It is only supported for secure transactions in France.
challenge_cancel_code: Option<String>,
/// This field indicates the score calculated by the 3D Securing platform. It is only supported for secure transactions in France.
network_score: Option<u32>,
/// This is the transaction ID generated by the access control server. This field is supported only for secure transactions in France.
acs_transaction_id: Option<String>,
/// This is the algorithm for generating a cardholder authentication verification value (CAVV) or universal cardholder authentication field (UCAF) data.
cavv_algorithm: Option<String>,
}
#[derive(Debug, Serialize)]
pub enum EffectiveAuthenticationType {
CH,
FR,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MerchantDefinedInformation {
key: u8,
value: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum CybersourceActionsList {
TokenCreate,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum CybersourceActionsTokenType {
Customer,
PaymentInstrument,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CybersourceAuthorizationOptions {
initiator: Option<CybersourcePaymentInitiator>,
merchant_initiated_transaction: Option<MerchantInitiatedTransaction>,
ignore_avs_result: Option<bool>,
ignore_cv_result: Option<bool>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MerchantInitiatedTransaction {
reason: Option<String>,
previous_transaction_id: Option<Secret<String>>,
//Required for recurring mandates payment
original_authorized_amount: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CybersourcePaymentInitiator {
#[serde(rename = "type")]
initiator_type: Option<CybersourcePaymentInitiatorTypes>,
credential_stored_on_file: Option<bool>,
stored_credential_used: Option<bool>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum CybersourcePaymentInitiatorTypes {
Customer,
Merchant,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CaptureOptions {
capture_sequence_number: u32,
total_capture_count: u32,
is_final: Option<bool>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NetworkTokenizedCard {
number: NetworkToken,
expiration_month: Secret<String>,
expiration_year: Secret<String>,
cryptogram: Option<Secret<String>>,
transaction_type: TransactionType,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NetworkTokenPaymentInformation {
tokenized_card: NetworkTokenizedCard,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CardPaymentInformation {
card: Card,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TokenizedCard {
number: cards::CardNumber,
expiration_month: Secret<String>,
expiration_year: Secret<String>,
cryptogram: Option<Secret<String>>,
transaction_type: TransactionType,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ApplePayTokenizedCard {
transaction_type: TransactionType,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ApplePayTokenPaymentInformation {
fluid_data: FluidData,
tokenized_card: ApplePayTokenizedCard,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ApplePayPaymentInformation {
tokenized_card: TokenizedCard,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MandatePaymentTokenizedCard {
transaction_type: TransactionType,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MandateCard {
type_selection_indicator: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MandatePaymentInformation {
payment_instrument: CybersoucrePaymentInstrument,
#[serde(skip_serializing_if = "Option::is_none")]
tokenized_card: Option<MandatePaymentTokenizedCard>,
card: Option<MandateCard>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FluidData {
value: Secret<String>,
#[serde(skip_serializing_if = "Option::is_none")]
descriptor: Option<String>,
}
pub const FLUID_DATA_DESCRIPTOR: &str = "RklEPUNPTU1PTi5BUFBMRS5JTkFQUC5QQVlNRU5U";
pub const FLUID_DATA_DESCRIPTOR_FOR_SAMSUNG_PAY: &str = "FID=COMMON.SAMSUNG.INAPP.PAYMENT";
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GooglePayTokenPaymentInformation {
fluid_data: FluidData,
tokenized_card: GooglePayTokenizedCard,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GooglePayTokenizedCard {
transaction_type: TransactionType,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GooglePayPaymentInformation {
tokenized_card: TokenizedCard,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SamsungPayTokenizedCard {
transaction_type: TransactionType,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SamsungPayPaymentInformation {
fluid_data: FluidData,
tokenized_card: SamsungPayTokenizedCard,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SamsungPayFluidDataValue {
public_key_hash: Secret<String>,
version: String,
data: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum PaymentInformation {
Cards(Box<CardPaymentInformation>),
GooglePayToken(Box<GooglePayTokenPaymentInformation>),
GooglePay(Box<GooglePayPaymentInformation>),
ApplePay(Box<ApplePayPaymentInformation>),
ApplePayToken(Box<ApplePayTokenPaymentInformation>),
MandatePayment(Box<MandatePaymentInformation>),
SamsungPay(Box<SamsungPayPaymentInformation>),
NetworkToken(Box<NetworkTokenPaymentInformation>),
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CybersoucrePaymentInstrument {
id: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Card {
number: cards::CardNumber,
expiration_month: Secret<String>,
expiration_year: Secret<String>,
security_code: Option<Secret<String>>,
#[serde(rename = "type")]
card_type: Option<String>,
type_selection_indicator: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct OrderInformationWithBill {
amount_details: Amount,
bill_to: Option<BillTo>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct OrderInformationIncrementalAuthorization {
amount_details: AdditionalAmount,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct OrderInformation {
amount_details: Amount,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Amount {
total_amount: StringMajorUnit,
currency: api_models::enums::Currency,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AdditionalAmount {
additional_amount: StringMajorUnit,
currency: String,
}
#[derive(Debug, Serialize)]
pub enum PaymentSolution {
ApplePay,
GooglePay,
SamsungPay,
}
#[derive(Debug, Serialize)]
pub enum TransactionType {
#[serde(rename = "1")]
InApp,
#[serde(rename = "2")]
ContactlessNFC,
#[serde(rename = "3")]
StoredCredentials,
}
impl From<PaymentSolution> for String {
fn from(solution: PaymentSolution) -> Self {
let payment_solution = match solution {
PaymentSolution::ApplePay => "001",
PaymentSolution::GooglePay => "012",
PaymentSolution::SamsungPay => "008",
};
payment_solution.to_string()
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BillTo {
first_name: Option<Secret<String>>,
last_name: Option<Secret<String>>,
address1: Option<Secret<String>>,
locality: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
administrative_area: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
postal_code: Option<Secret<String>>,
country: Option<enums::CountryAlpha2>,
email: pii::Email,
}
impl From<&CybersourceRouterData<&PaymentsPreAuthenticateRouterData>>
for ClientReferenceInformation
{
fn from(item: &CybersourceRouterData<&PaymentsPreAuthenticateRouterData>) -> Self {
Self {
code: Some(item.router_data.connector_request_reference_id.clone()),
}
}
}
impl From<&CybersourceRouterData<&PaymentsAuthorizeRouterData>> for ClientReferenceInformation {
fn from(item: &CybersourceRouterData<&PaymentsAuthorizeRouterData>) -> Self {
Self {
code: Some(item.router_data.connector_request_reference_id.clone()),
}
}
}
impl From<&CybersourceRouterData<&PaymentsCompleteAuthorizeRouterData>>
for ClientReferenceInformation
{
fn from(item: &CybersourceRouterData<&PaymentsCompleteAuthorizeRouterData>) -> Self {
Self {
code: Some(item.router_data.connector_request_reference_id.clone()),
}
}
}
impl
TryFrom<(
&CybersourceRouterData<&PaymentsAuthorizeRouterData>,
Option<PaymentSolution>,
Option<String>,
)> for ProcessingInformation
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, solution, network): (
&CybersourceRouterData<&PaymentsAuthorizeRouterData>,
Option<PaymentSolution>,
Option<String>,
),
) -> Result<Self, Self::Error> {
let mut commerce_indicator = solution
.as_ref()
.map(|pm_solution| match pm_solution {
PaymentSolution::ApplePay | PaymentSolution::SamsungPay => network
.as_ref()
.map(|card_network| match card_network.to_lowercase().as_str() {
"amex" => "internet",
"discover" => "internet",
"mastercard" => "spa",
"visa" => "internet",
_ => "internet",
})
.unwrap_or("internet"),
PaymentSolution::GooglePay => "internet",
})
.unwrap_or("internet")
.to_string();
let connector_merchant_config =
CybersourceConnectorMetadataObject::try_from(&item.router_data.connector_meta_data)?;
let (action_list, action_token_types, authorization_options) = if item
.router_data
.request
.setup_future_usage
== Some(FutureUsage::OffSession)
&& (item.router_data.request.customer_acceptance.is_some()
|| item
.router_data
.request
.setup_mandate_details
.clone()
.is_some_and(|mandate_details| mandate_details.customer_acceptance.is_some()))
{
let skip_psp_tokenization = matches!(
item.router_data.request.tokenization,
Some(common_enums::Tokenization::SkipPsp)
);
if skip_psp_tokenization {
// COMPLETELY SKIP TOKENIZATION - don't send any tokenization fields
(
None,
None,
Some(CybersourceAuthorizationOptions {
initiator: Some(CybersourcePaymentInitiator {
initiator_type: Some(CybersourcePaymentInitiatorTypes::Customer),
credential_stored_on_file: Some(false),
stored_credential_used: None,
}),
ignore_avs_result: connector_merchant_config.disable_avs,
ignore_cv_result: connector_merchant_config.disable_cvn,
merchant_initiated_transaction: 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/opayo/transformers.rs | crates/hyperswitch_connectors/src/connectors/opayo/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::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RefundsResponseData},
types::{PaymentsAuthorizeRouterData, RefundsRouterData},
};
use hyperswitch_interfaces::errors;
use masking::Secret;
use serde::{Deserialize, Serialize};
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{PaymentsAuthorizeRequestData, RouterData as OtherRouterData},
};
#[derive(Debug, Serialize)]
pub struct OpayoRouterData<T> {
pub amount: MinorUnit,
pub router_data: T,
}
impl<T> From<(MinorUnit, T)> for OpayoRouterData<T> {
fn from((amount, router_data): (MinorUnit, T)) -> Self {
Self {
amount,
router_data,
}
}
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct OpayoPaymentsRequest {
amount: MinorUnit,
card: OpayoCard,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct OpayoCard {
name: Secret<String>,
number: cards::CardNumber,
expiry_month: Secret<String>,
expiry_year: Secret<String>,
cvc: Secret<String>,
complete: bool,
}
impl TryFrom<&OpayoRouterData<&PaymentsAuthorizeRouterData>> for OpayoPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item_data: &OpayoRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let item = item_data.router_data.clone();
match item.request.payment_method_data.clone() {
PaymentMethodData::Card(req_card) => {
let card = OpayoCard {
name: item
.get_optional_billing_full_name()
.unwrap_or(Secret::new("".to_string())),
number: req_card.card_number,
expiry_month: req_card.card_exp_month,
expiry_year: req_card.card_exp_year,
cvc: req_card.card_cvc,
complete: item.request.is_auto_capture()?,
};
Ok(Self {
amount: item_data.amount,
card,
})
}
PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Wallet(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
crate::utils::get_unimplemented_payment_method_error_message("Opayo"),
)
.into())
}
}
}
}
// Auth Struct
pub struct OpayoAuthType {
pub(super) api_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for OpayoAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
api_key: api_key.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
// PaymentsResponse
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum OpayoPaymentStatus {
Succeeded,
Failed,
#[default]
Processing,
}
impl From<OpayoPaymentStatus> for enums::AttemptStatus {
fn from(item: OpayoPaymentStatus) -> Self {
match item {
OpayoPaymentStatus::Succeeded => Self::Charged,
OpayoPaymentStatus::Failed => Self::Failure,
OpayoPaymentStatus::Processing => Self::Authorizing,
}
}
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct OpayoPaymentsResponse {
status: OpayoPaymentStatus,
id: String,
transaction_id: String,
}
impl<F, T> TryFrom<ResponseRouterData<F, OpayoPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, OpayoPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: enums::AttemptStatus::from(item.response.status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.transaction_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.transaction_id),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
// REFUND :
// Type definition for RefundRequest
#[derive(Default, Debug, Serialize)]
pub struct OpayoRefundRequest {
pub amount: MinorUnit,
}
impl<F> TryFrom<&OpayoRouterData<&RefundsRouterData<F>>> for OpayoRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &OpayoRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.amount,
})
}
}
// Type definition for Refund Response
#[allow(dead_code)]
#[derive(Debug, Serialize, Default, Deserialize, Clone)]
pub enum RefundStatus {
Succeeded,
Failed,
#[default]
Processing,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Succeeded => Self::Success,
RefundStatus::Failed => Self::Failure,
RefundStatus::Processing => Self::Pending,
//TODO: Review mapping
}
}
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct RefundResponse {
id: String,
status: RefundStatus,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct OpayoErrorResponse {
pub status_code: u16,
pub code: String,
pub message: String,
pub reason: Option<String>,
}
| 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/hipay/transformers.rs | crates/hyperswitch_connectors/src/connectors/hipay/transformers.rs | use std::collections::HashMap;
use common_enums::{enums, CardNetwork};
use common_utils::{
pii::{self},
request::Method,
types::StringMajorUnit,
};
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{
AdditionalPaymentMethodConnectorResponse, ConnectorAuthType, ConnectorResponseData,
ErrorResponse, PaymentMethodToken, RouterData,
},
router_flow_types::refunds::{Execute, RSync},
router_request_types::{BrowserInformation, ResponseId},
router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsSyncRouterData, RefundsRouterData, TokenizationRouterData,
},
};
use hyperswitch_interfaces::{
consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE},
errors,
};
use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
types::{
PaymentsCancelResponseRouterData, PaymentsCaptureResponseRouterData,
PaymentsResponseRouterData, PaymentsSyncResponseRouterData, RefundsResponseRouterData,
ResponseRouterData,
},
unimplemented_payment_method,
utils::{self, AddressDetailsData, CardData, PaymentsAuthorizeRequestData, RouterData as _},
};
pub struct HipayRouterData<T> {
pub amount: StringMajorUnit,
pub router_data: T,
}
impl<T> From<(StringMajorUnit, T)> for HipayRouterData<T> {
fn from((amount, item): (StringMajorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Operation {
Authorization,
Sale,
Capture,
Refund,
Cancel,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct HipayBrowserInfo {
java_enabled: Option<bool>,
javascript_enabled: Option<bool>,
ipaddr: Option<std::net::IpAddr>,
http_accept: String,
http_user_agent: Option<String>,
language: Option<String>,
color_depth: Option<u8>,
screen_height: Option<u32>,
screen_width: Option<u32>,
timezone: Option<i32>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct HipayPaymentsRequest {
operation: Operation,
authentication_indicator: u8,
cardtoken: Secret<String>,
orderid: String,
currency: enums::Currency,
payment_product: String,
amount: StringMajorUnit,
description: String,
decline_url: Option<String>,
pending_url: Option<String>,
cancel_url: Option<String>,
accept_url: Option<String>,
notify_url: Option<String>,
#[serde(flatten)]
#[serde(skip_serializing_if = "Option::is_none")]
three_ds_data: Option<ThreeDSPaymentData>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct ThreeDSPaymentData {
#[serde(skip_serializing_if = "Option::is_none")]
pub firstname: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub lastname: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub email: Option<pii::Email>,
#[serde(skip_serializing_if = "Option::is_none")]
pub streetaddress: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub city: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub zipcode: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub state: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub country: Option<enums::CountryAlpha2>,
#[serde(skip_serializing_if = "Option::is_none")]
pub browser_info: Option<HipayBrowserInfo>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct HipayMaintenanceRequest {
operation: Operation,
currency: Option<enums::Currency>,
amount: Option<StringMajorUnit>,
}
impl From<BrowserInformation> for HipayBrowserInfo {
fn from(browser_info: BrowserInformation) -> Self {
Self {
java_enabled: browser_info.java_enabled,
javascript_enabled: browser_info.java_script_enabled,
ipaddr: browser_info.ip_address,
http_accept: "*/*".to_string(),
http_user_agent: browser_info.user_agent,
language: browser_info.language,
color_depth: browser_info.color_depth,
screen_height: browser_info.screen_height,
screen_width: browser_info.screen_width,
timezone: browser_info.time_zone,
}
}
}
#[derive(Default, Debug, Serialize, Deserialize)]
pub struct HiPayTokenRequest {
pub card_number: cards::CardNumber,
pub card_expiry_month: Secret<String>,
pub card_expiry_year: Secret<String>,
pub card_holder: Secret<String>,
pub cvc: Secret<String>,
}
impl TryFrom<&HipayRouterData<&PaymentsAuthorizeRouterData>> for HipayPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &HipayRouterData<&PaymentsAuthorizeRouterData>) -> Result<Self, Self::Error> {
let (domestic_card_network, domestic_network) = item
.router_data
.connector_response
.clone()
.and_then(|response| match response.additional_payment_method_data {
Some(AdditionalPaymentMethodConnectorResponse::Card {
card_network,
domestic_network,
..
}) => Some((card_network, domestic_network)),
_ => None,
})
.unwrap_or_default();
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(req_card) => Ok(Self {
operation: if item.router_data.request.is_auto_capture()? {
Operation::Sale
} else {
Operation::Authorization
},
authentication_indicator: if item.router_data.is_three_ds() { 2 } else { 0 },
cardtoken: match item.router_data.get_payment_method_token()? {
PaymentMethodToken::Token(token) => token,
PaymentMethodToken::ApplePayDecrypt(_) => {
return Err(unimplemented_payment_method!("Apple Pay", "Hipay").into());
}
PaymentMethodToken::PazeDecrypt(_) => {
return Err(unimplemented_payment_method!("Paze", "Hipay").into());
}
PaymentMethodToken::GooglePayDecrypt(_) => {
return Err(unimplemented_payment_method!("Google Pay", "Hipay").into());
}
},
orderid: item.router_data.connector_request_reference_id.clone(),
currency: item.router_data.request.currency,
payment_product: match (domestic_network, domestic_card_network.as_deref()) {
(Some(domestic), _) => domestic,
(None, Some("VISA")) => "visa".to_string(),
(None, Some("MASTERCARD")) => "mastercard".to_string(),
(None, Some("MAESTRO")) => "maestro".to_string(),
(None, Some("AMERICAN EXPRESS")) => "american-express".to_string(),
(None, Some("CB")) => "cb".to_string(),
(None, Some("BCMC")) => "bcmc".to_string(),
(None, _) => match req_card.card_network {
Some(CardNetwork::Visa) => "visa".to_string(),
Some(CardNetwork::Mastercard) => "mastercard".to_string(),
Some(CardNetwork::AmericanExpress) => "american-express".to_string(),
Some(CardNetwork::JCB) => "jcb".to_string(),
Some(CardNetwork::DinersClub) => "diners".to_string(),
Some(CardNetwork::Discover) => "discover".to_string(),
Some(CardNetwork::CartesBancaires) => "cb".to_string(),
Some(CardNetwork::UnionPay) => "unionpay".to_string(),
Some(CardNetwork::Interac) => "interac".to_string(),
Some(CardNetwork::RuPay) => "rupay".to_string(),
Some(CardNetwork::Maestro) => "maestro".to_string(),
Some(CardNetwork::Star)
| Some(CardNetwork::Accel)
| Some(CardNetwork::Pulse)
| Some(CardNetwork::Nyce)
| None => "".to_string(),
},
},
amount: item.amount.clone(),
description: item
.router_data
.get_description()
.map(|s| s.to_string())
.unwrap_or("Short Description".to_string()),
decline_url: item.router_data.request.router_return_url.clone(),
pending_url: item.router_data.request.router_return_url.clone(),
cancel_url: item.router_data.request.router_return_url.clone(),
accept_url: item.router_data.request.router_return_url.clone(),
notify_url: item.router_data.request.router_return_url.clone(),
three_ds_data: if item.router_data.is_three_ds() {
let billing_address = item.router_data.get_billing_address()?;
Some(ThreeDSPaymentData {
firstname: billing_address.get_optional_first_name(),
lastname: billing_address.get_optional_last_name(),
email: Some(
item.router_data
.get_billing_email()
.or(item.router_data.request.get_email())?,
),
city: billing_address.get_optional_city(),
streetaddress: billing_address.get_optional_line1(),
zipcode: billing_address.get_optional_zip(),
state: billing_address.get_optional_state(),
country: billing_address.get_optional_country(),
browser_info: Some(HipayBrowserInfo::from(
item.router_data.request.get_browser_info()?,
)),
})
} else {
None
},
}),
_ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()),
}
}
}
impl TryFrom<&TokenizationRouterData> for HiPayTokenRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &TokenizationRouterData) -> Result<Self, Self::Error> {
match item.request.payment_method_data.clone() {
PaymentMethodData::Card(card_data) => Ok(Self {
card_number: card_data.card_number.clone(),
card_expiry_month: card_data.card_exp_month.clone(),
card_expiry_year: card_data.get_expiry_year_4_digit(),
card_holder: item.get_billing_full_name()?,
cvc: card_data.card_cvc,
}),
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Hipay"),
)
.into()),
}
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct HipayTokenResponse {
token: Secret<String>,
brand: String,
domestic_network: Option<String>,
}
impl From<&HipayTokenResponse> for AdditionalPaymentMethodConnectorResponse {
fn from(hipay_token_response: &HipayTokenResponse) -> Self {
Self::Card {
authentication_data: None,
payment_checks: None,
card_network: Some(hipay_token_response.brand.clone()),
domestic_network: hipay_token_response.domestic_network.clone(),
}
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct HipayErrorResponse {
pub code: u8,
pub message: String,
pub description: Option<String>,
}
impl<F, T> TryFrom<ResponseRouterData<F, HipayTokenResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, HipayTokenResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(PaymentsResponseData::TokenizationResponse {
token: item.response.token.clone().expose(),
}),
connector_response: Some(ConnectorResponseData::with_additional_payment_method_data(
AdditionalPaymentMethodConnectorResponse::from(&item.response),
)),
..item.data
})
}
}
pub struct HipayAuthType {
pub(super) api_key: Secret<String>,
pub(super) key1: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for HipayAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
api_key: api_key.clone(),
key1: key1.clone(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct HipayPaymentsResponse {
status: HipayPaymentStatus,
message: String,
order: PaymentOrder,
forward_url: String,
transaction_reference: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PaymentOrder {
id: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct HipayMaintenanceResponse<S> {
status: S,
message: String,
transaction_reference: String,
}
impl TryFrom<PaymentsResponseRouterData<HipayPaymentsResponse>> for PaymentsAuthorizeRouterData {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsResponseRouterData<HipayPaymentsResponse>,
) -> Result<Self, Self::Error> {
let status = common_enums::AttemptStatus::from(item.response.status);
let response = if status == enums::AttemptStatus::Failure {
Err(ErrorResponse {
code: NO_ERROR_CODE.to_string(),
message: item.response.message.clone(),
reason: Some(item.response.message.clone()),
attempt_status: None,
connector_transaction_id: Some(item.response.transaction_reference),
status_code: item.http_code,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.transaction_reference,
),
redirection_data: match item.data.is_three_ds() {
true => Box::new(Some(RedirectForm::Form {
endpoint: item.response.forward_url,
method: Method::Get,
form_fields: HashMap::new(),
})),
false => Box::new(None),
},
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
})
};
Ok(Self {
status,
response,
..item.data
})
}
}
impl<F> TryFrom<&HipayRouterData<&RefundsRouterData<F>>> for HipayMaintenanceRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &HipayRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
Ok(Self {
amount: Some(item.amount.to_owned()),
operation: Operation::Refund,
currency: Some(item.router_data.request.currency),
})
}
}
impl TryFrom<&PaymentsCancelRouterData> for HipayMaintenanceRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> {
Ok(Self {
operation: Operation::Cancel,
currency: item.request.currency,
amount: None,
})
}
}
impl TryFrom<&HipayRouterData<&PaymentsCaptureRouterData>> for HipayMaintenanceRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &HipayRouterData<&PaymentsCaptureRouterData>) -> Result<Self, Self::Error> {
Ok(Self {
amount: Some(item.amount.to_owned()),
operation: Operation::Capture,
currency: Some(item.router_data.request.currency),
})
}
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub enum RefundStatus {
#[serde(rename = "124")]
RefundRequested,
#[serde(rename = "125")]
Refunded,
#[serde(rename = "126")]
PartiallyRefunded,
#[serde(rename = "165")]
RefundRefused,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::RefundRequested => Self::Pending,
RefundStatus::Refunded | RefundStatus::PartiallyRefunded => Self::Success,
RefundStatus::RefundRefused => Self::Failure,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum HipayPaymentStatus {
#[serde(rename = "109")]
AuthenticationFailed,
#[serde(rename = "110")]
Blocked,
#[serde(rename = "111")]
Denied,
#[serde(rename = "112")]
AuthorizedAndPending,
#[serde(rename = "113")]
Refused,
#[serde(rename = "114")]
Expired,
#[serde(rename = "115")]
Cancelled,
#[serde(rename = "116")]
Authorized,
#[serde(rename = "117")]
CaptureRequested,
#[serde(rename = "118")]
Captured,
#[serde(rename = "119")]
PartiallyCaptured,
#[serde(rename = "129")]
ChargedBack,
#[serde(rename = "173")]
CaptureRefused,
#[serde(rename = "174")]
AwaitingTerminal,
#[serde(rename = "175")]
AuthorizationCancellationRequested,
#[serde(rename = "177")]
ChallengeRequested,
#[serde(rename = "178")]
SoftDeclined,
#[serde(rename = "200")]
PendingPayment,
#[serde(rename = "101")]
Created,
#[serde(rename = "105")]
UnableToAuthenticate,
#[serde(rename = "106")]
CardholderAuthenticated,
#[serde(rename = "107")]
AuthenticationAttempted,
#[serde(rename = "108")]
CouldNotAuthenticate,
#[serde(rename = "120")]
Collected,
#[serde(rename = "121")]
PartiallyCollected,
#[serde(rename = "122")]
Settled,
#[serde(rename = "123")]
PartiallySettled,
#[serde(rename = "140")]
AuthenticationRequested,
#[serde(rename = "141")]
Authenticated,
#[serde(rename = "151")]
AcquirerNotFound,
#[serde(rename = "161")]
RiskAccepted,
#[serde(rename = "163")]
AuthorizationRefused,
}
impl From<HipayPaymentStatus> for common_enums::AttemptStatus {
fn from(status: HipayPaymentStatus) -> Self {
match status {
HipayPaymentStatus::AuthenticationFailed => Self::AuthenticationFailed,
HipayPaymentStatus::Blocked
| HipayPaymentStatus::Refused
| HipayPaymentStatus::Expired
| HipayPaymentStatus::Denied => Self::Failure,
HipayPaymentStatus::AuthorizedAndPending => Self::Pending,
HipayPaymentStatus::Cancelled => Self::Voided,
HipayPaymentStatus::Authorized => Self::Authorized,
HipayPaymentStatus::CaptureRequested => Self::CaptureInitiated,
HipayPaymentStatus::Captured => Self::Charged,
HipayPaymentStatus::PartiallyCaptured => Self::PartialCharged,
HipayPaymentStatus::CaptureRefused => Self::CaptureFailed,
HipayPaymentStatus::AwaitingTerminal => Self::Pending,
HipayPaymentStatus::AuthorizationCancellationRequested => Self::VoidInitiated,
HipayPaymentStatus::ChallengeRequested => Self::AuthenticationPending,
HipayPaymentStatus::SoftDeclined => Self::Failure,
HipayPaymentStatus::PendingPayment => Self::Pending,
HipayPaymentStatus::ChargedBack => Self::Failure,
HipayPaymentStatus::Created => Self::Started,
HipayPaymentStatus::UnableToAuthenticate | HipayPaymentStatus::CouldNotAuthenticate => {
Self::AuthenticationFailed
}
HipayPaymentStatus::CardholderAuthenticated => Self::Pending,
HipayPaymentStatus::AuthenticationAttempted => Self::AuthenticationPending,
HipayPaymentStatus::Collected
| HipayPaymentStatus::PartiallySettled
| HipayPaymentStatus::PartiallyCollected
| HipayPaymentStatus::Settled => Self::Charged,
HipayPaymentStatus::AuthenticationRequested => Self::AuthenticationPending,
HipayPaymentStatus::Authenticated => Self::AuthenticationSuccessful,
HipayPaymentStatus::AcquirerNotFound => Self::Failure,
HipayPaymentStatus::RiskAccepted => Self::Pending,
HipayPaymentStatus::AuthorizationRefused => Self::Failure,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RefundResponse {
id: u64,
status: u16,
}
impl TryFrom<RefundsResponseRouterData<Execute, HipayMaintenanceResponse<RefundStatus>>>
for RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, HipayMaintenanceResponse<RefundStatus>>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.transaction_reference,
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: match item.response.status {
25 | 26 => enums::RefundStatus::Success,
65 => enums::RefundStatus::Failure,
24 => enums::RefundStatus::Pending,
_ => enums::RefundStatus::Pending,
},
}),
..item.data
})
}
}
impl TryFrom<PaymentsCaptureResponseRouterData<HipayMaintenanceResponse<HipayPaymentStatus>>>
for PaymentsCaptureRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsCaptureResponseRouterData<HipayMaintenanceResponse<HipayPaymentStatus>>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: common_enums::AttemptStatus::from(item.response.status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.transaction_reference.clone().to_string(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
impl TryFrom<PaymentsCancelResponseRouterData<HipayMaintenanceResponse<HipayPaymentStatus>>>
for PaymentsCancelRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsCancelResponseRouterData<HipayMaintenanceResponse<HipayPaymentStatus>>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: common_enums::AttemptStatus::from(item.response.status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.transaction_reference.clone().to_string(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Reason {
reason: Option<String>,
code: Option<u64>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum HipaySyncResponse {
Response { status: i32, reason: Reason },
Error { message: String, code: u32 },
}
fn get_sync_status(state: i32) -> enums::AttemptStatus {
match state {
9 => enums::AttemptStatus::AuthenticationFailed,
10 => enums::AttemptStatus::Failure,
11 => enums::AttemptStatus::Failure,
12 => enums::AttemptStatus::Pending,
13 => enums::AttemptStatus::Failure,
14 => enums::AttemptStatus::Failure,
15 => enums::AttemptStatus::Voided,
16 => enums::AttemptStatus::Authorized,
17 => enums::AttemptStatus::CaptureInitiated,
18 => enums::AttemptStatus::Charged,
19 => enums::AttemptStatus::PartialCharged,
29 => enums::AttemptStatus::Failure,
73 => enums::AttemptStatus::CaptureFailed,
74 => enums::AttemptStatus::Pending,
75 => enums::AttemptStatus::VoidInitiated,
77 => enums::AttemptStatus::AuthenticationPending,
78 => enums::AttemptStatus::Failure,
200 => enums::AttemptStatus::Pending,
1 => enums::AttemptStatus::Started,
5 => enums::AttemptStatus::AuthenticationFailed,
6 => enums::AttemptStatus::Pending,
7 => enums::AttemptStatus::AuthenticationPending,
8 => enums::AttemptStatus::AuthenticationFailed,
20 => enums::AttemptStatus::Charged,
21 => enums::AttemptStatus::Charged,
22 => enums::AttemptStatus::Charged,
23 => enums::AttemptStatus::Charged,
40 => enums::AttemptStatus::AuthenticationPending,
41 => enums::AttemptStatus::AuthenticationSuccessful,
51 => enums::AttemptStatus::Failure,
61 => enums::AttemptStatus::Pending,
63 => enums::AttemptStatus::Failure,
_ => enums::AttemptStatus::Failure,
}
}
impl TryFrom<PaymentsSyncResponseRouterData<HipaySyncResponse>> for PaymentsSyncRouterData {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsSyncResponseRouterData<HipaySyncResponse>,
) -> Result<Self, Self::Error> {
match item.response {
HipaySyncResponse::Error { message, code } => {
let response = Err(ErrorResponse {
code: code.to_string(),
message: message.clone(),
reason: Some(message.clone()),
attempt_status: None,
connector_transaction_id: None,
status_code: item.http_code,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
});
Ok(Self {
status: enums::AttemptStatus::Failure,
response,
..item.data
})
}
HipaySyncResponse::Response { status, reason } => {
let status = get_sync_status(status);
let response = if status == enums::AttemptStatus::Failure {
let error_code = reason
.code
.map_or(NO_ERROR_CODE.to_string(), |c| c.to_string());
let error_message = reason
.reason
.clone()
.unwrap_or_else(|| NO_ERROR_MESSAGE.to_owned());
Err(ErrorResponse {
code: error_code,
message: error_message.clone(),
reason: Some(error_message),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
})
};
Ok(Self {
status,
response,
..item.data
})
}
}
}
}
| 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/dummyconnector/transformers.rs | crates/hyperswitch_connectors/src/connectors/dummyconnector/transformers.rs | use common_enums::{AttemptStatus, Currency, RefundStatus};
use common_utils::{pii, request::Method, types::MinorUnit};
use hyperswitch_domain_models::{
payment_method_data::{
Card, PayLaterData, PaymentMethodData, UpiCollectData, UpiData, WalletData,
},
router_data::{ConnectorAuthType, RouterData},
router_flow_types::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
types::{PaymentsAuthorizeRouterData, RefundsRouterData},
};
use hyperswitch_interfaces::errors::ConnectorError;
use masking::Secret;
use serde::{Deserialize, Serialize};
use url::Url;
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::RouterData as _,
};
#[derive(Debug, Serialize)]
pub struct DummyConnectorRouterData<T> {
pub amount: MinorUnit,
pub router_data: T,
}
impl<T> From<(MinorUnit, T)> for DummyConnectorRouterData<T> {
fn from((amount, router_data): (MinorUnit, T)) -> Self {
Self {
amount,
router_data,
}
}
}
#[derive(Debug, Serialize, strum::Display, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum DummyConnectors {
#[serde(rename = "phonypay")]
#[strum(serialize = "phonypay")]
PhonyPay,
#[serde(rename = "fauxpay")]
#[strum(serialize = "fauxpay")]
FauxPay,
#[serde(rename = "pretendpay")]
#[strum(serialize = "pretendpay")]
PretendPay,
StripeTest,
AdyenTest,
CheckoutTest,
PaypalTest,
}
impl DummyConnectors {
pub fn get_dummy_connector_id(self) -> &'static str {
match self {
Self::PhonyPay => "phonypay",
Self::FauxPay => "fauxpay",
Self::PretendPay => "pretendpay",
Self::StripeTest => "stripe_test",
Self::AdyenTest => "adyen_test",
Self::CheckoutTest => "checkout_test",
Self::PaypalTest => "paypal_test",
}
}
}
impl From<u8> for DummyConnectors {
fn from(value: u8) -> Self {
match value {
1 => Self::PhonyPay,
2 => Self::FauxPay,
3 => Self::PretendPay,
4 => Self::StripeTest,
5 => Self::AdyenTest,
6 => Self::CheckoutTest,
7 => Self::PaypalTest,
_ => Self::PhonyPay,
}
}
}
#[derive(Debug, Serialize, Eq, PartialEq)]
pub struct DummyConnectorPaymentsRequest<const T: u8> {
amount: MinorUnit,
currency: Currency,
payment_method_data: DummyPaymentMethodData,
return_url: Option<String>,
connector: DummyConnectors,
}
#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum DummyPaymentMethodData {
Card(DummyConnectorCard),
Wallet(DummyConnectorWallet),
PayLater(DummyConnectorPayLater),
Upi(DummyConnectorUpi),
}
#[derive(Clone, Debug, serde::Serialize, Eq, PartialEq, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DummyConnectorUpi {
UpiCollect(DummyConnectorUpiCollect),
}
#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)]
pub struct DummyConnectorUpiCollect {
vpa_id: Secret<String, pii::UpiVpaMaskingStrategy>,
}
impl TryFrom<UpiCollectData> for DummyConnectorUpi {
type Error = error_stack::Report<ConnectorError>;
fn try_from(value: UpiCollectData) -> Result<Self, Self::Error> {
Ok(Self::UpiCollect(DummyConnectorUpiCollect {
vpa_id: value.vpa_id.ok_or(ConnectorError::MissingRequiredField {
field_name: "vpa_id",
})?,
}))
}
}
#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)]
pub struct DummyConnectorCard {
name: Secret<String>,
number: cards::CardNumber,
expiry_month: Secret<String>,
expiry_year: Secret<String>,
cvc: Secret<String>,
}
impl TryFrom<(Card, Option<Secret<String>>)> for DummyConnectorCard {
type Error = error_stack::Report<ConnectorError>;
fn try_from(
(value, card_holder_name): (Card, Option<Secret<String>>),
) -> Result<Self, Self::Error> {
Ok(Self {
name: card_holder_name.unwrap_or(Secret::new("".to_string())),
number: value.card_number,
expiry_month: value.card_exp_month,
expiry_year: value.card_exp_year,
cvc: value.card_cvc,
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq)]
pub enum DummyConnectorWallet {
GooglePay,
Paypal,
WeChatPay,
MbWay,
AliPay,
AliPayHK,
}
impl TryFrom<WalletData> for DummyConnectorWallet {
type Error = error_stack::Report<ConnectorError>;
fn try_from(value: WalletData) -> Result<Self, Self::Error> {
match value {
WalletData::GooglePayRedirect(_) => Ok(Self::GooglePay),
WalletData::PaypalRedirect(_) => Ok(Self::Paypal),
WalletData::WeChatPayRedirect(_) => Ok(Self::WeChatPay),
WalletData::MbWayRedirect(_) => Ok(Self::MbWay),
WalletData::AliPayRedirect(_) => Ok(Self::AliPay),
WalletData::AliPayHkRedirect(_) => Ok(Self::AliPayHK),
_ => Err(ConnectorError::NotImplemented("Dummy wallet".to_string()).into()),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq)]
pub enum DummyConnectorPayLater {
Klarna,
Affirm,
AfterPayClearPay,
}
impl TryFrom<PayLaterData> for DummyConnectorPayLater {
type Error = error_stack::Report<ConnectorError>;
fn try_from(value: PayLaterData) -> Result<Self, Self::Error> {
match value {
PayLaterData::KlarnaRedirect { .. } => Ok(Self::Klarna),
PayLaterData::AffirmRedirect {} => Ok(Self::Affirm),
PayLaterData::AfterpayClearpayRedirect { .. } => Ok(Self::AfterPayClearPay),
_ => Err(ConnectorError::NotImplemented("Dummy pay later".to_string()).into()),
}
}
}
impl<const T: u8> TryFrom<&DummyConnectorRouterData<&PaymentsAuthorizeRouterData>>
for DummyConnectorPaymentsRequest<T>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: &DummyConnectorRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let payment_method_data: Result<DummyPaymentMethodData, Self::Error> =
match item.router_data.request.payment_method_data {
PaymentMethodData::Card(ref req_card) => {
let card_holder_name = item.router_data.get_optional_billing_full_name();
Ok(DummyPaymentMethodData::Card(DummyConnectorCard::try_from(
(req_card.clone(), card_holder_name),
)?))
}
PaymentMethodData::Upi(ref req_upi_data) => match req_upi_data {
UpiData::UpiCollect(data) => Ok(DummyPaymentMethodData::Upi(
DummyConnectorUpi::try_from(data.clone())?,
)),
UpiData::UpiIntent(_) | UpiData::UpiQr(_) => {
Err(ConnectorError::NotImplemented("UPI flow".to_string()).into())
}
},
PaymentMethodData::Wallet(ref wallet_data) => Ok(DummyPaymentMethodData::Wallet(
wallet_data.clone().try_into()?,
)),
PaymentMethodData::PayLater(ref pay_later_data) => Ok(
DummyPaymentMethodData::PayLater(pay_later_data.clone().try_into()?),
),
_ => Err(ConnectorError::NotImplemented("Payment methods".to_string()).into()),
};
Ok(Self {
amount: item.router_data.request.minor_amount,
currency: item.router_data.request.currency,
payment_method_data: payment_method_data?,
return_url: item.router_data.request.router_return_url.clone(),
connector: Into::<DummyConnectors>::into(T),
})
}
}
// Auth Struct
pub struct DummyConnectorAuthType {
pub(super) api_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for DummyConnectorAuthType {
type Error = error_stack::Report<ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
api_key: api_key.to_owned(),
}),
_ => Err(ConnectorError::FailedToObtainAuthType.into()),
}
}
}
// PaymentsResponse
//TODO: Append the remaining status flags
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum DummyConnectorPaymentStatus {
Succeeded,
Failed,
#[default]
Processing,
}
impl From<DummyConnectorPaymentStatus> for AttemptStatus {
fn from(item: DummyConnectorPaymentStatus) -> Self {
match item {
DummyConnectorPaymentStatus::Succeeded => Self::Charged,
DummyConnectorPaymentStatus::Failed => Self::Failure,
DummyConnectorPaymentStatus::Processing => Self::AuthenticationPending,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct PaymentsResponse {
status: DummyConnectorPaymentStatus,
id: String,
amount: MinorUnit,
currency: Currency,
created: String,
payment_method_type: PaymentMethodType,
next_action: Option<DummyConnectorNextAction>,
}
#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum PaymentMethodType {
Card,
Upi(DummyConnectorUpiType),
Wallet(DummyConnectorWallet),
PayLater(DummyConnectorPayLater),
}
#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq)]
pub enum DummyConnectorUpiType {
UpiCollect,
}
impl<F, T> TryFrom<ResponseRouterData<F, PaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<F, PaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let redirection_data = item
.response
.next_action
.and_then(|redirection_data| redirection_data.get_url())
.map(|redirection_url| RedirectForm::from((redirection_url, Method::Get)));
Ok(Self {
status: AttemptStatus::from(item.response.status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id),
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum DummyConnectorNextAction {
RedirectToUrl(Url),
}
impl DummyConnectorNextAction {
fn get_url(&self) -> Option<Url> {
match self {
Self::RedirectToUrl(redirect_to_url) => Some(redirect_to_url.to_owned()),
}
}
}
// REFUND :
// Type definition for RefundRequest
#[derive(Default, Debug, Serialize)]
pub struct DummyConnectorRefundRequest {
pub amount: MinorUnit,
}
impl<F> TryFrom<&DummyConnectorRouterData<&RefundsRouterData<F>>> for DummyConnectorRefundRequest {
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: &DummyConnectorRouterData<&RefundsRouterData<F>>,
) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.router_data.request.minor_refund_amount,
})
}
}
// Type definition for Refund Response
#[allow(dead_code)]
#[derive(Debug, Serialize, Default, Deserialize, Clone)]
#[serde(rename_all = "lowercase")]
pub enum DummyRefundStatus {
Succeeded,
Failed,
#[default]
Processing,
}
impl From<DummyRefundStatus> for RefundStatus {
fn from(item: DummyRefundStatus) -> Self {
match item {
DummyRefundStatus::Succeeded => Self::Success,
DummyRefundStatus::Failed => Self::Failure,
DummyRefundStatus::Processing => Self::Pending,
//TODO: Review mapping
}
}
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct RefundResponse {
id: String,
status: DummyRefundStatus,
currency: Currency,
created: String,
payment_amount: MinorUnit,
refund_amount: MinorUnit,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct DummyConnectorErrorResponse {
pub error: ErrorData,
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct ErrorData {
pub code: String,
pub message: String,
pub reason: Option<String>,
}
| 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/vgs/transformers.rs | crates/hyperswitch_connectors/src/connectors/vgs/transformers.rs | use common_utils::{
ext_traits::{Encode, StringExt},
types::StringMinorUnit,
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
router_data::{AccessToken, ConnectorAuthType, RouterData},
router_flow_types::{ExternalVaultInsertFlow, ExternalVaultRetrieveFlow},
router_request_types::VaultRequestData,
router_response_types::{MultiVaultIdType, VaultIdType, VaultResponseData},
types::{RefreshTokenRouterData, VaultRouterData},
vault::{PaymentMethodCustomVaultingData, PaymentMethodVaultingData},
};
use hyperswitch_interfaces::errors;
use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::types::ResponseRouterData;
pub struct VgsRouterData<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 VgsRouterData<T> {
fn from((amount, item): (StringMinorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
const VGS_FORMAT: &str = "UUID";
const VGS_CLASSIFIER: &str = "data";
#[derive(Debug, Serialize)]
pub struct VgsTokenRequestItem {
value: Secret<String>,
classifiers: Vec<String>,
format: String,
storage: VgsStorageType,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum VgsStorageType {
Persistent,
Volatile,
}
#[derive(Debug, Serialize)]
pub struct VgsInsertRequest {
data: Vec<VgsTokenRequestItem>,
}
impl<F> TryFrom<&VaultRouterData<F>> for VgsInsertRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &VaultRouterData<F>) -> Result<Self, Self::Error> {
match item.request.payment_method_vaulting_data.clone() {
Some(PaymentMethodCustomVaultingData::CardData(req_card)) => {
if item.request.should_generate_multiple_tokens == Some(true) {
let mut data: Vec<VgsTokenRequestItem> = Vec::new();
if let Some(card_number) = req_card.card_number {
data.push(VgsTokenRequestItem {
value: Secret::new(card_number.get_card_no()),
classifiers: vec!["card_number".to_string()],
format: VGS_FORMAT.to_string(),
storage: VgsStorageType::Volatile,
});
}
if let Some(card_exp_month) = req_card.card_exp_month {
data.push(VgsTokenRequestItem {
value: card_exp_month,
classifiers: vec!["card_expiry_month".to_string()],
format: VGS_FORMAT.to_string(),
storage: VgsStorageType::Volatile,
});
}
if let Some(card_exp_year) = req_card.card_exp_year {
data.push(VgsTokenRequestItem {
value: card_exp_year,
classifiers: vec!["card_expiry_year".to_string()],
format: VGS_FORMAT.to_string(),
storage: VgsStorageType::Volatile,
});
}
if let Some(card_cvc) = req_card.card_cvc {
data.push(VgsTokenRequestItem {
value: card_cvc,
classifiers: vec!["card_cvc".to_string()],
format: VGS_FORMAT.to_string(),
storage: VgsStorageType::Volatile,
});
}
Ok(Self { data })
} else {
let stringified_card = req_card
.encode_to_string_of_json()
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
Ok(Self {
data: vec![VgsTokenRequestItem {
value: Secret::new(stringified_card),
classifiers: vec![VGS_CLASSIFIER.to_string()],
format: VGS_FORMAT.to_string(),
storage: VgsStorageType::Persistent,
}],
})
}
}
Some(PaymentMethodCustomVaultingData::NetworkTokenData(network_token_data)) => {
let mut data: Vec<VgsTokenRequestItem> = Vec::new();
if let Some(network_token) = network_token_data.network_token {
data.push(VgsTokenRequestItem {
value: Secret::new(network_token.get_card_no()),
classifiers: vec!["payment_token".to_string()],
format: VGS_FORMAT.to_string(),
storage: VgsStorageType::Volatile,
});
}
if let Some(network_token_exp_month) = network_token_data.network_token_exp_month {
data.push(VgsTokenRequestItem {
value: network_token_exp_month,
classifiers: vec!["token_expiry_month".to_string()],
format: VGS_FORMAT.to_string(),
storage: VgsStorageType::Volatile,
});
}
if let Some(network_token_exp_year) = network_token_data.network_token_exp_year {
data.push(VgsTokenRequestItem {
value: network_token_exp_year,
classifiers: vec!["token_expiry_year".to_string()],
format: VGS_FORMAT.to_string(),
storage: VgsStorageType::Volatile,
});
}
if let Some(cryptogram) = network_token_data.cryptogram {
data.push(VgsTokenRequestItem {
value: cryptogram,
classifiers: vec!["token_cryptogram".to_string()],
format: VGS_FORMAT.to_string(),
storage: VgsStorageType::Volatile,
});
}
Ok(Self { data })
}
_ => Err(errors::ConnectorError::NotImplemented(
"Payment method apart from card".to_string(),
)
.into()),
}
}
}
pub struct VgsAuthType {
pub(super) username: Secret<String>,
pub(super) password: Secret<String>,
pub(super) vault_id: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for VgsAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} => Ok(Self {
username: api_key.to_owned(),
password: key1.to_owned(),
vault_id: api_secret.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct VgsAliasItem {
alias: String,
format: String,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct VgsTokenResponseItem {
value: Secret<String>,
classifiers: Vec<String>,
aliases: Vec<VgsAliasItem>,
created_at: Option<String>,
storage: String,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct VgsInsertResponse {
data: Vec<VgsTokenResponseItem>,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct VgsRetrieveResponse {
data: Vec<VgsTokenResponseItem>,
}
fn get_token_from_response(
response: &Vec<VgsTokenResponseItem>,
value: &str,
) -> Option<Secret<String>> {
for token_data in response {
if token_data.value.peek() == value {
for alias in &token_data.aliases {
if matches!(alias.format.as_str(), VGS_FORMAT) {
return Some(Secret::new(alias.alias.clone()));
}
}
}
}
None
}
impl
TryFrom<
ResponseRouterData<
ExternalVaultInsertFlow,
VgsInsertResponse,
VaultRequestData,
VaultResponseData,
>,
> for RouterData<ExternalVaultInsertFlow, VaultRequestData, VaultResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
ExternalVaultInsertFlow,
VgsInsertResponse,
VaultRequestData,
VaultResponseData,
>,
) -> Result<Self, Self::Error> {
match item.data.request.payment_method_vaulting_data.clone() {
Some(PaymentMethodCustomVaultingData::NetworkTokenData(network_token_data)) => {
let multi_tokens = MultiVaultIdType::NetworkToken {
tokenized_network_token: network_token_data.network_token.clone().and_then(
|network_token| {
get_token_from_response(&item.response.data, network_token.peek())
},
),
tokenized_network_token_exp_year: network_token_data
.network_token_exp_year
.clone()
.and_then(|network_token_exp_year| {
get_token_from_response(
&item.response.data,
network_token_exp_year.peek(),
)
}),
tokenized_network_token_exp_month: network_token_data
.network_token_exp_month
.clone()
.and_then(|network_token_exp_month| {
get_token_from_response(
&item.response.data,
network_token_exp_month.peek(),
)
}),
tokenized_cryptogram: network_token_data.cryptogram.clone().and_then(
|cryptogram| {
get_token_from_response(&item.response.data, cryptogram.peek())
},
),
};
Ok(Self {
status: common_enums::AttemptStatus::Started,
response: Ok(VaultResponseData::ExternalVaultInsertResponse {
connector_vault_id: VaultIdType::MultiVauldIds(multi_tokens),
fingerprint_id: network_token_data
.network_token
.clone()
.and_then(|network_token| {
get_token_from_response(&item.response.data, network_token.peek())
})
.unwrap_or(Secret::new("default".to_string()))
.expose(),
}),
..item.data
})
}
Some(PaymentMethodCustomVaultingData::CardData(card_data)) => {
if item.data.request.should_generate_multiple_tokens == Some(true) {
let multi_tokens = MultiVaultIdType::Card {
tokenized_card_number: card_data.card_number.clone().and_then(
|card_number| {
get_token_from_response(&item.response.data, card_number.peek())
},
),
tokenized_card_expiry_month: card_data.card_exp_month.clone().and_then(
|card_exp_month| {
get_token_from_response(&item.response.data, card_exp_month.peek())
},
),
tokenized_card_expiry_year: card_data.card_exp_year.clone().and_then(
|card_exp_year| {
get_token_from_response(&item.response.data, card_exp_year.peek())
},
),
tokenized_card_cvc: card_data.card_cvc.clone().and_then(|card_cvc| {
get_token_from_response(&item.response.data, card_cvc.peek())
}),
};
Ok(Self {
status: common_enums::AttemptStatus::Started,
response: Ok(VaultResponseData::ExternalVaultInsertResponse {
connector_vault_id: VaultIdType::MultiVauldIds(multi_tokens),
fingerprint_id: card_data
.card_number
.clone()
.and_then(|card_number| {
get_token_from_response(&item.response.data, card_number.peek())
})
.unwrap_or(Secret::new("default".to_string()))
.expose(),
}),
..item.data
})
} else {
let vgs_alias = item
.response
.data
.first()
.and_then(|val| val.aliases.first())
.ok_or(errors::ConnectorError::ResponseHandlingFailed)?;
Ok(Self {
status: common_enums::AttemptStatus::Started,
response: Ok(VaultResponseData::ExternalVaultInsertResponse {
connector_vault_id: VaultIdType::SingleVaultId(vgs_alias.alias.clone()),
fingerprint_id: vgs_alias.alias.clone(),
}),
..item.data
})
}
}
_ => {
let vgs_alias = item
.response
.data
.first()
.and_then(|val| val.aliases.first())
.ok_or(errors::ConnectorError::ResponseHandlingFailed)?;
Ok(Self {
status: common_enums::AttemptStatus::Started,
response: Ok(VaultResponseData::ExternalVaultInsertResponse {
connector_vault_id: VaultIdType::SingleVaultId(vgs_alias.alias.clone()),
fingerprint_id: vgs_alias.alias.clone(),
}),
..item.data
})
}
}
}
}
impl
TryFrom<
ResponseRouterData<
ExternalVaultRetrieveFlow,
VgsRetrieveResponse,
VaultRequestData,
VaultResponseData,
>,
> for RouterData<ExternalVaultRetrieveFlow, VaultRequestData, VaultResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
ExternalVaultRetrieveFlow,
VgsRetrieveResponse,
VaultRequestData,
VaultResponseData,
>,
) -> Result<Self, Self::Error> {
let token_response_item = item
.response
.data
.first()
.ok_or(errors::ConnectorError::ResponseHandlingFailed)?;
let card_detail: api_models::payment_methods::CardDetail = token_response_item
.value
.clone()
.expose()
.parse_struct("CardDetail")
.change_context(errors::ConnectorError::ParsingFailed)?;
Ok(Self {
status: common_enums::AttemptStatus::Started,
response: Ok(VaultResponseData::ExternalVaultRetrieveResponse {
vault_data: PaymentMethodVaultingData::Card(card_detail),
}),
..item.data
})
}
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct VgsErrorItem {
pub status: u16,
pub code: String,
pub detail: Option<String>,
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct VgsErrorResponse {
pub errors: Vec<VgsErrorItem>,
pub trace_id: String,
}
#[derive(Debug, Clone, Serialize, PartialEq)]
pub struct VgsAuthUpdateRequest {
grant_type: String,
client_id: Secret<String>,
client_secret: Secret<String>,
}
impl TryFrom<&RefreshTokenRouterData> for VgsAuthUpdateRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &RefreshTokenRouterData) -> Result<Self, Self::Error> {
let auth = VgsAuthType::try_from(&item.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(Self {
grant_type: "client_credentials".to_string(),
client_id: auth.username,
client_secret: auth.password,
})
}
}
#[derive(Default, Debug, Clone, Deserialize, PartialEq, Serialize)]
pub struct VgsAuthUpdateResponse {
pub access_token: Secret<String>,
pub token_type: String,
pub expires_in: i64,
}
impl<F, T> TryFrom<ResponseRouterData<F, VgsAuthUpdateResponse, T, AccessToken>>
for RouterData<F, T, AccessToken>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, VgsAuthUpdateResponse, T, AccessToken>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(AccessToken {
token: item.response.access_token,
expires: item.response.expires_in,
}),
..item.data
})
}
}
#[derive(Deserialize, Debug, Serialize)]
pub struct VgsAccessTokenErrorResponse {
pub error: String,
pub error_description: 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/cashtocode/transformers.rs | crates/hyperswitch_connectors/src/connectors/cashtocode/transformers.rs | use std::collections::HashMap;
use common_enums::enums;
pub use common_utils::request::Method;
use common_utils::{
errors::CustomResult, ext_traits::ValueExt, id_type, pii::Email, types::FloatMajorUnit,
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
router_data::{ConnectorAuthType, ErrorResponse, RouterData},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RedirectForm},
types::PaymentsAuthorizeRouterData,
};
use hyperswitch_interfaces::errors;
use masking::Secret;
use serde::{Deserialize, Serialize};
use crate::{
types::{PaymentsResponseRouterData, ResponseRouterData},
utils::{self, PaymentsAuthorizeRequestData, RouterData as OtherRouterData},
};
#[derive(Default, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CashtocodePaymentsRequest {
amount: FloatMajorUnit,
transaction_id: String,
user_id: Secret<id_type::CustomerId>,
currency: enums::Currency,
first_name: Option<Secret<String>>,
last_name: Option<Secret<String>>,
user_alias: Secret<id_type::CustomerId>,
requested_url: String,
cancel_url: String,
email: Option<Email>,
mid: Secret<String>,
}
fn get_mid(
connector_auth_type: &ConnectorAuthType,
payment_method_type: Option<enums::PaymentMethodType>,
currency: enums::Currency,
) -> Result<Secret<String>, errors::ConnectorError> {
match CashtocodeAuth::try_from((connector_auth_type, ¤cy)) {
Ok(cashtocode_auth) => match payment_method_type {
Some(enums::PaymentMethodType::ClassicReward) => Ok(cashtocode_auth
.merchant_id_classic
.ok_or(errors::ConnectorError::FailedToObtainAuthType)?),
Some(enums::PaymentMethodType::Evoucher) => Ok(cashtocode_auth
.merchant_id_evoucher
.ok_or(errors::ConnectorError::FailedToObtainAuthType)?),
_ => Err(errors::ConnectorError::FailedToObtainAuthType),
},
Err(_) => Err(errors::ConnectorError::FailedToObtainAuthType)?,
}
}
impl TryFrom<(&PaymentsAuthorizeRouterData, FloatMajorUnit)> for CashtocodePaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, amount): (&PaymentsAuthorizeRouterData, FloatMajorUnit),
) -> Result<Self, Self::Error> {
let customer_id = item.get_customer_id()?;
let url = item.request.get_router_return_url()?;
let mid = get_mid(
&item.connector_auth_type,
item.request.payment_method_type,
item.request.currency,
)?;
match item.payment_method {
enums::PaymentMethod::Reward => Ok(Self {
amount,
transaction_id: item.attempt_id.clone(),
currency: item.request.currency,
user_id: Secret::new(customer_id.to_owned()),
first_name: None,
last_name: None,
user_alias: Secret::new(customer_id),
requested_url: url.to_owned(),
cancel_url: url,
email: item.request.email.clone(),
mid,
}),
_ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()),
}
}
}
#[derive(Default, Debug, Deserialize)]
pub struct CashtocodeAuthType {
pub auths: HashMap<enums::Currency, CashtocodeAuth>,
}
#[derive(Default, Debug, Deserialize)]
pub struct CashtocodeAuth {
pub password_classic: Option<Secret<String>>,
pub password_evoucher: Option<Secret<String>>,
pub username_classic: Option<Secret<String>>,
pub username_evoucher: Option<Secret<String>>,
pub merchant_id_classic: Option<Secret<String>>,
pub merchant_id_evoucher: Option<Secret<String>>,
}
impl TryFrom<&ConnectorAuthType> for CashtocodeAuthType {
type Error = error_stack::Report<errors::ConnectorError>; // Assuming ErrorStack is the appropriate error type
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::CurrencyAuthKey { auth_key_map } => {
let transformed_auths = auth_key_map
.iter()
.map(|(currency, identity_auth_key)| {
let cashtocode_auth = identity_auth_key
.to_owned()
.parse_value::<CashtocodeAuth>("CashtocodeAuth")
.change_context(errors::ConnectorError::InvalidDataFormat {
field_name: "auth_key_map",
})?;
Ok((currency.to_owned(), cashtocode_auth))
})
.collect::<Result<_, Self::Error>>()?;
Ok(Self {
auths: transformed_auths,
})
}
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
impl TryFrom<(&ConnectorAuthType, &enums::Currency)> for CashtocodeAuth {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(value: (&ConnectorAuthType, &enums::Currency)) -> Result<Self, Self::Error> {
let (auth_type, currency) = value;
if let ConnectorAuthType::CurrencyAuthKey { auth_key_map } = auth_type {
if let Some(identity_auth_key) = auth_key_map.get(currency) {
let cashtocode_auth: Self = identity_auth_key
.to_owned()
.parse_value("CashtocodeAuth")
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(cashtocode_auth)
} else {
Err(errors::ConnectorError::CurrencyNotSupported {
message: currency.to_string(),
connector: "CashToCode",
}
.into())
}
} else {
Err(errors::ConnectorError::FailedToObtainAuthType.into())
}
}
}
#[derive(Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum CashtocodePaymentStatus {
Succeeded,
#[default]
Processing,
}
impl From<CashtocodePaymentStatus> for enums::AttemptStatus {
fn from(item: CashtocodePaymentStatus) -> Self {
match item {
CashtocodePaymentStatus::Succeeded => Self::Charged,
CashtocodePaymentStatus::Processing => Self::AuthenticationPending,
}
}
}
#[derive(Debug, Deserialize, Clone, Serialize)]
pub struct CashtocodeErrors {
pub message: String,
pub path: String,
#[serde(rename = "type")]
pub event_type: String,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum CashtocodePaymentsResponse {
CashtoCodeError(CashtocodeErrorResponse),
CashtoCodeData(CashtocodePaymentsResponseData),
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CashtocodePaymentsResponseData {
pub pay_url: url::Url,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CashtocodePaymentsSyncResponse {
pub transaction_id: String,
pub amount: FloatMajorUnit,
}
fn get_redirect_form_data(
payment_method_type: enums::PaymentMethodType,
response_data: CashtocodePaymentsResponseData,
) -> CustomResult<RedirectForm, errors::ConnectorError> {
match payment_method_type {
enums::PaymentMethodType::ClassicReward => Ok(RedirectForm::Form {
//redirect form is manually constructed because the connector for this pm type expects query params in the url
endpoint: response_data.pay_url.to_string(),
method: Method::Post,
form_fields: Default::default(),
}),
enums::PaymentMethodType::Evoucher => Ok(RedirectForm::from((
//here the pay url gets parsed, and query params are sent as formfields as the connector expects
response_data.pay_url,
Method::Get,
))),
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("CashToCode"),
))?,
}
}
impl TryFrom<PaymentsResponseRouterData<CashtocodePaymentsResponse>>
for PaymentsAuthorizeRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsResponseRouterData<CashtocodePaymentsResponse>,
) -> Result<Self, Self::Error> {
let (status, response) = match item.response {
CashtocodePaymentsResponse::CashtoCodeError(error_data) => (
enums::AttemptStatus::Failure,
Err(ErrorResponse {
code: error_data.error.to_string(),
status_code: item.http_code,
message: error_data.error_description.clone(),
reason: Some(error_data.error_description),
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
),
CashtocodePaymentsResponse::CashtoCodeData(response_data) => {
let payment_method_type = item
.data
.request
.payment_method_type
.ok_or(errors::ConnectorError::MissingPaymentMethodType)?;
let redirection_data = get_redirect_form_data(payment_method_type, response_data)?;
(
enums::AttemptStatus::AuthenticationPending,
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.data.attempt_id.clone(),
),
redirection_data: Box::new(Some(redirection_data)),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
)
}
};
Ok(Self {
status,
response,
..item.data
})
}
}
impl<F, T> TryFrom<ResponseRouterData<F, CashtocodePaymentsSyncResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, CashtocodePaymentsSyncResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: enums::AttemptStatus::Charged, // Charged status is hardcoded because cashtocode do not support Psync, and we only receive webhooks when payment is succeeded, this tryFrom is used for CallConnectorAction.
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.data.attempt_id.clone(), //in response they only send PayUrl, so we use attempt_id as connector_transaction_id
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct CashtocodeErrorResponse {
pub error: serde_json::Value,
pub error_description: String,
pub errors: Option<Vec<CashtocodeErrors>>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CashtocodeIncomingWebhook {
pub amount: FloatMajorUnit,
pub currency: String,
pub foreign_transaction_id: String,
#[serde(rename = "type")]
pub event_type: String,
pub transaction_id: String,
}
| 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/celero/transformers.rs | crates/hyperswitch_connectors/src/connectors/celero/transformers.rs | use common_enums::{enums, Currency};
use common_utils::{id_type::CustomerId, pii::Email, types::MinorUnit};
use hyperswitch_domain_models::{
address::Address as DomainAddress,
payment_method_data::PaymentMethodData,
router_data::{
AdditionalPaymentMethodConnectorResponse, ConnectorAuthType, ConnectorResponseData,
RouterData,
},
router_flow_types::{
payments::Capture,
refunds::{Execute, RSync},
},
router_request_types::{PaymentsCaptureData, ResponseId},
router_response_types::{MandateReference, PaymentsResponseData, RefundsResponseData},
types::{
PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData,
RefundSyncRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::{
consts,
errors::{self},
};
use masking::{PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{
get_unimplemented_payment_method_error_message, AddressDetailsData,
PaymentsAuthorizeRequestData, RefundsRequestData, RouterData as _,
},
};
//TODO: Fill the struct with respective fields
pub struct CeleroRouterData<T> {
pub amount: MinorUnit, // CeleroCommerce expects integer cents
pub router_data: T,
}
impl<T> TryFrom<(MinorUnit, T)> for CeleroRouterData<T> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from((amount, item): (MinorUnit, T)) -> Result<Self, Self::Error> {
Ok(Self {
amount,
router_data: item,
})
}
}
// CeleroCommerce Search Request for sync operations - POST /api/transaction/search
#[derive(Debug, Serialize, PartialEq)]
pub struct CeleroSearchRequest {
transaction_id: String,
}
impl TryFrom<&PaymentsSyncRouterData> for CeleroSearchRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsSyncRouterData) -> Result<Self, Self::Error> {
let transaction_id = match &item.request.connector_transaction_id {
ResponseId::ConnectorTransactionId(id) => id.clone(),
_ => {
return Err(errors::ConnectorError::MissingConnectorTransactionID.into());
}
};
Ok(Self { transaction_id })
}
}
impl TryFrom<&RefundSyncRouterData> for CeleroSearchRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &RefundSyncRouterData) -> Result<Self, Self::Error> {
Ok(Self {
transaction_id: item.request.get_connector_refund_id()?,
})
}
}
// CeleroCommerce Payment Request according to API specs
#[derive(Debug, Serialize, PartialEq)]
pub struct CeleroPaymentsRequest {
idempotency_key: String,
#[serde(rename = "type")]
transaction_type: TransactionType,
amount: MinorUnit, // CeleroCommerce expects integer cents
currency: Currency,
payment_method: CeleroPaymentMethod,
#[serde(skip_serializing_if = "Option::is_none")]
billing_address: Option<CeleroAddress>,
#[serde(skip_serializing_if = "Option::is_none")]
shipping_address: Option<CeleroAddress>,
#[serde(skip_serializing_if = "Option::is_none")]
create_vault_record: Option<bool>,
// CIT/MIT fields
#[serde(skip_serializing_if = "Option::is_none")]
card_on_file_indicator: Option<CardOnFileIndicator>,
#[serde(skip_serializing_if = "Option::is_none")]
initiated_by: Option<InitiatedBy>,
#[serde(skip_serializing_if = "Option::is_none")]
initial_transaction_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
stored_credential_indicator: Option<StoredCredentialIndicator>,
#[serde(skip_serializing_if = "Option::is_none")]
billing_method: Option<BillingMethod>,
}
#[derive(Debug, Serialize, PartialEq)]
pub struct CeleroAddress {
first_name: Option<Secret<String>>,
last_name: Option<Secret<String>>,
address_line_1: Option<Secret<String>>,
address_line_2: Option<Secret<String>>,
city: Option<String>,
state: Option<Secret<String>>,
postal_code: Option<Secret<String>>,
country: Option<common_enums::CountryAlpha2>,
phone: Option<Secret<String>>,
email: Option<Email>,
}
impl TryFrom<&DomainAddress> for CeleroAddress {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(address: &DomainAddress) -> Result<Self, Self::Error> {
let address_details = address.address.as_ref();
match address_details {
Some(address_details) => Ok(Self {
first_name: address_details.get_optional_first_name(),
last_name: address_details.get_optional_last_name(),
address_line_1: address_details.get_optional_line1(),
address_line_2: address_details.get_optional_line2(),
city: address_details.get_optional_city(),
state: address_details.get_optional_state(),
postal_code: address_details.get_optional_zip(),
country: address_details.get_optional_country(),
phone: address
.phone
.as_ref()
.and_then(|phone| phone.number.clone()),
email: address.email.clone(),
}),
None => Err(errors::ConnectorError::MissingRequiredField {
field_name: "address_details",
}
.into()),
}
}
}
#[derive(Debug, Serialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum CeleroPaymentMethod {
Card(CeleroCard),
Customer(CeleroCustomer),
}
#[derive(Debug, Serialize, PartialEq)]
pub struct CeleroCustomer {
id: Option<CustomerId>,
payment_method_id: Option<String>,
}
#[derive(Debug, Serialize, PartialEq, Clone, Copy)]
#[serde(rename_all = "lowercase")]
pub enum CeleroEntryType {
Keyed,
}
#[derive(Debug, Serialize, PartialEq)]
pub struct CeleroCard {
entry_type: CeleroEntryType,
number: cards::CardNumber,
expiration_date: Secret<String>,
cvc: Secret<String>,
}
impl TryFrom<&PaymentMethodData> for CeleroPaymentMethod {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentMethodData) -> Result<Self, Self::Error> {
match item {
PaymentMethodData::Card(req_card) => {
let card = CeleroCard {
entry_type: CeleroEntryType::Keyed,
number: req_card.card_number.clone(),
expiration_date: Secret::new(format!(
"{}/{}",
req_card.card_exp_month.peek(),
req_card.card_exp_year.peek()
)),
cvc: req_card.card_cvc.clone(),
};
Ok(Self::Card(card))
}
PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Wallet(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::MobilePayment(_) => Err(errors::ConnectorError::NotImplemented(
"Selected payment method through celero".to_string(),
)
.into()),
}
}
}
// Implementation for handling 3DS specifically
impl TryFrom<(&PaymentMethodData, bool)> for CeleroPaymentMethod {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from((item, is_three_ds): (&PaymentMethodData, bool)) -> Result<Self, Self::Error> {
// If 3DS is requested, return an error
if is_three_ds {
return Err(errors::ConnectorError::NotSupported {
message: "Cards 3DS".to_string(),
connector: "celero",
}
.into());
}
// Otherwise, delegate to the standard implementation
Self::try_from(item)
}
}
impl TryFrom<&CeleroRouterData<&PaymentsAuthorizeRouterData>> for CeleroPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &CeleroRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let is_auto_capture = item.router_data.request.is_auto_capture()?;
let transaction_type = if is_auto_capture {
TransactionType::Sale
} else {
TransactionType::Authorize
};
let billing_address: Option<CeleroAddress> = item
.router_data
.get_optional_billing()
.and_then(|address| address.try_into().ok());
let shipping_address: Option<CeleroAddress> = item
.router_data
.get_optional_shipping()
.and_then(|address| address.try_into().ok());
// Determine CIT/MIT fields based on mandate data
let (mandate_fields, payment_method) = determine_cit_mit_fields(item.router_data)?;
let request = Self {
idempotency_key: item.router_data.connector_request_reference_id.clone(),
transaction_type,
amount: item.amount,
currency: item.router_data.request.currency,
payment_method,
billing_address,
shipping_address,
create_vault_record: Some(false),
card_on_file_indicator: mandate_fields.card_on_file_indicator,
initiated_by: mandate_fields.initiated_by,
initial_transaction_id: mandate_fields.initial_transaction_id,
stored_credential_indicator: mandate_fields.stored_credential_indicator,
billing_method: mandate_fields.billing_method,
};
Ok(request)
}
}
// Define a struct to hold CIT/MIT fields to avoid complex tuple return type
#[derive(Debug, Default)]
pub struct CeleroMandateFields {
pub card_on_file_indicator: Option<CardOnFileIndicator>,
pub initiated_by: Option<InitiatedBy>,
pub initial_transaction_id: Option<String>,
pub stored_credential_indicator: Option<StoredCredentialIndicator>,
pub billing_method: Option<BillingMethod>,
}
// Helper function to determine CIT/MIT fields based on mandate data
fn determine_cit_mit_fields(
router_data: &PaymentsAuthorizeRouterData,
) -> Result<(CeleroMandateFields, CeleroPaymentMethod), error_stack::Report<errors::ConnectorError>>
{
// Default null values
let mut mandate_fields = CeleroMandateFields::default();
// First check if there's a mandate_id in the request
match router_data
.request
.mandate_id
.clone()
.and_then(|mandate_ids| mandate_ids.mandate_reference_id)
{
// If there's a connector mandate ID, this is a MIT (Merchant Initiated Transaction)
Some(api_models::payments::MandateReferenceId::ConnectorMandateId(
connector_mandate_id,
)) => {
mandate_fields.card_on_file_indicator = Some(CardOnFileIndicator::RecurringPayment);
mandate_fields.initiated_by = Some(InitiatedBy::Merchant); // This is a MIT
mandate_fields.stored_credential_indicator = Some(StoredCredentialIndicator::Used);
mandate_fields.billing_method = Some(BillingMethod::Recurring);
mandate_fields.initial_transaction_id =
connector_mandate_id.get_connector_mandate_request_reference_id();
Ok((
mandate_fields,
CeleroPaymentMethod::Customer(CeleroCustomer {
id: Some(router_data.get_customer_id()?),
payment_method_id: connector_mandate_id.get_payment_method_id(),
}),
))
}
// For other mandate types that might not be supported
Some(api_models::payments::MandateReferenceId::NetworkMandateId(_))
| Some(api_models::payments::MandateReferenceId::NetworkTokenWithNTI(_)) => {
// These might need different handling or return an error
Err(errors::ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("Celero"),
)
.into())
}
// If no mandate ID is present, check if it's a mandate payment
None => {
if router_data.request.is_mandate_payment() {
// This is a customer-initiated transaction for a recurring payment
mandate_fields.initiated_by = Some(InitiatedBy::Customer);
mandate_fields.card_on_file_indicator = Some(CardOnFileIndicator::RecurringPayment);
mandate_fields.billing_method = Some(BillingMethod::Recurring);
mandate_fields.stored_credential_indicator = Some(StoredCredentialIndicator::Used);
}
let is_three_ds = router_data.is_three_ds();
Ok((
mandate_fields,
CeleroPaymentMethod::try_from((
&router_data.request.payment_method_data,
is_three_ds,
))?,
))
}
}
}
// Auth Struct for CeleroCommerce API key authentication
pub struct CeleroAuthType {
pub(super) api_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for CeleroAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
api_key: api_key.clone(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
// CeleroCommerce API Response Structures
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum CeleroResponseStatus {
#[serde(alias = "success", alias = "Success", alias = "SUCCESS")]
Success,
#[serde(alias = "error", alias = "Error", alias = "ERROR")]
Error,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum CeleroTransactionStatus {
Approved,
Declined,
Error,
Pending,
PendingSettlement,
Settled,
Voided,
Reversed,
}
impl From<CeleroTransactionStatus> for common_enums::AttemptStatus {
fn from(item: CeleroTransactionStatus) -> Self {
match item {
CeleroTransactionStatus::Approved => Self::Authorized,
CeleroTransactionStatus::Settled => Self::Charged,
CeleroTransactionStatus::Declined | CeleroTransactionStatus::Error => Self::Failure,
CeleroTransactionStatus::Pending | CeleroTransactionStatus::PendingSettlement => {
Self::Pending
}
CeleroTransactionStatus::Voided | CeleroTransactionStatus::Reversed => Self::Voided,
}
}
}
#[serde_with::skip_serializing_none]
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct CeleroCardResponse {
pub status: CeleroTransactionStatus,
pub auth_code: Option<String>,
pub processor_response_code: Option<String>,
pub avs_response_code: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum CeleroPaymentMethodResponse {
Card(CeleroCardResponse),
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum TransactionType {
Sale,
Authorize,
}
// CIT/MIT related enums
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum CardOnFileIndicator {
#[serde(rename = "C")]
GeneralPurposeStorage,
#[serde(rename = "R")]
RecurringPayment,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum InitiatedBy {
Customer,
Merchant,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum StoredCredentialIndicator {
Used,
Stored,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum BillingMethod {
Straight,
#[serde(rename = "initial_recurring")]
InitialRecurring,
Recurring,
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
#[serde_with::skip_serializing_none]
pub struct CeleroTransactionResponseData {
pub id: String,
#[serde(rename = "type")]
pub transaction_type: TransactionType,
pub amount: i64,
pub currency: String,
pub response: CeleroPaymentMethodResponse,
pub billing_address: Option<CeleroAddressResponse>,
pub shipping_address: Option<CeleroAddressResponse>,
// Additional fields from the sample response
pub status: Option<String>,
pub response_code: Option<i32>,
pub customer_id: Option<String>,
pub payment_method_id: Option<String>,
}
impl CeleroTransactionResponseData {
pub fn get_mandate_reference(&self) -> Box<Option<MandateReference>> {
if self.payment_method_id.is_some() {
Box::new(Some(MandateReference {
connector_mandate_id: None,
payment_method_id: self.payment_method_id.clone(),
mandate_metadata: None,
connector_mandate_request_reference_id: Some(self.id.clone()),
}))
} else {
Box::new(None)
}
}
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
pub struct CeleroAddressResponse {
first_name: Option<Secret<String>>,
last_name: Option<Secret<String>>,
address_line_1: Option<Secret<String>>,
address_line_2: Option<Secret<String>>,
city: Option<String>,
state: Option<Secret<String>>,
postal_code: Option<Secret<String>>,
country: Option<common_enums::CountryAlpha2>,
phone: Option<Secret<String>>,
email: Option<Secret<String>>,
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
pub struct CeleroPaymentsResponse {
pub status: CeleroResponseStatus,
pub msg: String,
pub data: Option<CeleroTransactionResponseData>,
}
impl<F, T> TryFrom<ResponseRouterData<F, CeleroPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, CeleroPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
match item.response.status {
CeleroResponseStatus::Success => {
if let Some(data) = item.response.data {
let CeleroPaymentMethodResponse::Card(response) = &data.response;
// Check if transaction itself failed despite successful API call
match response.status {
CeleroTransactionStatus::Declined | CeleroTransactionStatus::Error => {
// Transaction failed - create error response with transaction details
let error_details = CeleroErrorDetails::from_transaction_response(
response,
item.response.msg,
);
Ok(Self {
status: common_enums::AttemptStatus::Failure,
response: Err(
hyperswitch_domain_models::router_data::ErrorResponse {
code: error_details
.error_code
.unwrap_or_else(|| "TRANSACTION_FAILED".to_string()),
message: error_details.error_message,
reason: error_details.decline_reason,
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(data.id),
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
connector_metadata: None,
},
),
..item.data
})
}
_ => {
let connector_response_data =
convert_to_additional_payment_method_connector_response(
response.avs_response_code.clone(),
)
.map(ConnectorResponseData::with_additional_payment_method_data);
let final_status: enums::AttemptStatus = response.status.into();
Ok(Self {
status: final_status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
data.id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: data.get_mandate_reference(),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: response.auth_code.clone(),
incremental_authorization_allowed: None,
charges: None,
}),
connector_response: connector_response_data,
..item.data
})
}
}
} else {
// No transaction data in successful response
// We don't have a transaction ID in this case
Ok(Self {
status: common_enums::AttemptStatus::Failure,
response: Err(hyperswitch_domain_models::router_data::ErrorResponse {
code: "MISSING_DATA".to_string(),
message: "No transaction data in response".to_string(),
reason: Some(item.response.msg),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: None,
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
})
}
}
CeleroResponseStatus::Error => {
// Top-level API error
let error_details =
CeleroErrorDetails::from_top_level_error(item.response.msg.clone());
// Extract transaction ID from the top-level data if available
let connector_transaction_id =
item.response.data.as_ref().map(|data| data.id.clone());
Ok(Self {
status: common_enums::AttemptStatus::Failure,
response: Err(hyperswitch_domain_models::router_data::ErrorResponse {
code: error_details
.error_code
.unwrap_or_else(|| "API_ERROR".to_string()),
message: error_details.error_message,
reason: error_details.decline_reason,
status_code: item.http_code,
attempt_status: None,
connector_transaction_id,
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
})
}
}
}
}
// CAPTURE:
// Type definition for CaptureRequest
#[derive(Default, Debug, Serialize)]
pub struct CeleroCaptureRequest {
pub amount: MinorUnit,
#[serde(skip_serializing_if = "Option::is_none")]
pub order_id: Option<String>,
}
impl TryFrom<&CeleroRouterData<&PaymentsCaptureRouterData>> for CeleroCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &CeleroRouterData<&PaymentsCaptureRouterData>) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.amount,
order_id: Some(item.router_data.payment_id.clone()),
})
}
}
// CeleroCommerce Capture Response
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct CeleroCaptureResponse {
pub status: CeleroResponseStatus,
pub msg: Option<String>,
pub data: Option<serde_json::Value>, // Usually null for capture responses
}
impl
TryFrom<
ResponseRouterData<
Capture,
CeleroCaptureResponse,
PaymentsCaptureData,
PaymentsResponseData,
>,
> for RouterData<Capture, PaymentsCaptureData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
Capture,
CeleroCaptureResponse,
PaymentsCaptureData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
match item.response.status {
CeleroResponseStatus::Success => Ok(Self {
status: common_enums::AttemptStatus::Charged,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.data.request.connector_transaction_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
}),
CeleroResponseStatus::Error => Ok(Self {
status: common_enums::AttemptStatus::Failure,
response: Err(hyperswitch_domain_models::router_data::ErrorResponse {
code: "CAPTURE_FAILED".to_string(),
message: item
.response
.msg
.clone()
.unwrap_or(consts::NO_ERROR_MESSAGE.to_string()),
reason: None,
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(
item.data.request.connector_transaction_id.clone(),
),
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
}),
}
}
}
// CeleroCommerce Void Response - matches API spec format
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct CeleroVoidResponse {
pub status: CeleroResponseStatus,
pub msg: String,
pub data: Option<serde_json::Value>, // Usually null for void responses
}
impl
TryFrom<
ResponseRouterData<
hyperswitch_domain_models::router_flow_types::payments::Void,
CeleroVoidResponse,
hyperswitch_domain_models::router_request_types::PaymentsCancelData,
PaymentsResponseData,
>,
>
for RouterData<
hyperswitch_domain_models::router_flow_types::payments::Void,
hyperswitch_domain_models::router_request_types::PaymentsCancelData,
PaymentsResponseData,
>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
hyperswitch_domain_models::router_flow_types::payments::Void,
CeleroVoidResponse,
hyperswitch_domain_models::router_request_types::PaymentsCancelData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
match item.response.status {
CeleroResponseStatus::Success => Ok(Self {
status: common_enums::AttemptStatus::Voided,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.data.request.connector_transaction_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
}),
CeleroResponseStatus::Error => Ok(Self {
status: common_enums::AttemptStatus::Failure,
response: Err(hyperswitch_domain_models::router_data::ErrorResponse {
code: "VOID_FAILED".to_string(),
message: item.response.msg.clone(),
reason: Some(item.response.msg),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(
item.data.request.connector_transaction_id.clone(),
),
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
}),
}
}
}
#[derive(Default, Debug, Serialize)]
pub struct CeleroRefundRequest {
pub amount: MinorUnit,
pub surcharge: MinorUnit, // Required field as per API specification
}
impl<F> TryFrom<&CeleroRouterData<&RefundsRouterData<F>>> for CeleroRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &CeleroRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.amount,
surcharge: MinorUnit::zero(), // Default to 0 as per API specification
})
}
}
// CeleroCommerce Refund Response - matches API spec format
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct CeleroRefundResponse {
pub status: CeleroResponseStatus,
pub msg: String,
pub data: Option<serde_json::Value>, // Usually null for refund responses
}
impl TryFrom<RefundsResponseRouterData<Execute, CeleroRefundResponse>>
for RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, CeleroRefundResponse>,
) -> Result<Self, Self::Error> {
match item.response.status {
CeleroResponseStatus::Success => Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.data.request.refund_id.clone(),
refund_status: enums::RefundStatus::Success,
}),
..item.data
}),
CeleroResponseStatus::Error => Ok(Self {
| 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/plaid/transformers.rs | crates/hyperswitch_connectors/src/connectors/plaid/transformers.rs | use api_models::payments::OpenBankingSessionToken;
use common_enums::{AttemptStatus, Currency};
use common_utils::types::FloatMajorUnit;
use hyperswitch_domain_models::{
payment_method_data::{OpenBankingData, PaymentMethodData},
router_data::{ConnectorAuthType, ErrorResponse, RouterData},
router_request_types::ResponseId,
router_response_types::PaymentsResponseData,
types::{PaymentsAuthorizeRouterData, PaymentsSyncRouterData},
};
use hyperswitch_interfaces::errors::ConnectorError;
use masking::{PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
types::{PaymentsPostProcessingRouterData, ResponseRouterData},
utils::is_payment_failure,
};
pub struct PlaidRouterData<T> {
pub amount: FloatMajorUnit,
pub router_data: T,
}
impl<T> From<(FloatMajorUnit, T)> for PlaidRouterData<T> {
fn from((amount, item): (FloatMajorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
#[derive(Default, Debug, Serialize)]
pub struct PlaidPaymentsRequest {
amount: PlaidAmount,
recipient_id: String,
reference: String,
#[serde(skip_serializing_if = "Option::is_none")]
schedule: Option<PlaidSchedule>,
#[serde(skip_serializing_if = "Option::is_none")]
options: Option<PlaidOptions>,
}
#[derive(Default, Debug, Serialize, Deserialize)]
pub struct PlaidAmount {
currency: Currency,
value: FloatMajorUnit,
}
#[derive(Default, Debug, Serialize, Deserialize)]
pub struct PlaidSchedule {
interval: String,
interval_execution_day: String,
start_date: String,
end_date: Option<String>,
adjusted_start_date: Option<String>,
}
#[derive(Default, Debug, Serialize, Deserialize)]
pub struct PlaidOptions {
request_refund_details: bool,
iban: Option<Secret<String>>,
bacs: Option<PlaidBacs>,
scheme: String,
}
#[derive(Default, Debug, Serialize, Deserialize)]
pub struct PlaidBacs {
account: Secret<String>,
sort_code: Secret<String>,
}
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct PlaidLinkTokenRequest {
client_name: String,
country_codes: Vec<String>,
language: String,
products: Vec<String>,
user: User,
payment_initiation: PlaidPaymentInitiation,
redirect_uri: Option<String>,
android_package_name: Option<String>,
}
#[derive(Default, Debug, Serialize, Deserialize)]
pub struct User {
pub client_user_id: String,
}
#[derive(Default, Debug, Serialize, Deserialize)]
pub struct PlaidPaymentInitiation {
payment_id: String,
}
impl TryFrom<&PlaidRouterData<&PaymentsAuthorizeRouterData>> for PlaidPaymentsRequest {
type Error = error_stack::Report<ConnectorError>;
fn try_from(item: &PlaidRouterData<&PaymentsAuthorizeRouterData>) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::OpenBanking(ref data) => match data {
OpenBankingData::OpenBankingPIS { .. } => {
let amount = item.amount;
let currency = item.router_data.request.currency;
let payment_id = item.router_data.payment_id.clone();
let id_len = payment_id.len();
let reference = if id_len > 18 {
payment_id.get(id_len - 18..id_len).map(|id| id.to_string())
} else {
Some(payment_id)
}
.ok_or(ConnectorError::MissingRequiredField {
field_name: "payment_id",
})?;
let recipient_type = item
.router_data
.additional_merchant_data
.as_ref()
.map(|merchant_data| match merchant_data {
api_models::admin::AdditionalMerchantData::OpenBankingRecipientData(
data,
) => data.clone(),
})
.ok_or(ConnectorError::MissingRequiredField {
field_name: "additional_merchant_data",
})?;
let recipient_id = match recipient_type {
api_models::admin::MerchantRecipientData::ConnectorRecipientId(id) => {
Ok(id.peek().to_string())
}
_ => Err(ConnectorError::MissingRequiredField {
field_name: "ConnectorRecipientId",
}),
}?;
Ok(Self {
amount: PlaidAmount {
currency,
value: amount,
},
reference,
recipient_id,
schedule: None,
options: None,
})
}
},
_ => Err(ConnectorError::NotImplemented("Payment methods".to_string()).into()),
}
}
}
impl TryFrom<&PaymentsSyncRouterData> for PlaidSyncRequest {
type Error = error_stack::Report<ConnectorError>;
fn try_from(item: &PaymentsSyncRouterData) -> Result<Self, Self::Error> {
match item.request.connector_transaction_id {
ResponseId::ConnectorTransactionId(ref id) => Ok(Self {
payment_id: id.clone(),
}),
_ => Err((ConnectorError::MissingConnectorTransactionID).into()),
}
}
}
impl TryFrom<&PaymentsPostProcessingRouterData> for PlaidLinkTokenRequest {
type Error = error_stack::Report<ConnectorError>;
fn try_from(item: &PaymentsPostProcessingRouterData) -> Result<Self, Self::Error> {
match item.request.payment_method_data {
PaymentMethodData::OpenBanking(ref data) => match data {
OpenBankingData::OpenBankingPIS { .. } => {
let headers = item.header_payload.clone();
let platform = headers
.as_ref()
.and_then(|headers| headers.x_client_platform.clone());
let (is_android, is_ios) = match platform {
Some(common_enums::ClientPlatform::Android) => (true, false),
Some(common_enums::ClientPlatform::Ios) => (false, true),
_ => (false, false),
};
Ok(Self {
client_name: "Hyperswitch".to_string(),
country_codes: item
.request
.country
.map(|code| vec![code.to_string()])
.ok_or(ConnectorError::MissingRequiredField {
field_name: "billing.address.country",
})?,
language: "en".to_string(),
products: vec!["payment_initiation".to_string()],
user: User {
client_user_id: item
.request
.customer_id
.clone()
.map(|id| id.get_string_repr().to_string())
.unwrap_or("default cust".to_string()),
},
payment_initiation: PlaidPaymentInitiation {
payment_id: item
.request
.connector_transaction_id
.clone()
.ok_or(ConnectorError::MissingConnectorTransactionID)?,
},
android_package_name: if is_android {
headers
.as_ref()
.and_then(|headers| headers.x_app_id.clone())
} else {
None
},
redirect_uri: if is_ios {
headers
.as_ref()
.and_then(|headers| headers.x_redirect_uri.clone())
} else {
None
},
})
}
},
_ => Err(ConnectorError::NotImplemented("Payment methods".to_string()).into()),
}
}
}
pub struct PlaidAuthType {
pub client_id: Secret<String>,
pub secret: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for PlaidAuthType {
type Error = error_stack::Report<ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
client_id: api_key.to_owned(),
secret: key1.to_owned(),
}),
_ => Err(ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
#[derive(strum::Display)]
pub enum PlaidPaymentStatus {
PaymentStatusInputNeeded,
PaymentStatusInitiated,
PaymentStatusInsufficientFunds,
PaymentStatusFailed,
PaymentStatusBlocked,
PaymentStatusCancelled,
PaymentStatusExecuted,
PaymentStatusSettled,
PaymentStatusEstablished,
PaymentStatusRejected,
PaymentStatusAuthorising,
}
impl From<PlaidPaymentStatus> for AttemptStatus {
fn from(item: PlaidPaymentStatus) -> Self {
match item {
PlaidPaymentStatus::PaymentStatusAuthorising => Self::Authorizing,
PlaidPaymentStatus::PaymentStatusBlocked
| PlaidPaymentStatus::PaymentStatusInsufficientFunds
| PlaidPaymentStatus::PaymentStatusRejected => Self::AuthorizationFailed,
PlaidPaymentStatus::PaymentStatusCancelled => Self::Voided,
PlaidPaymentStatus::PaymentStatusEstablished => Self::Authorized,
PlaidPaymentStatus::PaymentStatusExecuted
| PlaidPaymentStatus::PaymentStatusSettled
| PlaidPaymentStatus::PaymentStatusInitiated => Self::Charged,
PlaidPaymentStatus::PaymentStatusFailed => Self::Failure,
PlaidPaymentStatus::PaymentStatusInputNeeded => Self::AuthenticationPending,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct PlaidPaymentsResponse {
status: PlaidPaymentStatus,
payment_id: String,
}
impl<F, T> TryFrom<ResponseRouterData<F, PlaidPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<F, PlaidPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let status = AttemptStatus::from(item.response.status.clone());
Ok(Self {
status,
response: if is_payment_failure(status) {
Err(ErrorResponse {
// populating status everywhere as plaid only sends back a status
code: item.response.status.clone().to_string(),
message: item.response.status.clone().to_string(),
reason: Some(item.response.status.to_string()),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(item.response.payment_id),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.payment_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.payment_id),
incremental_authorization_allowed: None,
charges: None,
})
},
..item.data
})
}
}
#[derive(Default, Debug, Serialize, Deserialize)]
pub struct PlaidLinkTokenResponse {
link_token: String,
}
impl<F, T> TryFrom<ResponseRouterData<F, PlaidLinkTokenResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<F, PlaidLinkTokenResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let session_token = Some(OpenBankingSessionToken {
open_banking_session_token: item.response.link_token,
});
Ok(Self {
status: AttemptStatus::AuthenticationPending,
response: Ok(PaymentsResponseData::PostProcessingResponse { session_token }),
..item.data
})
}
}
#[derive(Default, Debug, Serialize, Deserialize)]
pub struct PlaidSyncRequest {
payment_id: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct PlaidSyncResponse {
payment_id: String,
amount: PlaidAmount,
status: PlaidPaymentStatus,
recipient_id: String,
reference: String,
last_status_update: String,
adjusted_reference: Option<String>,
schedule: Option<PlaidSchedule>,
iban: Option<Secret<String>>,
bacs: Option<PlaidBacs>,
scheme: Option<String>,
adjusted_scheme: Option<String>,
request_id: String,
}
impl<F, T> TryFrom<ResponseRouterData<F, PlaidSyncResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<F, PlaidSyncResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let status = AttemptStatus::from(item.response.status.clone());
Ok(Self {
status,
response: if is_payment_failure(status) {
Err(ErrorResponse {
// populating status everywhere as plaid only sends back a status
code: item.response.status.clone().to_string(),
message: item.response.status.clone().to_string(),
reason: Some(item.response.status.to_string()),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(item.response.payment_id),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.payment_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.payment_id),
incremental_authorization_allowed: None,
charges: None,
})
},
..item.data
})
}
}
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub struct PlaidErrorResponse {
pub display_message: Option<String>,
pub error_code: Option<String>,
pub error_message: String,
pub error_type: Option<String>,
}
| 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/braintree/transformers.rs | crates/hyperswitch_connectors/src/connectors/braintree/transformers.rs | use api_models::{
payments as payment_types,
payments::{ApplePaySessionResponse, SessionToken},
webhooks::IncomingWebhookEvent,
};
use common_enums::enums;
use common_utils::{
ext_traits::{OptionExt, ValueExt},
pii,
types::{AmountConvertor, MinorUnit, StringMajorUnit, StringMajorUnitForConnector},
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{PaymentMethodData, WalletData},
router_data::{ConnectorAuthType, PaymentMethodToken, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::{CompleteAuthorizeData, MandateRevokeRequestData, ResponseId},
router_response_types::{
MandateReference, MandateRevokeResponseData, PaymentsResponseData, RedirectForm,
RefundsResponseData,
},
types::{self, RefundsRouterData},
};
use hyperswitch_interfaces::{
consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE},
errors,
};
use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use strum::Display;
use time::PrimitiveDateTime;
use crate::{
types::{
PaymentsCaptureResponseRouterData, PaymentsResponseRouterData,
PaymentsSessionResponseRouterData, RefundsResponseRouterData, ResponseRouterData,
},
unimplemented_payment_method,
utils::{
self, ForeignTryFrom, PaymentsAuthorizeRequestData, PaymentsCompleteAuthorizeRequestData,
RefundsRequestData, RouterData as _,
},
};
pub const CHANNEL_CODE: &str = "HyperSwitchBT_Ecom";
pub const CLIENT_TOKEN_MUTATION: &str = "mutation createClientToken($input: CreateClientTokenInput!) { createClientToken(input: $input) { clientToken}}";
pub const TOKENIZE_CREDIT_CARD: &str = "mutation tokenizeCreditCard($input: TokenizeCreditCardInput!) { tokenizeCreditCard(input: $input) { clientMutationId paymentMethod { id } } }";
pub const CHARGE_CREDIT_CARD_MUTATION: &str = "mutation ChargeCreditCard($input: ChargeCreditCardInput!) { chargeCreditCard(input: $input) { transaction { id legacyId createdAt amount { value currencyCode } status } } }";
pub const AUTHORIZE_CREDIT_CARD_MUTATION: &str = "mutation authorizeCreditCard($input: AuthorizeCreditCardInput!) { authorizeCreditCard(input: $input) { transaction { id legacyId amount { value currencyCode } status } } }";
pub const CAPTURE_TRANSACTION_MUTATION: &str = "mutation captureTransaction($input: CaptureTransactionInput!) { captureTransaction(input: $input) { clientMutationId transaction { id legacyId amount { value currencyCode } status } } }";
pub const VOID_TRANSACTION_MUTATION: &str = "mutation voidTransaction($input: ReverseTransactionInput!) { reverseTransaction(input: $input) { clientMutationId reversal { ... on Transaction { id legacyId amount { value currencyCode } status } } } }";
pub const REFUND_TRANSACTION_MUTATION: &str = "mutation refundTransaction($input: RefundTransactionInput!) { refundTransaction(input: $input) {clientMutationId refund { id legacyId amount { value currencyCode } status } } }";
pub const AUTHORIZE_AND_VAULT_CREDIT_CARD_MUTATION: &str="mutation authorizeCreditCard($input: AuthorizeCreditCardInput!) { authorizeCreditCard(input: $input) { transaction { id status createdAt paymentMethod { id } } } }";
pub const CHARGE_AND_VAULT_TRANSACTION_MUTATION: &str ="mutation ChargeCreditCard($input: ChargeCreditCardInput!) { chargeCreditCard(input: $input) { transaction { id status createdAt paymentMethod { id } } } }";
pub const DELETE_PAYMENT_METHOD_FROM_VAULT_MUTATION: &str = "mutation deletePaymentMethodFromVault($input: DeletePaymentMethodFromVaultInput!) { deletePaymentMethodFromVault(input: $input) { clientMutationId } }";
pub const TRANSACTION_QUERY: &str = "query($input: TransactionSearchInput!) { search { transactions(input: $input) { edges { node { id status } } } } }";
pub const REFUND_QUERY: &str = "query($input: RefundSearchInput!) { search { refunds(input: $input, first: 1) { edges { node { id status createdAt amount { value currencyCode } orderId } } } } }";
pub const CHARGE_GOOGLE_PAY_MUTATION: &str = "mutation ChargeGPay($input: ChargePaymentMethodInput!) { chargePaymentMethod(input: $input) { transaction { id status amount { value currencyCode } } } }";
pub const AUTHORIZE_GOOGLE_PAY_MUTATION: &str = "mutation authorizeGPay($input: AuthorizePaymentMethodInput!) { authorizePaymentMethod(input: $input) { transaction { id legacyId amount { value currencyCode } status } } }";
pub const CHARGE_APPLE_PAY_MUTATION: &str = "mutation ChargeApplepay($input: ChargePaymentMethodInput!) { chargePaymentMethod(input: $input) { transaction { id status amount { value currencyCode } } } }";
pub const AUTHORIZE_APPLE_PAY_MUTATION: &str = "mutation authorizeApplepay($input: AuthorizePaymentMethodInput!) { authorizePaymentMethod(input: $input) { transaction { id legacyId amount { value currencyCode } status } } }";
pub const CHARGE_AND_VAULT_APPLE_PAY_MUTATION: &str = "mutation ChargeApplepay($input: ChargePaymentMethodInput!) { chargePaymentMethod(input: $input) { transaction { id status amount { value currencyCode } paymentMethod { id } } } }";
pub const AUTHORIZE_AND_VAULT_APPLE_PAY_MUTATION: &str = "mutation authorizeApplepay($input: AuthorizePaymentMethodInput!) { authorizePaymentMethod(input: $input) { transaction { id legacyId amount { value currencyCode } status paymentMethod { id } } } }";
pub const CHARGE_PAYPAL_MUTATION: &str = "mutation ChargePaypal($input: ChargePaymentMethodInput!) { chargePaymentMethod(input: $input) { transaction { id status amount { value currencyCode } } } }";
pub const AUTHORIZE_PAYPAL_MUTATION: &str = "mutation authorizePaypal($input: AuthorizePaymentMethodInput!) { authorizePaymentMethod(input: $input) { transaction { id legacyId amount { value currencyCode } status } } }";
pub const TOKENIZE_NETWORK_TOKEN: &str = "mutation tokenizeNetworkToken($input: TokenizeNetworkTokenInput!) { tokenizeNetworkToken(input: $input) { clientMutationId paymentMethod { id } } }";
pub type CardPaymentRequest = GenericBraintreeRequest<VariablePaymentInput>;
pub type MandatePaymentRequest = GenericBraintreeRequest<VariablePaymentInput>;
pub type BraintreeClientTokenRequest = GenericBraintreeRequest<VariableClientTokenInput>;
pub type BraintreeTokenRequest = GenericBraintreeRequest<VariableInput>;
pub type BraintreeCaptureRequest = GenericBraintreeRequest<VariableCaptureInput>;
pub type BraintreeRefundRequest = GenericBraintreeRequest<BraintreeRefundVariables>;
pub type BraintreePSyncRequest = GenericBraintreeRequest<PSyncInput>;
pub type BraintreeRSyncRequest = GenericBraintreeRequest<RSyncInput>;
pub type BraintreeApplePayTokenizeRequest = GenericBraintreeRequest<VariablePaymentInput>;
pub type BraintreeRefundResponse = GenericBraintreeResponse<RefundResponse>;
pub type BraintreeCaptureResponse = GenericBraintreeResponse<CaptureResponse>;
pub type BraintreePSyncResponse = GenericBraintreeResponse<PSyncResponse>;
pub type VariablePaymentInput = GenericVariableInput<PaymentInput>;
pub type VariableClientTokenInput = GenericVariableInput<InputClientTokenData>;
pub type VariableInput = GenericVariableInput<InputData>;
pub type VariableCaptureInput = GenericVariableInput<CaptureInputData>;
pub type BraintreeRefundVariables = GenericVariableInput<BraintreeRefundInput>;
pub type PSyncInput = GenericVariableInput<TransactionSearchInput>;
pub type RSyncInput = GenericVariableInput<RefundSearchInput>;
pub type BraintreeWalletRequest = GenericBraintreeRequest<GenericVariableInput<WalletPaymentInput>>;
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NetworkTokenData {
cryptogram: Secret<String>,
#[serde(skip_serializing_if = "Option::is_none")]
e_commerce_indicator: Option<String>,
expiration_month: Secret<String>,
expiration_year: Secret<String>,
number: cards::CardNumber,
origin_details: NetworkTokenOriginDetailsInput,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NetworkTokenOriginDetailsInput {
origin: NetworkTokenOrigin,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum NetworkTokenOrigin {
ApplePay,
GooglePay,
NetworkToken,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct WalletTransactionBody {
amount: StringMajorUnit,
merchant_account_id: Secret<String>,
order_id: String,
#[serde(skip_serializing_if = "Option::is_none")]
customer_details: Option<CustomerBody>,
#[serde(skip_serializing_if = "Option::is_none")]
vault_payment_method_after_transacting: Option<TransactionTiming>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct WalletPaymentInput {
payment_method_id: Secret<String>,
transaction: WalletTransactionBody,
}
#[derive(Debug, Clone, Serialize)]
pub struct GenericBraintreeRequest<T> {
query: String,
variables: T,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(untagged)]
pub enum GenericBraintreeResponse<T> {
SuccessResponse(Box<T>),
ErrorResponse(Box<ErrorResponse>),
}
#[derive(Debug, Clone, Serialize)]
pub struct GenericVariableInput<T> {
input: T,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BraintreeApiErrorResponse {
pub api_error_response: ApiErrorResponse,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct ErrorsObject {
pub errors: Vec<ErrorObject>,
pub transaction: Option<TransactionError>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TransactionError {
pub errors: Vec<ErrorObject>,
pub credit_card: Option<CreditCardError>,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct CreditCardError {
pub errors: Vec<ErrorObject>,
}
#[derive(Debug, Serialize)]
pub struct BraintreeRouterData<T> {
pub amount: StringMajorUnit,
pub router_data: T,
}
impl<T> TryFrom<(StringMajorUnit, T)> for BraintreeRouterData<T> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from((amount, item): (StringMajorUnit, T)) -> Result<Self, Self::Error> {
Ok(Self {
amount,
router_data: item,
})
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct ErrorObject {
pub code: String,
pub message: String,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BraintreeErrorResponse {
pub errors: String,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
#[serde(untagged)]
pub enum ErrorResponses {
BraintreeApiErrorResponse(Box<BraintreeApiErrorResponse>),
BraintreeErrorResponse(Box<BraintreeErrorResponse>),
}
#[derive(Debug, Deserialize, Serialize)]
pub struct ApiErrorResponse {
pub message: String,
pub errors: ErrorsObject,
}
pub struct BraintreeAuthType {
pub(super) public_key: Secret<String>,
pub(super) private_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for BraintreeAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &ConnectorAuthType) -> Result<Self, Self::Error> {
if let ConnectorAuthType::SignatureKey {
api_key,
api_secret,
key1: _merchant_id,
} = item
{
Ok(Self {
public_key: api_key.to_owned(),
private_key: api_secret.to_owned(),
})
} else {
Err(errors::ConnectorError::FailedToObtainAuthType)?
}
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentInput {
payment_method_id: Secret<String>,
transaction: TransactionBody,
#[serde(skip_serializing_if = "Option::is_none")]
options: Option<CreditCardTransactionOptions>,
}
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum BraintreePaymentsRequest {
Card(CardPaymentRequest),
CardThreeDs(BraintreeClientTokenRequest),
Mandate(MandatePaymentRequest),
Wallet(BraintreeWalletRequest),
Session(BraintreeClientTokenRequest),
}
#[derive(Debug, Deserialize)]
pub struct BraintreeMeta {
merchant_account_id: Secret<String>,
merchant_config_currency: enums::Currency,
}
impl TryFrom<&Option<pii::SecretSerdeValue>> for BraintreeMeta {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(meta_data: &Option<pii::SecretSerdeValue>) -> Result<Self, Self::Error> {
let metadata: Self = utils::to_connector_meta_from_secret::<Self>(meta_data.clone())
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "metadata",
})?;
Ok(metadata)
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CustomerBody {
email: pii::Email,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RegularTransactionBody {
amount: StringMajorUnit,
merchant_account_id: Secret<String>,
channel: String,
#[serde(skip_serializing_if = "Option::is_none")]
customer_details: Option<CustomerBody>,
order_id: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct VaultTransactionBody {
amount: StringMajorUnit,
merchant_account_id: Secret<String>,
vault_payment_method_after_transacting: TransactionTiming,
#[serde(skip_serializing_if = "Option::is_none")]
customer_details: Option<CustomerBody>,
order_id: String,
}
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum TransactionBody {
Regular(RegularTransactionBody),
Vault(VaultTransactionBody),
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum VaultTiming {
Always,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TransactionTiming {
when: VaultTiming,
}
impl
TryFrom<(
&BraintreeRouterData<&types::PaymentsAuthorizeRouterData>,
String,
BraintreeMeta,
)> for MandatePaymentRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, connector_mandate_id, metadata): (
&BraintreeRouterData<&types::PaymentsAuthorizeRouterData>,
String,
BraintreeMeta,
),
) -> Result<Self, Self::Error> {
let (query, transaction_body) = (
match item.router_data.request.is_auto_capture()? {
true => CHARGE_CREDIT_CARD_MUTATION.to_string(),
false => AUTHORIZE_CREDIT_CARD_MUTATION.to_string(),
},
TransactionBody::Regular(RegularTransactionBody {
amount: item.amount.to_owned(),
merchant_account_id: metadata.merchant_account_id,
channel: CHANNEL_CODE.to_string(),
customer_details: None,
order_id: item.router_data.connector_request_reference_id.clone(),
}),
);
Ok(Self {
query,
variables: VariablePaymentInput {
input: PaymentInput {
payment_method_id: connector_mandate_id.into(),
transaction: transaction_body,
options: None,
},
},
})
}
}
impl TryFrom<&BraintreeRouterData<&types::PaymentsAuthorizeRouterData>>
for BraintreePaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &BraintreeRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let metadata: BraintreeMeta = if let (
Some(merchant_account_id),
Some(merchant_config_currency),
) = (
item.router_data.request.merchant_account_id.clone(),
item.router_data.request.merchant_config_currency,
) {
router_env::logger::info!(
"BRAINTREE: Picking merchant_account_id and merchant_config_currency from payments request"
);
BraintreeMeta {
merchant_account_id,
merchant_config_currency,
}
} else {
utils::to_connector_meta_from_secret(item.router_data.connector_meta_data.clone())
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "metadata",
})?
};
utils::validate_currency(
item.router_data.request.currency,
Some(metadata.merchant_config_currency),
)?;
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(_) => {
if item.router_data.is_three_ds()
&& item.router_data.request.authentication_data.is_none()
{
Ok(Self::CardThreeDs(BraintreeClientTokenRequest::try_from(
metadata,
)?))
} else {
Ok(Self::Card(CardPaymentRequest::try_from((item, metadata))?))
}
}
PaymentMethodData::MandatePayment => {
let connector_mandate_id = item.router_data.request.connector_mandate_id().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "connector_mandate_id",
},
)?;
Ok(Self::Mandate(MandatePaymentRequest::try_from((
item,
connector_mandate_id,
metadata,
))?))
}
PaymentMethodData::Wallet(ref wallet_data) => match wallet_data {
WalletData::GooglePayThirdPartySdk(ref req_wallet) => {
let payment_method_id = &req_wallet.token;
let query = match item.router_data.request.is_auto_capture()? {
true => CHARGE_GOOGLE_PAY_MUTATION.to_string(),
false => AUTHORIZE_GOOGLE_PAY_MUTATION.to_string(),
};
Ok(Self::Wallet(BraintreeWalletRequest {
query,
variables: GenericVariableInput {
input: WalletPaymentInput {
payment_method_id: payment_method_id.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "google_pay token",
},
)?,
transaction: WalletTransactionBody {
amount: item.amount.clone(),
merchant_account_id: metadata.merchant_account_id,
order_id: item
.router_data
.connector_request_reference_id
.clone(),
customer_details: None,
vault_payment_method_after_transacting: None,
},
},
},
}))
}
WalletData::ApplePayThirdPartySdk(ref req_wallet) => {
let payment_method_id = &req_wallet.token;
let is_mandate = item.router_data.request.is_mandate_payment();
let is_auto_capture = item.router_data.request.is_auto_capture()?;
let (query, customer_details, vault_payment_method_after_transacting) =
if is_mandate {
(
if is_auto_capture {
CHARGE_AND_VAULT_APPLE_PAY_MUTATION.to_string()
} else {
AUTHORIZE_AND_VAULT_APPLE_PAY_MUTATION.to_string()
},
item.router_data
.get_billing_email()
.ok()
.map(|email| CustomerBody { email }),
Some(TransactionTiming {
when: VaultTiming::Always,
}),
)
} else {
(
if is_auto_capture {
CHARGE_APPLE_PAY_MUTATION.to_string()
} else {
AUTHORIZE_APPLE_PAY_MUTATION.to_string()
},
None,
None,
)
};
Ok(Self::Wallet(BraintreeWalletRequest {
query,
variables: GenericVariableInput {
input: WalletPaymentInput {
payment_method_id: payment_method_id.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "apple_pay token",
},
)?,
transaction: WalletTransactionBody {
amount: item.amount.clone(),
merchant_account_id: metadata.merchant_account_id,
order_id: item
.router_data
.connector_request_reference_id
.clone(),
customer_details,
vault_payment_method_after_transacting,
},
},
},
}))
}
WalletData::PaypalSdk(ref req_wallet) => {
let payment_method_id = req_wallet.token.clone();
let query = match item.router_data.request.is_auto_capture()? {
true => CHARGE_PAYPAL_MUTATION.to_string(),
false => AUTHORIZE_PAYPAL_MUTATION.to_string(),
};
Ok(Self::Wallet(BraintreeWalletRequest {
query,
variables: GenericVariableInput {
input: WalletPaymentInput {
payment_method_id: payment_method_id.clone().into(),
transaction: WalletTransactionBody {
amount: item.amount.clone(),
merchant_account_id: metadata.merchant_account_id,
order_id: item
.router_data
.connector_request_reference_id
.clone(),
customer_details: None,
vault_payment_method_after_transacting: None,
},
},
},
}))
}
WalletData::ApplePay(_apple_pay_data) => {
match item.router_data.payment_method_token {
Some(ref payment_method_token) => match payment_method_token {
PaymentMethodToken::Token(token) => {
let is_mandate = item.router_data.request.is_mandate_payment();
let is_auto_capture = item.router_data.request.is_auto_capture()?;
let (
query,
customer_details,
vault_payment_method_after_transacting,
) = if is_mandate {
(
if is_auto_capture {
CHARGE_AND_VAULT_TRANSACTION_MUTATION.to_string()
} else {
AUTHORIZE_AND_VAULT_CREDIT_CARD_MUTATION.to_string()
},
item.router_data
.get_billing_email()
.ok()
.map(|email| CustomerBody { email }),
Some(TransactionTiming {
when: VaultTiming::Always,
}),
)
} else {
(
if is_auto_capture {
CHARGE_CREDIT_CARD_MUTATION.to_string()
} else {
AUTHORIZE_CREDIT_CARD_MUTATION.to_string()
},
None,
None,
)
};
Ok(Self::Wallet(BraintreeWalletRequest {
query,
variables: GenericVariableInput {
input: WalletPaymentInput {
payment_method_id: token.clone(),
transaction: WalletTransactionBody {
amount: item.amount.clone(),
merchant_account_id: metadata
.merchant_account_id
.clone(),
order_id: item
.router_data
.connector_request_reference_id
.clone(),
customer_details,
vault_payment_method_after_transacting,
},
},
},
}))
}
PaymentMethodToken::ApplePayDecrypt(_apple_pay_decrypt_data) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message(
"braintree",
),
)
.into())
}
PaymentMethodToken::PazeDecrypt(_) => {
Err(unimplemented_payment_method!("Paze", "Braintree"))?
}
PaymentMethodToken::GooglePayDecrypt(_) => {
Err(unimplemented_payment_method!("Google Pay", "Braintree"))?
}
},
None => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("braintree"),
)
.into()),
}
}
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("braintree"),
)
.into()),
},
PaymentMethodData::CardRedirect(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("braintree"),
)
.into())
}
}
}
}
impl TryFrom<&BraintreeRouterData<&types::PaymentsCompleteAuthorizeRouterData>>
for BraintreePaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &BraintreeRouterData<&types::PaymentsCompleteAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.payment_method {
api_models::enums::PaymentMethod::Card => {
Ok(Self::Card(CardPaymentRequest::try_from(item)?))
}
api_models::enums::PaymentMethod::CardRedirect
| api_models::enums::PaymentMethod::PayLater
| api_models::enums::PaymentMethod::Wallet
| api_models::enums::PaymentMethod::BankRedirect
| api_models::enums::PaymentMethod::BankTransfer
| api_models::enums::PaymentMethod::Crypto
| api_models::enums::PaymentMethod::BankDebit
| api_models::enums::PaymentMethod::Reward
| api_models::enums::PaymentMethod::RealTimePayment
| api_models::enums::PaymentMethod::MobilePayment
| api_models::enums::PaymentMethod::Upi
| api_models::enums::PaymentMethod::OpenBanking
| api_models::enums::PaymentMethod::Voucher
| api_models::enums::PaymentMethod::GiftCard
| api_models::enums::PaymentMethod::NetworkToken => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message(
"complete authorize flow",
),
)
.into())
}
}
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct AuthResponse {
data: DataAuthResponse,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(untagged)]
pub enum BraintreeAuthResponse {
AuthResponse(Box<AuthResponse>),
ClientTokenResponse(Box<ClientTokenResponse>),
ErrorResponse(Box<ErrorResponse>),
WalletAuthResponse(Box<WalletAuthResponse>),
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(untagged)]
pub enum BraintreeCompleteAuthResponse {
AuthResponse(Box<AuthResponse>),
ErrorResponse(Box<ErrorResponse>),
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct PaymentMethodInfo {
id: Secret<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TransactionAuthChargeResponseBody {
id: String,
status: BraintreePaymentStatus,
payment_method: Option<PaymentMethodInfo>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DataAuthResponse {
authorize_credit_card: AuthChargeCreditCard,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct AuthChargeCreditCard {
transaction: TransactionAuthChargeResponseBody,
}
impl TryFrom<PaymentsResponseRouterData<BraintreeAuthResponse>>
for types::PaymentsAuthorizeRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsResponseRouterData<BraintreeAuthResponse>,
) -> Result<Self, Self::Error> {
match item.response {
| 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/dwolla/transformers.rs | crates/hyperswitch_connectors/src/connectors/dwolla/transformers.rs | use common_enums::{enums, AttemptStatus};
use common_utils::{errors::CustomResult, types::StringMajorUnit};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
payment_method_data::{BankDebitData, PaymentMethodData},
router_data::{AccessToken, ConnectorAuthType, PaymentMethodToken, RouterData},
router_flow_types::refunds::RSync,
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RefundsResponseData},
types,
types::{PaymentsAuthorizeRouterData, RefundsRouterData},
};
use hyperswitch_interfaces::errors;
use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{self, CustomerData, RouterData as _},
};
pub struct DwollaAuthType {
pub(super) client_id: Secret<String>,
pub(super) client_secret: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for DwollaAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
client_id: api_key.to_owned(),
client_secret: key1.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Default, Debug, Serialize, PartialEq)]
pub struct DwollaAccessTokenRequest {
pub grant_type: String,
}
#[derive(Default, Debug, Clone, Deserialize, PartialEq, Serialize)]
pub struct DwollaAccessTokenResponse {
access_token: Secret<String>,
expires_in: i64,
token_type: String,
}
pub fn extract_token_from_body(body: &[u8]) -> CustomResult<String, errors::ConnectorError> {
let parsed: serde_json::Value = serde_json::from_slice(body)
.map_err(|_| report!(errors::ConnectorError::ResponseDeserializationFailed))?;
parsed
.get("_links")
.and_then(|links| links.get("about"))
.and_then(|about| about.get("href"))
.and_then(|href| href.as_str())
.and_then(|url| url.rsplit('/').next())
.map(|id| id.to_string())
.ok_or_else(|| report!(errors::ConnectorError::ResponseHandlingFailed))
}
fn map_topic_to_status(topic: &str) -> DwollaPaymentStatus {
match topic {
"customer_transfer_created" | "customer_bank_transfer_created" => {
DwollaPaymentStatus::Pending
}
"customer_transfer_completed" | "customer_bank_transfer_completed" => {
DwollaPaymentStatus::Succeeded
}
"customer_transfer_failed" | "customer_bank_transfer_failed" => DwollaPaymentStatus::Failed,
_ => DwollaPaymentStatus::Pending,
}
}
impl<F, T> TryFrom<ResponseRouterData<F, DwollaAccessTokenResponse, T, AccessToken>>
for RouterData<F, T, AccessToken>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, DwollaAccessTokenResponse, T, AccessToken>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(AccessToken {
token: item.response.access_token,
expires: item.response.expires_in,
}),
..item.data
})
}
}
#[derive(Debug)]
pub struct DwollaRouterData<'a, T> {
pub amount: StringMajorUnit,
pub router_data: T,
pub base_url: &'a str,
}
impl<'a, T> TryFrom<(StringMajorUnit, T, &'a str)> for DwollaRouterData<'a, T> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(amount, router_data, base_url): (StringMajorUnit, T, &'a str),
) -> Result<Self, Self::Error> {
Ok(Self {
amount,
router_data,
base_url,
})
}
}
#[derive(Default, Debug, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct DwollaCustomerRequest {
first_name: Secret<String>,
last_name: Secret<String>,
email: common_utils::pii::Email,
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct DwollaCustomerResponse {}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct DwollaFundingSourceResponse {}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DwollaFundingSourceRequest {
routing_number: Secret<String>,
account_number: Secret<String>,
#[serde(rename = "type")]
account_type: common_enums::BankType,
name: Secret<String>,
}
#[derive(Debug, Serialize, PartialEq, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct DwollaPaymentsRequest {
#[serde(rename = "_links")]
links: DwollaPaymentLinks,
amount: DwollaAmount,
correlation_id: String,
}
#[derive(Default, Debug, Serialize, PartialEq, Deserialize, Clone)]
pub struct DwollaPaymentLinks {
source: DwollaRequestLink,
destination: DwollaRequestLink,
}
#[derive(Default, Debug, Serialize, PartialEq, Deserialize, Clone)]
pub struct DwollaRequestLink {
href: String,
}
#[derive(Debug, Serialize, PartialEq, Deserialize, Clone)]
pub struct DwollaAmount {
pub currency: common_enums::Currency,
pub value: StringMajorUnit,
}
#[derive(Debug, Serialize, PartialEq, Deserialize, Clone)]
#[serde(untagged)]
pub enum DwollaPSyncResponse {
Payment(DwollaPaymentSyncResponse),
Webhook(DwollaWebhookDetails),
}
#[derive(Debug, PartialEq, Serialize, Deserialize, Clone)]
pub struct DwollaPaymentSyncResponse {
pub id: String,
pub status: DwollaPaymentStatus,
pub amount: DwollaAmount,
}
#[derive(Debug, Serialize, PartialEq, Deserialize, Clone)]
#[serde(untagged)]
pub enum DwollaRSyncResponse {
Payment(DwollaRefundSyncResponse),
Webhook(DwollaWebhookDetails),
}
#[derive(Debug, PartialEq, Serialize, Deserialize, Clone)]
pub struct DwollaRefundSyncResponse {
id: String,
status: DwollaPaymentStatus,
amount: DwollaAmount,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct DwollaMetaData {
pub merchant_funding_source: Secret<String>,
}
#[derive(Debug, Serialize, PartialEq, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct DwollaRefundsRequest {
#[serde(rename = "_links")]
links: DwollaPaymentLinks,
amount: DwollaAmount,
correlation_id: String,
}
impl TryFrom<&types::ConnectorCustomerRouterData> for DwollaCustomerRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::ConnectorCustomerRouterData) -> Result<Self, Self::Error> {
Ok(Self {
first_name: item.get_billing_first_name()?,
last_name: item.get_billing_last_name()?,
email: item
.request
.get_email()
.or_else(|_| item.get_billing_email())?,
})
}
}
impl TryFrom<&types::TokenizationRouterData> for DwollaFundingSourceRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::TokenizationRouterData) -> Result<Self, Self::Error> {
match item.request.payment_method_data.clone() {
PaymentMethodData::BankDebit(BankDebitData::AchBankDebit {
ref routing_number,
ref account_number,
ref bank_type,
ref bank_account_holder_name,
..
}) => {
let account_type =
(*bank_type).ok_or_else(|| errors::ConnectorError::MissingRequiredField {
field_name: "bank_type",
})?;
let name = bank_account_holder_name.clone().ok_or_else(|| {
errors::ConnectorError::MissingRequiredField {
field_name: "bank_account_holder_name",
}
})?;
let request = Self {
routing_number: routing_number.clone(),
account_number: account_number.clone(),
account_type,
name,
};
Ok(request)
}
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("dwolla"),
))?,
}
}
}
impl<'a> TryFrom<&DwollaRouterData<'a, &PaymentsAuthorizeRouterData>> for DwollaPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &DwollaRouterData<'a, &PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let source_funding = match item.router_data.get_payment_method_token().ok() {
Some(PaymentMethodToken::Token(pm_token)) => pm_token,
_ => {
return Err(report!(errors::ConnectorError::MissingRequiredField {
field_name: "payment_method_token",
}))
}
};
let metadata = utils::to_connector_meta_from_secret::<DwollaMetaData>(
item.router_data.connector_meta_data.clone(),
)
.change_context(errors::ConnectorError::InvalidConnectorConfig { config: "metadata" })?;
let source_url = format!(
"{}/funding-sources/{}",
item.base_url,
source_funding.expose()
);
let destination_url = format!(
"{}/funding-sources/{}",
item.base_url,
metadata.merchant_funding_source.expose()
);
let request = Self {
links: DwollaPaymentLinks {
source: DwollaRequestLink { href: source_url },
destination: DwollaRequestLink {
href: destination_url,
},
},
amount: DwollaAmount {
currency: item.router_data.request.currency,
value: item.amount.to_owned(),
},
correlation_id: format!(
"payment_{}",
item.router_data.connector_request_reference_id
),
};
Ok(request)
}
}
impl<F, T> TryFrom<ResponseRouterData<F, DwollaPSyncResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, DwollaPSyncResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let connector_metadata =
item.data
.payment_method_token
.as_ref()
.and_then(|token| match token {
PaymentMethodToken::Token(t) => {
Some(serde_json::json!({ "payment_token": t.clone().expose() }))
}
_ => None,
});
match item.response {
DwollaPSyncResponse::Payment(payment_response) => {
let payment_id = payment_response.id.clone();
let status = payment_response.status;
Ok(Self {
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(payment_id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata,
network_txn_id: None,
connector_response_reference_id: Some(payment_id.clone()),
incremental_authorization_allowed: None,
charges: None,
}),
status: AttemptStatus::from(status),
..item.data
})
}
DwollaPSyncResponse::Webhook(webhook_response) => {
let payment_id = webhook_response.resource_id.clone();
Ok(Self {
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(payment_id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata,
network_txn_id: None,
connector_response_reference_id: Some(payment_id.clone()),
incremental_authorization_allowed: None,
charges: None,
}),
status: AttemptStatus::from(map_topic_to_status(
webhook_response.topic.as_str(),
)),
..item.data
})
}
}
}
}
impl<'a, F> TryFrom<&DwollaRouterData<'a, &RefundsRouterData<F>>> for DwollaRefundsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &DwollaRouterData<'a, &RefundsRouterData<F>>) -> Result<Self, Self::Error> {
let destination_funding = item
.router_data
.request
.connector_metadata
.as_ref()
.and_then(|meta| {
meta.get("payment_token")
.and_then(|token| token.as_str().map(|s| s.to_string()))
})
.ok_or_else(|| errors::ConnectorError::MissingRequiredField {
field_name: "payment_token",
})?;
let metadata = utils::to_connector_meta_from_secret::<DwollaMetaData>(
item.router_data.connector_meta_data.clone(),
)
.change_context(errors::ConnectorError::InvalidConnectorConfig { config: "metadata" })?;
let source_url = format!(
"{}/funding-sources/{}",
item.base_url,
metadata.merchant_funding_source.expose()
);
let destination_url = format!("{}/funding-sources/{}", item.base_url, destination_funding);
let request = Self {
links: DwollaPaymentLinks {
source: DwollaRequestLink { href: source_url },
destination: DwollaRequestLink {
href: destination_url,
},
},
amount: DwollaAmount {
currency: item.router_data.request.currency,
value: item.amount.to_owned(),
},
correlation_id: format!("refund_{}", item.router_data.connector_request_reference_id),
};
Ok(request)
}
}
impl TryFrom<RefundsResponseRouterData<RSync, DwollaRSyncResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, DwollaRSyncResponse>,
) -> Result<Self, Self::Error> {
match item.response {
DwollaRSyncResponse::Payment(refund_response) => {
let refund_id = refund_response.id.clone();
let status = refund_response.status;
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: refund_id,
refund_status: enums::RefundStatus::from(status),
}),
..item.data
})
}
DwollaRSyncResponse::Webhook(webhook_response) => {
let refund_id = webhook_response.resource_id.clone();
let status = map_topic_to_status(webhook_response.topic.as_str());
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: refund_id,
refund_status: enums::RefundStatus::from(status),
}),
..item.data
})
}
}
}
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum DwollaPaymentStatus {
Succeeded,
Failed,
Pending,
#[default]
Processing,
Processed,
}
impl From<DwollaPaymentStatus> for AttemptStatus {
fn from(item: DwollaPaymentStatus) -> Self {
match item {
DwollaPaymentStatus::Succeeded => Self::Charged,
DwollaPaymentStatus::Processed => Self::Charged,
DwollaPaymentStatus::Failed => Self::Failure,
DwollaPaymentStatus::Processing => Self::Pending,
DwollaPaymentStatus::Pending => Self::Pending,
}
}
}
impl From<DwollaPaymentStatus> for enums::RefundStatus {
fn from(item: DwollaPaymentStatus) -> Self {
match item {
DwollaPaymentStatus::Succeeded => Self::Success,
DwollaPaymentStatus::Processed => Self::Success,
DwollaPaymentStatus::Failed => Self::Failure,
DwollaPaymentStatus::Processing => Self::Pending,
DwollaPaymentStatus::Pending => Self::Pending,
}
}
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct DwollaErrorResponse {
pub code: String,
pub message: String,
#[serde(rename = "_embedded")]
pub embedded: Option<DwollaErrorDetails>,
pub reason: Option<String>,
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct DwollaErrorDetails {
pub errors: Vec<DwollaErrorDetail>,
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct DwollaErrorDetail {
pub code: Option<String>,
pub message: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct DwollaWebhookDetails {
pub id: String,
pub resource_id: String,
pub topic: String,
pub correlation_id: Option<String>,
}
impl From<&str> for DwollaWebhookEventType {
fn from(topic: &str) -> Self {
match topic {
"customer_created" => Self::CustomerCreated,
"customer_verified" => Self::CustomerVerified,
"customer_funding_source_added" => Self::CustomerFundingSourceAdded,
"customer_funding_source_removed" => Self::CustomerFundingSourceRemoved,
"customer_funding_source_verified" => Self::CustomerFundingSourceVerified,
"customer_funding_source_unverified" => Self::CustomerFundingSourceUnverified,
"customer_microdeposits_added" => Self::CustomerMicrodepositsAdded,
"customer_microdeposits_failed" => Self::CustomerMicrodepositsFailed,
"customer_microdeposits_completed" => Self::CustomerMicrodepositsCompleted,
"customer_microdeposits_maxattempts" => Self::CustomerMicrodepositsMaxAttempts,
"customer_bank_transfer_creation_failed" => Self::CustomerBankTransferCreationFailed,
"customer_bank_transfer_created" => Self::CustomerBankTransferCreated,
"customer_transfer_created" => Self::CustomerTransferCreated,
"customer_bank_transfer_failed" => Self::CustomerBankTransferFailed,
"customer_bank_transfer_completed" => Self::CustomerBankTransferCompleted,
"customer_transfer_completed" => Self::CustomerTransferCompleted,
"customer_transfer_failed" => Self::CustomerTransferFailed,
"transfer_created" => Self::TransferCreated,
"transfer_pending" => Self::TransferPending,
"transfer_completed" => Self::TransferCompleted,
"transfer_failed" => Self::TransferFailed,
_ => Self::Unknown,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "kebab-case")]
pub enum DwollaWebhookEventType {
CustomerCreated,
CustomerVerified,
CustomerFundingSourceAdded,
CustomerFundingSourceRemoved,
CustomerFundingSourceUnverified,
CustomerFundingSourceVerified,
CustomerMicrodepositsAdded,
CustomerMicrodepositsFailed,
CustomerMicrodepositsCompleted,
CustomerMicrodepositsMaxAttempts,
CustomerTransferCreated,
CustomerBankTransferCreationFailed,
CustomerBankTransferCreated,
CustomerBankTransferCompleted,
CustomerBankTransferFailed,
CustomerTransferCompleted,
CustomerTransferFailed,
TransferCreated,
TransferPending,
TransferCompleted,
TransferFailed,
#[serde(other)]
Unknown,
}
impl TryFrom<DwollaWebhookDetails> for api_models::webhooks::IncomingWebhookEvent {
type Error = errors::ConnectorError;
fn try_from(details: DwollaWebhookDetails) -> Result<Self, Self::Error> {
let correlation_id = match details.correlation_id.as_deref() {
Some(cid) => cid,
None => {
return Ok(Self::EventNotSupported);
}
};
let event_type = DwollaWebhookEventType::from(details.topic.as_str());
let is_refund = correlation_id.starts_with("refund_");
Ok(match (event_type, is_refund) {
(DwollaWebhookEventType::CustomerTransferCompleted, true)
| (DwollaWebhookEventType::CustomerBankTransferCompleted, true) => Self::RefundSuccess,
(DwollaWebhookEventType::CustomerTransferFailed, true)
| (DwollaWebhookEventType::CustomerBankTransferFailed, true) => Self::RefundFailure,
(DwollaWebhookEventType::CustomerTransferCreated, false)
| (DwollaWebhookEventType::CustomerBankTransferCreated, false) => {
Self::PaymentIntentProcessing
}
(DwollaWebhookEventType::CustomerTransferCompleted, false)
| (DwollaWebhookEventType::CustomerBankTransferCompleted, false) => {
Self::PaymentIntentSuccess
}
(DwollaWebhookEventType::CustomerTransferFailed, false)
| (DwollaWebhookEventType::CustomerBankTransferFailed, false) => {
Self::PaymentIntentFailure
}
_ => Self::EventNotSupported,
})
}
}
| 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/affirm/transformers.rs | crates/hyperswitch_connectors/src/connectors/affirm/transformers.rs | use common_enums::{enums, CountryAlpha2, Currency};
use common_utils::{pii, request::Method, types::MinorUnit};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
payment_method_data::{PayLaterData, PaymentMethodData},
router_data::{ConnectorAuthType, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsCompleteAuthorizeRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::errors;
use masking::Secret;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::{
types::{
PaymentsCancelResponseRouterData, PaymentsCaptureResponseRouterData,
RefundsResponseRouterData, ResponseRouterData,
},
utils::{PaymentsAuthorizeRequestData, RouterData as OtherRouterData},
};
pub struct AffirmRouterData<T> {
pub amount: MinorUnit,
pub router_data: T,
}
impl<T> From<(MinorUnit, T)> for AffirmRouterData<T> {
fn from((amount, item): (MinorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
#[derive(Debug, Serialize)]
pub struct AffirmPaymentsRequest {
pub merchant: Merchant,
pub items: Vec<Item>,
pub shipping: Option<Shipping>,
pub billing: Option<Billing>,
pub total: MinorUnit,
pub currency: Currency,
pub order_id: Option<String>,
}
#[derive(Debug, Serialize)]
pub struct AffirmCompleteAuthorizeRequest {
pub order_id: Option<String>,
pub reference_id: Option<String>,
pub transaction_id: String,
}
impl TryFrom<&PaymentsCompleteAuthorizeRouterData> for AffirmCompleteAuthorizeRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsCompleteAuthorizeRouterData) -> Result<Self, Self::Error> {
let transaction_id = item.request.connector_transaction_id.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "connector_transaction_id",
},
)?;
let reference_id = item.reference_id.clone();
let order_id = item.connector_request_reference_id.clone();
Ok(Self {
transaction_id,
order_id: Some(order_id),
reference_id,
})
}
}
#[derive(Debug, Serialize)]
pub struct Merchant {
pub public_api_key: Secret<String>,
pub user_confirmation_url: String,
pub user_cancel_url: String,
pub user_confirmation_url_action: Option<String>,
pub use_vcn: Option<String>,
pub name: Option<String>,
}
#[derive(Debug, Serialize)]
pub struct Item {
pub display_name: String,
pub sku: String,
pub unit_price: MinorUnit,
pub qty: i64,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Shipping {
pub name: Name,
pub address: Address,
#[serde(skip_serializing_if = "Option::is_none")]
pub phone_number: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub email: Option<pii::Email>,
}
#[derive(Debug, Serialize)]
pub struct Billing {
pub name: Name,
pub address: Address,
#[serde(skip_serializing_if = "Option::is_none")]
pub phone_number: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub email: Option<pii::Email>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Name {
pub first: Option<Secret<String>>,
pub last: Option<Secret<String>>,
pub full: Option<Secret<String>>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Address {
pub line1: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub line2: Option<Secret<String>>,
pub city: Option<String>,
pub state: Option<Secret<String>>,
pub zipcode: Option<Secret<String>>,
pub country: Option<CountryAlpha2>,
}
#[derive(Debug, Serialize)]
pub struct Metadata {
#[serde(skip_serializing_if = "Option::is_none")]
pub shipping_type: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub entity_name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub platform_type: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub platform_version: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub platform_affirm: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub webhook_session_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub mode: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub customer: Option<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub itinerary: Option<Vec<Value>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub checkout_channel_type: Option<String>,
#[serde(rename = "BOPIS", skip_serializing_if = "Option::is_none")]
pub bopis: Option<bool>,
}
#[derive(Debug, Serialize)]
pub struct Discount {
pub discount_amount: MinorUnit,
pub discount_display_name: String,
pub discount_code: Option<String>,
}
impl TryFrom<&AffirmRouterData<&PaymentsAuthorizeRouterData>> for AffirmPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &AffirmRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let router_data = &item.router_data;
let request = &router_data.request;
let billing = Some(Billing {
name: Name {
first: item.router_data.get_optional_billing_first_name(),
last: item.router_data.get_optional_billing_last_name(),
full: item.router_data.get_optional_billing_full_name(),
},
address: Address {
line1: item.router_data.get_optional_billing_line1(),
line2: item.router_data.get_optional_billing_line2(),
city: item.router_data.get_optional_billing_city(),
state: item.router_data.get_optional_billing_state(),
zipcode: item.router_data.get_optional_billing_zip(),
country: item.router_data.get_optional_billing_country(),
},
phone_number: item.router_data.get_optional_billing_phone_number(),
email: item.router_data.get_optional_billing_email(),
});
let shipping = Some(Shipping {
name: Name {
first: item.router_data.get_optional_shipping_first_name(),
last: item.router_data.get_optional_shipping_last_name(),
full: item.router_data.get_optional_shipping_full_name(),
},
address: Address {
line1: item.router_data.get_optional_shipping_line1(),
line2: item.router_data.get_optional_shipping_line2(),
city: item.router_data.get_optional_shipping_city(),
state: item.router_data.get_optional_shipping_state(),
zipcode: item.router_data.get_optional_shipping_zip(),
country: item.router_data.get_optional_shipping_country(),
},
phone_number: item.router_data.get_optional_shipping_phone_number(),
email: item.router_data.get_optional_shipping_email(),
});
match request.payment_method_data.clone() {
PaymentMethodData::PayLater(PayLaterData::AffirmRedirect {}) => {
let items = match request.order_details.clone() {
Some(order_details) => order_details
.iter()
.map(|data| {
Ok(Item {
display_name: data.product_name.clone(),
sku: data.product_id.clone().unwrap_or_default(),
unit_price: data.amount,
qty: data.quantity.into(),
})
})
.collect::<Result<Vec<_>, _>>(),
None => Err(report!(errors::ConnectorError::MissingRequiredField {
field_name: "order_details",
})),
}?;
let auth_type = AffirmAuthType::try_from(&item.router_data.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let public_api_key = auth_type.public_key;
let merchant = Merchant {
public_api_key,
user_confirmation_url: request.get_complete_authorize_url()?,
user_cancel_url: request.get_router_return_url()?,
user_confirmation_url_action: None,
use_vcn: None,
name: None,
};
Ok(Self {
merchant,
items,
shipping,
billing,
total: item.amount,
currency: request.currency,
order_id: Some(item.router_data.connector_request_reference_id.clone()),
})
}
_ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()),
}
}
}
pub struct AffirmAuthType {
pub public_key: Secret<String>,
pub private_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for AffirmAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
public_key: api_key.to_owned(),
private_key: key1.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
impl From<AffirmTransactionStatus> for common_enums::AttemptStatus {
fn from(item: AffirmTransactionStatus) -> Self {
match item {
AffirmTransactionStatus::Authorized => Self::Authorized,
AffirmTransactionStatus::AuthExpired => Self::Failure,
AffirmTransactionStatus::Canceled => Self::Voided,
AffirmTransactionStatus::Captured => Self::Charged,
AffirmTransactionStatus::ConfirmationExpired => Self::Failure,
AffirmTransactionStatus::Confirmed => Self::Authorized,
AffirmTransactionStatus::Created => Self::Pending,
AffirmTransactionStatus::Declined => Self::Failure,
AffirmTransactionStatus::Disputed => Self::Unresolved,
AffirmTransactionStatus::DisputeRefunded => Self::Unresolved,
AffirmTransactionStatus::ExpiredAuthorization => Self::Failure,
AffirmTransactionStatus::ExpiredConfirmation => Self::Failure,
AffirmTransactionStatus::PartiallyCaptured => Self::Charged,
AffirmTransactionStatus::Voided => Self::Voided,
AffirmTransactionStatus::PartiallyVoided => Self::Voided,
}
}
}
impl From<AffirmRefundStatus> for common_enums::RefundStatus {
fn from(item: AffirmRefundStatus) -> Self {
match item {
AffirmRefundStatus::PartiallyRefunded => Self::Success,
AffirmRefundStatus::Refunded => Self::Success,
}
}
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct AffirmPaymentsResponse {
checkout_id: String,
redirect_url: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct AffirmCompleteAuthorizeResponse {
pub id: String,
pub status: AffirmTransactionStatus,
pub amount: MinorUnit,
pub amount_refunded: MinorUnit,
pub authorization_expiration: String,
pub checkout_id: String,
pub created: String,
pub currency: Currency,
pub events: Vec<TransactionEvent>,
pub settlement_transaction_id: Option<String>,
pub transaction_id: String,
pub order_id: String,
pub shipping_carrier: Option<String>,
pub shipping_confirmation: Option<String>,
pub shipping: Option<Shipping>,
pub agent_alias: Option<String>,
pub merchant_transaction_id: Option<String>,
pub provider_id: Option<i64>,
pub remove_tax: Option<bool>,
pub checkout: Option<Value>,
pub refund_expires: Option<String>,
pub remaining_capturable_amount: Option<i64>,
pub loan_information: Option<LoanInformation>,
pub user_id: Option<String>,
pub platform: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct TransactionEvent {
pub id: String,
pub amount: MinorUnit,
pub created: String,
pub currency: Currency,
pub fee: Option<i64>,
pub fee_refunded: Option<MinorUnit>,
pub reference_id: Option<String>,
#[serde(rename = "type")]
pub event_type: AffirmEventType,
pub settlement_transaction_id: Option<String>,
pub transaction_id: String,
pub order_id: String,
pub shipping_carrier: Option<String>,
pub shipping_confirmation: Option<String>,
pub shipping: Option<Shipping>,
pub agent_alias: Option<String>,
pub merchant_transaction_id: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct LoanInformation {
pub fees: Option<LoanFees>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct LoanFees {
pub amount: Option<MinorUnit>,
pub description: Option<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AffirmTransactionStatus {
Authorized,
AuthExpired,
Canceled,
Captured,
ConfirmationExpired,
Confirmed,
Created,
Declined,
Disputed,
DisputeRefunded,
ExpiredAuthorization,
ExpiredConfirmation,
PartiallyCaptured,
Voided,
PartiallyVoided,
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AffirmRefundStatus {
PartiallyRefunded,
Refunded,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct AffirmPSyncResponse {
pub amount: MinorUnit,
pub amount_refunded: MinorUnit,
pub authorization_expiration: Option<String>,
pub checkout_id: String,
pub created: String,
pub currency: Currency,
pub events: Vec<TransactionEvent>,
pub id: String,
pub order_id: String,
pub provider_id: Option<i64>,
pub remove_tax: Option<bool>,
pub status: AffirmTransactionStatus,
pub checkout: Option<Value>,
pub refund_expires: Option<String>,
pub remaining_capturable_amount: Option<MinorUnit>,
pub loan_information: Option<LoanInformation>,
pub shipping_carrier: Option<String>,
pub shipping_confirmation: Option<String>,
pub shipping: Option<Shipping>,
pub merchant_transaction_id: Option<String>,
pub settlement_transaction_id: Option<String>,
pub transaction_id: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct AffirmRsyncResponse {
pub amount: MinorUnit,
pub amount_refunded: MinorUnit,
pub authorization_expiration: String,
pub checkout_id: String,
pub created: String,
pub currency: Currency,
pub events: Vec<TransactionEvent>,
pub id: String,
pub order_id: String,
pub status: AffirmRefundStatus,
pub refund_expires: Option<String>,
pub remaining_capturable_amount: Option<MinorUnit>,
pub shipping_carrier: Option<String>,
pub shipping_confirmation: Option<String>,
pub shipping: Option<Shipping>,
pub merchant_transaction_id: Option<String>,
pub settlement_transaction_id: Option<String>,
pub transaction_id: String,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum AffirmResponseWrapper {
Authorize(AffirmPaymentsResponse),
Psync(Box<AffirmPSyncResponse>),
}
impl<F, T> TryFrom<ResponseRouterData<F, AffirmResponseWrapper, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, AffirmResponseWrapper, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
match &item.response {
AffirmResponseWrapper::Authorize(resp) => {
let redirection_data = url::Url::parse(&resp.redirect_url)
.ok()
.map(|url| RedirectForm::from((url, Method::Get)));
Ok(Self {
status: enums::AttemptStatus::AuthenticationPending,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(resp.checkout_id.clone()),
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
charges: None,
incremental_authorization_allowed: None,
}),
..item.data
})
}
AffirmResponseWrapper::Psync(resp) => {
let status = enums::AttemptStatus::from(resp.status);
Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(resp.id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
charges: None,
incremental_authorization_allowed: None,
}),
..item.data
})
}
}
}
}
impl<F, T> TryFrom<ResponseRouterData<F, AffirmCompleteAuthorizeResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, AffirmCompleteAuthorizeResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: common_enums::AttemptStatus::from(item.response.status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Default, Debug, Serialize)]
pub struct AffirmRefundRequest {
pub amount: MinorUnit,
#[serde(skip_serializing_if = "Option::is_none")]
pub reference_id: Option<String>,
}
impl<F> TryFrom<&AffirmRouterData<&RefundsRouterData<F>>> for AffirmRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &AffirmRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
let reference_id = item.router_data.request.connector_transaction_id.clone();
Ok(Self {
amount: item.amount.to_owned(),
reference_id: Some(reference_id),
})
}
}
#[allow(dead_code)]
#[derive(Debug, Copy, Serialize, Default, Deserialize, Clone)]
pub enum RefundStatus {
Succeeded,
Failed,
#[default]
Processing,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct AffirmRefundResponse {
pub id: String,
pub amount: MinorUnit,
pub created: String,
pub currency: Currency,
pub fee: Option<MinorUnit>,
pub fee_refunded: Option<MinorUnit>,
pub reference_id: Option<String>,
#[serde(rename = "type")]
pub event_type: AffirmEventType,
pub settlement_transaction_id: Option<String>,
pub transaction_id: String,
pub order_id: String,
pub shipping_carrier: Option<String>,
pub shipping_confirmation: Option<String>,
pub shipping: Option<Shipping>,
pub agent_alias: Option<String>,
pub merchant_transaction_id: Option<String>,
}
impl From<AffirmEventType> for enums::RefundStatus {
fn from(event_type: AffirmEventType) -> Self {
match event_type {
AffirmEventType::Refund => Self::Success,
_ => Self::Pending,
}
}
}
impl TryFrom<RefundsResponseRouterData<Execute, AffirmRefundResponse>>
for RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, AffirmRefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.event_type),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, AffirmRsyncResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, AffirmRsyncResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct AffirmErrorResponse {
pub status_code: u16,
pub code: String,
pub message: String,
#[serde(rename = "type")]
pub error_type: String,
}
#[derive(Debug, Serialize)]
pub struct AffirmCaptureRequest {
pub order_id: Option<String>,
pub reference_id: Option<String>,
pub amount: MinorUnit,
pub shipping_carrier: Option<String>,
pub shipping_confirmation: Option<String>,
}
impl TryFrom<&AffirmRouterData<&PaymentsCaptureRouterData>> for AffirmCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &AffirmRouterData<&PaymentsCaptureRouterData>) -> Result<Self, Self::Error> {
let reference_id = match item.router_data.connector_request_reference_id.clone() {
ref_id if ref_id.is_empty() => None,
ref_id => Some(ref_id),
};
let amount = item.amount;
Ok(Self {
reference_id,
amount,
order_id: None,
shipping_carrier: None,
shipping_confirmation: None,
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct AffirmCaptureResponse {
pub id: String,
pub amount: MinorUnit,
pub created: String,
pub currency: Currency,
pub fee: Option<MinorUnit>,
pub fee_refunded: Option<MinorUnit>,
pub reference_id: Option<String>,
#[serde(rename = "type")]
pub event_type: AffirmEventType,
pub settlement_transaction_id: Option<String>,
pub transaction_id: String,
pub order_id: String,
pub shipping_carrier: Option<String>,
pub shipping_confirmation: Option<String>,
pub shipping: Option<Shipping>,
pub agent_alias: Option<String>,
pub merchant_transaction_id: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum AffirmEventType {
Auth,
AuthExpired,
Capture,
ChargeOff,
Confirm,
ConfirmationExpired,
ExpireAuthorization,
ExpireConfirmation,
Refund,
SplitCapture,
Update,
Void,
PartialVoid,
RefundVoided,
}
impl From<AffirmEventType> for enums::AttemptStatus {
fn from(event_type: AffirmEventType) -> Self {
match event_type {
AffirmEventType::Auth => Self::Authorized,
AffirmEventType::Capture | AffirmEventType::SplitCapture | AffirmEventType::Confirm => {
Self::Charged
}
AffirmEventType::AuthExpired
| AffirmEventType::ChargeOff
| AffirmEventType::ConfirmationExpired
| AffirmEventType::ExpireAuthorization
| AffirmEventType::ExpireConfirmation => Self::Failure,
AffirmEventType::Refund | AffirmEventType::RefundVoided => Self::AutoRefunded,
AffirmEventType::Update => Self::Pending,
AffirmEventType::Void | AffirmEventType::PartialVoid => Self::Voided,
}
}
}
impl TryFrom<PaymentsCaptureResponseRouterData<AffirmCaptureResponse>>
for PaymentsCaptureRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsCaptureResponseRouterData<AffirmCaptureResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: enums::AttemptStatus::from(item.response.event_type.clone()),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
impl TryFrom<&PaymentsCancelRouterData> for AffirmCancelRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> {
let request = &item.request;
let reference_id = request.connector_transaction_id.clone();
let amount = item
.request
.amount
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "amount",
})?;
Ok(Self {
reference_id: Some(reference_id),
amount,
merchant_transaction_id: None,
})
}
}
#[derive(Debug, Serialize)]
pub struct AffirmCancelRequest {
pub reference_id: Option<String>,
pub amount: i64,
pub merchant_transaction_id: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct AffirmCancelResponse {
pub id: String,
pub amount: MinorUnit,
pub created: String,
pub currency: Currency,
pub fee: Option<MinorUnit>,
pub fee_refunded: Option<MinorUnit>,
pub reference_id: Option<String>,
#[serde(rename = "type")]
pub event_type: AffirmEventType,
pub settlement_transaction_id: Option<String>,
pub transaction_id: String,
pub order_id: String,
pub shipping_carrier: Option<String>,
pub shipping_confirmation: Option<String>,
pub shipping: Option<Shipping>,
pub agent_alias: Option<String>,
pub merchant_transaction_id: Option<String>,
}
impl TryFrom<PaymentsCancelResponseRouterData<AffirmCancelResponse>> for PaymentsCancelRouterData {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsCancelResponseRouterData<AffirmCancelResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: enums::AttemptStatus::from(item.response.event_type.clone()),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: 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/jpmorgan/transformers.rs | crates/hyperswitch_connectors/src/connectors/jpmorgan/transformers.rs | use common_enums::enums::CaptureMethod;
use common_utils::{pii::SecretSerdeValue, types::MinorUnit};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{AccessToken, ConnectorAuthType, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RefundsResponseData},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
RefreshTokenRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::errors;
use masking::{PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
types::{PaymentsCancelResponseRouterData, RefundsResponseRouterData, ResponseRouterData},
utils::{
self, get_unimplemented_payment_method_error_message, CardData,
RouterData as OtherRouterData,
},
};
pub struct JpmorganRouterData<T> {
pub amount: MinorUnit,
pub router_data: T,
}
impl<T> From<(MinorUnit, T)> for JpmorganRouterData<T> {
fn from((amount, item): (MinorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
#[derive(Debug, Clone, Serialize)]
pub struct JpmorganAuthUpdateRequest {
pub grant_type: String,
pub scope: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct JpmorganAuthUpdateResponse {
pub access_token: Secret<String>,
pub scope: String,
pub token_type: String,
pub expires_in: i64,
}
/// JPMorgan connector metadata containing merchant software information
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct JpmorganConnectorMetadataObject {
pub company_name: Secret<String>,
pub product_name: Secret<String>,
}
impl TryFrom<&Option<SecretSerdeValue>> for JpmorganConnectorMetadataObject {
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<&RefreshTokenRouterData> for JpmorganAuthUpdateRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(_item: &RefreshTokenRouterData) -> Result<Self, Self::Error> {
Ok(Self {
grant_type: String::from("client_credentials"),
scope: String::from("jpm:payments:sandbox"),
})
}
}
impl<F, T> TryFrom<ResponseRouterData<F, JpmorganAuthUpdateResponse, T, AccessToken>>
for RouterData<F, T, AccessToken>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, JpmorganAuthUpdateResponse, T, AccessToken>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(AccessToken {
token: item.response.access_token,
expires: item.response.expires_in,
}),
..item.data
})
}
}
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct JpmorganPaymentsRequest {
capture_method: CapMethod,
amount: MinorUnit,
currency: common_enums::Currency,
merchant: JpmorganMerchant,
payment_method_type: JpmorganPaymentMethodType,
}
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct JpmorganCard {
account_number: Secret<String>,
expiry: Expiry,
}
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct JpmorganPaymentMethodType {
card: JpmorganCard,
}
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Expiry {
month: Secret<i32>,
year: Secret<i32>,
}
#[derive(Serialize, Debug, Default, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct JpmorganMerchantSoftware {
company_name: Secret<String>,
product_name: Secret<String>,
}
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct JpmorganMerchant {
merchant_software: JpmorganMerchantSoftware,
}
fn map_capture_method(
capture_method: CaptureMethod,
) -> Result<CapMethod, error_stack::Report<errors::ConnectorError>> {
match capture_method {
CaptureMethod::Automatic => Ok(CapMethod::Now),
CaptureMethod::Manual => Ok(CapMethod::Manual),
CaptureMethod::Scheduled
| CaptureMethod::ManualMultiple
| CaptureMethod::SequentialAutomatic => {
Err(errors::ConnectorError::NotImplemented("Capture Method".to_string()).into())
}
}
}
impl TryFrom<&JpmorganRouterData<&PaymentsAuthorizeRouterData>> for JpmorganPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &JpmorganRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(req_card) => {
if item.router_data.is_three_ds() {
return Err(errors::ConnectorError::NotSupported {
message: "3DS payments".to_string(),
connector: "Jpmorgan",
}
.into());
}
let capture_method =
map_capture_method(item.router_data.request.capture_method.unwrap_or_default());
let connector_metadata = JpmorganConnectorMetadataObject::try_from(
&item.router_data.connector_meta_data.clone(),
)?;
let merchant = JpmorganMerchant {
merchant_software: JpmorganMerchantSoftware {
company_name: connector_metadata.company_name,
product_name: connector_metadata.product_name,
},
};
let expiry: Expiry = Expiry {
month: Secret::new(
req_card
.card_exp_month
.peek()
.clone()
.parse::<i32>()
.change_context(errors::ConnectorError::RequestEncodingFailed)?,
),
year: req_card.get_expiry_year_as_4_digit_i32()?,
};
let account_number = Secret::new(req_card.card_number.to_string());
let card = JpmorganCard {
account_number,
expiry,
};
let payment_method_type = JpmorganPaymentMethodType { card };
Ok(Self {
capture_method: capture_method?,
currency: item.router_data.request.currency,
amount: item.amount,
merchant,
payment_method_type,
})
}
PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Wallet(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_) => Err(errors::ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("jpmorgan"),
)
.into()),
}
}
}
//JP Morgan uses access token only due to which we aren't reading the fields in this struct
#[derive(Debug)]
pub struct JpmorganAuthType {
pub(super) _api_key: Secret<String>,
pub(super) _key1: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for JpmorganAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
_api_key: api_key.to_owned(),
_key1: key1.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "UPPERCASE")]
pub enum JpmorganTransactionStatus {
Success,
Denied,
Error,
}
#[derive(Default, Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "UPPERCASE")]
pub enum JpmorganTransactionState {
Closed,
Authorized,
Voided,
#[default]
Pending,
Declined,
Error,
}
#[derive(Default, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct JpmorganPaymentsResponse {
transaction_id: String,
request_id: String,
transaction_state: JpmorganTransactionState,
response_status: String,
response_code: String,
response_message: String,
payment_method_type: PaymentMethodType,
capture_method: Option<CapMethod>,
}
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Merchant {
merchant_id: Option<String>,
merchant_software: JpmorganMerchantSoftware,
merchant_category_code: Option<String>,
}
#[derive(Default, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentMethodType {
card: Option<Card>,
}
#[derive(Default, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Card {
expiry: Option<ExpiryResponse>,
card_type: Option<Secret<String>>,
card_type_name: Option<Secret<String>>,
masked_account_number: Option<Secret<String>>,
card_type_indicators: Option<CardTypeIndicators>,
network_response: Option<NetworkResponse>,
}
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NetworkResponse {
address_verification_result: Option<Secret<String>>,
address_verification_result_code: Option<Secret<String>>,
card_verification_result_code: Option<Secret<String>>,
}
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ExpiryResponse {
month: Option<Secret<i32>>,
year: Option<Secret<i32>>,
}
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CardTypeIndicators {
issuance_country_code: Option<Secret<String>>,
is_durbin_regulated: Option<bool>,
card_product_types: Secret<Vec<String>>,
}
pub fn attempt_status_from_transaction_state(
transaction_state: JpmorganTransactionState,
) -> common_enums::AttemptStatus {
match transaction_state {
JpmorganTransactionState::Authorized => common_enums::AttemptStatus::Authorized,
JpmorganTransactionState::Closed => common_enums::AttemptStatus::Charged,
JpmorganTransactionState::Declined | JpmorganTransactionState::Error => {
common_enums::AttemptStatus::Failure
}
JpmorganTransactionState::Pending => common_enums::AttemptStatus::Pending,
JpmorganTransactionState::Voided => common_enums::AttemptStatus::Voided,
}
}
impl<F, T> TryFrom<ResponseRouterData<F, JpmorganPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, JpmorganPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let transaction_state = match item.response.transaction_state {
JpmorganTransactionState::Closed => match item.response.capture_method {
Some(CapMethod::Now) => JpmorganTransactionState::Closed,
_ => JpmorganTransactionState::Authorized,
},
JpmorganTransactionState::Authorized => JpmorganTransactionState::Authorized,
JpmorganTransactionState::Voided => JpmorganTransactionState::Voided,
JpmorganTransactionState::Pending => JpmorganTransactionState::Pending,
JpmorganTransactionState::Declined => JpmorganTransactionState::Declined,
JpmorganTransactionState::Error => JpmorganTransactionState::Error,
};
let status = attempt_status_from_transaction_state(transaction_state);
Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.transaction_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.transaction_id.clone()),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Default, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct JpmorganCaptureRequest {
capture_method: CapMethod,
amount: MinorUnit,
currency: common_enums::Currency,
}
#[derive(Debug, Default, Copy, Serialize, Deserialize, Clone)]
#[serde(rename_all = "UPPERCASE")]
pub enum CapMethod {
#[default]
Now,
Delayed,
Manual,
}
impl TryFrom<&JpmorganRouterData<&PaymentsCaptureRouterData>> for JpmorganCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &JpmorganRouterData<&PaymentsCaptureRouterData>,
) -> Result<Self, Self::Error> {
let amount_to_capture = item.amount;
// When AuthenticationType is `Manual`, Documentation suggests us to pass `isAmountFinal` field being `true`
// isAmountFinal is by default `true`. Since Manual Multiple support is not added here, the field is not used.
Ok(Self {
capture_method: CapMethod::Now,
amount: amount_to_capture,
currency: item.router_data.request.currency,
})
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct JpmorganCaptureResponse {
pub transaction_id: String,
pub request_id: String,
pub transaction_state: JpmorganTransactionState,
pub response_status: JpmorganTransactionStatus,
pub response_code: String,
pub response_message: String,
pub payment_method_type: PaymentMethodTypeCapRes,
}
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentMethodTypeCapRes {
pub card: Option<CardCapRes>,
}
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CardCapRes {
pub card_type: Option<Secret<String>>,
pub card_type_name: Option<Secret<String>>,
unmasked_account_number: Option<Secret<String>>,
}
impl<F, T> TryFrom<ResponseRouterData<F, JpmorganCaptureResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, JpmorganCaptureResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let status = attempt_status_from_transaction_state(item.response.transaction_state);
Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.transaction_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.transaction_id.clone()),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct JpmorganPSyncResponse {
transaction_id: String,
transaction_state: JpmorganTransactionState,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum JpmorganResponseStatus {
Success,
Denied,
Error,
}
impl<F, PaymentsSyncData>
TryFrom<ResponseRouterData<F, JpmorganPSyncResponse, PaymentsSyncData, PaymentsResponseData>>
for RouterData<F, PaymentsSyncData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, JpmorganPSyncResponse, PaymentsSyncData, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let status = attempt_status_from_transaction_state(item.response.transaction_state);
Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.transaction_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.transaction_id.clone()),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct TransactionData {
payment_type: Option<Secret<String>>,
status_code: Secret<i32>,
txn_secret: Option<Secret<String>>,
tid: Option<Secret<i64>>,
test_mode: Option<Secret<i8>>,
status: Option<JpmorganTransactionStatus>,
}
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct JpmorganRefundRequest {
pub merchant: MerchantRefundReq,
pub amount: MinorUnit,
pub currency: common_enums::Currency,
}
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MerchantRefundReq {
pub merchant_software: JpmorganMerchantSoftware,
}
impl<F> TryFrom<&JpmorganRouterData<&RefundsRouterData<F>>> for JpmorganRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &JpmorganRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
let connector_metadata = JpmorganConnectorMetadataObject::try_from(
&item.router_data.connector_meta_data.clone(),
)?;
let merchant = MerchantRefundReq {
merchant_software: JpmorganMerchantSoftware {
company_name: connector_metadata.company_name,
product_name: connector_metadata.product_name,
},
};
let amount = item.amount;
let currency = item.router_data.request.currency;
Ok(Self {
merchant,
amount,
currency,
})
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct JpmorganRefundResponse {
pub transaction_id: Option<String>,
pub request_id: String,
pub transaction_state: JpmorganTransactionState,
pub amount: MinorUnit,
pub currency: common_enums::Currency,
pub response_status: JpmorganResponseStatus,
pub response_code: String,
pub response_message: String,
pub transaction_reference_id: Option<String>,
pub remaining_refundable_amount: Option<i64>,
}
#[derive(Debug, Serialize, Default, Deserialize, Clone)]
pub enum RefundStatus {
Succeeded,
Failed,
#[default]
Processing,
}
impl From<RefundStatus> for common_enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Succeeded => Self::Success,
RefundStatus::Failed => Self::Failure,
RefundStatus::Processing => Self::Pending,
}
}
}
impl From<(JpmorganResponseStatus, JpmorganTransactionState)> for RefundStatus {
fn from(
(response_status, transaction_state): (JpmorganResponseStatus, JpmorganTransactionState),
) -> Self {
match response_status {
JpmorganResponseStatus::Success => match transaction_state {
JpmorganTransactionState::Voided | JpmorganTransactionState::Closed => {
Self::Succeeded
}
JpmorganTransactionState::Declined | JpmorganTransactionState::Error => {
Self::Failed
}
JpmorganTransactionState::Pending | JpmorganTransactionState::Authorized => {
Self::Processing
}
},
JpmorganResponseStatus::Denied | JpmorganResponseStatus::Error => Self::Failed,
}
}
}
impl TryFrom<RefundsResponseRouterData<Execute, JpmorganRefundResponse>>
for RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, JpmorganRefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item
.response
.transaction_id
.clone()
.ok_or(errors::ConnectorError::ResponseHandlingFailed)?,
refund_status: RefundStatus::from((
item.response.response_status,
item.response.transaction_state,
))
.into(),
}),
..item.data
})
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct JpmorganRefundSyncResponse {
transaction_id: String,
request_id: String,
transaction_state: JpmorganTransactionState,
amount: MinorUnit,
currency: common_enums::Currency,
response_status: JpmorganResponseStatus,
response_code: String,
}
impl TryFrom<RefundsResponseRouterData<RSync, JpmorganRefundSyncResponse>>
for RefundsRouterData<RSync>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, JpmorganRefundSyncResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.transaction_id.clone(),
refund_status: RefundStatus::from((
item.response.response_status,
item.response.transaction_state,
))
.into(),
}),
..item.data
})
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct JpmorganCancelRequest {
// As per the docs, this is not a required field
// Since we always pass `true` in `isVoid` only during the void call, it makes more sense to have it required field
pub is_void: bool,
}
impl TryFrom<JpmorganRouterData<&PaymentsCancelRouterData>> for JpmorganCancelRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(_item: JpmorganRouterData<&PaymentsCancelRouterData>) -> Result<Self, Self::Error> {
Ok(Self { is_void: true })
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct JpmorganCancelResponse {
transaction_id: String,
request_id: String,
response_status: JpmorganResponseStatus,
response_code: String,
response_message: String,
payment_method_type: JpmorganPaymentMethodTypeCancelResponse,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct JpmorganPaymentMethodTypeCancelResponse {
pub card: CardCancelResponse,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CardCancelResponse {
pub card_type: Secret<String>,
pub card_type_name: Secret<String>,
}
impl TryFrom<PaymentsCancelResponseRouterData<JpmorganCancelResponse>>
for PaymentsCancelRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsCancelResponseRouterData<JpmorganCancelResponse>,
) -> Result<Self, Self::Error> {
let status = match item.response.response_status {
JpmorganResponseStatus::Success => common_enums::AttemptStatus::Voided,
JpmorganResponseStatus::Denied | JpmorganResponseStatus::Error => {
common_enums::AttemptStatus::Failure
}
};
Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.transaction_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.transaction_id.clone()),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct JpmorganValidationErrors {
pub code: Option<String>,
pub message: Option<String>,
pub entity: Option<String>,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct JpmorganErrorInformation {
pub code: Option<String>,
pub message: Option<String>,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct JpmorganErrorResponse {
pub response_status: JpmorganTransactionStatus,
pub response_code: String,
pub response_message: Option<String>,
}
| 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/bankofamerica/transformers.rs | crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs | use base64::Engine;
use common_enums::{enums, FutureUsage};
use common_types::payments::ApplePayPredecryptData;
use common_utils::{consts, ext_traits::OptionExt, pii, types::StringMajorUnit};
use hyperswitch_domain_models::{
payment_method_data::{
ApplePayWalletData, GooglePayWalletData, PaymentMethodData, SamsungPayWalletData,
WalletData,
},
router_data::{
AdditionalPaymentMethodConnectorResponse, ConnectorAuthType, ConnectorResponseData,
ErrorResponse, PaymentMethodToken, RouterData,
},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{MandateReference, PaymentsResponseData, RefundsResponseData},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsSyncRouterData, RefundsRouterData, SetupMandateRouterData,
},
};
use hyperswitch_interfaces::{api, errors};
use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::{
constants,
types::{
PaymentsCancelResponseRouterData, PaymentsCaptureResponseRouterData,
PaymentsResponseRouterData, PaymentsSyncResponseRouterData, RefundsResponseRouterData,
ResponseRouterData,
},
unimplemented_payment_method,
utils::{
self, AddressDetailsData, CardData, PaymentsAuthorizeRequestData,
PaymentsSetupMandateRequestData, PaymentsSyncRequestData, RecurringMandateData,
RouterData as OtherRouterData,
},
};
pub struct BankOfAmericaAuthType {
pub(super) api_key: Secret<String>,
pub(super) merchant_account: Secret<String>,
pub(super) api_secret: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for BankOfAmericaAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
if let ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} = auth_type
{
Ok(Self {
api_key: api_key.to_owned(),
merchant_account: key1.to_owned(),
api_secret: api_secret.to_owned(),
})
} else {
Err(errors::ConnectorError::FailedToObtainAuthType)?
}
}
}
pub struct BankOfAmericaRouterData<T> {
pub amount: StringMajorUnit,
pub router_data: T,
}
impl<T> TryFrom<(StringMajorUnit, T)> for BankOfAmericaRouterData<T> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from((amount, item): (StringMajorUnit, T)) -> Result<Self, Self::Error> {
Ok(Self {
amount,
router_data: item,
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BankOfAmericaPaymentsRequest {
processing_information: ProcessingInformation,
payment_information: PaymentInformation,
order_information: OrderInformationWithBill,
client_reference_information: ClientReferenceInformation,
#[serde(skip_serializing_if = "Option::is_none")]
consumer_authentication_information: Option<BankOfAmericaConsumerAuthInformation>,
#[serde(skip_serializing_if = "Option::is_none")]
merchant_defined_information: Option<Vec<MerchantDefinedInformation>>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ProcessingInformation {
action_list: Option<Vec<BankOfAmericaActionsList>>,
action_token_types: Option<Vec<BankOfAmericaActionsTokenType>>,
authorization_options: Option<BankOfAmericaAuthorizationOptions>,
commerce_indicator: String,
capture: Option<bool>,
capture_options: Option<CaptureOptions>,
payment_solution: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum BankOfAmericaActionsList {
TokenCreate,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum BankOfAmericaActionsTokenType {
PaymentInstrument,
Customer,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BankOfAmericaAuthorizationOptions {
initiator: Option<BankOfAmericaPaymentInitiator>,
merchant_initiated_transaction: Option<MerchantInitiatedTransaction>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BankOfAmericaPaymentInitiator {
#[serde(rename = "type")]
initiator_type: Option<BankOfAmericaPaymentInitiatorTypes>,
credential_stored_on_file: Option<bool>,
stored_credential_used: Option<bool>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum BankOfAmericaPaymentInitiatorTypes {
Customer,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MerchantInitiatedTransaction {
reason: Option<String>,
//Required for recurring mandates payment
original_authorized_amount: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MerchantDefinedInformation {
key: u8,
value: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BankOfAmericaConsumerAuthInformation {
ucaf_collection_indicator: Option<String>,
cavv: Option<String>,
ucaf_authentication_data: Option<Secret<String>>,
xid: Option<String>,
directory_server_transaction_id: Option<Secret<String>>,
specification_version: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CaptureOptions {
capture_sequence_number: u32,
total_capture_count: u32,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BankOfAmericaPaymentInstrument {
id: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CardPaymentInformation {
card: Card,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GooglePayPaymentInformation {
fluid_data: FluidData,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ApplePayTokenizedCard {
transaction_type: TransactionType,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ApplePayTokenPaymentInformation {
fluid_data: FluidData,
tokenized_card: ApplePayTokenizedCard,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ApplePayPaymentInformation {
tokenized_card: TokenizedCard,
}
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum PaymentInformation {
Cards(Box<CardPaymentInformation>),
GooglePay(Box<GooglePayPaymentInformation>),
ApplePay(Box<ApplePayPaymentInformation>),
ApplePayToken(Box<ApplePayTokenPaymentInformation>),
MandatePayment(Box<MandatePaymentInformation>),
SamsungPay(Box<SamsungPayPaymentInformation>),
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MandatePaymentInformation {
payment_instrument: BankOfAmericaPaymentInstrument,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Card {
number: cards::CardNumber,
expiration_month: Secret<String>,
expiration_year: Secret<String>,
security_code: Secret<String>,
#[serde(rename = "type")]
card_type: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TokenizedCard {
number: cards::CardNumber,
expiration_month: Secret<String>,
expiration_year: Secret<String>,
cryptogram: Secret<String>,
transaction_type: TransactionType,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FluidData {
value: Secret<String>,
#[serde(skip_serializing_if = "Option::is_none")]
descriptor: Option<String>,
}
pub const FLUID_DATA_DESCRIPTOR_FOR_SAMSUNG_PAY: &str = "FID=COMMON.SAMSUNG.INAPP.PAYMENT";
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct OrderInformationWithBill {
amount_details: Amount,
bill_to: Option<BillTo>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Amount {
total_amount: StringMajorUnit,
currency: api_models::enums::Currency,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BillTo {
first_name: Option<Secret<String>>,
last_name: Option<Secret<String>>,
address1: Option<Secret<String>>,
locality: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
administrative_area: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
postal_code: Option<Secret<String>>,
country: Option<enums::CountryAlpha2>,
email: pii::Email,
}
impl TryFrom<&SetupMandateRouterData> for BankOfAmericaPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &SetupMandateRouterData) -> Result<Self, Self::Error> {
match item.request.payment_method_data.clone() {
PaymentMethodData::Card(card_data) => Self::try_from((item, card_data)),
PaymentMethodData::Wallet(wallet_data) => match wallet_data {
WalletData::ApplePay(apple_pay_data) => Self::try_from((item, apple_pay_data)),
WalletData::GooglePay(google_pay_data) => Self::try_from((item, google_pay_data)),
WalletData::AliPayQr(_)
| WalletData::AliPayRedirect(_)
| WalletData::AliPayHkRedirect(_)
| WalletData::AmazonPayRedirect(_)
| WalletData::Paysera(_)
| WalletData::Skrill(_)
| WalletData::BluecodeRedirect {}
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
| WalletData::GcashRedirect(_)
| WalletData::ApplePayRedirect(_)
| WalletData::ApplePayThirdPartySdk(_)
| WalletData::DanaRedirect {}
| WalletData::GooglePayRedirect(_)
| WalletData::GooglePayThirdPartySdk(_)
| WalletData::MbWayRedirect(_)
| WalletData::MobilePayRedirect(_)
| WalletData::PaypalRedirect(_)
| WalletData::PaypalSdk(_)
| WalletData::Paze(_)
| WalletData::SamsungPay(_)
| WalletData::AmazonPay(_)
| WalletData::TwintRedirect {}
| WalletData::VippsRedirect {}
| WalletData::TouchNGoRedirect(_)
| WalletData::WeChatPayRedirect(_)
| WalletData::WeChatPayQr(_)
| WalletData::CashappQr(_)
| WalletData::SwishQr(_)
| WalletData::Mifinity(_)
| WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("BankOfAmerica"),
))?,
},
PaymentMethodData::CardRedirect(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("BankOfAmerica"),
))?
}
}
}
}
impl<F, T>
TryFrom<ResponseRouterData<F, BankOfAmericaSetupMandatesResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, BankOfAmericaSetupMandatesResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
match item.response {
BankOfAmericaSetupMandatesResponse::ClientReferenceInformation(info_response) => {
let mandate_reference =
info_response
.token_information
.clone()
.map(|token_info| MandateReference {
connector_mandate_id: token_info
.payment_instrument
.map(|payment_instrument| payment_instrument.id.expose()),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
});
let mut mandate_status =
map_boa_attempt_status((info_response.status.clone(), false));
if matches!(mandate_status, enums::AttemptStatus::Authorized) {
//In case of zero auth mandates we want to make the payment reach the terminal status so we are converting the authorized status to charged as well.
mandate_status = enums::AttemptStatus::Charged
}
let error_response =
get_error_response_if_failure((&info_response, mandate_status, item.http_code));
let connector_response = match item.data.payment_method {
common_enums::PaymentMethod::Card => info_response
.processor_information
.as_ref()
.and_then(|processor_information| {
info_response
.consumer_authentication_information
.as_ref()
.map(|consumer_auth_information| {
convert_to_additional_payment_method_connector_response(
processor_information,
consumer_auth_information,
)
})
})
.map(ConnectorResponseData::with_additional_payment_method_data),
common_enums::PaymentMethod::CardRedirect
| common_enums::PaymentMethod::PayLater
| common_enums::PaymentMethod::Wallet
| common_enums::PaymentMethod::BankRedirect
| common_enums::PaymentMethod::BankTransfer
| common_enums::PaymentMethod::Crypto
| common_enums::PaymentMethod::BankDebit
| common_enums::PaymentMethod::Reward
| common_enums::PaymentMethod::RealTimePayment
| common_enums::PaymentMethod::MobilePayment
| common_enums::PaymentMethod::Upi
| common_enums::PaymentMethod::Voucher
| common_enums::PaymentMethod::OpenBanking
| common_enums::PaymentMethod::GiftCard
| common_enums::PaymentMethod::NetworkToken => None,
};
Ok(Self {
status: mandate_status,
response: match error_response {
Some(error) => Err(error),
None => Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
info_response.id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(mandate_reference),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(
info_response
.client_reference_information
.code
.clone()
.unwrap_or(info_response.id),
),
incremental_authorization_allowed: None,
charges: None,
}),
},
connector_response,
..item.data
})
}
BankOfAmericaSetupMandatesResponse::ErrorInformation(error_response) => {
let response = Err(convert_to_error_response_from_error_info(
&error_response,
item.http_code,
));
Ok(Self {
response,
status: enums::AttemptStatus::Failure,
..item.data
})
}
}
}
}
// for bankofamerica each item in Billing is mandatory
// fn build_bill_to(
// address_details: &payments::Address,
// email: pii::Email,
// ) -> Result<BillTo, error_stack::Report<errors::ConnectorError>> {
// let address = address_details
// .address
// .as_ref()
// .ok_or_else(utils::missing_field_err("billing.address"))?;
// let country = address.get_country()?.to_owned();
// let first_name = address.get_first_name()?;
// let (administrative_area, postal_code) =
// if country == api_enums::CountryAlpha2::US || country == api_enums::CountryAlpha2::CA {
// let mut state = address.to_state_code()?.peek().clone();
// state.truncate(20);
// (
// Some(Secret::from(state)),
// Some(address.get_zip()?.to_owned()),
// )
// } else {
// let zip = address.zip.clone();
// let mut_state = address.state.clone().map(|state| state.expose());
// match mut_state {
// Some(mut state) => {
// state.truncate(20);
// (Some(Secret::from(state)), zip)
// }
// None => (None, zip),
// }
// };
// Ok(BillTo {
// first_name: first_name.clone(),
// last_name: address.get_last_name().unwrap_or(first_name).clone(),
// address1: address.get_line1()?.to_owned(),
// locality: Secret::new(address.get_city()?.to_owned()),
// administrative_area,
// postal_code,
// country,
// email,
// })
// }
fn build_bill_to(
address_details: Option<&hyperswitch_domain_models::address::Address>,
email: pii::Email,
) -> Result<BillTo, error_stack::Report<errors::ConnectorError>> {
let default_address = BillTo {
first_name: None,
last_name: None,
address1: None,
locality: None,
administrative_area: None,
postal_code: None,
country: None,
email: email.clone(),
};
Ok(address_details
.and_then(|addr| {
addr.address.as_ref().map(|addr| {
let administrative_area = addr.to_state_code_as_optional().unwrap_or_else(|_| {
addr.state
.clone()
.map(|state| Secret::new(format!("{:.20}", state.expose())))
});
BillTo {
first_name: addr.first_name.clone(),
last_name: addr.last_name.clone(),
address1: addr.line1.clone(),
locality: addr.city.clone(),
administrative_area,
postal_code: addr.zip.clone(),
country: addr.country,
email,
}
})
})
.unwrap_or(default_address))
}
fn get_boa_card_type(card_network: common_enums::CardNetwork) -> Option<&'static str> {
match card_network {
common_enums::CardNetwork::Visa => Some("001"),
common_enums::CardNetwork::Mastercard => Some("002"),
common_enums::CardNetwork::AmericanExpress => Some("003"),
common_enums::CardNetwork::JCB => Some("007"),
common_enums::CardNetwork::DinersClub => Some("005"),
common_enums::CardNetwork::Discover => Some("004"),
common_enums::CardNetwork::CartesBancaires => Some("006"),
common_enums::CardNetwork::UnionPay => Some("062"),
//"042" is the type code for Masetro Cards(International). For Maestro Cards(UK-Domestic) the mapping should be "024"
common_enums::CardNetwork::Maestro => Some("042"),
common_enums::CardNetwork::Interac
| common_enums::CardNetwork::RuPay
| common_enums::CardNetwork::Star
| common_enums::CardNetwork::Accel
| common_enums::CardNetwork::Pulse
| common_enums::CardNetwork::Nyce => None,
}
}
#[derive(Debug, Serialize)]
pub enum PaymentSolution {
ApplePay,
GooglePay,
SamsungPay,
}
impl From<PaymentSolution> for String {
fn from(solution: PaymentSolution) -> Self {
let payment_solution = match solution {
PaymentSolution::ApplePay => "001",
PaymentSolution::GooglePay => "012",
PaymentSolution::SamsungPay => "008",
};
payment_solution.to_string()
}
}
#[derive(Debug, Serialize)]
pub enum TransactionType {
#[serde(rename = "1")]
ApplePay,
#[serde(rename = "1")]
SamsungPay,
}
impl
From<(
&BankOfAmericaRouterData<&PaymentsAuthorizeRouterData>,
Option<BillTo>,
)> for OrderInformationWithBill
{
fn from(
(item, bill_to): (
&BankOfAmericaRouterData<&PaymentsAuthorizeRouterData>,
Option<BillTo>,
),
) -> Self {
Self {
amount_details: Amount {
total_amount: item.amount.to_owned(),
currency: item.router_data.request.currency,
},
bill_to,
}
}
}
impl
TryFrom<(
&BankOfAmericaRouterData<&PaymentsAuthorizeRouterData>,
Option<PaymentSolution>,
Option<String>,
)> for ProcessingInformation
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, solution, network): (
&BankOfAmericaRouterData<&PaymentsAuthorizeRouterData>,
Option<PaymentSolution>,
Option<String>,
),
) -> Result<Self, Self::Error> {
let (action_list, action_token_types, authorization_options) =
if item.router_data.request.setup_future_usage == Some(FutureUsage::OffSession)
&& (item.router_data.request.customer_acceptance.is_some()
|| item
.router_data
.request
.setup_mandate_details
.clone()
.is_some_and(|mandate_details| {
mandate_details.customer_acceptance.is_some()
}))
{
get_boa_mandate_action_details()
} else if item.router_data.request.connector_mandate_id().is_some() {
let original_amount = item
.router_data
.get_recurring_mandate_payment_data()?
.get_original_payment_amount()?;
let original_currency = item
.router_data
.get_recurring_mandate_payment_data()?
.get_original_payment_currency()?;
(
None,
None,
Some(BankOfAmericaAuthorizationOptions {
initiator: None,
merchant_initiated_transaction: Some(MerchantInitiatedTransaction {
reason: None,
original_authorized_amount: Some(utils::get_amount_as_string(
&api::CurrencyUnit::Base,
original_amount,
original_currency,
)?),
}),
}),
)
} else {
(None, None, None)
};
let commerce_indicator = get_commerce_indicator(network);
Ok(Self {
capture: Some(matches!(
item.router_data.request.capture_method,
Some(enums::CaptureMethod::Automatic) | None
)),
payment_solution: solution.map(String::from),
action_list,
action_token_types,
authorization_options,
capture_options: None,
commerce_indicator,
})
}
}
impl From<&BankOfAmericaRouterData<&PaymentsAuthorizeRouterData>> for ClientReferenceInformation {
fn from(item: &BankOfAmericaRouterData<&PaymentsAuthorizeRouterData>) -> Self {
Self {
code: Some(item.router_data.connector_request_reference_id.clone()),
}
}
}
impl From<&SetupMandateRouterData> for ClientReferenceInformation {
fn from(item: &SetupMandateRouterData) -> Self {
Self {
code: Some(item.connector_request_reference_id.clone()),
}
}
}
fn convert_metadata_to_merchant_defined_info(metadata: Value) -> Vec<MerchantDefinedInformation> {
let hashmap: std::collections::BTreeMap<String, Value> =
serde_json::from_str(&metadata.to_string()).unwrap_or(std::collections::BTreeMap::new());
let mut vector = Vec::new();
let mut iter = 1;
for (key, value) in hashmap {
vector.push(MerchantDefinedInformation {
key: iter,
value: format!("{key}={value}"),
});
iter += 1;
}
vector
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ClientReferenceInformation {
code: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ClientProcessorInformation {
avs: Option<Avs>,
card_verification: Option<CardVerification>,
processor: Option<ProcessorResponse>,
network_transaction_id: Option<Secret<String>>,
approval_code: Option<String>,
merchant_advice: Option<MerchantAdvice>,
response_code: Option<String>,
ach_verification: Option<AchVerification>,
system_trace_audit_number: Option<String>,
event_status: Option<String>,
retrieval_reference_number: Option<String>,
consumer_authentication_response: Option<ConsumerAuthenticationResponse>,
response_details: Option<String>,
transaction_id: Option<Secret<String>>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MerchantAdvice {
code: Option<String>,
code_raw: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ConsumerAuthenticationResponse {
code: Option<String>,
code_raw: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AchVerification {
result_code_raw: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ProcessorResponse {
name: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CardVerification {
result_code: Option<String>,
result_code_raw: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ClientRiskInformation {
rules: Option<Vec<ClientRiskInformationRules>>,
profile: Option<Profile>,
score: Option<Score>,
info_codes: Option<InfoCodes>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct InfoCodes {
address: Option<Vec<String>>,
identity_change: Option<Vec<String>>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Score {
factor_codes: Option<Vec<String>>,
result: Option<RiskResult>,
model_used: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(untagged)]
pub enum RiskResult {
StringVariant(String),
IntVariant(u64),
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Profile {
early_decision: Option<String>,
name: Option<String>,
decision: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ClientRiskInformationRules {
name: Option<Secret<String>>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Avs {
code: Option<String>,
code_raw: Option<String>,
}
impl
TryFrom<(
&BankOfAmericaRouterData<&PaymentsAuthorizeRouterData>,
hyperswitch_domain_models::payment_method_data::Card,
)> for BankOfAmericaPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, ccard): (
&BankOfAmericaRouterData<&PaymentsAuthorizeRouterData>,
hyperswitch_domain_models::payment_method_data::Card,
),
) -> Result<Self, Self::Error> {
if item.router_data.is_three_ds() {
Err(errors::ConnectorError::NotSupported {
message: "Card 3DS".to_string(),
connector: "BankOfAmerica",
})?
};
let email = item.router_data.request.get_email()?;
let bill_to = build_bill_to(item.router_data.get_optional_billing(), email)?;
let order_information = OrderInformationWithBill::from((item, Some(bill_to)));
let payment_information = PaymentInformation::try_from(&ccard)?;
let processing_information = ProcessingInformation::try_from((item, None, None))?;
let client_reference_information = ClientReferenceInformation::from(item);
let merchant_defined_information = item
.router_data
.request
.metadata
.clone()
.map(convert_metadata_to_merchant_defined_info);
Ok(Self {
processing_information,
payment_information,
order_information,
client_reference_information,
merchant_defined_information,
consumer_authentication_information: None,
})
}
}
impl
TryFrom<(
&BankOfAmericaRouterData<&PaymentsAuthorizeRouterData>,
Box<ApplePayPredecryptData>,
ApplePayWalletData,
)> for BankOfAmericaPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, apple_pay_data, apple_pay_wallet_data): (
&BankOfAmericaRouterData<&PaymentsAuthorizeRouterData>,
Box<ApplePayPredecryptData>,
ApplePayWalletData,
),
) -> Result<Self, Self::Error> {
let email = item.router_data.request.get_email()?;
let bill_to = build_bill_to(item.router_data.get_optional_billing(), email)?;
let order_information = OrderInformationWithBill::from((item, Some(bill_to)));
let processing_information = ProcessingInformation::try_from((
item,
Some(PaymentSolution::ApplePay),
Some(apple_pay_wallet_data.payment_method.network.clone()),
))?;
let client_reference_information = ClientReferenceInformation::from(item);
let payment_information = PaymentInformation::try_from(&apple_pay_data)?;
let merchant_defined_information = item
.router_data
.request
.metadata
.clone()
.map(convert_metadata_to_merchant_defined_info);
let ucaf_collection_indicator = match apple_pay_wallet_data
.payment_method
.network
.to_lowercase()
.as_str()
{
"mastercard" => Some("2".to_string()),
_ => None,
};
Ok(Self {
processing_information,
payment_information,
order_information,
client_reference_information,
| 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/payme/transformers.rs | crates/hyperswitch_connectors/src/connectors/payme/transformers.rs | use std::collections::HashMap;
use api_models::enums::{AuthenticationType, PaymentMethod};
use common_enums::enums;
use common_utils::{
ext_traits::OptionExt,
pii,
types::{MinorUnit, StringMajorUnit},
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{PaymentMethodData, WalletData},
router_data::{ConnectorAuthType, ErrorResponse, PaymentMethodToken, RouterData},
router_flow_types::{Execute, Void},
router_request_types::{
CreateOrderRequestData, PaymentsCancelData, PaymentsPreProcessingData, ResponseId,
},
router_response_types::{
MandateReference, PaymentsResponseData, PreprocessingResponseId, RedirectForm,
RefundsResponseData,
},
types::{
CreateOrderRouterData, PaymentsAuthorizeRouterData, PaymentsCancelRouterData,
PaymentsCaptureRouterData, PaymentsCompleteAuthorizeRouterData,
PaymentsPreProcessingRouterData, PaymentsSyncRouterData, RefundSyncRouterData,
RefundsRouterData, TokenizationRouterData,
},
};
use hyperswitch_interfaces::{consts, errors};
use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use url::Url;
use crate::{
types::{PaymentsCancelResponseRouterData, RefundsResponseRouterData, ResponseRouterData},
unimplemented_payment_method,
utils::{
self, AddressDetailsData, CardData, PaymentsAuthorizeRequestData,
PaymentsCancelRequestData, PaymentsCompleteAuthorizeRequestData,
PaymentsPreProcessingRequestData, PaymentsSyncRequestData, RouterData as OtherRouterData,
},
};
const LANGUAGE: &str = "en";
#[derive(Debug, Serialize)]
pub struct PaymeRouterData<T> {
pub amount: MinorUnit,
pub router_data: T,
}
impl<T> TryFrom<(MinorUnit, T)> for PaymeRouterData<T> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from((amount, item): (MinorUnit, T)) -> Result<Self, Self::Error> {
Ok(Self {
amount,
router_data: item,
})
}
}
#[derive(Debug, Serialize)]
pub struct PayRequest {
buyer_name: Secret<String>,
buyer_email: pii::Email,
payme_sale_id: String,
#[serde(flatten)]
card: PaymeCard,
language: String,
}
#[derive(Debug, Serialize)]
pub struct MandateRequest {
currency: enums::Currency,
sale_price: MinorUnit,
transaction_id: String,
product_name: String,
sale_return_url: String,
seller_payme_id: Secret<String>,
sale_callback_url: String,
buyer_key: Secret<String>,
language: String,
}
#[derive(Debug, Serialize)]
pub struct Pay3dsRequest {
buyer_name: Secret<String>,
buyer_email: pii::Email,
buyer_key: Secret<String>,
payme_sale_id: String,
meta_data_jwt: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum PaymePaymentRequest {
MandateRequest(MandateRequest),
PayRequest(PayRequest),
}
#[derive(Debug, Serialize)]
pub struct PaymeQuerySaleRequest {
sale_payme_id: String,
seller_payme_id: Secret<String>,
}
#[derive(Debug, Serialize)]
pub struct PaymeQueryTransactionRequest {
payme_transaction_id: String,
seller_payme_id: Secret<String>,
}
#[derive(Debug, Serialize)]
pub struct PaymeCard {
credit_card_cvv: Secret<String>,
credit_card_exp: Secret<String>,
credit_card_number: cards::CardNumber,
}
#[derive(Debug, Serialize)]
pub struct CaptureBuyerRequest {
seller_payme_id: Secret<String>,
#[serde(flatten)]
card: PaymeCard,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct CaptureBuyerResponse {
buyer_key: Secret<String>,
}
#[derive(Debug, Serialize)]
pub struct GenerateSaleRequest {
currency: enums::Currency,
sale_type: SaleType,
sale_price: MinorUnit,
transaction_id: String,
product_name: String,
sale_return_url: String,
seller_payme_id: Secret<String>,
sale_callback_url: String,
sale_payment_method: SalePaymentMethod,
services: Option<ThreeDs>,
language: String,
}
#[derive(Debug, Serialize)]
pub struct ThreeDs {
name: ThreeDsType,
settings: ThreeDsSettings,
}
#[derive(Debug, Serialize)]
pub enum ThreeDsType {
#[serde(rename = "3D Secure")]
ThreeDs,
}
#[derive(Debug, Serialize)]
pub struct ThreeDsSettings {
active: bool,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct GenerateSaleResponse {
payme_sale_id: String,
}
impl<F, T> TryFrom<ResponseRouterData<F, PaymePaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, PaymePaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
match item.response {
// To handle webhook response
PaymePaymentsResponse::PaymePaySaleResponse(response) => {
Self::try_from(ResponseRouterData {
response,
data: item.data,
http_code: item.http_code,
})
}
// To handle PSync response
PaymePaymentsResponse::SaleQueryResponse(response) => {
Self::try_from(ResponseRouterData {
response,
data: item.data,
http_code: item.http_code,
})
}
}
}
}
impl<F, T> TryFrom<ResponseRouterData<F, PaymePaySaleResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, PaymePaySaleResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let status = enums::AttemptStatus::from(item.response.sale_status.clone());
let response = if utils::is_payment_failure(status) {
// To populate error message in case of failure
Err(get_pay_sale_error_response((
&item.response,
item.http_code,
)))
} else {
Ok(PaymentsResponseData::try_from(&item.response)?)
};
Ok(Self {
status,
response,
..item.data
})
}
}
fn get_pay_sale_error_response(
(pay_sale_response, http_code): (&PaymePaySaleResponse, u16),
) -> ErrorResponse {
let code = pay_sale_response
.status_error_code
.map(|error_code| error_code.to_string())
.unwrap_or(consts::NO_ERROR_CODE.to_string());
ErrorResponse {
code,
message: pay_sale_response
.status_error_details
.clone()
.unwrap_or(consts::NO_ERROR_MESSAGE.to_string()),
reason: pay_sale_response.status_error_details.to_owned(),
status_code: http_code,
attempt_status: None,
connector_transaction_id: Some(pay_sale_response.payme_sale_id.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}
}
impl TryFrom<&PaymePaySaleResponse> for PaymentsResponseData {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(value: &PaymePaySaleResponse) -> Result<Self, Self::Error> {
let redirection_data = match value.sale_3ds {
Some(true) => value.redirect_url.clone().map(|url| RedirectForm::Form {
endpoint: url.to_string(),
method: common_utils::request::Method::Get,
form_fields: HashMap::<String, String>::new(),
}),
_ => None,
};
Ok(Self::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(value.payme_sale_id.clone()),
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(value.buyer_key.clone().map(|buyer_key| {
MandateReference {
connector_mandate_id: Some(buyer_key.expose()),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
}
})),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
})
}
}
impl<F, T> TryFrom<ResponseRouterData<F, SaleQueryResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, SaleQueryResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
// Only one element would be present since we are passing one transaction id in the PSync request
let transaction_response = item
.response
.items
.first()
.cloned()
.ok_or(errors::ConnectorError::ResponseHandlingFailed)?;
let status = enums::AttemptStatus::from(transaction_response.sale_status.clone());
let response = if utils::is_payment_failure(status) {
// To populate error message in case of failure
Err(get_sale_query_error_response((
&transaction_response,
item.http_code,
)))
} else {
Ok(PaymentsResponseData::from(&transaction_response))
};
Ok(Self {
status,
response,
..item.data
})
}
}
fn get_sale_query_error_response(
(sale_query_response, http_code): (&SaleQuery, u16),
) -> ErrorResponse {
ErrorResponse {
code: sale_query_response
.sale_error_code
.clone()
.unwrap_or(consts::NO_ERROR_CODE.to_string()),
message: sale_query_response
.sale_error_text
.clone()
.unwrap_or(consts::NO_ERROR_MESSAGE.to_string()),
reason: sale_query_response.sale_error_text.clone(),
status_code: http_code,
attempt_status: None,
connector_transaction_id: Some(sale_query_response.sale_payme_id.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}
}
impl From<&SaleQuery> for PaymentsResponseData {
fn from(value: &SaleQuery) -> Self {
Self::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(value.sale_payme_id.clone()),
redirection_data: Box::new(None),
// mandate reference will be updated with webhooks only. That has been handled with PaymePaySaleResponse struct
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum SaleType {
Sale,
Authorize,
Token,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum SalePaymentMethod {
CreditCard,
ApplePay,
}
impl TryFrom<&PaymeRouterData<&CreateOrderRouterData>> for GenerateSaleRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymeRouterData<&CreateOrderRouterData>) -> Result<Self, Self::Error> {
let sale_type = SaleType::try_from(item.router_data)?;
let seller_payme_id =
PaymeAuthType::try_from(&item.router_data.connector_auth_type)?.seller_payme_id;
let order_details = item
.router_data
.request
.order_details
.clone()
.get_required_value("order_details")
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "order_details",
})?;
let services = get_services(item.router_data.auth_type);
let product_name = order_details
.first()
.ok_or_else(utils::missing_field_err("order_details"))?
.product_name
.clone();
let pmd = item
.router_data
.request
.payment_method_data
.to_owned()
.ok_or_else(utils::missing_field_err("payment_method_data"))?;
let sale_return_url = item
.router_data
.request
.router_return_url
.clone()
.get_required_value("router_return_url")
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "router_return_url",
})?;
let sale_callback_url = item
.router_data
.request
.webhook_url
.clone()
.get_required_value("webhook_url")
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "webhook_url",
})?;
Ok(Self {
seller_payme_id,
sale_price: item.amount.to_owned(),
currency: item.router_data.request.currency,
product_name,
sale_payment_method: SalePaymentMethod::try_from(&pmd)?,
sale_type,
transaction_id: item.router_data.payment_id.clone(),
sale_return_url,
sale_callback_url,
language: LANGUAGE.to_string(),
services,
})
}
}
impl TryFrom<&PaymeRouterData<&PaymentsPreProcessingRouterData>> for GenerateSaleRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &PaymeRouterData<&PaymentsPreProcessingRouterData>,
) -> Result<Self, Self::Error> {
let sale_type = SaleType::try_from(item.router_data)?;
let seller_payme_id =
PaymeAuthType::try_from(&item.router_data.connector_auth_type)?.seller_payme_id;
let order_details = item.router_data.request.get_order_details()?;
let services = get_services(item.router_data.auth_type);
let product_name = order_details
.first()
.ok_or_else(utils::missing_field_err("order_details"))?
.product_name
.clone();
let pmd = item
.router_data
.request
.payment_method_data
.to_owned()
.ok_or_else(utils::missing_field_err("payment_method_data"))?;
Ok(Self {
seller_payme_id,
sale_price: item.amount.to_owned(),
currency: item.router_data.request.get_currency()?,
product_name,
sale_payment_method: SalePaymentMethod::try_from(&pmd)?,
sale_type,
transaction_id: item.router_data.payment_id.clone(),
sale_return_url: item.router_data.request.get_router_return_url()?,
sale_callback_url: item.router_data.request.get_webhook_url()?,
language: LANGUAGE.to_string(),
services,
})
}
}
impl TryFrom<&PaymentMethodData> for SalePaymentMethod {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentMethodData) -> Result<Self, Self::Error> {
match item {
PaymentMethodData::Card(_) => Ok(Self::CreditCard),
PaymentMethodData::Wallet(wallet_data) => match wallet_data {
WalletData::ApplePayThirdPartySdk(_) => Ok(Self::ApplePay),
WalletData::AliPayQr(_)
| WalletData::AliPayRedirect(_)
| WalletData::BluecodeRedirect {}
| WalletData::AliPayHkRedirect(_)
| WalletData::AmazonPay(_)
| WalletData::AmazonPayRedirect(_)
| WalletData::Paysera(_)
| WalletData::Skrill(_)
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
| WalletData::GcashRedirect(_)
| WalletData::ApplePayRedirect(_)
| WalletData::DanaRedirect {}
| WalletData::GooglePay(_)
| WalletData::GooglePayRedirect(_)
| WalletData::GooglePayThirdPartySdk(_)
| WalletData::MbWayRedirect(_)
| WalletData::MobilePayRedirect(_)
| WalletData::PaypalRedirect(_)
| WalletData::PaypalSdk(_)
| WalletData::Paze(_)
| WalletData::SamsungPay(_)
| WalletData::TwintRedirect {}
| WalletData::VippsRedirect {}
| WalletData::TouchNGoRedirect(_)
| WalletData::WeChatPayRedirect(_)
| WalletData::WeChatPayQr(_)
| WalletData::CashappQr(_)
| WalletData::ApplePay(_)
| WalletData::SwishQr(_)
| WalletData::Mifinity(_)
| WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotSupported {
message: "Wallet".to_string(),
connector: "payme",
}
.into()),
},
PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into())
}
}
}
}
impl TryFrom<&PaymeRouterData<&PaymentsAuthorizeRouterData>> for PaymePaymentRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
value: &PaymeRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let payme_request = if value.router_data.request.mandate_id.is_some() {
Self::MandateRequest(MandateRequest::try_from(value)?)
} else {
Self::PayRequest(PayRequest::try_from(value.router_data)?)
};
Ok(payme_request)
}
}
impl TryFrom<&PaymentsSyncRouterData> for PaymeQuerySaleRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(value: &PaymentsSyncRouterData) -> Result<Self, Self::Error> {
let seller_payme_id = PaymeAuthType::try_from(&value.connector_auth_type)?.seller_payme_id;
Ok(Self {
sale_payme_id: value.request.get_connector_transaction_id()?,
seller_payme_id,
})
}
}
impl TryFrom<&RefundSyncRouterData> for PaymeQueryTransactionRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(value: &RefundSyncRouterData) -> Result<Self, Self::Error> {
let seller_payme_id = PaymeAuthType::try_from(&value.connector_auth_type)?.seller_payme_id;
Ok(Self {
payme_transaction_id: value
.request
.connector_refund_id
.clone()
.ok_or(errors::ConnectorError::MissingConnectorRefundID)?,
seller_payme_id,
})
}
}
impl<F>
utils::ForeignTryFrom<(
ResponseRouterData<
F,
GenerateSaleResponse,
PaymentsPreProcessingData,
PaymentsResponseData,
>,
StringMajorUnit,
)> for RouterData<F, PaymentsPreProcessingData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(
(item, apple_pay_amount): (
ResponseRouterData<
F,
GenerateSaleResponse,
PaymentsPreProcessingData,
PaymentsResponseData,
>,
StringMajorUnit,
),
) -> Result<Self, Self::Error> {
match item.data.payment_method {
PaymentMethod::Card => {
match item.data.auth_type {
AuthenticationType::NoThreeDs => {
Ok(Self {
// We don't get any status from payme, so defaulting it to pending
// then move to authorize flow
status: enums::AttemptStatus::Pending,
preprocessing_id: Some(item.response.payme_sale_id.to_owned()),
response: Ok(PaymentsResponseData::PreProcessingResponse {
pre_processing_id: PreprocessingResponseId::ConnectorTransactionId(
item.response.payme_sale_id,
),
connector_metadata: None,
session_token: None,
connector_response_reference_id: None,
}),
..item.data
})
}
AuthenticationType::ThreeDs => Ok(Self {
// We don't go to authorize flow in 3ds,
// Response is send directly after preprocessing flow
// redirection data is send to run script along
// status is made authentication_pending to show redirection
status: enums::AttemptStatus::AuthenticationPending,
preprocessing_id: Some(item.response.payme_sale_id.to_owned()),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.payme_sale_id.to_owned(),
),
redirection_data: Box::new(Some(RedirectForm::Payme)),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
}),
}
}
_ => {
let currency_code = item.data.request.get_currency()?;
let pmd = item.data.request.payment_method_data.to_owned();
let payme_auth_type = PaymeAuthType::try_from(&item.data.connector_auth_type)?;
let session_token = match pmd {
Some(PaymentMethodData::Wallet(WalletData::ApplePayThirdPartySdk(
_,
))) => Some(api_models::payments::SessionToken::ApplePay(Box::new(
api_models::payments::ApplepaySessionTokenResponse {
session_token_data: Some(
api_models::payments::ApplePaySessionResponse::NoSessionResponse(api_models::payments::NullObject),
),
payment_request_data: Some(
api_models::payments::ApplePayPaymentRequest {
country_code: item.data.get_billing_country()?,
currency_code,
total: api_models::payments::AmountInfo {
label: "Apple Pay".to_string(),
total_type: None,
amount: apple_pay_amount,
},
merchant_capabilities: None,
supported_networks: None,
merchant_identifier: None,
required_billing_contact_fields: None,
required_shipping_contact_fields: None,
recurring_payment_request: None,
},
),
connector: "payme".to_string(),
delayed_session_token: true,
sdk_next_action: api_models::payments::SdkNextAction {
next_action: api_models::payments::NextActionCall::Sync,
},
connector_reference_id: Some(item.response.payme_sale_id.to_owned()),
connector_sdk_public_key: Some(
payme_auth_type.payme_public_key.expose(),
),
connector_merchant_id: payme_auth_type
.payme_merchant_id
.map(|mid| mid.expose()),
},
))),
_ => None,
};
Ok(Self {
// We don't get any status from payme, so defaulting it to pending
status: enums::AttemptStatus::Pending,
preprocessing_id: Some(item.response.payme_sale_id.to_owned()),
response: Ok(PaymentsResponseData::PreProcessingResponse {
pre_processing_id: PreprocessingResponseId::ConnectorTransactionId(
item.response.payme_sale_id,
),
connector_metadata: None,
session_token,
connector_response_reference_id: None,
}),
..item.data
})
}
}
}
}
impl<F>
utils::ForeignTryFrom<(
ResponseRouterData<F, GenerateSaleResponse, CreateOrderRequestData, PaymentsResponseData>,
StringMajorUnit,
)> for RouterData<F, CreateOrderRequestData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(
(item, apple_pay_amount): (
ResponseRouterData<
F,
GenerateSaleResponse,
CreateOrderRequestData,
PaymentsResponseData,
>,
StringMajorUnit,
),
) -> Result<Self, Self::Error> {
match item.data.payment_method {
PaymentMethod::Card => {
match item.data.auth_type {
AuthenticationType::NoThreeDs => {
Ok(Self {
// We don't get any status from payme, so defaulting it to pending
// then move to authorize flow
status: enums::AttemptStatus::Pending,
preprocessing_id: Some(item.response.payme_sale_id.to_owned()),
response: Ok(PaymentsResponseData::PreProcessingResponse {
pre_processing_id: PreprocessingResponseId::ConnectorTransactionId(
item.response.payme_sale_id,
),
connector_metadata: None,
session_token: None,
connector_response_reference_id: None,
}),
..item.data
})
}
AuthenticationType::ThreeDs => Ok(Self {
// We don't go to authorize flow in 3ds,
// Response is send directly after preprocessing flow
// redirection data is send to run script along
// status is made authentication_pending to show redirection
status: enums::AttemptStatus::AuthenticationPending,
preprocessing_id: Some(item.response.payme_sale_id.to_owned()),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.payme_sale_id.to_owned(),
),
redirection_data: Box::new(Some(RedirectForm::Payme)),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
}),
}
}
_ => {
let currency_code = item.data.request.currency;
let pmd = item.data.request.payment_method_data.to_owned();
let payme_auth_type = PaymeAuthType::try_from(&item.data.connector_auth_type)?;
let session_token = match pmd {
Some(PaymentMethodData::Wallet(WalletData::ApplePayThirdPartySdk(
_,
))) => Some(api_models::payments::SessionToken::ApplePay(Box::new(
api_models::payments::ApplepaySessionTokenResponse {
session_token_data: Some(
api_models::payments::ApplePaySessionResponse::NoSessionResponse(api_models::payments::NullObject),
),
payment_request_data: Some(
api_models::payments::ApplePayPaymentRequest {
country_code: item.data.get_billing_country()?,
currency_code,
total: api_models::payments::AmountInfo {
label: "Apple Pay".to_string(),
total_type: None,
amount: apple_pay_amount,
},
merchant_capabilities: None,
supported_networks: None,
merchant_identifier: None,
required_billing_contact_fields: None,
required_shipping_contact_fields: None,
recurring_payment_request: None,
},
),
connector: "payme".to_string(),
delayed_session_token: true,
sdk_next_action: api_models::payments::SdkNextAction {
next_action: api_models::payments::NextActionCall::Sync,
},
connector_reference_id: Some(item.response.payme_sale_id.to_owned()),
connector_sdk_public_key: Some(
payme_auth_type.payme_public_key.expose(),
),
connector_merchant_id: payme_auth_type
.payme_merchant_id
.map(|mid| mid.expose()),
},
))),
_ => None,
};
Ok(Self {
// We don't get any status from payme, so defaulting it to pending
status: enums::AttemptStatus::Pending,
preprocessing_id: Some(item.response.payme_sale_id.to_owned()),
response: Ok(PaymentsResponseData::PreProcessingResponse {
pre_processing_id: PreprocessingResponseId::ConnectorTransactionId(
| 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/placetopay/transformers.rs | crates/hyperswitch_connectors/src/connectors/placetopay/transformers.rs | use common_enums::{enums, Currency};
use common_utils::{consts::BASE64_ENGINE, date_time, types::MinorUnit};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{ConnectorAuthType, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RefundsResponseData},
types,
};
use hyperswitch_interfaces::errors;
use masking::{PeekInterface, Secret};
use ring::digest;
use serde::{Deserialize, Serialize};
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{
self, generate_random_bytes, BrowserInformationData, CardData as _,
PaymentsAuthorizeRequestData, PaymentsSyncRequestData, RouterData as _,
},
};
pub struct PlacetopayRouterData<T> {
pub amount: MinorUnit,
pub router_data: T,
}
impl<T> From<(MinorUnit, T)> for PlacetopayRouterData<T> {
fn from((amount, item): (MinorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlacetopayPaymentsRequest {
auth: PlacetopayAuth,
payment: PlacetopayPayment,
instrument: PlacetopayInstrument,
ip_address: Secret<String, common_utils::pii::IpAddress>,
user_agent: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum PlacetopayAuthorizeAction {
Checkin,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlacetopayAuthType {
login: Secret<String>,
tran_key: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlacetopayAuth {
login: Secret<String>,
tran_key: Secret<String>,
nonce: Secret<String>,
seed: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlacetopayPayment {
reference: String,
description: String,
amount: PlacetopayAmount,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlacetopayAmount {
currency: Currency,
total: MinorUnit,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlacetopayInstrument {
card: PlacetopayCard,
}
#[derive(Debug, Serialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct PlacetopayCard {
number: cards::CardNumber,
expiration: Secret<String>,
cvv: Secret<String>,
}
impl TryFrom<&PlacetopayRouterData<&types::PaymentsAuthorizeRouterData>>
for PlacetopayPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &PlacetopayRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let browser_info = item.router_data.request.get_browser_info()?;
let ip_address = browser_info.get_ip_address()?;
let user_agent = browser_info.get_user_agent()?;
let auth = PlacetopayAuth::try_from(&item.router_data.connector_auth_type)?;
let payment = PlacetopayPayment {
reference: item.router_data.connector_request_reference_id.clone(),
description: item.router_data.get_description()?,
amount: PlacetopayAmount {
currency: item.router_data.request.currency,
total: item.amount,
},
};
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(req_card) => {
if item.router_data.is_three_ds() {
Err(errors::ConnectorError::NotSupported {
message: "Cards 3DS".to_string(),
connector: "Placetopay",
})?
}
let card = PlacetopayCard {
number: req_card.card_number.clone(),
expiration: req_card
.clone()
.get_card_expiry_month_year_2_digit_with_delimiter("/".to_owned())?,
cvv: req_card.card_cvc.clone(),
};
Ok(Self {
ip_address,
user_agent,
auth,
payment,
instrument: PlacetopayInstrument {
card: card.to_owned(),
},
})
}
PaymentMethodData::Wallet(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Placetopay"),
)
.into())
}
}
}
}
impl TryFrom<&ConnectorAuthType> for PlacetopayAuth {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
let placetopay_auth = PlacetopayAuthType::try_from(auth_type)?;
let nonce_bytes = generate_random_bytes(16);
let now = date_time::date_as_yyyymmddthhmmssmmmz()
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
let seed = format!("{}+00:00", now.split_at(now.len() - 5).0);
let mut context = digest::Context::new(&digest::SHA256);
context.update(&nonce_bytes);
context.update(seed.as_bytes());
context.update(placetopay_auth.tran_key.peek().as_bytes());
let encoded_digest = base64::Engine::encode(&BASE64_ENGINE, context.finish());
let nonce = Secret::new(base64::Engine::encode(&BASE64_ENGINE, &nonce_bytes));
Ok(Self {
login: placetopay_auth.login,
tran_key: encoded_digest.into(),
nonce,
seed,
})
}
}
impl TryFrom<&ConnectorAuthType> for PlacetopayAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
if let ConnectorAuthType::BodyKey { api_key, key1 } = auth_type {
Ok(Self {
login: api_key.to_owned(),
tran_key: key1.to_owned(),
})
} else {
Err(errors::ConnectorError::FailedToObtainAuthType)?
}
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PlacetopayTransactionStatus {
Ok,
Failed,
Approved,
// ApprovedPartial,
// PartialExpired,
Rejected,
Pending,
PendingValidation,
PendingProcess,
// Refunded,
// Reversed,
Error,
// Unknown,
// Manual,
// Dispute,
//The statuses that are commented out are awaiting clarification on the connector.
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlacetopayStatusResponse {
status: PlacetopayTransactionStatus,
}
impl From<PlacetopayTransactionStatus> for enums::AttemptStatus {
fn from(item: PlacetopayTransactionStatus) -> Self {
match item {
PlacetopayTransactionStatus::Approved | PlacetopayTransactionStatus::Ok => {
Self::Charged
}
PlacetopayTransactionStatus::Failed
| PlacetopayTransactionStatus::Rejected
| PlacetopayTransactionStatus::Error => Self::Failure,
PlacetopayTransactionStatus::Pending
| PlacetopayTransactionStatus::PendingValidation
| PlacetopayTransactionStatus::PendingProcess => Self::Pending,
}
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlacetopayPaymentsResponse {
status: PlacetopayStatusResponse,
internal_reference: u64,
authorization: Option<String>,
}
impl<F, T> TryFrom<ResponseRouterData<F, PlacetopayPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, PlacetopayPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: enums::AttemptStatus::from(item.response.status.status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.internal_reference.to_string(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: item
.response
.authorization
.clone()
.map(|authorization| serde_json::json!(authorization)),
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
// REFUND :
// Type definition for RefundRequest
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlacetopayRefundRequest {
auth: PlacetopayAuth,
internal_reference: u64,
action: PlacetopayNextAction,
authorization: Option<String>,
}
impl<F> TryFrom<&types::RefundsRouterData<F>> for PlacetopayRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> {
if item.request.minor_refund_amount == item.request.minor_payment_amount {
let auth = PlacetopayAuth::try_from(&item.connector_auth_type)?;
let internal_reference = item
.request
.connector_transaction_id
.parse::<u64>()
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
let action = PlacetopayNextAction::Reverse;
let authorization = match item.request.connector_metadata.clone() {
Some(metadata) => metadata.as_str().map(|auth| auth.to_string()),
None => None,
};
Ok(Self {
auth,
internal_reference,
action,
authorization,
})
} else {
Err(errors::ConnectorError::NotSupported {
message: "Partial Refund".to_string(),
connector: "placetopay",
}
.into())
}
}
}
impl From<PlacetopayRefundStatus> for enums::RefundStatus {
fn from(item: PlacetopayRefundStatus) -> Self {
match item {
PlacetopayRefundStatus::Ok
| PlacetopayRefundStatus::Approved
| PlacetopayRefundStatus::Refunded => Self::Success,
PlacetopayRefundStatus::Failed
| PlacetopayRefundStatus::Rejected
| PlacetopayRefundStatus::Error => Self::Failure,
PlacetopayRefundStatus::Pending
| PlacetopayRefundStatus::PendingProcess
| PlacetopayRefundStatus::PendingValidation => Self::Pending,
}
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PlacetopayRefundStatus {
Ok,
Failed,
Approved,
// ApprovedPartial,
// PartialExpired,
Rejected,
Pending,
PendingValidation,
PendingProcess,
Refunded,
// Reversed,
Error,
// Unknown,
// Manual,
// Dispute,
//The statuses that are commented out are awaiting clarification on the connector.
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlacetopayRefundStatusResponse {
status: PlacetopayRefundStatus,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlacetopayRefundResponse {
status: PlacetopayRefundStatusResponse,
internal_reference: u64,
}
impl TryFrom<RefundsResponseRouterData<Execute, PlacetopayRefundResponse>>
for types::RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, PlacetopayRefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.internal_reference.to_string(),
refund_status: enums::RefundStatus::from(item.response.status.status),
}),
..item.data
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlacetopayRsyncRequest {
auth: PlacetopayAuth,
internal_reference: u64,
}
impl TryFrom<&types::RefundsRouterData<RSync>> for PlacetopayRsyncRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::RefundsRouterData<RSync>) -> Result<Self, Self::Error> {
let auth = PlacetopayAuth::try_from(&item.connector_auth_type)?;
let internal_reference = item
.request
.connector_transaction_id
.parse::<u64>()
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
Ok(Self {
auth,
internal_reference,
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, PlacetopayRefundResponse>>
for types::RefundsRouterData<RSync>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, PlacetopayRefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.internal_reference.to_string(),
refund_status: enums::RefundStatus::from(item.response.status.status),
}),
..item.data
})
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlacetopayErrorResponse {
pub status: PlacetopayError,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlacetopayError {
pub status: PlacetopayErrorStatus,
pub message: String,
pub reason: String,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PlacetopayErrorStatus {
Failed,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlacetopayPsyncRequest {
auth: PlacetopayAuth,
internal_reference: u64,
}
impl TryFrom<&types::PaymentsSyncRouterData> for PlacetopayPsyncRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::PaymentsSyncRouterData) -> Result<Self, Self::Error> {
let auth = PlacetopayAuth::try_from(&item.connector_auth_type)?;
let internal_reference = item
.request
.get_connector_transaction_id()?
.parse::<u64>()
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
Ok(Self {
auth,
internal_reference,
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlacetopayNextActionRequest {
auth: PlacetopayAuth,
internal_reference: u64,
action: PlacetopayNextAction,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum PlacetopayNextAction {
Refund,
Reverse,
Void,
Process,
Checkout,
}
impl TryFrom<&types::PaymentsCaptureRouterData> for PlacetopayNextActionRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::PaymentsCaptureRouterData) -> Result<Self, Self::Error> {
let auth = PlacetopayAuth::try_from(&item.connector_auth_type)?;
let internal_reference = item
.request
.connector_transaction_id
.parse::<u64>()
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
let action = PlacetopayNextAction::Checkout;
Ok(Self {
auth,
internal_reference,
action,
})
}
}
impl TryFrom<&types::PaymentsCancelRouterData> for PlacetopayNextActionRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::PaymentsCancelRouterData) -> Result<Self, Self::Error> {
let auth = PlacetopayAuth::try_from(&item.connector_auth_type)?;
let internal_reference = item
.request
.connector_transaction_id
.parse::<u64>()
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
let action = PlacetopayNextAction::Void;
Ok(Self {
auth,
internal_reference,
action,
})
}
}
| 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/stripe/transformers.rs | crates/hyperswitch_connectors/src/connectors/stripe/transformers.rs | use std::{collections::HashMap, fmt::Debug, ops::Deref};
use api_models::{self, enums as api_enums, payments};
use common_enums::{enums, AttemptStatus, PaymentChargeType, StripeChargeType};
use common_types::{
payments::{AcceptanceType, SplitPaymentsRequest},
primitive_wrappers,
};
use common_utils::{
collect_missing_value_keys,
errors::CustomResult,
ext_traits::{ByteSliceExt, Encode, OptionExt as _},
pii::{self, Email},
request::{Method, RequestContent},
types::MinorUnit,
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{
self, BankRedirectData, Card, CardRedirectData, GiftCardData, GooglePayWalletData,
PayLaterData, PaymentMethodData, VoucherData, WalletData,
},
router_data::{
AdditionalPaymentMethodConnectorResponse, ConnectorAuthType, ConnectorResponseData,
ExtendedAuthorizationResponseData, PaymentMethodToken, RouterData,
},
router_flow_types::{Execute, RSync},
router_request_types::{
BrowserInformation, ChargeRefundsOptions, DestinationChargeRefund, DirectChargeRefund,
PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData,
PaymentsIncrementalAuthorizationData, ResponseId, SplitRefundsRequest,
},
router_response_types::{
ConnectorCustomerResponseData, MandateReference, PaymentsResponseData,
PreprocessingResponseId, RedirectForm, RefundsResponseData,
},
types::{
ConnectorCustomerRouterData, PaymentsAuthorizeRouterData, PaymentsCancelRouterData,
PaymentsUpdateMetadataRouterData, RefundsRouterData, SetupMandateRouterData,
TokenizationRouterData,
},
};
use hyperswitch_interfaces::{consts, errors::ConnectorError};
use masking::{ExposeInterface, Mask, Maskable, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use time::PrimitiveDateTime;
use url::Url;
use crate::{
constants::headers::STRIPE_COMPATIBLE_CONNECT_ACCOUNT,
utils::{
convert_uppercase, deserialize_zero_minor_amount_as_none, ApplePay,
RouterData as OtherRouterData,
},
};
#[cfg(feature = "payouts")]
pub mod connect;
#[cfg(feature = "payouts")]
pub use self::connect::*;
use crate::{
types::{
RefundsResponseRouterData, ResponseRouterData, SubmitEvidenceRouterData,
UploadFileRouterData,
},
utils::{
get_unimplemented_payment_method_error_message, is_payment_failure, is_refund_failure,
PaymentsAuthorizeRequestData, SplitPaymentData,
},
};
pub mod auth_headers {
pub const STRIPE_API_VERSION: &str = "stripe-version";
pub const STRIPE_VERSION: &str = "2022-11-15";
}
trait GetRequestIncrementalAuthorization {
fn get_request_incremental_authorization(&self) -> Option<bool>;
}
impl GetRequestIncrementalAuthorization for PaymentsAuthorizeData {
fn get_request_incremental_authorization(&self) -> Option<bool> {
Some(self.request_incremental_authorization)
}
}
impl GetRequestIncrementalAuthorization for PaymentsCaptureData {
fn get_request_incremental_authorization(&self) -> Option<bool> {
None
}
}
impl GetRequestIncrementalAuthorization for PaymentsCancelData {
fn get_request_incremental_authorization(&self) -> Option<bool> {
None
}
}
pub struct StripeAuthType {
pub(super) api_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for StripeAuthType {
type Error = error_stack::Report<ConnectorError>;
fn try_from(item: &ConnectorAuthType) -> Result<Self, Self::Error> {
if let ConnectorAuthType::HeaderKey { api_key } = item {
Ok(Self {
api_key: api_key.to_owned(),
})
} else {
Err(ConnectorError::FailedToObtainAuthType.into())
}
}
}
#[derive(Debug, Default, Eq, PartialEq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum StripeCaptureMethod {
Manual,
#[default]
Automatic,
}
impl From<Option<enums::CaptureMethod>> for StripeCaptureMethod {
fn from(item: Option<enums::CaptureMethod>) -> Self {
match item {
Some(p) => match p {
enums::CaptureMethod::ManualMultiple => Self::Manual,
enums::CaptureMethod::Manual => Self::Manual,
enums::CaptureMethod::Automatic | enums::CaptureMethod::SequentialAutomatic => {
Self::Automatic
}
enums::CaptureMethod::Scheduled => Self::Manual,
},
None => Self::Automatic,
}
}
}
#[derive(Debug, Default, Eq, PartialEq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Auth3ds {
#[default]
Automatic,
Any,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum StripeCardNetwork {
CartesBancaires,
Mastercard,
Visa,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
#[serde(
rename_all = "snake_case",
tag = "mandate_data[customer_acceptance][type]"
)]
pub enum StripeMandateType {
Online {
#[serde(rename = "mandate_data[customer_acceptance][online][ip_address]")]
ip_address: Secret<String, pii::IpAddress>,
#[serde(rename = "mandate_data[customer_acceptance][online][user_agent]")]
user_agent: String,
},
Offline,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct StripeMandateRequest {
#[serde(flatten)]
mandate_type: StripeMandateType,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ExpandableObjects {
LatestCharge,
Customer,
LatestAttempt,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct StripeBrowserInformation {
#[serde(rename = "payment_method_data[ip]")]
pub ip_address: Option<Secret<String, pii::IpAddress>>,
#[serde(rename = "payment_method_data[user_agent]")]
pub user_agent: Option<String>,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct PaymentIntentRequest {
pub amount: MinorUnit, //amount in cents, hence passed as integer
pub currency: String,
pub statement_descriptor_suffix: Option<String>,
pub statement_descriptor: Option<String>,
#[serde(flatten)]
pub meta_data: HashMap<String, String>,
pub return_url: String,
pub confirm: bool,
pub payment_method: Option<Secret<String>>,
pub customer: Option<Secret<String>>,
#[serde(flatten)]
pub setup_mandate_details: Option<StripeMandateRequest>,
pub description: Option<String>,
#[serde(flatten)]
pub shipping: Option<StripeShippingAddress>,
#[serde(flatten)]
pub billing: StripeBillingAddress,
#[serde(flatten)]
pub payment_data: Option<StripePaymentMethodData>,
pub capture_method: StripeCaptureMethod,
#[serde(flatten)]
pub payment_method_options: Option<StripePaymentMethodOptions>, // For mandate txns using network_txns_id, needs to be validated
pub setup_future_usage: Option<enums::FutureUsage>,
pub off_session: Option<bool>,
#[serde(rename = "payment_method_types[0]")]
pub payment_method_types: Option<StripePaymentMethodType>,
#[serde(rename = "expand[0]")]
pub expand: Option<ExpandableObjects>,
#[serde(flatten)]
pub browser_info: Option<StripeBrowserInformation>,
#[serde(flatten)]
pub charges: Option<IntentCharges>,
#[serde(rename = "payment_method_options[card][moto]")]
pub moto: Option<bool>,
}
#[derive(Debug, Eq, PartialEq, Serialize, Clone)]
pub struct IntentCharges {
pub application_fee_amount: Option<MinorUnit>,
#[serde(
rename = "transfer_data[destination]",
skip_serializing_if = "Option::is_none"
)]
pub destination_account_id: Option<String>,
}
// Field rename is required only in case of serialization as it is passed in the request to the connector.
// Deserialization is happening only in case of webhooks, where fields name should be used as defined in the struct.
// Whenever adding new fields, Please ensure it doesn't break the webhook flow
#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
pub struct StripeMetadata {
// merchant_reference_id
#[serde(rename(serialize = "metadata[order_id]"))]
pub order_id: Option<String>,
// to check whether the order_id is refund_id or payment_id
// before deployment, order id is set to payment_id in refunds but now it is set as refund_id
// it is set as string instead of bool because stripe pass it as string even if we set it as bool
#[serde(rename(serialize = "metadata[is_refund_id_as_reference]"))]
pub is_refund_id_as_reference: Option<String>,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct SetupIntentRequest {
pub confirm: bool,
pub usage: Option<enums::FutureUsage>,
pub customer: Option<Secret<String>>,
pub off_session: Option<bool>,
pub return_url: Option<String>,
#[serde(flatten)]
pub payment_data: StripePaymentMethodData,
pub payment_method_options: Option<StripePaymentMethodOptions>, // For mandate txns using network_txns_id, needs to be validated
#[serde(flatten)]
pub meta_data: Option<HashMap<String, String>>,
#[serde(rename = "payment_method_types[0]")]
pub payment_method_types: Option<StripePaymentMethodType>,
#[serde(rename = "expand[0]")]
pub expand: Option<ExpandableObjects>,
#[serde(flatten)]
pub browser_info: Option<StripeBrowserInformation>,
#[serde(rename = "payment_method_options[card][moto]")]
pub moto: Option<bool>,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct StripeCardData {
#[serde(rename = "payment_method_data[type]")]
pub payment_method_data_type: StripePaymentMethodType,
#[serde(rename = "payment_method_data[card][number]")]
pub payment_method_data_card_number: cards::CardNumber,
#[serde(rename = "payment_method_data[card][exp_month]")]
pub payment_method_data_card_exp_month: Secret<String>,
#[serde(rename = "payment_method_data[card][exp_year]")]
pub payment_method_data_card_exp_year: Secret<String>,
#[serde(rename = "payment_method_data[card][cvc]")]
pub payment_method_data_card_cvc: Option<Secret<String>>,
#[serde(rename = "payment_method_options[card][request_three_d_secure]")]
pub payment_method_auth_type: Option<Auth3ds>,
#[serde(rename = "payment_method_options[card][network]")]
pub payment_method_data_card_preferred_network: Option<StripeCardNetwork>,
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(rename = "payment_method_options[card][request_incremental_authorization]")]
pub request_incremental_authorization: Option<StripeRequestIncrementalAuthorization>,
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(rename = "payment_method_options[card][request_extended_authorization]")]
request_extended_authorization: Option<StripeRequestExtendedAuthorization>,
#[serde(rename = "payment_method_options[card][request_overcapture]")]
pub request_overcapture: Option<StripeRequestOvercaptureBool>,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum StripeRequestIncrementalAuthorization {
IfAvailable,
Never,
}
#[derive(Debug, Eq, PartialEq, Serialize, Deserialize, Clone)]
#[serde(rename_all = "snake_case")]
pub enum StripeRequestExtendedAuthorization {
IfAvailable,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum StripeRequestOvercaptureBool {
IfAvailable,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct StripePayLaterData {
#[serde(rename = "payment_method_data[type]")]
pub payment_method_data_type: StripePaymentMethodType,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct TokenRequest {
#[serde(flatten)]
pub token_data: StripePaymentMethodData,
}
#[derive(Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct StripeTokenResponse {
pub id: Secret<String>,
pub object: String,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct CustomerRequest {
pub description: Option<String>,
pub email: Option<Email>,
pub phone: Option<Secret<String>>,
pub name: Option<Secret<String>>,
pub source: Option<Secret<String>>,
}
#[derive(Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct StripeCustomerResponse {
pub id: String,
pub description: Option<String>,
pub email: Option<Email>,
pub phone: Option<Secret<String>>,
pub name: Option<Secret<String>>,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct ChargesRequest {
pub amount: MinorUnit,
pub currency: String,
pub customer: Secret<String>,
pub source: Secret<String>,
#[serde(flatten)]
pub meta_data: Option<HashMap<String, String>>,
}
#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
pub struct ChargesResponse {
pub id: String,
pub amount: MinorUnit,
pub amount_captured: MinorUnit,
pub currency: String,
pub status: StripePaymentStatus,
pub source: StripeSourceResponse,
pub failure_code: Option<String>,
pub failure_message: Option<String>,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
#[serde(untagged)]
pub enum StripeBankName {
Eps {
#[serde(rename = "payment_method_data[eps][bank]")]
bank_name: Option<StripeBankNames>,
},
Ideal {
#[serde(rename = "payment_method_data[ideal][bank]")]
ideal_bank_name: Option<StripeBankNames>,
},
Przelewy24 {
#[serde(rename = "payment_method_data[p24][bank]")]
bank_name: Option<StripeBankNames>,
},
}
#[derive(Debug, Eq, PartialEq, Serialize)]
#[serde(untagged)]
pub enum StripeBankRedirectData {
StripeGiropay(Box<StripeGiropay>),
StripeIdeal(Box<StripeIdeal>),
StripeBancontactCard(Box<StripeBancontactCard>),
StripePrezelewy24(Box<StripePrezelewy24>),
StripeEps(Box<StripeEps>),
StripeBlik(Box<StripeBlik>),
StripeOnlineBankingFpx(Box<StripeOnlineBankingFpx>),
}
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct StripeGiropay {
#[serde(rename = "payment_method_data[type]")]
pub payment_method_data_type: StripePaymentMethodType,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct StripeIdeal {
#[serde(rename = "payment_method_data[type]")]
pub payment_method_data_type: StripePaymentMethodType,
#[serde(rename = "payment_method_data[ideal][bank]")]
ideal_bank_name: Option<StripeBankNames>,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct StripeBancontactCard {
#[serde(rename = "payment_method_data[type]")]
pub payment_method_data_type: StripePaymentMethodType,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct StripePrezelewy24 {
#[serde(rename = "payment_method_data[type]")]
pub payment_method_data_type: StripePaymentMethodType,
#[serde(rename = "payment_method_data[p24][bank]")]
bank_name: Option<StripeBankNames>,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct StripeEps {
#[serde(rename = "payment_method_data[type]")]
pub payment_method_data_type: StripePaymentMethodType,
#[serde(rename = "payment_method_data[eps][bank]")]
bank_name: Option<StripeBankNames>,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct StripeBlik {
#[serde(rename = "payment_method_data[type]")]
pub payment_method_data_type: StripePaymentMethodType,
#[serde(rename = "payment_method_options[blik][code]")]
pub code: Secret<String>,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct StripeOnlineBankingFpx {
#[serde(rename = "payment_method_data[type]")]
pub payment_method_data_type: StripePaymentMethodType,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct AchTransferData {
#[serde(rename = "payment_method_data[type]")]
pub payment_method_data_type: StripePaymentMethodType,
#[serde(rename = "payment_method_options[customer_balance][bank_transfer][type]")]
pub bank_transfer_type: StripeCreditTransferTypes,
#[serde(rename = "payment_method_types[0]")]
pub payment_method_type: StripePaymentMethodType,
#[serde(rename = "payment_method_options[customer_balance][funding_type]")]
pub balance_funding_type: BankTransferType,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct MultibancoTransferData {
#[serde(rename = "payment_method_data[type]")]
pub payment_method_data_type: StripeCreditTransferTypes,
#[serde(rename = "payment_method_types[0]")]
pub payment_method_type: StripeCreditTransferTypes,
#[serde(rename = "payment_method_data[billing_details][email]")]
pub email: Email,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct BacsBankTransferData {
#[serde(rename = "payment_method_data[type]")]
pub payment_method_data_type: StripePaymentMethodType,
#[serde(rename = "payment_method_options[customer_balance][bank_transfer][type]")]
pub bank_transfer_type: BankTransferType,
#[serde(rename = "payment_method_options[customer_balance][funding_type]")]
pub balance_funding_type: BankTransferType,
#[serde(rename = "payment_method_types[0]")]
pub payment_method_type: StripePaymentMethodType,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct SepaBankTransferData {
#[serde(rename = "payment_method_data[type]")]
pub payment_method_data_type: StripePaymentMethodType,
#[serde(rename = "payment_method_options[customer_balance][bank_transfer][type]")]
pub bank_transfer_type: BankTransferType,
#[serde(rename = "payment_method_options[customer_balance][funding_type]")]
pub balance_funding_type: BankTransferType,
#[serde(rename = "payment_method_types[0]")]
pub payment_method_type: StripePaymentMethodType,
#[serde(
rename = "payment_method_options[customer_balance][bank_transfer][eu_bank_transfer][country]"
)]
pub country: enums::CountryAlpha2,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
#[serde(untagged)]
pub enum StripeCreditTransferSourceRequest {
AchBankTansfer(AchCreditTransferSourceRequest),
MultibancoBankTansfer(MultibancoCreditTransferSourceRequest),
}
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct AchCreditTransferSourceRequest {
#[serde(rename = "type")]
pub transfer_type: StripeCreditTransferTypes,
#[serde(flatten)]
pub payment_method_data: AchTransferData,
pub currency: enums::Currency,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct MultibancoCreditTransferSourceRequest {
#[serde(rename = "type")]
pub transfer_type: StripeCreditTransferTypes,
#[serde(flatten)]
pub payment_method_data: MultibancoTransferData,
pub currency: enums::Currency,
pub amount: Option<MinorUnit>,
#[serde(rename = "redirect[return_url]")]
pub return_url: Option<String>,
}
// Remove untagged when Deserialize is added
#[derive(Debug, Eq, PartialEq, Serialize)]
#[serde(untagged)]
pub enum StripePaymentMethodData {
CardToken(StripeCardToken),
Card(StripeCardData),
PayLater(StripePayLaterData),
Wallet(StripeWallet),
BankRedirect(StripeBankRedirectData),
BankDebit(StripeBankDebitData),
BankTransfer(StripeBankTransferData),
}
#[derive(Debug, Clone, Default, Eq, PartialEq, Serialize)]
pub struct StripeBillingAddressCardToken {
#[serde(rename = "billing_details[name]")]
pub name: Option<Secret<String>>,
#[serde(rename = "billing_details[email]")]
pub email: Option<Email>,
#[serde(rename = "billing_details[phone]")]
pub phone: Option<Secret<String>>,
#[serde(rename = "billing_details[address][line1]")]
pub address_line1: Option<Secret<String>>,
#[serde(rename = "billing_details[address][line2]")]
pub address_line2: Option<Secret<String>>,
#[serde(rename = "billing_details[address][state]")]
pub state: Option<Secret<String>>,
#[serde(rename = "billing_details[address][city]")]
pub city: Option<String>,
}
// Struct to call the Stripe tokens API to create a PSP token for the card details provided
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct StripeCardToken {
#[serde(rename = "type")]
pub payment_method_type: Option<StripePaymentMethodType>,
#[serde(rename = "card[number]")]
pub token_card_number: cards::CardNumber,
#[serde(rename = "card[exp_month]")]
pub token_card_exp_month: Secret<String>,
#[serde(rename = "card[exp_year]")]
pub token_card_exp_year: Secret<String>,
#[serde(rename = "card[cvc]")]
pub token_card_cvc: Secret<String>,
#[serde(flatten)]
pub billing: StripeBillingAddressCardToken,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
#[serde(tag = "payment_method_data[type]")]
pub enum BankDebitData {
#[serde(rename = "us_bank_account")]
Ach {
#[serde(rename = "payment_method_data[us_bank_account][account_holder_type]")]
account_holder_type: String,
#[serde(rename = "payment_method_data[us_bank_account][account_number]")]
account_number: Secret<String>,
#[serde(rename = "payment_method_data[us_bank_account][routing_number]")]
routing_number: Secret<String>,
},
#[serde(rename = "sepa_debit")]
Sepa {
#[serde(rename = "payment_method_data[sepa_debit][iban]")]
iban: Secret<String>,
},
#[serde(rename = "au_becs_debit")]
Becs {
#[serde(rename = "payment_method_data[au_becs_debit][account_number]")]
account_number: Secret<String>,
#[serde(rename = "payment_method_data[au_becs_debit][bsb_number]")]
bsb_number: Secret<String>,
},
#[serde(rename = "bacs_debit")]
Bacs {
#[serde(rename = "payment_method_data[bacs_debit][account_number]")]
account_number: Secret<String>,
#[serde(rename = "payment_method_data[bacs_debit][sort_code]")]
sort_code: Secret<String>,
},
}
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct StripeBankDebitData {
#[serde(flatten)]
pub bank_specific_data: Option<BankDebitData>,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct BankTransferData {
pub email: Email,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
#[serde(untagged)]
pub enum StripeBankTransferData {
AchBankTransfer(Box<AchTransferData>),
SepaBankTransfer(Box<SepaBankTransferData>),
BacsBankTransfers(Box<BacsBankTransferData>),
MultibancoBankTransfers(Box<MultibancoTransferData>),
}
#[derive(Debug, Eq, PartialEq, Serialize)]
#[serde(untagged)]
pub enum StripeWallet {
ApplepayToken(StripeApplePay),
GooglepayToken(GooglePayToken),
ApplepayPayment(ApplepayPayment),
AmazonpayPayment(AmazonpayPayment),
WechatpayPayment(WechatpayPayment),
AlipayPayment(AlipayPayment),
Cashapp(CashappPayment),
RevolutPay(RevolutpayPayment),
ApplePayPredecryptToken(Box<StripeApplePayPredecrypt>),
}
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct StripeApplePayPredecrypt {
#[serde(rename = "card[number]")]
number: cards::CardNumber,
#[serde(rename = "card[exp_year]")]
exp_year: Secret<String>,
#[serde(rename = "card[exp_month]")]
exp_month: Secret<String>,
#[serde(rename = "card[cryptogram]")]
cryptogram: Secret<String>,
#[serde(rename = "card[eci]")]
eci: Option<String>,
#[serde(rename = "card[tokenization_method]")]
tokenization_method: String,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct StripeApplePay {
pub pk_token: Secret<String>,
pub pk_token_instrument_name: String,
pub pk_token_payment_network: String,
pub pk_token_transaction_id: Secret<String>,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct GooglePayToken {
#[serde(rename = "payment_method_data[type]")]
pub payment_type: StripePaymentMethodType,
#[serde(rename = "payment_method_data[card][token]")]
pub token: Secret<String>,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct ApplepayPayment {
#[serde(rename = "payment_method_data[card][token]")]
pub token: Secret<String>,
#[serde(rename = "payment_method_data[type]")]
pub payment_method_types: StripePaymentMethodType,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct AmazonpayPayment {
#[serde(rename = "payment_method_data[type]")]
pub payment_method_types: StripePaymentMethodType,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct RevolutpayPayment {
#[serde(rename = "payment_method_data[type]")]
pub payment_method_types: StripePaymentMethodType,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct AlipayPayment {
#[serde(rename = "payment_method_data[type]")]
pub payment_method_data_type: StripePaymentMethodType,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct CashappPayment {
#[serde(rename = "payment_method_data[type]")]
pub payment_method_data_type: StripePaymentMethodType,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct WechatpayPayment {
#[serde(rename = "payment_method_data[type]")]
pub payment_method_data_type: StripePaymentMethodType,
#[serde(rename = "payment_method_options[wechat_pay][client]")]
pub client: WechatClient,
}
#[derive(Debug, Eq, PartialEq, Serialize, Clone, Copy)]
#[serde(rename_all = "snake_case")]
pub enum WechatClient {
Web,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct GooglepayPayment {
#[serde(rename = "payment_method_data[card][token]")]
pub token: Secret<String>,
#[serde(rename = "payment_method_data[type]")]
pub payment_method_types: StripePaymentMethodType,
}
// All supported payment_method_types in stripe
// This enum goes in payment_method_types[] field in stripe request body
// https://stripe.com/docs/api/payment_intents/create#create_payment_intent-payment_method_types
#[derive(Eq, PartialEq, Serialize, Clone, Debug, Copy)]
#[serde(rename_all = "snake_case")]
pub enum StripePaymentMethodType {
Affirm,
AfterpayClearpay,
Alipay,
#[serde(rename = "amazon_pay")]
AmazonPay,
#[serde(rename = "au_becs_debit")]
Becs,
#[serde(rename = "bacs_debit")]
Bacs,
Bancontact,
Blik,
Card,
CustomerBalance,
Eps,
Giropay,
Ideal,
Klarna,
#[serde(rename = "p24")]
Przelewy24,
#[serde(rename = "sepa_debit")]
Sepa,
Sofort,
#[serde(rename = "us_bank_account")]
Ach,
#[serde(rename = "wechat_pay")]
Wechatpay,
#[serde(rename = "cashapp")]
Cashapp,
RevolutPay,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
#[allow(dead_code)]
pub enum StripeCreditTransferTypes {
#[serde(rename = "us_bank_transfer")]
AchCreditTransfer,
Multibanco,
Blik,
}
impl TryFrom<enums::PaymentMethodType> for StripePaymentMethodType {
type Error = error_stack::Report<ConnectorError>;
fn try_from(value: enums::PaymentMethodType) -> Result<Self, Self::Error> {
match value {
enums::PaymentMethodType::Credit => Ok(Self::Card),
enums::PaymentMethodType::Debit => Ok(Self::Card),
#[cfg(feature = "v2")]
enums::PaymentMethodType::Card => Ok(Self::Card),
enums::PaymentMethodType::Klarna => Ok(Self::Klarna),
enums::PaymentMethodType::Affirm => Ok(Self::Affirm),
enums::PaymentMethodType::AfterpayClearpay => Ok(Self::AfterpayClearpay),
enums::PaymentMethodType::Eps => Ok(Self::Eps),
enums::PaymentMethodType::Giropay => Ok(Self::Giropay),
enums::PaymentMethodType::Ideal => Ok(Self::Ideal),
enums::PaymentMethodType::Sofort => Ok(Self::Sofort),
enums::PaymentMethodType::AmazonPay => Ok(Self::AmazonPay),
enums::PaymentMethodType::ApplePay => Ok(Self::Card),
enums::PaymentMethodType::Ach => Ok(Self::Ach),
enums::PaymentMethodType::Sepa => Ok(Self::Sepa),
enums::PaymentMethodType::Becs => Ok(Self::Becs),
enums::PaymentMethodType::Bacs => Ok(Self::Bacs),
enums::PaymentMethodType::BancontactCard => Ok(Self::Bancontact),
enums::PaymentMethodType::WeChatPay => Ok(Self::Wechatpay),
enums::PaymentMethodType::Blik => Ok(Self::Blik),
enums::PaymentMethodType::AliPay => Ok(Self::Alipay),
enums::PaymentMethodType::Przelewy24 => Ok(Self::Przelewy24),
enums::PaymentMethodType::RevolutPay => Ok(Self::RevolutPay),
// Stripe expects PMT as Card for Recurring Mandates Payments
enums::PaymentMethodType::GooglePay => Ok(Self::Card),
enums::PaymentMethodType::Boleto
| enums::PaymentMethodType::Paysera
| enums::PaymentMethodType::Skrill
| enums::PaymentMethodType::CardRedirect
| enums::PaymentMethodType::CryptoCurrency
| enums::PaymentMethodType::Multibanco
| enums::PaymentMethodType::OnlineBankingFpx
| enums::PaymentMethodType::Paypal
| enums::PaymentMethodType::BhnCardNetwork
| enums::PaymentMethodType::Pix
| enums::PaymentMethodType::UpiCollect
| enums::PaymentMethodType::UpiIntent
| enums::PaymentMethodType::Cashapp
| enums::PaymentMethodType::Bluecode
| enums::PaymentMethodType::SepaGuarenteedDebit
| enums::PaymentMethodType::Oxxo
| enums::PaymentMethodType::Payjustnow => Err(ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("stripe"),
)
.into()),
enums::PaymentMethodType::AliPayHk
| enums::PaymentMethodType::Atome
| enums::PaymentMethodType::Bizum
| enums::PaymentMethodType::Alma
| enums::PaymentMethodType::ClassicReward
| enums::PaymentMethodType::Dana
| enums::PaymentMethodType::DirectCarrierBilling
| enums::PaymentMethodType::Efecty
| enums::PaymentMethodType::Eft
| enums::PaymentMethodType::Evoucher
| enums::PaymentMethodType::GoPay
| enums::PaymentMethodType::Gcash
| enums::PaymentMethodType::Interac
| enums::PaymentMethodType::KakaoPay
| enums::PaymentMethodType::LocalBankRedirect
| enums::PaymentMethodType::MbWay
| enums::PaymentMethodType::MobilePay
| enums::PaymentMethodType::Momo
| enums::PaymentMethodType::MomoAtm
| enums::PaymentMethodType::OnlineBankingThailand
| enums::PaymentMethodType::OnlineBankingCzechRepublic
| enums::PaymentMethodType::OnlineBankingFinland
| enums::PaymentMethodType::OnlineBankingPoland
| enums::PaymentMethodType::OnlineBankingSlovakia
| enums::PaymentMethodType::OpenBankingUk
| enums::PaymentMethodType::OpenBankingPIS
| enums::PaymentMethodType::PagoEfectivo
| enums::PaymentMethodType::PayBright
| enums::PaymentMethodType::Pse
| enums::PaymentMethodType::RedCompra
| enums::PaymentMethodType::RedPagos
| enums::PaymentMethodType::SamsungPay
| enums::PaymentMethodType::Swish
| enums::PaymentMethodType::TouchNGo
| enums::PaymentMethodType::Trustly
| enums::PaymentMethodType::Twint
| enums::PaymentMethodType::Vipps
| enums::PaymentMethodType::Venmo
| enums::PaymentMethodType::Alfamart
| enums::PaymentMethodType::BcaBankTransfer
| enums::PaymentMethodType::BniVa
| enums::PaymentMethodType::CimbVa
| enums::PaymentMethodType::BriVa
| enums::PaymentMethodType::DanamonVa
| enums::PaymentMethodType::Indomaret
| enums::PaymentMethodType::MandiriVa
| enums::PaymentMethodType::PermataBankTransfer
| enums::PaymentMethodType::PaySafeCard
| enums::PaymentMethodType::Paze
| enums::PaymentMethodType::Givex
| enums::PaymentMethodType::Benefit
| enums::PaymentMethodType::Knet
| enums::PaymentMethodType::SevenEleven
| enums::PaymentMethodType::Lawson
| enums::PaymentMethodType::MiniStop
| enums::PaymentMethodType::FamilyMart
| enums::PaymentMethodType::Seicomart
| enums::PaymentMethodType::PayEasy
| enums::PaymentMethodType::LocalBankTransfer
| enums::PaymentMethodType::InstantBankTransfer
| enums::PaymentMethodType::InstantBankTransferFinland
| enums::PaymentMethodType::InstantBankTransferPoland
| 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/stripe/transformers/connect.rs | crates/hyperswitch_connectors/src/connectors/stripe/transformers/connect.rs | use common_enums::{enums, Currency};
use common_utils::{ext_traits::OptionExt as _, pii::Email};
use error_stack::ResultExt;
use hyperswitch_domain_models::types::{PayoutsResponseData, PayoutsRouterData};
use hyperswitch_interfaces::errors;
use masking::Secret;
use serde::{Deserialize, Serialize};
use super::ErrorDetails;
use crate::{
types::{PayoutIndividualDetailsExt as _, PayoutsResponseRouterData},
utils::{CustomerDetails as _, PayoutsData as _, RouterData},
};
type Error = error_stack::Report<errors::ConnectorError>;
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum StripeConnectPayoutStatus {
Canceled,
Failed,
InTransit,
Paid,
Pending,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct StripeConnectErrorResponse {
pub error: ErrorDetails,
}
// Payouts
#[derive(Clone, Debug, Serialize)]
pub struct StripeConnectPayoutCreateRequest {
amount: i64,
currency: Currency,
destination: String,
transfer_group: String,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct StripeConnectPayoutCreateResponse {
id: String,
description: Option<String>,
source_transaction: Option<String>,
}
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct TransferReversals {
object: String,
has_more: bool,
total_count: i32,
url: String,
}
#[derive(Clone, Debug, Serialize)]
pub struct StripeConnectPayoutFulfillRequest {
amount: i64,
currency: Currency,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct StripeConnectPayoutFulfillResponse {
id: String,
currency: String,
description: Option<String>,
failure_balance_transaction: Option<String>,
failure_code: Option<String>,
failure_message: Option<String>,
original_payout: Option<String>,
reversed_by: Option<String>,
statement_descriptor: Option<String>,
status: StripeConnectPayoutStatus,
}
#[derive(Clone, Debug, Serialize)]
pub struct StripeConnectReversalRequest {
amount: i64,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct StripeConnectReversalResponse {
id: String,
source_refund: Option<String>,
}
#[derive(Clone, Debug, Serialize)]
pub struct StripeConnectRecipientCreateRequest {
#[serde(rename = "type")]
account_type: String,
country: Option<enums::CountryAlpha2>,
email: Option<Email>,
#[serde(rename = "capabilities[card_payments][requested]")]
capabilities_card_payments: Option<bool>,
#[serde(rename = "capabilities[transfers][requested]")]
capabilities_transfers: Option<bool>,
#[serde(rename = "tos_acceptance[date]")]
tos_acceptance_date: Option<i64>,
#[serde(rename = "tos_acceptance[ip]")]
tos_acceptance_ip: Option<Secret<String>>,
business_type: String,
#[serde(rename = "business_profile[mcc]")]
business_profile_mcc: Option<i32>,
#[serde(rename = "business_profile[url]")]
business_profile_url: Option<String>,
#[serde(rename = "business_profile[name]")]
business_profile_name: Option<Secret<String>>,
#[serde(rename = "company[name]")]
company_name: Option<Secret<String>>,
#[serde(rename = "company[address][line1]")]
company_address_line1: Option<Secret<String>>,
#[serde(rename = "company[address][line2]")]
company_address_line2: Option<Secret<String>>,
#[serde(rename = "company[address][postal_code]")]
company_address_postal_code: Option<Secret<String>>,
#[serde(rename = "company[address][city]")]
company_address_city: Option<Secret<String>>,
#[serde(rename = "company[address][state]")]
company_address_state: Option<Secret<String>>,
#[serde(rename = "company[phone]")]
company_phone: Option<Secret<String>>,
#[serde(rename = "company[tax_id]")]
company_tax_id: Option<Secret<String>>,
#[serde(rename = "company[owners_provided]")]
company_owners_provided: Option<bool>,
#[serde(rename = "individual[first_name]")]
individual_first_name: Option<Secret<String>>,
#[serde(rename = "individual[last_name]")]
individual_last_name: Option<Secret<String>>,
#[serde(rename = "individual[dob][day]")]
individual_dob_day: Option<Secret<String>>,
#[serde(rename = "individual[dob][month]")]
individual_dob_month: Option<Secret<String>>,
#[serde(rename = "individual[dob][year]")]
individual_dob_year: Option<Secret<String>>,
#[serde(rename = "individual[address][line1]")]
individual_address_line1: Option<Secret<String>>,
#[serde(rename = "individual[address][line2]")]
individual_address_line2: Option<Secret<String>>,
#[serde(rename = "individual[address][postal_code]")]
individual_address_postal_code: Option<Secret<String>>,
#[serde(rename = "individual[address][city]")]
individual_address_city: Option<String>,
#[serde(rename = "individual[address][state]")]
individual_address_state: Option<Secret<String>>,
#[serde(rename = "individual[email]")]
individual_email: Option<Email>,
#[serde(rename = "individual[phone]")]
individual_phone: Option<Secret<String>>,
#[serde(rename = "individual[id_number]")]
individual_id_number: Option<Secret<String>>,
#[serde(rename = "individual[ssn_last_4]")]
individual_ssn_last_4: Option<Secret<String>>,
}
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct StripeConnectRecipientCreateResponse {
id: String,
}
#[derive(Clone, Debug, Serialize)]
#[serde(untagged)]
pub enum StripeConnectRecipientAccountCreateRequest {
Bank(RecipientBankAccountRequest),
Card(RecipientCardAccountRequest),
Token(RecipientTokenRequest),
}
#[derive(Clone, Debug, Serialize)]
pub struct RecipientTokenRequest {
external_account: String,
}
#[derive(Clone, Debug, Serialize)]
pub struct RecipientCardAccountRequest {
#[serde(rename = "external_account[object]")]
external_account_object: String,
#[serde(rename = "external_account[number]")]
external_account_number: Secret<String>,
#[serde(rename = "external_account[exp_month]")]
external_account_exp_month: Secret<String>,
#[serde(rename = "external_account[exp_year]")]
external_account_exp_year: Secret<String>,
}
#[derive(Clone, Debug, Serialize)]
pub struct RecipientBankAccountRequest {
#[serde(rename = "external_account[object]")]
external_account_object: String,
#[serde(rename = "external_account[country]")]
external_account_country: enums::CountryAlpha2,
#[serde(rename = "external_account[currency]")]
external_account_currency: Currency,
#[serde(rename = "external_account[account_holder_name]")]
external_account_account_holder_name: Secret<String>,
#[serde(rename = "external_account[account_number]")]
external_account_account_number: Secret<String>,
#[serde(rename = "external_account[account_holder_type]")]
external_account_account_holder_type: String,
#[serde(rename = "external_account[routing_number]")]
external_account_routing_number: Secret<String>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct StripeConnectRecipientAccountCreateResponse {
id: String,
}
// Payouts create/transfer request transform
impl<F> TryFrom<&PayoutsRouterData<F>> for StripeConnectPayoutCreateRequest {
type Error = Error;
fn try_from(item: &PayoutsRouterData<F>) -> Result<Self, Self::Error> {
let request = item.request.to_owned();
let connector_customer_id = item.get_connector_customer_id()?;
Ok(Self {
amount: request.amount,
currency: request.destination_currency,
destination: connector_customer_id,
transfer_group: item.connector_request_reference_id.clone(),
})
}
}
// Payouts create response transform
impl<F> TryFrom<PayoutsResponseRouterData<F, StripeConnectPayoutCreateResponse>>
for PayoutsRouterData<F>
{
type Error = Error;
fn try_from(
item: PayoutsResponseRouterData<F, StripeConnectPayoutCreateResponse>,
) -> Result<Self, Self::Error> {
let response: StripeConnectPayoutCreateResponse = item.response;
Ok(Self {
response: Ok(PayoutsResponseData {
status: Some(enums::PayoutStatus::RequiresFulfillment),
connector_payout_id: Some(response.id),
payout_eligible: None,
should_add_next_step_to_process_tracker: false,
error_code: None,
error_message: None,
payout_connector_metadata: None,
}),
..item.data
})
}
}
// Payouts fulfill request transform
impl<F> TryFrom<&PayoutsRouterData<F>> for StripeConnectPayoutFulfillRequest {
type Error = Error;
fn try_from(item: &PayoutsRouterData<F>) -> Result<Self, Self::Error> {
let request = item.request.to_owned();
Ok(Self {
amount: request.amount,
currency: request.destination_currency,
})
}
}
// Payouts fulfill response transform
impl<F> TryFrom<PayoutsResponseRouterData<F, StripeConnectPayoutFulfillResponse>>
for PayoutsRouterData<F>
{
type Error = Error;
fn try_from(
item: PayoutsResponseRouterData<F, StripeConnectPayoutFulfillResponse>,
) -> Result<Self, Self::Error> {
let response: StripeConnectPayoutFulfillResponse = item.response;
Ok(Self {
response: Ok(PayoutsResponseData {
status: Some(enums::PayoutStatus::from(response.status)),
connector_payout_id: Some(response.id),
payout_eligible: None,
should_add_next_step_to_process_tracker: false,
error_code: None,
error_message: None,
payout_connector_metadata: None,
}),
..item.data
})
}
}
// Payouts reversal request transform
impl<F> TryFrom<&PayoutsRouterData<F>> for StripeConnectReversalRequest {
type Error = Error;
fn try_from(item: &PayoutsRouterData<F>) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.request.amount,
})
}
}
// Payouts reversal response transform
impl<F> TryFrom<PayoutsResponseRouterData<F, StripeConnectReversalResponse>>
for PayoutsRouterData<F>
{
type Error = Error;
fn try_from(
item: PayoutsResponseRouterData<F, StripeConnectReversalResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(PayoutsResponseData {
status: Some(enums::PayoutStatus::Cancelled),
connector_payout_id: item.data.request.connector_payout_id.clone(),
payout_eligible: None,
should_add_next_step_to_process_tracker: false,
error_code: None,
error_message: None,
payout_connector_metadata: None,
}),
..item.data
})
}
}
// Recipient creation request transform
impl<F> TryFrom<&PayoutsRouterData<F>> for StripeConnectRecipientCreateRequest {
type Error = Error;
fn try_from(item: &PayoutsRouterData<F>) -> Result<Self, Self::Error> {
let request = item.request.to_owned();
let customer_details = request.get_customer_details()?;
let customer_email = customer_details.get_customer_email()?;
let address = item.get_billing_address()?.clone();
let payout_vendor_details = request.get_vendor_details()?;
let (vendor_details, individual_details) = (
payout_vendor_details.vendor_details,
payout_vendor_details.individual_details,
);
Ok(Self {
account_type: vendor_details.account_type,
country: address.country,
email: Some(customer_email.clone()),
capabilities_card_payments: vendor_details.capabilities_card_payments,
capabilities_transfers: vendor_details.capabilities_transfers,
tos_acceptance_date: individual_details.tos_acceptance_date,
tos_acceptance_ip: individual_details.tos_acceptance_ip,
business_type: vendor_details.business_type,
business_profile_mcc: vendor_details.business_profile_mcc,
business_profile_url: vendor_details.business_profile_url,
business_profile_name: vendor_details.business_profile_name.clone(),
company_name: vendor_details.business_profile_name,
company_address_line1: vendor_details.company_address_line1,
company_address_line2: vendor_details.company_address_line2,
company_address_postal_code: vendor_details.company_address_postal_code,
company_address_city: vendor_details.company_address_city,
company_address_state: vendor_details.company_address_state,
company_phone: vendor_details.company_phone,
company_tax_id: vendor_details.company_tax_id,
company_owners_provided: vendor_details.company_owners_provided,
individual_first_name: address.first_name,
individual_last_name: address.last_name,
individual_dob_day: individual_details.individual_dob_day,
individual_dob_month: individual_details.individual_dob_month,
individual_dob_year: individual_details.individual_dob_year,
individual_address_line1: address.line1,
individual_address_line2: address.line2,
individual_address_postal_code: address.zip,
individual_address_city: address.city,
individual_address_state: address.state,
individual_email: Some(customer_email),
individual_phone: customer_details.phone,
individual_id_number: individual_details.individual_id_number,
individual_ssn_last_4: individual_details.individual_ssn_last_4,
})
}
}
// Recipient creation response transform
impl<F> TryFrom<PayoutsResponseRouterData<F, StripeConnectRecipientCreateResponse>>
for PayoutsRouterData<F>
{
type Error = Error;
fn try_from(
item: PayoutsResponseRouterData<F, StripeConnectRecipientCreateResponse>,
) -> Result<Self, Self::Error> {
let response: StripeConnectRecipientCreateResponse = item.response;
Ok(Self {
response: Ok(PayoutsResponseData {
status: Some(enums::PayoutStatus::RequiresVendorAccountCreation),
connector_payout_id: Some(response.id),
payout_eligible: None,
should_add_next_step_to_process_tracker: true,
error_code: None,
error_message: None,
payout_connector_metadata: None,
}),
..item.data
})
}
}
// Recipient account's creation request
impl<F> TryFrom<&PayoutsRouterData<F>> for StripeConnectRecipientAccountCreateRequest {
type Error = Error;
fn try_from(item: &PayoutsRouterData<F>) -> Result<Self, Self::Error> {
let request = item.request.to_owned();
let payout_method_data = item.get_payout_method_data()?;
let customer_details = request.get_customer_details()?;
let customer_name = customer_details.get_customer_name()?;
let payout_vendor_details = request.get_vendor_details()?;
match payout_method_data {
api_models::payouts::PayoutMethodData::Card(_) => {
Ok(Self::Token(RecipientTokenRequest {
external_account: "tok_visa_debit".to_string(),
}))
}
api_models::payouts::PayoutMethodData::Bank(bank) => match bank {
api_models::payouts::Bank::Ach(bank_details) => {
Ok(Self::Bank(RecipientBankAccountRequest {
external_account_object: "bank_account".to_string(),
external_account_country: bank_details
.bank_country_code
.get_required_value("bank_country_code")
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "bank_country_code",
})?,
external_account_currency: request.destination_currency.to_owned(),
external_account_account_holder_name: customer_name,
external_account_account_holder_type: payout_vendor_details
.individual_details
.get_external_account_account_holder_type()?,
external_account_account_number: bank_details.bank_account_number,
external_account_routing_number: bank_details.bank_routing_number,
}))
}
api_models::payouts::Bank::Bacs(_) => Err(errors::ConnectorError::NotSupported {
message: "BACS payouts are not supported".to_string(),
connector: "stripe",
}
.into()),
api_models::payouts::Bank::Sepa(_) => Err(errors::ConnectorError::NotSupported {
message: "SEPA payouts are not supported".to_string(),
connector: "stripe",
}
.into()),
api_models::payouts::Bank::Pix(_) => Err(errors::ConnectorError::NotSupported {
message: "PIX payouts are not supported".to_string(),
connector: "stripe",
}
.into()),
},
api_models::payouts::PayoutMethodData::Wallet(_) => {
Err(errors::ConnectorError::NotSupported {
message: "Payouts via wallets are not supported".to_string(),
connector: "stripe",
}
.into())
}
api_models::payouts::PayoutMethodData::BankRedirect(_) => {
Err(errors::ConnectorError::NotSupported {
message: "Payouts via BankRedirect are not supported".to_string(),
connector: "stripe",
}
.into())
}
api_models::payouts::PayoutMethodData::Passthrough(_) => {
Err(errors::ConnectorError::NotSupported {
message: "Payouts via Passthrough are not supported".to_string(),
connector: "stripe",
}
.into())
}
}
}
}
// Recipient account's creation response
impl<F> TryFrom<PayoutsResponseRouterData<F, StripeConnectRecipientAccountCreateResponse>>
for PayoutsRouterData<F>
{
type Error = Error;
fn try_from(
item: PayoutsResponseRouterData<F, StripeConnectRecipientAccountCreateResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(PayoutsResponseData {
status: Some(enums::PayoutStatus::RequiresCreation),
connector_payout_id: item.data.request.connector_payout_id.clone(),
payout_eligible: None,
should_add_next_step_to_process_tracker: false,
error_code: None,
error_message: None,
payout_connector_metadata: None,
}),
..item.data
})
}
}
impl From<StripeConnectPayoutStatus> for enums::PayoutStatus {
fn from(stripe_connect_status: StripeConnectPayoutStatus) -> Self {
match stripe_connect_status {
StripeConnectPayoutStatus::Paid => Self::Success,
StripeConnectPayoutStatus::Failed => Self::Failed,
StripeConnectPayoutStatus::Canceled => Self::Cancelled,
StripeConnectPayoutStatus::Pending | StripeConnectPayoutStatus::InTransit => {
Self::Pending
}
}
}
}
| 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/unified_authentication_service/transformers.rs | crates/hyperswitch_connectors/src/connectors/unified_authentication_service/transformers.rs | use common_enums::{enums, MerchantCategoryCode};
use common_types::payments::MerchantCountryCode;
use common_utils::{ext_traits::OptionExt as _, types::FloatMajorUnit};
use hyperswitch_domain_models::{
router_data::{ConnectorAuthType, RouterData},
router_request_types::{
authentication::{AuthNFlowType, ChallengeParams},
unified_authentication_service::{
AuthenticationInfo, DynamicData, PostAuthenticationDetails, PreAuthenticationDetails,
RawCardDetails, TokenDetails, UasAuthenticationResponseData,
},
},
types::{
UasAuthenticationConfirmationRouterData, UasAuthenticationRouterData,
UasPostAuthenticationRouterData, UasPreAuthenticationRouterData,
},
};
use hyperswitch_interfaces::errors;
use masking::Secret;
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
use crate::types::ResponseRouterData;
//TODO: Fill the struct with respective fields
pub struct UnifiedAuthenticationServiceRouterData<T> {
pub amount: FloatMajorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc.
pub router_data: T,
}
impl<T> From<(FloatMajorUnit, T)> for UnifiedAuthenticationServiceRouterData<T> {
fn from((amount, item): (FloatMajorUnit, T)) -> Self {
//Todo : use utils to convert the amount to the type of amount that a connector accepts
Self {
amount,
router_data: item,
}
}
}
use error_stack::ResultExt;
#[derive(Debug, Serialize)]
pub struct UnifiedAuthenticationServicePreAuthenticateRequest {
pub authenticate_by: String,
pub session_id: common_utils::id_type::AuthenticationId,
pub source_authentication_id: common_utils::id_type::AuthenticationId,
pub authentication_info: Option<AuthenticationInfo>,
pub service_details: Option<CtpServiceDetails>,
pub customer_details: Option<CustomerDetails>,
pub pmt_details: Option<PaymentDetails>,
pub auth_creds: UnifiedAuthenticationServiceAuthType,
pub transaction_details: Option<TransactionDetails>,
pub acquirer_details: Option<Acquirer>,
pub billing_address: Option<Address>,
}
#[derive(Debug, Serialize)]
pub struct UnifiedAuthenticationServiceAuthenticateConfirmationRequest {
pub authenticate_by: String,
pub source_authentication_id: common_utils::id_type::AuthenticationId,
pub auth_creds: UnifiedAuthenticationServiceAuthType,
pub x_src_flow_id: Option<String>,
pub transaction_amount: Option<FloatMajorUnit>,
pub transaction_currency: Option<enums::Currency>,
pub checkout_event_type: Option<String>,
pub checkout_event_status: Option<String>,
pub confirmation_status: Option<String>,
pub confirmation_reason: Option<String>,
pub confirmation_timestamp: Option<String>,
pub network_authorization_code: Option<String>,
pub network_transaction_identifier: Option<String>,
pub correlation_id: Option<String>,
pub merchant_transaction_id: Option<String>,
}
#[derive(Debug, Serialize, PartialEq, Deserialize)]
pub struct UnifiedAuthenticationServiceAuthenticateConfirmationResponse {
status: String,
}
impl<F, T>
TryFrom<
ResponseRouterData<
F,
UnifiedAuthenticationServiceAuthenticateConfirmationResponse,
T,
UasAuthenticationResponseData,
>,
> for RouterData<F, T, UasAuthenticationResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
UnifiedAuthenticationServiceAuthenticateConfirmationResponse,
T,
UasAuthenticationResponseData,
>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(UasAuthenticationResponseData::Confirmation {}),
..item.data
})
}
}
#[derive(Default, Debug, Serialize, PartialEq)]
pub struct PaymentDetails {
pub pan: cards::CardNumber,
pub digital_card_id: Option<String>,
pub payment_data_type: Option<common_enums::PaymentMethodType>,
pub encrypted_src_card_details: Option<String>,
pub card_expiry_month: Secret<String>,
pub card_expiry_year: Secret<String>,
pub cardholder_name: Option<Secret<String>>,
pub card_token_number: Option<Secret<String>>,
pub account_type: Option<common_enums::PaymentMethodType>,
pub card_cvc: Option<Secret<String>>,
}
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct TransactionDetails {
pub amount: FloatMajorUnit,
pub currency: enums::Currency,
pub date: Option<PrimitiveDateTime>,
pub pan_source: Option<String>,
pub protection_type: Option<String>,
pub entry_mode: Option<String>,
pub transaction_type: Option<String>,
pub otp_value: Option<String>,
pub three_ds_data: Option<ThreeDSData>,
pub message_category: Option<MessageCategory>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum MessageCategory {
Payment,
NonPayment,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ThreeDSData {
pub preferred_protocol_version: common_utils::types::SemanticVersion,
pub threeds_method_comp_ind: api_models::payments::ThreeDsCompletionIndicator,
pub force_3ds_challenge: Option<bool>,
pub psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>,
}
#[derive(Default, Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct Acquirer {
pub acquirer_merchant_id: Option<String>,
pub acquirer_bin: Option<String>,
pub acquirer_country_code: Option<String>,
}
#[derive(Default, Debug, Serialize, PartialEq, Clone, Deserialize)]
pub struct BrowserInfo {
pub color_depth: Option<u8>,
pub java_enabled: Option<bool>,
pub java_script_enabled: Option<bool>,
pub language: Option<String>,
pub screen_height: Option<u32>,
pub screen_width: Option<u32>,
pub time_zone: Option<i32>,
pub ip_address: Option<std::net::IpAddr>,
pub accept_header: Option<String>,
pub user_agent: Option<String>,
pub os_type: Option<String>,
pub os_version: Option<String>,
pub device_model: Option<String>,
pub accept_language: Option<String>,
}
#[derive(Default, Debug, Serialize, PartialEq)]
pub struct CtpServiceDetails {
pub service_session_ids: Option<ServiceSessionIds>,
pub merchant_details: Option<MerchantDetails>,
}
#[derive(Default, Debug, Serialize, PartialEq)]
pub struct ServiceSessionIds {
pub client_id: Option<String>,
pub service_id: Option<String>,
pub correlation_id: Option<String>,
pub client_reference_id: Option<String>,
pub merchant_transaction_id: Option<String>,
pub x_src_flow_id: Option<String>,
}
#[derive(Default, Debug, Serialize, PartialEq)]
pub struct MerchantDetails {
pub merchant_id: Option<String>,
pub merchant_name: Option<String>,
pub merchant_category_code: Option<MerchantCategoryCode>,
pub configuration_id: Option<String>,
pub endpoint_prefix: Option<String>,
pub three_ds_requestor_url: Option<String>,
pub three_ds_requestor_id: Option<String>,
pub three_ds_requestor_name: Option<String>,
pub merchant_country_code: Option<MerchantCountryCode>,
pub notification_url: Option<url::Url>,
}
#[derive(Default, Clone, Debug, Serialize, PartialEq, Deserialize)]
pub struct Address {
pub city: Option<String>,
pub country: Option<common_enums::CountryAlpha2>,
pub line1: Option<Secret<String>>,
pub line2: Option<Secret<String>>,
pub line3: Option<Secret<String>>,
pub post_code: Option<Secret<String>>,
pub state: Option<Secret<String>>,
}
#[derive(Default, Clone, Debug, Serialize, PartialEq, Deserialize)]
pub struct CustomerDetails {
pub name: Secret<String>,
pub email: Option<Secret<String>>,
pub phone_number: Option<Secret<String>>,
pub customer_id: String,
#[serde(rename = "type")]
pub customer_type: Option<String>,
pub billing_address: Address,
pub shipping_address: Address,
pub wallet_account_id: Secret<String>,
pub email_hash: Secret<String>,
pub country_code: String,
pub national_identifier: String,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct UnifiedAuthenticationServiceCard {
number: cards::CardNumber,
expiry_month: Secret<String>,
expiry_year: Secret<String>,
cvc: Secret<String>,
complete: bool,
}
impl TryFrom<&UnifiedAuthenticationServiceRouterData<&UasPreAuthenticationRouterData>>
for UnifiedAuthenticationServicePreAuthenticateRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &UnifiedAuthenticationServiceRouterData<&UasPreAuthenticationRouterData>,
) -> Result<Self, Self::Error> {
let authentication_id = item.router_data.authentication_id.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "authentication_id",
},
)?;
let authentication_info = item.router_data.request.authentication_info.clone();
let auth_type =
UnifiedAuthenticationServiceAuthType::try_from(&item.router_data.connector_auth_type)?;
Ok(Self {
authenticate_by: item.router_data.connector.clone(),
session_id: authentication_id.clone(),
source_authentication_id: authentication_id,
authentication_info,
service_details: Some(CtpServiceDetails {
service_session_ids: item.router_data.request.service_details.clone().map(
|service_details| ServiceSessionIds {
client_id: None,
service_id: None,
correlation_id: service_details
.service_session_ids
.clone()
.and_then(|service_session_ids| service_session_ids.correlation_id),
client_reference_id: None,
merchant_transaction_id: service_details
.service_session_ids
.clone()
.and_then(|service_session_ids| {
service_session_ids.merchant_transaction_id
}),
x_src_flow_id: service_details
.service_session_ids
.clone()
.and_then(|service_session_ids| service_session_ids.x_src_flow_id),
},
),
merchant_details: None,
}),
customer_details: None,
pmt_details: None,
auth_creds: auth_type,
acquirer_details: None,
billing_address: None,
transaction_details: Some(TransactionDetails {
amount: item.amount,
currency: item
.router_data
.request
.transaction_details
.clone()
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "transaction_details",
})?
.currency
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "currency",
})?,
date: None,
pan_source: None,
protection_type: None,
entry_mode: None,
transaction_type: None,
otp_value: None,
three_ds_data: None,
message_category: None,
}),
})
}
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum UnifiedAuthenticationServicePreAuthenticateStatus {
ACKSUCCESS,
ACKFAILURE,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct UnifiedAuthenticationServicePreAuthenticateResponse {
status: UnifiedAuthenticationServicePreAuthenticateStatus,
pub eligibility: Option<Eligibility>,
}
impl<F, T>
TryFrom<
ResponseRouterData<
F,
UnifiedAuthenticationServicePreAuthenticateResponse,
T,
UasAuthenticationResponseData,
>,
> for RouterData<F, T, UasAuthenticationResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
UnifiedAuthenticationServicePreAuthenticateResponse,
T,
UasAuthenticationResponseData,
>,
) -> Result<Self, Self::Error> {
let three_ds_eligibility_response = if let Some(Eligibility::ThreeDsEligibilityResponse {
three_ds_eligibility_response,
}) = item.response.eligibility
{
Some(three_ds_eligibility_response)
} else {
None
};
let max_acs_protocol_version = three_ds_eligibility_response
.as_ref()
.and_then(|response| response.get_max_acs_protocol_version_if_available());
let maximum_supported_3ds_version = max_acs_protocol_version
.as_ref()
.map(|acs_protocol_version| acs_protocol_version.version.clone());
let three_ds_method_data =
three_ds_eligibility_response
.as_ref()
.and_then(|three_ds_eligibility_response| {
three_ds_eligibility_response
.three_ds_method_data_form
.as_ref()
.and_then(|form| form.three_ds_method_data.clone())
});
let three_ds_method_url = max_acs_protocol_version
.and_then(|acs_protocol_version| acs_protocol_version.three_ds_method_url);
Ok(Self {
response: Ok(UasAuthenticationResponseData::PreAuthentication {
authentication_details: PreAuthenticationDetails {
threeds_server_transaction_id: three_ds_eligibility_response
.as_ref()
.map(|response| response.three_ds_server_trans_id.clone()),
maximum_supported_3ds_version: maximum_supported_3ds_version.clone(),
connector_authentication_id: three_ds_eligibility_response
.as_ref()
.map(|response| response.three_ds_server_trans_id.clone()),
three_ds_method_data,
three_ds_method_url,
message_version: maximum_supported_3ds_version,
connector_metadata: None,
directory_server_id: three_ds_eligibility_response
.as_ref()
.and_then(|response| response.directory_server_id.clone()),
scheme_id: three_ds_eligibility_response
.as_ref()
.and_then(|response| response.scheme_id.clone()),
},
}),
..item.data
})
}
}
#[derive(Debug, Serialize)]
pub struct UnifiedAuthenticationServicePostAuthenticateRequest {
pub authenticate_by: String,
pub source_authentication_id: common_utils::id_type::AuthenticationId,
pub auth_creds: ConnectorAuthType,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct UnifiedAuthenticationServicePostAuthenticateResponse {
pub authentication_details: AuthenticationDetails,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct AuthenticationDetails {
pub eci: Option<String>,
pub token_details: Option<UasTokenDetails>,
pub dynamic_data_details: Option<UasDynamicData>,
pub trans_status: Option<common_enums::TransactionStatus>,
pub raw_card_details: Option<UasRawCardDetails>,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct UasTokenDetails {
pub payment_token: cards::NetworkToken,
pub payment_account_reference: String,
pub token_expiration_month: Secret<String>,
pub token_expiration_year: Secret<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct UasRawCardDetails {
pub pan: cards::CardNumber,
pub expiration_month: Secret<String>,
pub expiration_year: Secret<String>,
pub card_security_code: Option<Secret<String>>,
pub payment_account_reference: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct UasDynamicData {
pub dynamic_data_value: Option<Secret<String>>,
pub dynamic_data_type: Option<String>,
pub ds_trans_id: Option<String>,
}
impl TryFrom<&UasPostAuthenticationRouterData>
for UnifiedAuthenticationServicePostAuthenticateRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &UasPostAuthenticationRouterData) -> Result<Self, Self::Error> {
Ok(Self {
authenticate_by: item.connector.clone(),
source_authentication_id: item.authentication_id.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "authentication_id",
},
)?,
auth_creds: item.connector_auth_type.clone(),
})
}
}
impl<F, T>
TryFrom<
ResponseRouterData<
F,
UnifiedAuthenticationServicePostAuthenticateResponse,
T,
UasAuthenticationResponseData,
>,
> for RouterData<F, T, UasAuthenticationResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
UnifiedAuthenticationServicePostAuthenticateResponse,
T,
UasAuthenticationResponseData,
>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(UasAuthenticationResponseData::PostAuthentication {
authentication_details: PostAuthenticationDetails {
eci: item.response.authentication_details.eci,
token_details: item.response.authentication_details.token_details.map(
|token_details| TokenDetails {
payment_token: token_details.payment_token,
payment_account_reference: token_details.payment_account_reference,
token_expiration_month: token_details.token_expiration_month,
token_expiration_year: token_details.token_expiration_year,
},
),
raw_card_details: item.response.authentication_details.raw_card_details.map(
|raw_card_details| RawCardDetails {
pan: raw_card_details.pan,
expiration_month: raw_card_details.expiration_month,
expiration_year: raw_card_details.expiration_year,
card_security_code: raw_card_details.card_security_code,
payment_account_reference: raw_card_details.payment_account_reference,
},
),
dynamic_data_details: item
.response
.authentication_details
.dynamic_data_details
.map(|dynamic_data| DynamicData {
dynamic_data_value: dynamic_data.dynamic_data_value,
dynamic_data_type: dynamic_data.dynamic_data_type,
ds_trans_id: dynamic_data.ds_trans_id,
}),
trans_status: item.response.authentication_details.trans_status,
challenge_cancel: None,
challenge_code_reason: None,
},
}),
..item.data
})
}
}
//TODO: Fill the struct with respective fields
#[derive(Default, Debug, Serialize, Deserialize, PartialEq, Clone)]
pub struct UnifiedAuthenticationServiceErrorResponse {
pub error: String,
}
impl TryFrom<&UnifiedAuthenticationServiceRouterData<&UasAuthenticationConfirmationRouterData>>
for UnifiedAuthenticationServiceAuthenticateConfirmationRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &UnifiedAuthenticationServiceRouterData<&UasAuthenticationConfirmationRouterData>,
) -> Result<Self, Self::Error> {
let authentication_id = item.router_data.authentication_id.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "authentication_id",
},
)?;
let auth_type =
UnifiedAuthenticationServiceAuthType::try_from(&item.router_data.connector_auth_type)?;
Ok(Self {
authenticate_by: item.router_data.connector.clone(),
auth_creds: auth_type,
source_authentication_id: authentication_id,
x_src_flow_id: item.router_data.request.x_src_flow_id.clone(),
transaction_amount: Some(item.amount),
transaction_currency: Some(item.router_data.request.transaction_currency),
checkout_event_type: item.router_data.request.checkout_event_type.clone(),
checkout_event_status: item.router_data.request.checkout_event_status.clone(),
confirmation_status: item.router_data.request.confirmation_status.clone(),
confirmation_reason: item.router_data.request.confirmation_reason.clone(),
confirmation_timestamp: item.router_data.request.confirmation_timestamp.clone(),
network_authorization_code: item.router_data.request.network_authorization_code.clone(),
network_transaction_identifier: item
.router_data
.request
.network_transaction_identifier
.clone(),
correlation_id: item.router_data.request.correlation_id.clone(),
merchant_transaction_id: item.router_data.request.merchant_transaction_id.clone(),
})
}
}
// ThreeDs request
impl TryFrom<&UasPreAuthenticationRouterData>
for UnifiedAuthenticationServicePreAuthenticateRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &UasPreAuthenticationRouterData) -> Result<Self, Self::Error> {
let auth_type = UnifiedAuthenticationServiceAuthType::try_from(&item.connector_auth_type)?;
let authentication_id =
item.authentication_id
.clone()
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "authentication_id",
})?;
let merchant_data = item.request.merchant_details.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "merchant_details",
},
)?;
let merchant_details = MerchantDetails {
merchant_id: merchant_data.merchant_id,
merchant_name: merchant_data.merchant_name,
merchant_category_code: merchant_data.merchant_category_code,
merchant_country_code: merchant_data.merchant_country_code.clone(),
endpoint_prefix: merchant_data.endpoint_prefix,
three_ds_requestor_url: merchant_data.three_ds_requestor_url,
three_ds_requestor_id: merchant_data.three_ds_requestor_id,
three_ds_requestor_name: merchant_data.three_ds_requestor_name,
configuration_id: None,
notification_url: merchant_data.notification_url,
};
let acquirer = Acquirer {
acquirer_bin: item.request.acquirer_bin.clone(),
acquirer_merchant_id: item.request.acquirer_merchant_id.clone(),
acquirer_country_code: merchant_data
.merchant_country_code
.map(|code| code.get_country_code()),
};
let service_details = Some(CtpServiceDetails {
service_session_ids: None,
merchant_details: Some(merchant_details),
});
let billing_address = item
.request
.billing_address
.clone()
.map(|address_wrap| Address {
city: address_wrap
.address
.clone()
.and_then(|address| address.city),
country: address_wrap
.address
.clone()
.and_then(|address| address.country),
line1: address_wrap
.address
.clone()
.and_then(|address| address.line1),
line2: address_wrap
.address
.clone()
.and_then(|address| address.line2),
line3: address_wrap
.address
.clone()
.and_then(|address| address.line3),
post_code: address_wrap.address.clone().and_then(|address| address.zip),
state: address_wrap.address.and_then(|address| address.state),
});
Ok(Self {
authenticate_by: item.connector.clone(),
session_id: authentication_id.clone(),
source_authentication_id: authentication_id,
authentication_info: None,
service_details,
customer_details: None,
pmt_details: item
.request
.payment_details
.clone()
.map(|details| PaymentDetails {
pan: details.pan,
digital_card_id: details.digital_card_id,
payment_data_type: details.payment_data_type,
encrypted_src_card_details: details.encrypted_src_card_details,
cardholder_name: details.cardholder_name,
card_token_number: details.card_token_number,
account_type: details.account_type,
card_expiry_month: details.card_expiry_month,
card_expiry_year: details.card_expiry_year,
card_cvc: details.card_cvc,
}),
auth_creds: auth_type,
transaction_details: None,
acquirer_details: Some(acquirer),
billing_address,
})
}
}
#[derive(Debug, Serialize, PartialEq)]
#[serde(tag = "auth_type")]
pub enum UnifiedAuthenticationServiceAuthType {
HeaderKey {
api_key: Secret<String>,
},
CertificateAuth {
certificate: Secret<String>,
private_key: Secret<String>,
},
SignatureKey {
api_key: Secret<String>,
key1: Secret<String>,
api_secret: Secret<String>,
},
NoKey,
}
impl TryFrom<&ConnectorAuthType> for UnifiedAuthenticationServiceAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::HeaderKey { api_key } => Ok(Self::HeaderKey {
api_key: api_key.clone(),
}),
ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} => Ok(Self::SignatureKey {
api_key: api_key.clone(),
key1: key1.clone(),
api_secret: api_secret.clone(),
}),
ConnectorAuthType::CertificateAuth {
certificate,
private_key,
} => Ok(Self::CertificateAuth {
certificate: certificate.clone(),
private_key: private_key.clone(),
}),
ConnectorAuthType::NoKey => Ok(Self::NoKey),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(tag = "eligibility")]
pub enum Eligibility {
None,
TokenEligibilityResponse {
token_eligibility_response: Box<TokenEligibilityResponse>,
},
ThreeDsEligibilityResponse {
three_ds_eligibility_response: Box<ThreeDsEligibilityResponse>,
},
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct TokenEligibilityResponse {
pub network_request_id: Option<String>,
pub network_client_id: Option<String>,
pub nonce: Option<String>,
pub payment_method_details: Option<PaymentMethodDetails>,
pub network_pan_enrollment_id: Option<String>,
pub ignore_00_field: Option<String>,
pub token_details: Option<TokenDetails>,
pub network_provisioned_token_id: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct PaymentMethodDetails {
pub ignore_01_field: String,
pub cvv2_printed_ind: String,
pub last4: String,
pub exp_date_printed_ind: String,
pub payment_account_reference: String,
pub exp_year: String,
pub exp_month: String,
pub verification_results: VerificationResults,
pub enabled_services: EnabledServices,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct VerificationResults {
pub address_verification_code: String,
pub cvv2_verification_code: String,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct EnabledServices {
pub merchant_presented_qr: String,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct ThreeDsEligibilityResponse {
pub three_ds_server_trans_id: String,
pub scheme_id: Option<String>,
pub acs_protocol_versions: Option<Vec<AcsProtocolVersion>>,
pub ds_protocol_versions: Option<Vec<String>>,
pub three_ds_method_data_form: Option<ThreeDsMethodDataForm>,
pub three_ds_method_data: Option<ThreeDsMethodData>,
pub error_details: Option<String>,
pub is_card_found_in_2x_ranges: bool,
pub directory_server_id: Option<String>,
}
impl ThreeDsEligibilityResponse {
pub fn get_max_acs_protocol_version_if_available(&self) -> Option<AcsProtocolVersion> {
let max_acs_version =
self.acs_protocol_versions
.as_ref()
.and_then(|acs_protocol_versions| {
acs_protocol_versions
.iter()
.max_by_key(|acs_protocol_versions| acs_protocol_versions.version.clone())
});
max_acs_version.cloned()
}
}
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct AcsProtocolVersion {
pub version: common_utils::types::SemanticVersion,
pub acs_info_ind: Vec<String>,
pub three_ds_method_url: Option<String>,
pub supported_msg_ext: Option<Vec<SupportedMsgExt>>,
}
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct SupportedMsgExt {
pub id: String,
pub version: String,
}
#[derive(Clone, Serialize, Deserialize, Debug, Default)]
pub struct ThreeDsMethodDataForm {
pub three_ds_method_data: Option<String>,
}
#[derive(Default, Clone, Serialize, Deserialize, Debug)]
pub struct ThreeDsMethodData {
pub three_ds_method_notification_url: String,
pub server_transaction_id: String,
}
#[derive(Serialize, Debug)]
pub struct UnifiedAuthenticationServiceAuthenticateRequest {
pub authenticate_by: String,
pub source_authentication_id: common_utils::id_type::AuthenticationId,
pub transaction_details: TransactionDetails,
pub device_details: DeviceDetails,
pub customer_details: Option<CustomerDetails>,
pub auth_creds: UnifiedAuthenticationServiceAuthType,
}
#[derive(Default, Debug, Serialize, PartialEq)]
pub struct ServiceDetails {
pub service_session_ids: Option<ServiceSessionIds>,
pub merchant_details: Option<MerchantDetails>,
}
#[derive(Serialize, Debug, Clone, Deserialize)]
#[serde(untagged)]
pub enum UnifiedAuthenticationServiceAuthenticateResponse {
Success(Box<ThreeDsResponseData>),
Failure(UnifiedAuthenticationServiceErrorResponse),
}
#[derive(Serialize, Debug, Clone, Deserialize)]
pub struct ThreeDsResponseData {
pub three_ds_auth_response: ThreeDsAuthDetails,
}
#[derive(Serialize, Debug, Clone, Deserialize)]
pub struct ThreeDsAuthDetails {
pub three_ds_server_trans_id: String,
pub acs_trans_id: String,
pub acs_reference_number: String,
pub acs_operator_id: Option<String>,
pub ds_reference_number: Option<String>,
pub ds_trans_id: String,
pub sdk_trans_id: Option<String>,
pub trans_status: common_enums::TransactionStatus,
| 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/xendit/transformers.rs | crates/hyperswitch_connectors/src/connectors/xendit/transformers.rs | use std::collections::HashMap;
use cards::CardNumber;
use common_enums::{enums, Currency};
use common_utils::{pii, request::Method, types::FloatMajorUnit};
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{ConnectorAuthType, ErrorResponse},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{
MandateReference, PaymentsResponseData, RedirectForm, RefundsResponseData,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsPreProcessingRouterData,
PaymentsSyncRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::{
consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE},
errors,
};
use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
types::{
PaymentsCaptureResponseRouterData, PaymentsPreprocessingResponseRouterData,
PaymentsResponseRouterData, PaymentsSyncResponseRouterData, RefundsResponseRouterData,
},
utils::{
get_unimplemented_payment_method_error_message, CardData, PaymentsAuthorizeRequestData,
PaymentsSyncRequestData, RouterData as OtherRouterData,
},
};
//TODO: Fill the struct with respective fields
pub struct XenditRouterData<T> {
pub amount: FloatMajorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc.
pub router_data: T,
}
#[derive(Serialize, Deserialize, Debug)]
pub enum PaymentMethodType {
CARD,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct ChannelProperties {
pub success_return_url: String,
pub failure_return_url: String,
pub skip_three_d_secure: bool,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(untagged)]
pub enum PaymentMethod {
Card(CardPaymentRequest),
}
#[derive(Serialize, Deserialize, Debug)]
pub struct CardPaymentRequest {
#[serde(rename = "type")]
pub payment_type: PaymentMethodType,
pub card: CardInfo,
pub reusability: TransactionType,
pub reference_id: Secret<String>,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct MandatePaymentRequest {
pub amount: FloatMajorUnit,
pub currency: Currency,
pub capture_method: String,
pub payment_method_id: Secret<String>,
pub channel_properties: ChannelProperties,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct XenditRedirectionResponse {
pub status: PaymentStatus,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct XenditPaymentsCaptureRequest {
pub capture_amount: FloatMajorUnit,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct XenditPaymentsRequest {
pub amount: FloatMajorUnit,
pub currency: Currency,
pub capture_method: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub payment_method: Option<PaymentMethod>,
#[serde(skip_serializing_if = "Option::is_none")]
pub payment_method_id: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub channel_properties: Option<ChannelProperties>,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct XenditSplitRoute {
#[serde(skip_serializing_if = "Option::is_none")]
pub flat_amount: Option<FloatMajorUnit>,
#[serde(skip_serializing_if = "Option::is_none")]
pub percent_amount: Option<i64>,
pub currency: Currency,
pub destination_account_id: String,
pub reference_id: String,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct XenditSplitRequest {
pub name: String,
pub description: String,
pub routes: Vec<XenditSplitRoute>,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct XenditSplitRequestData {
#[serde(flatten)]
pub split_data: XenditSplitRequest,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct XenditSplitResponse {
id: String,
name: String,
description: String,
routes: Vec<XenditSplitRoute>,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct CardInfo {
pub channel_properties: ChannelProperties,
pub card_information: CardInformation,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct CardInformation {
pub card_number: CardNumber,
pub expiry_month: Secret<String>,
pub expiry_year: Secret<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub cvv: Option<Secret<String>>,
pub cardholder_name: Secret<String>,
pub cardholder_email: pii::Email,
pub cardholder_phone_number: Secret<String>,
}
pub mod auth_headers {
pub const WITH_SPLIT_RULE: &str = "with-split-rule";
pub const FOR_USER_ID: &str = "for-user-id";
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum TransactionType {
OneTimeUse,
MultipleUse,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct XenditErrorResponse {
pub error_code: String,
pub message: String,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PaymentStatus {
Pending,
RequiresAction,
Failed,
Succeeded,
AwaitingCapture,
Verified,
}
#[derive(Debug, Deserialize, Serialize, Clone)]
#[serde(untagged)]
pub enum XenditResponse {
Payment(XenditPaymentResponse),
Webhook(XenditWebhookEvent),
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct XenditPaymentResponse {
pub id: String,
pub status: PaymentStatus,
pub actions: Option<Vec<Action>>,
pub payment_method: PaymentMethodInfo,
pub failure_code: Option<String>,
pub reference_id: Secret<String>,
pub amount: FloatMajorUnit,
pub currency: Currency,
}
fn map_payment_response_to_attempt_status(
response: XenditPaymentResponse,
is_auto_capture: bool,
) -> enums::AttemptStatus {
match response.status {
PaymentStatus::Failed => enums::AttemptStatus::Failure,
PaymentStatus::Succeeded | PaymentStatus::Verified => {
if is_auto_capture {
enums::AttemptStatus::Charged
} else {
enums::AttemptStatus::Authorized
}
}
PaymentStatus::Pending => enums::AttemptStatus::Pending,
PaymentStatus::RequiresAction => enums::AttemptStatus::AuthenticationPending,
PaymentStatus::AwaitingCapture => enums::AttemptStatus::Authorized,
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct XenditCaptureResponse {
pub id: String,
pub status: PaymentStatus,
pub actions: Option<Vec<Action>>,
pub payment_method: PaymentMethodInfo,
pub failure_code: Option<String>,
pub reference_id: Secret<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum MethodType {
Get,
Post,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Action {
pub method: MethodType,
pub url: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PaymentMethodInfo {
pub id: Secret<String>,
}
impl TryFrom<XenditRouterData<&PaymentsAuthorizeRouterData>> for XenditPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: XenditRouterData<&PaymentsAuthorizeRouterData>) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(card_data) => Ok(Self {
capture_method: match item.router_data.request.is_auto_capture()? {
true => "AUTOMATIC".to_string(),
false => "MANUAL".to_string(),
},
currency: item.router_data.request.currency,
amount: item.amount,
payment_method: Some(PaymentMethod::Card(CardPaymentRequest {
payment_type: PaymentMethodType::CARD,
reference_id: Secret::new(
item.router_data.connector_request_reference_id.clone(),
),
card: CardInfo {
channel_properties: ChannelProperties {
success_return_url: item.router_data.request.get_router_return_url()?,
failure_return_url: item.router_data.request.get_router_return_url()?,
skip_three_d_secure: !item.router_data.is_three_ds(),
},
card_information: CardInformation {
card_number: card_data.card_number.clone(),
expiry_month: card_data.card_exp_month.clone(),
expiry_year: card_data.get_expiry_year_4_digit(),
cvv: if card_data.card_cvc.clone().expose().is_empty() {
None
} else {
Some(card_data.card_cvc.clone())
},
cardholder_name: card_data
.get_cardholder_name()
.or(item.router_data.get_billing_full_name())?,
cardholder_email: item
.router_data
.get_billing_email()
.or(item.router_data.request.get_email())?,
cardholder_phone_number: item.router_data.get_billing_phone_number()?,
},
},
reusability: match item.router_data.request.is_mandate_payment() {
true => TransactionType::MultipleUse,
false => TransactionType::OneTimeUse,
},
})),
payment_method_id: None,
channel_properties: None,
}),
PaymentMethodData::MandatePayment => Ok(Self {
channel_properties: Some(ChannelProperties {
success_return_url: item.router_data.request.get_router_return_url()?,
failure_return_url: item.router_data.request.get_router_return_url()?,
skip_three_d_secure: true,
}),
capture_method: match item.router_data.request.is_auto_capture()? {
true => "AUTOMATIC".to_string(),
false => "MANUAL".to_string(),
},
currency: item.router_data.request.currency,
amount: item.amount,
payment_method_id: Some(Secret::new(
item.router_data.request.get_connector_mandate_id()?,
)),
payment_method: None,
}),
_ => Err(errors::ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("xendit"),
)
.into()),
}
}
}
impl TryFrom<XenditRouterData<&PaymentsCaptureRouterData>> for XenditPaymentsCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: XenditRouterData<&PaymentsCaptureRouterData>) -> Result<Self, Self::Error> {
Ok(Self {
capture_amount: item.amount,
})
}
}
impl TryFrom<PaymentsResponseRouterData<XenditPaymentResponse>> for PaymentsAuthorizeRouterData {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsResponseRouterData<XenditPaymentResponse>,
) -> Result<Self, Self::Error> {
let status = map_payment_response_to_attempt_status(
item.response.clone(),
item.data.request.is_auto_capture()?,
);
let response = if status == enums::AttemptStatus::Failure {
Err(ErrorResponse {
code: item
.response
.failure_code
.clone()
.unwrap_or_else(|| NO_ERROR_CODE.to_string()),
message: item
.response
.failure_code
.clone()
.unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()),
reason: Some(
item.response
.failure_code
.unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()),
),
attempt_status: None,
connector_transaction_id: Some(item.response.id.clone()),
status_code: item.http_code,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
let charges = match item.data.request.split_payments.as_ref() {
Some(common_types::payments::SplitPaymentsRequest::XenditSplitPayment(
common_types::payments::XenditSplitRequest::MultipleSplits(_),
)) => item
.data
.response
.as_ref()
.ok()
.and_then(|response| match response {
PaymentsResponseData::TransactionResponse { charges, .. } => {
charges.clone()
}
_ => None,
}),
Some(common_types::payments::SplitPaymentsRequest::XenditSplitPayment(
common_types::payments::XenditSplitRequest::SingleSplit(ref split_data),
)) => {
let charges = common_types::domain::XenditSplitSubMerchantData {
for_user_id: split_data.for_user_id.clone(),
};
Some(
common_types::payments::ConnectorChargeResponseData::XenditSplitPayment(
common_types::payments::XenditChargeResponseData::SingleSplit(charges),
),
)
}
_ => None,
};
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: match item.response.actions {
Some(actions) if !actions.is_empty() => {
actions.first().map_or(Box::new(None), |single_action| {
Box::new(Some(RedirectForm::Form {
endpoint: single_action.url.clone(),
method: match single_action.method {
MethodType::Get => Method::Get,
MethodType::Post => Method::Post,
},
form_fields: HashMap::new(),
}))
})
}
_ => Box::new(None),
},
mandate_reference: match item.data.request.is_mandate_payment() {
true => Box::new(Some(MandateReference {
connector_mandate_id: Some(item.response.payment_method.id.expose()),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
})),
false => Box::new(None),
},
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(
item.response.reference_id.peek().to_string(),
),
incremental_authorization_allowed: None,
charges,
})
};
Ok(Self {
status,
response,
..item.data
})
}
}
impl TryFrom<PaymentsCaptureResponseRouterData<XenditCaptureResponse>>
for PaymentsCaptureRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsCaptureResponseRouterData<XenditCaptureResponse>,
) -> Result<Self, Self::Error> {
let status = match item.response.status {
PaymentStatus::Failed => enums::AttemptStatus::Failure,
PaymentStatus::Succeeded | PaymentStatus::Verified => enums::AttemptStatus::Charged,
PaymentStatus::Pending => enums::AttemptStatus::Pending,
PaymentStatus::RequiresAction => enums::AttemptStatus::AuthenticationPending,
PaymentStatus::AwaitingCapture => enums::AttemptStatus::Authorized,
};
let response = if status == enums::AttemptStatus::Failure {
Err(ErrorResponse {
code: item
.response
.failure_code
.clone()
.unwrap_or_else(|| NO_ERROR_CODE.to_string()),
message: item
.response
.failure_code
.clone()
.unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()),
reason: Some(
item.response
.failure_code
.unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()),
),
attempt_status: None,
connector_transaction_id: None,
status_code: item.http_code,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(
item.response.reference_id.peek().to_string(),
),
incremental_authorization_allowed: None,
charges: None,
})
};
Ok(Self {
status,
response,
..item.data
})
}
}
impl TryFrom<PaymentsPreprocessingResponseRouterData<XenditSplitResponse>>
for PaymentsPreProcessingRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsPreprocessingResponseRouterData<XenditSplitResponse>,
) -> Result<Self, Self::Error> {
let for_user_id = match item.data.request.split_payments {
Some(common_types::payments::SplitPaymentsRequest::XenditSplitPayment(
common_types::payments::XenditSplitRequest::MultipleSplits(ref split_data),
)) => split_data.for_user_id.clone(),
_ => None,
};
let routes: Vec<common_types::payments::XenditSplitRoute> = item
.response
.routes
.iter()
.map(|route| {
let required_conversion_type = common_utils::types::FloatMajorUnitForConnector;
route
.flat_amount
.map(|amount| {
common_utils::types::AmountConvertor::convert_back(
&required_conversion_type,
amount,
item.data.request.currency.unwrap_or(Currency::USD),
)
.map_err(|_| {
errors::ConnectorError::RequestEncodingFailedWithReason(
"Failed to convert the amount into a major unit".to_owned(),
)
})
})
.transpose()
.map(|flat_amount| common_types::payments::XenditSplitRoute {
flat_amount,
percent_amount: route.percent_amount,
currency: route.currency,
destination_account_id: route.destination_account_id.clone(),
reference_id: route.reference_id.clone(),
})
})
.collect::<Result<Vec<_>, _>>()?;
let charges = common_types::payments::XenditMultipleSplitResponse {
split_rule_id: item.response.id,
for_user_id,
name: item.response.name,
description: item.response.description,
routes,
};
let response = PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: Some(
common_types::payments::ConnectorChargeResponseData::XenditSplitPayment(
common_types::payments::XenditChargeResponseData::MultipleSplits(charges),
),
),
};
Ok(Self {
response: Ok(response),
..item.data
})
}
}
impl TryFrom<PaymentsSyncResponseRouterData<XenditResponse>> for PaymentsSyncRouterData {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: PaymentsSyncResponseRouterData<XenditResponse>) -> Result<Self, Self::Error> {
match item.response {
XenditResponse::Payment(payment_response) => {
let status = map_payment_response_to_attempt_status(
payment_response.clone(),
item.data.request.is_auto_capture()?,
);
let response = if status == enums::AttemptStatus::Failure {
Err(ErrorResponse {
code: payment_response
.failure_code
.clone()
.unwrap_or_else(|| NO_ERROR_CODE.to_string()),
message: payment_response
.failure_code
.clone()
.unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()),
reason: Some(
payment_response
.failure_code
.unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()),
),
attempt_status: None,
connector_transaction_id: Some(payment_response.id.clone()),
status_code: item.http_code,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
})
};
Ok(Self {
status,
response,
..item.data
})
}
XenditResponse::Webhook(webhook_event) => {
let status = match webhook_event.event {
XenditEventType::PaymentSucceeded | XenditEventType::CaptureSucceeded => {
enums::AttemptStatus::Charged
}
XenditEventType::PaymentAwaitingCapture => enums::AttemptStatus::Authorized,
XenditEventType::PaymentFailed | XenditEventType::CaptureFailed => {
enums::AttemptStatus::Failure
}
};
Ok(Self {
status,
..item.data
})
}
}
}
}
impl<T> From<(FloatMajorUnit, T)> for XenditRouterData<T> {
fn from((amount, item): (FloatMajorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
pub struct XenditAuthType {
pub(super) api_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for XenditAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
api_key: api_key.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
impl TryFrom<&PaymentsPreProcessingRouterData> for XenditSplitRequestData {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsPreProcessingRouterData) -> Result<Self, Self::Error> {
if let Some(common_types::payments::SplitPaymentsRequest::XenditSplitPayment(
common_types::payments::XenditSplitRequest::MultipleSplits(ref split_data),
)) = item.request.split_payments.clone()
{
let routes: Vec<XenditSplitRoute> = split_data
.routes
.iter()
.map(|route| {
let required_conversion_type = common_utils::types::FloatMajorUnitForConnector;
route
.flat_amount
.map(|amount| {
common_utils::types::AmountConvertor::convert(
&required_conversion_type,
amount,
item.request.currency.unwrap_or(Currency::USD),
)
.map_err(|_| {
errors::ConnectorError::RequestEncodingFailedWithReason(
"Failed to convert the amount into a major unit".to_owned(),
)
})
})
.transpose()
.map(|flat_amount| XenditSplitRoute {
flat_amount,
percent_amount: route.percent_amount,
currency: route.currency,
destination_account_id: route.destination_account_id.clone(),
reference_id: route.reference_id.clone(),
})
})
.collect::<Result<Vec<_>, _>>()?;
let split_data = XenditSplitRequest {
name: split_data.name.clone(),
description: split_data.description.clone(),
routes,
};
Ok(Self { split_data })
} else {
Err(errors::ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("Xendit"),
)
.into())
}
}
}
//TODO: Fill the struct with respective fields
// REFUND :
// Type definition for RefundRequest
#[derive(Default, Debug, Serialize)]
pub struct XenditRefundRequest {
pub amount: FloatMajorUnit,
pub payment_request_id: String,
pub reason: String,
}
impl<F> TryFrom<&XenditRouterData<&RefundsRouterData<F>>> for XenditRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &XenditRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.amount.to_owned(),
payment_request_id: item.router_data.request.connector_transaction_id.clone(),
reason: "REQUESTED_BY_CUSTOMER".to_string(),
})
}
}
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum RefundStatus {
RequiresAction,
Succeeded,
Failed,
Pending,
Cancelled,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Succeeded => Self::Success,
RefundStatus::Failed | RefundStatus::Cancelled => Self::Failure,
RefundStatus::Pending | RefundStatus::RequiresAction => Self::Pending,
}
}
}
//TODO: Fill the struct with respective fields
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RefundResponse {
pub id: String,
pub status: RefundStatus,
pub amount: FloatMajorUnit,
pub currency: String,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id,
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
#[derive(Default, Debug, Serialize, Deserialize)]
pub struct XenditMetadata {
pub for_user_id: String,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct XenditWebhookEvent {
pub event: XenditEventType,
pub data: EventDetails,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct EventDetails {
pub id: String,
pub payment_request_id: Option<String>,
pub amount: FloatMajorUnit,
pub currency: String,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub enum XenditEventType {
#[serde(rename = "payment.succeeded")]
PaymentSucceeded,
#[serde(rename = "payment.awaiting_capture")]
PaymentAwaitingCapture,
#[serde(rename = "payment.failed")]
PaymentFailed,
#[serde(rename = "capture.succeeded")]
CaptureSucceeded,
#[serde(rename = "capture.failed")]
CaptureFailed,
}
| 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/blackhawknetwork/transformers.rs | crates/hyperswitch_connectors/src/connectors/blackhawknetwork/transformers.rs | use common_enums::{enums, Currency};
use common_utils::types::{MinorUnit, StringMajorUnit};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{GiftCardData, PaymentMethodData},
router_data::{
AccessToken, ConnectorAuthType, ErrorResponse, PaymentMethodBalance, RouterData,
},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, PreprocessingResponseId, RefundsResponseData},
types::{PaymentsAuthorizeRouterData, PaymentsPreProcessingRouterData, RefundsRouterData},
};
use hyperswitch_interfaces::{consts::NO_ERROR_MESSAGE, errors};
use masking::Secret;
use serde::{Deserialize, Serialize};
use crate::types::{
PaymentsPreprocessingResponseRouterData, RefundsResponseRouterData, ResponseRouterData,
};
pub struct BlackhawknetworkRouterData<T> {
pub amount: StringMajorUnit,
pub router_data: T,
}
impl<T> From<(StringMajorUnit, T)> for BlackhawknetworkRouterData<T> {
fn from((amount, item): (StringMajorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
#[derive(Debug, Clone)]
pub struct BlackhawknetworkAuthType {
pub(super) client_id: Secret<String>,
pub(super) client_secret: Secret<String>,
pub(super) product_line_id: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for BlackhawknetworkAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} => Ok(Self {
client_id: api_key.clone(),
client_secret: api_secret.clone(),
product_line_id: key1.clone(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType)
.attach_printable("Unsupported authentication type for Blackhawk Network"),
}
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct BlackhawknetworkAccessTokenRequest {
pub grant_type: String,
pub client_id: Secret<String>,
pub client_secret: Secret<String>,
pub scope: String,
}
impl<F, T> TryFrom<ResponseRouterData<F, BlackhawknetworkTokenResponse, T, AccessToken>>
for RouterData<F, T, AccessToken>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, BlackhawknetworkTokenResponse, T, AccessToken>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(AccessToken {
token: item.response.access_token,
expires: item.response.expires_in,
}),
..item.data
})
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BlackhawknetworkVerifyAccountRequest {
pub account_number: Secret<String>,
pub product_line_id: Secret<String>,
pub account_type: AccountType,
#[serde(skip_serializing_if = "Option::is_none")]
pub pin: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub cvv2: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub expiration_date: Option<Secret<String>>,
}
impl TryFrom<&PaymentsPreProcessingRouterData> for BlackhawknetworkVerifyAccountRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsPreProcessingRouterData) -> Result<Self, Self::Error> {
let auth = BlackhawknetworkAuthType::try_from(&item.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let gift_card_data = match &item.request.payment_method_data {
Some(PaymentMethodData::GiftCard(gc)) => match gc.as_ref() {
GiftCardData::BhnCardNetwork(data) => data,
_ => {
return Err(errors::ConnectorError::FlowNotSupported {
flow: "Balance".to_string(),
connector: "BlackHawkNetwork".to_string(),
}
.into())
}
},
_ => {
return Err(errors::ConnectorError::FlowNotSupported {
flow: "Balance".to_string(),
connector: "BlackHawkNetwork".to_string(),
}
.into())
}
};
Ok(Self {
account_number: gift_card_data.account_number.clone(),
product_line_id: auth.product_line_id,
account_type: AccountType::GiftCard,
pin: gift_card_data.pin.clone(),
cvv2: gift_card_data.cvv2.clone(),
expiration_date: gift_card_data.expiration_date.clone().map(Secret::new),
})
}
}
impl TryFrom<PaymentsPreprocessingResponseRouterData<BlackhawknetworkVerifyAccountResponse>>
for PaymentsPreProcessingRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsPreprocessingResponseRouterData<BlackhawknetworkVerifyAccountResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(PaymentsResponseData::PreProcessingResponse {
pre_processing_id: PreprocessingResponseId::PreProcessingId(
item.response.account.entity_id,
),
connector_metadata: None,
session_token: None,
connector_response_reference_id: None,
}),
payment_method_balance: Some(PaymentMethodBalance {
currency: item.response.account.currency,
amount: item.response.account.balance,
}),
..item.data
})
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct BlackhawknetworkTokenResponse {
pub access_token: Secret<String>,
pub expires_in: i64,
}
#[derive(Serialize, Debug)]
pub struct BlackhawknetworkPaymentsRequest {
pub account_id: String,
pub amount: StringMajorUnit,
pub currency: Currency,
}
impl TryFrom<&BlackhawknetworkRouterData<&PaymentsAuthorizeRouterData>>
for BlackhawknetworkPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &BlackhawknetworkRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match &item.router_data.request.payment_method_data {
PaymentMethodData::GiftCard(_gift_card) => {
let account_id = item
.router_data
.preprocessing_id
.to_owned()
.ok_or_else(|| {
errors::ConnectorError::MissingConnectorRelatedTransactionID {
id: "entity_id".to_string(),
}
})?;
Ok(Self {
account_id,
amount: item.amount.clone(),
currency: item.router_data.request.currency,
})
}
_ => Err(error_stack::Report::new(
errors::ConnectorError::NotImplemented("Non-gift card payment method".to_string()),
)),
}
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum BlackhawknetworkRedeemResponse {
Success(BlackhawknetworkPaymentsResponse),
Error(BlackhawknetworkErrorResponse),
}
#[derive(Debug, Deserialize, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BlackhawknetworkPaymentsResponse {
pub id: String,
#[serde(rename = "transactionStatus")]
pub status: BlackhawknetworkAttemptStatus,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum BlackhawknetworkAttemptStatus {
Approved,
Declined,
Pending,
}
impl<F, T> TryFrom<ResponseRouterData<F, BlackhawknetworkRedeemResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, BlackhawknetworkRedeemResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
match item.response {
BlackhawknetworkRedeemResponse::Success(response) => Ok(Self {
status: match response.status {
BlackhawknetworkAttemptStatus::Approved => enums::AttemptStatus::Charged,
BlackhawknetworkAttemptStatus::Declined => enums::AttemptStatus::Failure,
BlackhawknetworkAttemptStatus::Pending => enums::AttemptStatus::Pending,
},
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(response.id),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
}),
BlackhawknetworkRedeemResponse::Error(error_response) => Ok(Self {
response: Err(ErrorResponse {
status_code: item.http_code,
code: error_response.error.clone(),
message: error_response
.error_description
.clone()
.unwrap_or(NO_ERROR_MESSAGE.to_string()),
reason: error_response.error_description,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
}),
}
}
}
#[derive(Default, Debug, Serialize)]
pub struct BlackhawknetworkRefundRequest {
pub amount: StringMajorUnit,
}
impl<F> TryFrom<&BlackhawknetworkRouterData<&RefundsRouterData<F>>>
for BlackhawknetworkRefundRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &BlackhawknetworkRouterData<&RefundsRouterData<F>>,
) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.amount.to_owned(),
})
}
}
#[allow(dead_code)]
#[derive(Debug, Copy, Serialize, Default, Deserialize, Clone)]
pub enum RefundStatus {
Succeeded,
Failed,
#[default]
Processing,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Succeeded => Self::Success,
RefundStatus::Failed => Self::Failure,
RefundStatus::Processing => Self::Pending,
//TODO: Review mapping
}
}
}
//TODO: Fill the struct with respective fields
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct RefundResponse {
id: String,
status: RefundStatus,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
#[derive(Debug, Serialize, Deserialize, Clone, Copy)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum AccountType {
CreditCard,
GiftCard,
LoyaltyCard,
PhoneCard,
}
#[derive(Debug, Deserialize, Serialize, Clone)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum AccountStatus {
New,
Activated,
Closed,
}
impl From<AccountStatus> for common_enums::AttemptStatus {
fn from(item: AccountStatus) -> Self {
match item {
AccountStatus::New | AccountStatus::Activated => Self::Pending,
AccountStatus::Closed => Self::Failure,
}
}
}
#[derive(Debug, Deserialize, Serialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct AccountInformation {
pub entity_id: String,
pub balance: MinorUnit,
pub currency: Currency,
pub status: AccountStatus,
}
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct BlackhawknetworkVerifyAccountResponse {
account: AccountInformation,
}
#[derive(Debug, Deserialize, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BlackhawknetworkErrorResponse {
pub error: String,
pub error_description: Option<String>,
}
| 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/opennode/transformers.rs | crates/hyperswitch_connectors/src/connectors/opennode/transformers.rs | use std::collections::HashMap;
use common_enums::{enums, AttemptStatus};
use common_utils::{request::Method, types::MinorUnit};
use hyperswitch_domain_models::{
router_data::{ConnectorAuthType, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
types::{PaymentsAuthorizeRouterData, RefundsRouterData},
};
use hyperswitch_interfaces::errors;
use masking::Secret;
use serde::{Deserialize, Serialize};
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{PaymentsAuthorizeRequestData, RouterData as OtherRouterData},
};
#[derive(Debug, Serialize)]
pub struct OpennodeRouterData<T> {
pub amount: MinorUnit,
pub router_data: T,
}
impl<T> TryFrom<(MinorUnit, T)> for OpennodeRouterData<T> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from((amount, router_data): (MinorUnit, T)) -> Result<Self, Self::Error> {
Ok(Self {
amount,
router_data,
})
}
}
//TODO: Fill the struct with respective fields
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct OpennodePaymentsRequest {
amount: MinorUnit,
currency: String,
description: String,
auto_settle: bool,
success_url: String,
callback_url: String,
order_id: String,
}
impl TryFrom<&OpennodeRouterData<&PaymentsAuthorizeRouterData>> for OpennodePaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &OpennodeRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
get_crypto_specific_payment_data(item)
}
}
//TODO: Fill the struct with respective fields
// Auth Struct
pub struct OpennodeAuthType {
pub(super) api_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for OpennodeAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
api_key: api_key.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
// PaymentsResponse
//TODO: Append the remaining status flags
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum OpennodePaymentStatus {
Unpaid,
Paid,
Expired,
#[default]
Processing,
Underpaid,
Refunded,
#[serde(other)]
Unknown,
}
impl From<OpennodePaymentStatus> for AttemptStatus {
fn from(item: OpennodePaymentStatus) -> Self {
match item {
OpennodePaymentStatus::Unpaid => Self::AuthenticationPending,
OpennodePaymentStatus::Paid => Self::Charged,
OpennodePaymentStatus::Expired => Self::Failure,
OpennodePaymentStatus::Underpaid => Self::Unresolved,
_ => Self::Pending,
}
}
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct OpennodePaymentsResponseData {
id: String,
hosted_checkout_url: String,
status: OpennodePaymentStatus,
order_id: Option<String>,
}
//TODO: Fill the struct with respective fields
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct OpennodePaymentsResponse {
data: OpennodePaymentsResponseData,
}
impl<F, T> TryFrom<ResponseRouterData<F, OpennodePaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, OpennodePaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let form_fields = HashMap::new();
let redirection_data = RedirectForm::Form {
endpoint: item.response.data.hosted_checkout_url.to_string(),
method: Method::Get,
form_fields,
};
let connector_id = ResponseId::ConnectorTransactionId(item.response.data.id);
let attempt_status = item.response.data.status;
let response_data = if attempt_status != OpennodePaymentStatus::Underpaid {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: connector_id,
redirection_data: Box::new(Some(redirection_data)),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: item.response.data.order_id,
incremental_authorization_allowed: None,
charges: None,
})
} else {
Ok(PaymentsResponseData::TransactionUnresolvedResponse {
resource_id: connector_id,
reason: Some(api_models::enums::UnresolvedResponseReason {
code: "UNDERPAID".to_string(),
message:
"Please check the transaction in opennode dashboard and resolve manually"
.to_string(),
}),
connector_response_reference_id: item.response.data.order_id,
})
};
Ok(Self {
status: AttemptStatus::from(attempt_status),
response: response_data,
..item.data
})
}
}
//TODO: Fill the struct with respective fields
// REFUND :
// Type definition for RefundRequest
#[derive(Default, Debug, Serialize)]
pub struct OpennodeRefundRequest {
pub amount: i64,
}
impl<F> TryFrom<&OpennodeRouterData<&RefundsRouterData<F>>> for OpennodeRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &OpennodeRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.router_data.request.refund_amount,
})
}
}
// Type definition for Refund Response
#[allow(dead_code)]
#[derive(Debug, Serialize, Default, Deserialize, Clone)]
pub enum RefundStatus {
Refunded,
#[default]
Processing,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Refunded => Self::Success,
RefundStatus::Processing => Self::Pending,
}
}
}
//TODO: Fill the struct with respective fields
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct RefundResponse {
id: String,
status: RefundStatus,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
//TODO: Fill the struct with respective fields
#[derive(Debug, Deserialize, Serialize)]
pub struct OpennodeErrorResponse {
pub message: String,
}
fn get_crypto_specific_payment_data(
item: &OpennodeRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<OpennodePaymentsRequest, error_stack::Report<errors::ConnectorError>> {
let amount = item.amount;
let currency = item.router_data.request.currency.to_string();
let description = item.router_data.get_description()?;
let auto_settle = true;
let success_url = item.router_data.request.get_router_return_url()?;
let callback_url = item.router_data.request.get_webhook_url()?;
let order_id = item.router_data.connector_request_reference_id.clone();
Ok(OpennodePaymentsRequest {
amount,
currency,
description,
auto_settle,
success_url,
callback_url,
order_id,
})
}
#[derive(Debug, Serialize, Deserialize)]
pub struct OpennodeWebhookDetails {
pub id: String,
pub callback_url: String,
pub success_url: String,
pub status: OpennodePaymentStatus,
pub payment_method: String,
pub missing_amt: String,
pub order_id: String,
pub description: String,
pub price: String,
pub fee: String,
pub auto_settle: String,
pub fiat_value: String,
pub net_fiat_value: String,
pub overpaid_by: String,
pub hashed_order: String,
}
| 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/itaubank/transformers.rs | crates/hyperswitch_connectors/src/connectors/itaubank/transformers.rs | use api_models::payments::QrCodeInformation;
use common_enums::enums;
use common_utils::{errors::CustomResult, ext_traits::Encode, types::StringMajorUnit};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{BankTransferData, PaymentMethodData},
router_data::{AccessToken, ConnectorAuthType, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RefundsResponseData},
types,
};
use hyperswitch_interfaces::errors;
use masking::Secret;
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
use url::Url;
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{get_timestamp_in_milliseconds, QrImage, RouterData as _},
};
pub struct ItaubankRouterData<T> {
pub amount: StringMajorUnit,
pub router_data: T,
}
impl<T> From<(StringMajorUnit, T)> for ItaubankRouterData<T> {
fn from((amount, item): (StringMajorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
#[derive(Default, Debug, Serialize)]
pub struct ItaubankPaymentsRequest {
valor: PixPaymentValue, // amount
chave: Secret<String>, // pix-key
devedor: ItaubankDebtor, // debtor
}
#[derive(Default, Debug, Serialize)]
pub struct PixPaymentValue {
original: StringMajorUnit,
}
#[derive(Default, Debug, Serialize)]
pub struct ItaubankDebtor {
#[serde(skip_serializing_if = "Option::is_none")]
cpf: Option<Secret<String>>, // CPF is a Brazilian tax identification number
#[serde(skip_serializing_if = "Option::is_none")]
cnpj: Option<Secret<String>>, // CNPJ is a Brazilian company tax identification number
#[serde(skip_serializing_if = "Option::is_none")]
nome: Option<Secret<String>>, // name of the debtor
}
impl TryFrom<&ItaubankRouterData<&types::PaymentsAuthorizeRouterData>> for ItaubankPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &ItaubankRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::BankTransfer(bank_transfer_data) => {
match *bank_transfer_data {
BankTransferData::Pix {
pix_key, cpf, cnpj, ..
} => {
let nome = item.router_data.get_optional_billing_full_name();
// cpf and cnpj are mutually exclusive
let devedor = match (cnpj, cpf) {
(Some(cnpj), _) => ItaubankDebtor {
cpf: None,
cnpj: Some(cnpj),
nome,
},
(None, Some(cpf)) => ItaubankDebtor {
cpf: Some(cpf),
cnpj: None,
nome,
},
_ => Err(errors::ConnectorError::MissingRequiredField {
field_name: "cpf and cnpj both missing in payment_method_data",
})?,
};
Ok(Self {
valor: PixPaymentValue {
original: item.amount.to_owned(),
},
chave: pix_key.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "pix_key",
})?,
devedor,
})
}
BankTransferData::AchBankTransfer {}
| BankTransferData::SepaBankTransfer {}
| BankTransferData::BacsBankTransfer {}
| BankTransferData::MultibancoBankTransfer {}
| BankTransferData::PermataBankTransfer {}
| BankTransferData::BcaBankTransfer {}
| BankTransferData::BniVaBankTransfer {}
| BankTransferData::BriVaBankTransfer {}
| BankTransferData::CimbVaBankTransfer {}
| BankTransferData::DanamonVaBankTransfer {}
| BankTransferData::MandiriVaBankTransfer {}
| BankTransferData::Pse {}
| BankTransferData::InstantBankTransfer {}
| BankTransferData::InstantBankTransferFinland {}
| BankTransferData::InstantBankTransferPoland {}
| BankTransferData::IndonesianBankTransfer { .. }
| BankTransferData::LocalBankTransfer { .. } => {
Err(errors::ConnectorError::NotImplemented(
"Selected payment method through itaubank".to_string(),
)
.into())
}
}
}
PaymentMethodData::Card(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Wallet(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
"Selected payment method through itaubank".to_string(),
)
.into())
}
}
}
}
pub struct ItaubankAuthType {
pub(super) client_id: Secret<String>,
pub(super) client_secret: Secret<String>,
pub(super) certificate: Option<Secret<String>>,
pub(super) certificate_key: Option<Secret<String>>,
}
impl TryFrom<&ConnectorAuthType> for ItaubankAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::MultiAuthKey {
api_key,
key1,
api_secret,
key2,
} => Ok(Self {
client_secret: api_key.to_owned(),
client_id: key1.to_owned(),
certificate: Some(api_secret.to_owned()),
certificate_key: Some(key2.to_owned()),
}),
ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
client_secret: api_key.to_owned(),
client_id: key1.to_owned(),
certificate: None,
certificate_key: None,
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Debug, Serialize)]
pub struct ItaubankAuthRequest {
client_id: Secret<String>,
client_secret: Secret<String>,
grant_type: ItaubankGrantType,
}
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ItaubankGrantType {
ClientCredentials,
}
impl TryFrom<&types::RefreshTokenRouterData> for ItaubankAuthRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::RefreshTokenRouterData) -> Result<Self, Self::Error> {
let auth_details = ItaubankAuthType::try_from(&item.connector_auth_type)?;
Ok(Self {
client_id: auth_details.client_id,
client_secret: auth_details.client_secret,
grant_type: ItaubankGrantType::ClientCredentials,
})
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct ItaubankUpdateTokenResponse {
access_token: Secret<String>,
expires_in: i64,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ItaubankTokenErrorResponse {
pub status: i64,
pub title: Option<String>,
pub detail: Option<String>,
pub user_message: Option<String>,
}
impl<F, T> TryFrom<ResponseRouterData<F, ItaubankUpdateTokenResponse, T, AccessToken>>
for RouterData<F, T, AccessToken>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, ItaubankUpdateTokenResponse, T, AccessToken>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(AccessToken {
token: item.response.access_token,
expires: item.response.expires_in,
}),
..item.data
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum ItaubankPaymentStatus {
Ativa, // Active
Concluida, // Completed
RemovidaPeloPsp, // Removed by PSP
RemovidaPeloUsuarioRecebedor, // Removed by receiving User
}
impl From<ItaubankPaymentStatus> for enums::AttemptStatus {
fn from(item: ItaubankPaymentStatus) -> Self {
match item {
ItaubankPaymentStatus::Ativa => Self::AuthenticationPending,
ItaubankPaymentStatus::Concluida => Self::Charged,
ItaubankPaymentStatus::RemovidaPeloPsp
| ItaubankPaymentStatus::RemovidaPeloUsuarioRecebedor => Self::Failure,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ItaubankPaymentsResponse {
status: ItaubankPaymentStatus,
calendario: ItaubankPixExpireTime,
txid: String,
#[serde(rename = "pixCopiaECola")]
pix_qr_value: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ItaubankPixExpireTime {
#[serde(with = "common_utils::custom_serde::iso8601")]
criacao: PrimitiveDateTime,
expiracao: i64,
}
impl<F, T> TryFrom<ResponseRouterData<F, ItaubankPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, ItaubankPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let connector_metadata = get_qr_code_data(&item.response)?;
Ok(Self {
status: enums::AttemptStatus::from(item.response.status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.txid.to_owned()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata,
network_txn_id: None,
connector_response_reference_id: Some(item.response.txid),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
fn get_qr_code_data(
response: &ItaubankPaymentsResponse,
) -> CustomResult<Option<serde_json::Value>, errors::ConnectorError> {
let creation_time = get_timestamp_in_milliseconds(&response.calendario.criacao);
// convert expiration to milliseconds and add to creation time
let expiration_time = creation_time + (response.calendario.expiracao * 1000);
let image_data = QrImage::new_from_data(response.pix_qr_value.clone())
.change_context(errors::ConnectorError::ResponseHandlingFailed)?;
let image_data_url = Url::parse(image_data.data.clone().as_str())
.change_context(errors::ConnectorError::ResponseHandlingFailed)?;
let qr_code_info = QrCodeInformation::QrDataUrl {
image_data_url,
display_to_timestamp: Some(expiration_time),
};
Some(qr_code_info.encode_to_value())
.transpose()
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ItaubankPaymentsSyncResponse {
status: ItaubankPaymentStatus,
txid: String,
pix: Vec<ItaubankPixResponse>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ItaubankPixResponse {
#[serde(rename = "endToEndId")]
pix_id: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ItaubankMetaData {
pub pix_id: Option<String>,
}
impl<F, T> TryFrom<ResponseRouterData<F, ItaubankPaymentsSyncResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, ItaubankPaymentsSyncResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let pix_data = item
.response
.pix
.first()
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "pix_id",
})?
.to_owned();
let connector_metadata = Some(serde_json::json!(ItaubankMetaData {
pix_id: pix_data.pix_id
}));
Ok(Self {
status: enums::AttemptStatus::from(item.response.status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.txid.to_owned()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata,
network_txn_id: None,
connector_response_reference_id: Some(item.response.txid),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Default, Debug, Serialize)]
pub struct ItaubankRefundRequest {
pub valor: StringMajorUnit, // refund_amount
}
impl<F> TryFrom<&ItaubankRouterData<&types::RefundsRouterData<F>>> for ItaubankRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &ItaubankRouterData<&types::RefundsRouterData<F>>,
) -> Result<Self, Self::Error> {
Ok(Self {
valor: item.amount.to_owned(),
})
}
}
#[allow(dead_code)]
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum RefundStatus {
EmProcessamento, // Processing
Devolvido, // Returned
NaoRealizado, // Unrealized
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Devolvido => Self::Success,
RefundStatus::NaoRealizado => Self::Failure,
RefundStatus::EmProcessamento => Self::Pending,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RefundResponse {
rtr_id: String,
status: RefundStatus,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>>
for types::RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.rtr_id,
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for types::RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.rtr_id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct ItaubankErrorResponse {
pub error: ItaubankErrorBody,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct ItaubankErrorBody {
pub status: u16,
pub title: Option<String>,
pub detail: Option<String>,
pub violacoes: Option<Vec<Violations>>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Violations {
pub razao: String,
pub propriedade: String,
pub valor: String,
}
| 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/shift4/transformers.rs | crates/hyperswitch_connectors/src/connectors/shift4/transformers.rs | use api_models::webhooks::IncomingWebhookEvent;
use cards::CardNumber;
use common_enums::enums;
use common_utils::{
pii::{self, SecretSerdeValue},
request::Method,
types::MinorUnit,
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{
BankRedirectData, BankTransferData, Card as CardData, CryptoData, GiftCardData,
PayLaterData, PaymentMethodData, VoucherData, WalletData,
},
router_data::{ConnectorAuthType, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::{
CompleteAuthorizeData, PaymentsAuthorizeData, PaymentsPreProcessingData, ResponseId,
},
router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
types::{PaymentsPreProcessingRouterData, RefundsRouterData},
};
use hyperswitch_interfaces::errors;
use masking::Secret;
use serde::{Deserialize, Serialize};
use url::Url;
use crate::{
types::{
PaymentsPreprocessingResponseRouterData, RefundsResponseRouterData, ResponseRouterData,
},
utils::{
self, to_connector_meta, PaymentsAuthorizeRequestData,
PaymentsCompleteAuthorizeRequestData, PaymentsPreProcessingRequestData, RouterData as _,
},
};
type Error = error_stack::Report<errors::ConnectorError>;
trait Shift4AuthorizePreprocessingCommon {
fn is_automatic_capture(&self) -> Result<bool, Error>;
fn get_router_return_url(&self) -> Option<String>;
fn get_email_optional(&self) -> Option<pii::Email>;
fn get_complete_authorize_url(&self) -> Option<String>;
fn get_currency_required(&self) -> Result<enums::Currency, Error>;
fn get_metadata(&self) -> Result<Option<serde_json::Value>, Error>;
fn get_payment_method_data_required(&self) -> Result<PaymentMethodData, Error>;
}
pub struct Shift4RouterData<T> {
pub amount: MinorUnit,
pub router_data: T,
}
impl<T> TryFrom<(MinorUnit, T)> for Shift4RouterData<T> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from((amount, item): (MinorUnit, T)) -> Result<Self, Self::Error> {
Ok(Self {
amount,
router_data: item,
})
}
}
impl Shift4AuthorizePreprocessingCommon for PaymentsAuthorizeData {
fn get_email_optional(&self) -> Option<pii::Email> {
self.email.clone()
}
fn get_complete_authorize_url(&self) -> Option<String> {
self.complete_authorize_url.clone()
}
fn get_currency_required(
&self,
) -> Result<enums::Currency, error_stack::Report<errors::ConnectorError>> {
Ok(self.currency)
}
fn get_payment_method_data_required(
&self,
) -> Result<PaymentMethodData, error_stack::Report<errors::ConnectorError>> {
Ok(self.payment_method_data.clone())
}
fn is_automatic_capture(&self) -> Result<bool, Error> {
self.is_auto_capture()
}
fn get_router_return_url(&self) -> Option<String> {
self.router_return_url.clone()
}
fn get_metadata(
&self,
) -> Result<Option<serde_json::Value>, error_stack::Report<errors::ConnectorError>> {
Ok(self.metadata.clone())
}
}
impl Shift4AuthorizePreprocessingCommon for PaymentsPreProcessingData {
fn get_email_optional(&self) -> Option<pii::Email> {
self.email.clone()
}
fn get_complete_authorize_url(&self) -> Option<String> {
self.complete_authorize_url.clone()
}
fn get_currency_required(&self) -> Result<enums::Currency, Error> {
self.get_currency()
}
fn get_payment_method_data_required(&self) -> Result<PaymentMethodData, Error> {
self.payment_method_data.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "payment_method_data",
}
.into(),
)
}
fn is_automatic_capture(&self) -> Result<bool, Error> {
self.is_auto_capture()
}
fn get_router_return_url(&self) -> Option<String> {
self.router_return_url.clone()
}
fn get_metadata(
&self,
) -> Result<Option<serde_json::Value>, error_stack::Report<errors::ConnectorError>> {
Ok(None)
}
}
#[derive(Debug, Serialize)]
pub struct Shift4PaymentsRequest {
amount: MinorUnit,
currency: enums::Currency,
captured: bool,
metadata: Option<serde_json::Value>,
#[serde(flatten)]
payment_method: Shift4PaymentMethod,
}
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum Shift4PaymentMethod {
CardsNon3DSRequest(Box<CardsNon3DSRequest>),
BankRedirectRequest(Box<BankRedirectRequest>),
Cards3DSRequest(Box<Cards3DSRequest>),
VoucherRequest(Box<VoucherRequest>),
WalletRequest(Box<WalletRequest>),
PayLaterRequest(Box<PayLaterRequest>),
CryptoRequest(Box<CryptoRequest>),
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct WalletRequest {
flow: Flow,
payment_method: PaymentMethod,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PayLaterRequest {
flow: Flow,
payment_method: PaymentMethod,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CryptoRequest {
flow: Flow,
payment_method: PaymentMethod,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct VoucherRequest {
flow: Flow,
payment_method: PaymentMethod,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BankRedirectRequest {
payment_method: PaymentMethod,
flow: Flow,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Cards3DSRequest {
#[serde(rename = "card[number]")]
pub card_number: CardNumber,
#[serde(rename = "card[expMonth]")]
pub card_exp_month: Secret<String>,
#[serde(rename = "card[expYear]")]
pub card_exp_year: Secret<String>,
return_url: String,
}
#[serde_with::skip_serializing_none]
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CardsNon3DSRequest {
card: CardPayment,
description: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Flow {
pub return_url: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PaymentMethodType {
Eps,
Giropay,
Ideal,
Sofort,
Boleto,
Trustly,
Alipay,
Wechatpay,
Blik,
KlarnaDebitRisk,
Bitpay,
Paysera,
Skrill,
}
#[derive(Debug, Serialize)]
pub struct PaymentMethod {
#[serde(rename = "type")]
method_type: PaymentMethodType,
billing: Billing,
}
#[derive(Debug, Serialize)]
pub struct Billing {
name: Option<Secret<String>>,
email: Option<pii::Email>,
address: Option<Address>,
#[serde(skip_serializing_if = "Option::is_none")]
vat: Option<Secret<String>>,
}
#[derive(Debug, Serialize)]
pub struct Address {
line1: Option<Secret<String>>,
line2: Option<Secret<String>>,
zip: Option<Secret<String>>,
state: Option<Secret<String>>,
city: Option<String>,
country: Option<api_models::enums::CountryAlpha2>,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct DeviceData;
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Card {
pub number: CardNumber,
pub exp_month: Secret<String>,
pub exp_year: Secret<String>,
pub cardholder_name: Secret<String>,
}
#[derive(Debug, Serialize, Eq, PartialEq)]
#[serde(untagged)]
pub enum CardPayment {
RawCard(Box<Card>),
CardToken(Secret<String>),
}
impl<T, Req> TryFrom<&Shift4RouterData<&RouterData<T, Req, PaymentsResponseData>>>
for Shift4PaymentsRequest
where
Req: Shift4AuthorizePreprocessingCommon,
{
type Error = Error;
fn try_from(
item: &Shift4RouterData<&RouterData<T, Req, PaymentsResponseData>>,
) -> Result<Self, Self::Error> {
let submit_for_settlement = item.router_data.request.is_automatic_capture()?;
let amount = item.amount.to_owned();
let currency = item.router_data.request.get_currency_required()?;
let metadata = item.router_data.request.get_metadata()?;
let payment_method = Shift4PaymentMethod::try_from(item.router_data)?;
Ok(Self {
amount,
currency,
captured: submit_for_settlement,
metadata,
payment_method,
})
}
}
impl TryFrom<&PayLaterData> for PaymentMethodType {
type Error = Error;
fn try_from(value: &PayLaterData) -> Result<Self, Self::Error> {
match value {
PayLaterData::KlarnaRedirect { .. } => Ok(Self::KlarnaDebitRisk),
PayLaterData::AffirmRedirect { .. }
| PayLaterData::AfterpayClearpayRedirect { .. }
| PayLaterData::PayBrightRedirect { .. }
| PayLaterData::WalleyRedirect { .. }
| PayLaterData::AlmaRedirect { .. }
| PayLaterData::AtomeRedirect { .. }
| PayLaterData::FlexitiRedirect { .. }
| PayLaterData::KlarnaSdk { .. }
| PayLaterData::BreadpayRedirect { .. }
| PayLaterData::PayjustnowRedirect { .. } => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Shift4"),
)
.into())
}
}
}
}
impl<T, Req> TryFrom<(&RouterData<T, Req, PaymentsResponseData>, &PayLaterData)>
for Shift4PaymentMethod
where
Req: Shift4AuthorizePreprocessingCommon,
{
type Error = Error;
fn try_from(
(item, pay_later_data): (&RouterData<T, Req, PaymentsResponseData>, &PayLaterData),
) -> Result<Self, Self::Error> {
let flow = Flow::try_from(item.request.get_router_return_url())?;
let method_type = PaymentMethodType::try_from(pay_later_data)?;
let billing = Billing::try_from(item)?;
let payment_method = PaymentMethod {
method_type,
billing,
};
Ok(Self::BankRedirectRequest(Box::new(BankRedirectRequest {
payment_method,
flow,
})))
}
}
impl<T, Req> TryFrom<&RouterData<T, Req, PaymentsResponseData>> for Shift4PaymentMethod
where
Req: Shift4AuthorizePreprocessingCommon,
{
type Error = Error;
fn try_from(item: &RouterData<T, Req, PaymentsResponseData>) -> Result<Self, Self::Error> {
match item.request.get_payment_method_data_required()? {
PaymentMethodData::Card(ref ccard) => Self::try_from((item, ccard)),
PaymentMethodData::BankRedirect(ref redirect) => Self::try_from((item, redirect)),
PaymentMethodData::Wallet(ref wallet_data) => Self::try_from((item, wallet_data)),
PaymentMethodData::BankTransfer(ref bank_transfer_data) => {
Self::try_from(bank_transfer_data.as_ref())
}
PaymentMethodData::Voucher(ref voucher_data) => Self::try_from((item, voucher_data)),
PaymentMethodData::GiftCard(ref giftcard_data) => {
Self::try_from(giftcard_data.as_ref())
}
PaymentMethodData::PayLater(ref pay_later_data) => {
Self::try_from((item, pay_later_data))
}
PaymentMethodData::Crypto(ref crypto_data) => Self::try_from((item, crypto_data)),
PaymentMethodData::CardRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Shift4"),
)
.into())
}
}
}
}
impl TryFrom<&WalletData> for PaymentMethodType {
type Error = Error;
fn try_from(value: &WalletData) -> Result<Self, Self::Error> {
match value {
WalletData::AliPayRedirect { .. } => Ok(Self::Alipay),
WalletData::WeChatPayRedirect { .. } => Ok(Self::Wechatpay),
WalletData::Paysera(_) => Ok(Self::Paysera),
WalletData::Skrill(_) => Ok(Self::Skrill),
WalletData::AliPayQr(_)
| WalletData::AmazonPay(_)
| WalletData::AliPayHkRedirect(_)
| WalletData::AmazonPayRedirect(_)
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
| WalletData::GcashRedirect(_)
| WalletData::ApplePay(_)
| WalletData::ApplePayRedirect(_)
| WalletData::ApplePayThirdPartySdk(_)
| WalletData::DanaRedirect {}
| WalletData::GooglePayRedirect(_)
| WalletData::GooglePayThirdPartySdk(_)
| WalletData::GooglePay(_)
| WalletData::BluecodeRedirect {}
| WalletData::PaypalRedirect(_)
| WalletData::MbWayRedirect(_)
| WalletData::MobilePayRedirect(_)
| WalletData::PaypalSdk(_)
| WalletData::Paze(_)
| WalletData::SamsungPay(_)
| WalletData::TwintRedirect {}
| WalletData::VippsRedirect {}
| WalletData::TouchNGoRedirect(_)
| WalletData::WeChatPayQr(_)
| WalletData::CashappQr(_)
| WalletData::SwishQr(_)
| WalletData::Mifinity(_)
| WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Shift4"),
)
.into()),
}
}
}
impl<T, Req> TryFrom<(&RouterData<T, Req, PaymentsResponseData>, &WalletData)>
for Shift4PaymentMethod
where
Req: Shift4AuthorizePreprocessingCommon,
{
type Error = Error;
fn try_from(
(item, wallet_data): (&RouterData<T, Req, PaymentsResponseData>, &WalletData),
) -> Result<Self, Self::Error> {
let flow = Flow::try_from(item.request.get_router_return_url())?;
let method_type = PaymentMethodType::try_from(wallet_data)?;
let billing = Billing::try_from(item)?;
let payment_method = PaymentMethod {
method_type,
billing,
};
Ok(Self::WalletRequest(Box::new(WalletRequest {
payment_method,
flow,
})))
}
}
impl TryFrom<&BankTransferData> for Shift4PaymentMethod {
type Error = Error;
fn try_from(bank_transfer_data: &BankTransferData) -> Result<Self, Self::Error> {
match bank_transfer_data {
BankTransferData::MultibancoBankTransfer { .. }
| BankTransferData::AchBankTransfer { .. }
| BankTransferData::SepaBankTransfer { .. }
| BankTransferData::BacsBankTransfer { .. }
| BankTransferData::PermataBankTransfer { .. }
| BankTransferData::BcaBankTransfer { .. }
| BankTransferData::BniVaBankTransfer { .. }
| BankTransferData::BriVaBankTransfer { .. }
| BankTransferData::CimbVaBankTransfer { .. }
| BankTransferData::DanamonVaBankTransfer { .. }
| BankTransferData::MandiriVaBankTransfer { .. }
| BankTransferData::Pix { .. }
| BankTransferData::Pse {}
| BankTransferData::InstantBankTransfer {}
| BankTransferData::InstantBankTransferFinland { .. }
| BankTransferData::InstantBankTransferPoland { .. }
| BankTransferData::IndonesianBankTransfer { .. }
| BankTransferData::LocalBankTransfer { .. } => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Shift4"),
)
.into())
}
}
}
}
impl TryFrom<&VoucherData> for PaymentMethodType {
type Error = Error;
fn try_from(value: &VoucherData) -> Result<Self, Self::Error> {
match value {
VoucherData::Boleto { .. } => Ok(Self::Boleto),
VoucherData::Alfamart { .. }
| VoucherData::Indomaret { .. }
| VoucherData::Efecty
| VoucherData::PagoEfectivo
| VoucherData::RedCompra
| VoucherData::Oxxo
| VoucherData::RedPagos
| VoucherData::SevenEleven { .. }
| VoucherData::Lawson { .. }
| VoucherData::MiniStop { .. }
| VoucherData::FamilyMart { .. }
| VoucherData::Seicomart { .. }
| VoucherData::PayEasy { .. } => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Shift4"),
)
.into()),
}
}
}
impl<T, Req> TryFrom<(&RouterData<T, Req, PaymentsResponseData>, &VoucherData)>
for Shift4PaymentMethod
where
Req: Shift4AuthorizePreprocessingCommon,
{
type Error = Error;
fn try_from(
(item, voucher_data): (&RouterData<T, Req, PaymentsResponseData>, &VoucherData),
) -> Result<Self, Self::Error> {
let mut billing = Billing::try_from(item)?;
match voucher_data {
VoucherData::Boleto(boleto_data) => {
billing.vat = boleto_data.social_security_number.clone();
}
_ => {
billing.vat = None;
}
};
let method_type = PaymentMethodType::try_from(voucher_data)?;
let payment_method_details = PaymentMethod {
method_type,
billing,
};
let flow = Flow::try_from(item.request.get_router_return_url())?;
Ok(Self::VoucherRequest(Box::new(VoucherRequest {
payment_method: payment_method_details,
flow,
})))
}
}
impl TryFrom<&GiftCardData> for Shift4PaymentMethod {
type Error = Error;
fn try_from(gift_card_data: &GiftCardData) -> Result<Self, Self::Error> {
match gift_card_data {
GiftCardData::Givex(_)
| GiftCardData::PaySafeCard {}
| GiftCardData::BhnCardNetwork(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Shift4"),
)
.into()),
}
}
}
impl<T, Req> TryFrom<(&RouterData<T, Req, PaymentsResponseData>, &CardData)> for Shift4PaymentMethod
where
Req: Shift4AuthorizePreprocessingCommon,
{
type Error = Error;
fn try_from(
(item, card): (&RouterData<T, Req, PaymentsResponseData>, &CardData),
) -> Result<Self, Self::Error> {
let card_object = Card {
number: card.card_number.clone(),
exp_month: card.card_exp_month.clone(),
exp_year: card.card_exp_year.clone(),
cardholder_name: item
.get_optional_billing_full_name()
.unwrap_or(Secret::new("".to_string())),
};
if item.is_three_ds() {
Ok(Self::Cards3DSRequest(Box::new(Cards3DSRequest {
card_number: card_object.number,
card_exp_month: card_object.exp_month,
card_exp_year: card_object.exp_year,
return_url: item
.request
.get_complete_authorize_url()
.clone()
.ok_or_else(|| errors::ConnectorError::RequestEncodingFailed)?,
})))
} else {
Ok(Self::CardsNon3DSRequest(Box::new(CardsNon3DSRequest {
card: CardPayment::RawCard(Box::new(card_object)),
description: item.description.clone(),
})))
}
}
}
impl<T, Req> TryFrom<(&RouterData<T, Req, PaymentsResponseData>, &BankRedirectData)>
for Shift4PaymentMethod
where
Req: Shift4AuthorizePreprocessingCommon,
{
type Error = Error;
fn try_from(
(item, redirect_data): (&RouterData<T, Req, PaymentsResponseData>, &BankRedirectData),
) -> Result<Self, Self::Error> {
let flow = Flow::try_from(item.request.get_router_return_url())?;
let method_type = PaymentMethodType::try_from(redirect_data)?;
let billing = Billing::try_from(item)?;
let payment_method = PaymentMethod {
method_type,
billing,
};
Ok(Self::BankRedirectRequest(Box::new(BankRedirectRequest {
payment_method,
flow,
})))
}
}
impl TryFrom<&CryptoData> for PaymentMethodType {
type Error = Error;
fn try_from(_value: &CryptoData) -> Result<Self, Self::Error> {
Ok(Self::Bitpay)
}
}
impl<T, Req> TryFrom<(&RouterData<T, Req, PaymentsResponseData>, &CryptoData)>
for Shift4PaymentMethod
where
Req: Shift4AuthorizePreprocessingCommon,
{
type Error = Error;
fn try_from(
(item, redirect_data): (&RouterData<T, Req, PaymentsResponseData>, &CryptoData),
) -> Result<Self, Self::Error> {
let flow = Flow::try_from(item.request.get_router_return_url())?;
let method_type = PaymentMethodType::try_from(redirect_data)?;
let billing = Billing::try_from(item)?;
let payment_method = PaymentMethod {
method_type,
billing,
};
Ok(Self::CryptoRequest(Box::new(CryptoRequest {
payment_method,
flow,
})))
}
}
impl<T> TryFrom<&Shift4RouterData<&RouterData<T, CompleteAuthorizeData, PaymentsResponseData>>>
for Shift4PaymentsRequest
{
type Error = Error;
fn try_from(
item: &Shift4RouterData<&RouterData<T, CompleteAuthorizeData, PaymentsResponseData>>,
) -> Result<Self, Self::Error> {
match &item.router_data.request.payment_method_data {
Some(PaymentMethodData::Card(_)) => {
let card_token: Shift4CardToken =
to_connector_meta(item.router_data.request.connector_meta.clone())?;
let metadata = item.router_data.request.metadata.clone();
Ok(Self {
amount: item.amount.to_owned(),
currency: item.router_data.request.currency,
metadata,
payment_method: Shift4PaymentMethod::CardsNon3DSRequest(Box::new(
CardsNon3DSRequest {
card: CardPayment::CardToken(card_token.id),
description: item.router_data.description.clone(),
},
)),
captured: item.router_data.request.is_auto_capture()?,
})
}
Some(PaymentMethodData::Wallet(_))
| Some(PaymentMethodData::GiftCard(_))
| Some(PaymentMethodData::CardRedirect(_))
| Some(PaymentMethodData::PayLater(_))
| Some(PaymentMethodData::BankDebit(_))
| Some(PaymentMethodData::BankRedirect(_))
| Some(PaymentMethodData::BankTransfer(_))
| Some(PaymentMethodData::Crypto(_))
| Some(PaymentMethodData::MandatePayment)
| Some(PaymentMethodData::Voucher(_))
| Some(PaymentMethodData::Reward)
| Some(PaymentMethodData::RealTimePayment(_))
| Some(PaymentMethodData::MobilePayment(_))
| Some(PaymentMethodData::Upi(_))
| Some(PaymentMethodData::OpenBanking(_))
| Some(PaymentMethodData::CardToken(_))
| Some(PaymentMethodData::NetworkToken(_))
| Some(PaymentMethodData::CardDetailsForNetworkTransactionId(_))
| Some(PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_))
| None => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Shift4"),
)
.into()),
}
}
}
impl TryFrom<&BankRedirectData> for PaymentMethodType {
type Error = Error;
fn try_from(value: &BankRedirectData) -> Result<Self, Self::Error> {
match value {
BankRedirectData::Eps { .. } => Ok(Self::Eps),
BankRedirectData::Giropay { .. } => Ok(Self::Giropay),
BankRedirectData::Ideal { .. } => Ok(Self::Ideal),
BankRedirectData::Sofort { .. } => Ok(Self::Sofort),
BankRedirectData::Trustly { .. } => Ok(Self::Trustly),
BankRedirectData::Blik { .. } => Ok(Self::Blik),
BankRedirectData::BancontactCard { .. }
| BankRedirectData::Eft { .. }
| BankRedirectData::Przelewy24 { .. }
| BankRedirectData::Bizum {}
| BankRedirectData::Interac { .. }
| BankRedirectData::OnlineBankingCzechRepublic { .. }
| BankRedirectData::OnlineBankingFinland { .. }
| BankRedirectData::OnlineBankingPoland { .. }
| BankRedirectData::OnlineBankingSlovakia { .. }
| BankRedirectData::OpenBankingUk { .. }
| BankRedirectData::OnlineBankingFpx { .. }
| BankRedirectData::OnlineBankingThailand { .. }
| BankRedirectData::LocalBankRedirect {}
| BankRedirectData::OpenBanking { .. } => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Shift4"),
)
.into()),
}
}
}
impl TryFrom<Option<String>> for Flow {
type Error = Error;
fn try_from(router_return_url: Option<String>) -> Result<Self, Self::Error> {
Ok(Self {
return_url: router_return_url.ok_or(errors::ConnectorError::RequestEncodingFailed)?,
})
}
}
impl<T, Req> TryFrom<&RouterData<T, Req, PaymentsResponseData>> for Billing
where
Req: Shift4AuthorizePreprocessingCommon,
{
type Error = Error;
fn try_from(item: &RouterData<T, Req, PaymentsResponseData>) -> Result<Self, Self::Error> {
let billing_details = item.get_optional_billing();
let address_details_model = billing_details.as_ref().and_then(|b| b.address.as_ref());
let address = get_address_details(address_details_model);
Ok(Self {
name: item.get_optional_billing_full_name(),
email: item.request.get_email_optional(),
address,
vat: None,
})
}
}
fn get_address_details(
address_details: Option<&hyperswitch_domain_models::address::AddressDetails>,
) -> Option<Address> {
address_details.map(|address| Address {
line1: address.line1.clone(),
line2: address.line1.clone(),
zip: address.zip.clone(),
state: address.state.clone(),
city: address.city.clone(),
country: address.country,
})
}
// Auth Struct
pub struct Shift4AuthType {
pub(super) api_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for Shift4AuthType {
type Error = Error;
fn try_from(item: &ConnectorAuthType) -> Result<Self, Self::Error> {
if let ConnectorAuthType::HeaderKey { api_key } = item {
Ok(Self {
api_key: api_key.to_owned(),
})
} else {
Err(errors::ConnectorError::FailedToObtainAuthType)?
}
}
}
// PaymentsResponse
#[derive(Debug, Clone, Default, Serialize, Deserialize, Eq, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum Shift4PaymentStatus {
Successful,
Failed,
#[default]
Pending,
}
fn get_status(
captured: bool,
next_action: Option<&NextAction>,
payment_status: Shift4PaymentStatus,
) -> enums::AttemptStatus {
match payment_status {
Shift4PaymentStatus::Successful => {
if captured {
enums::AttemptStatus::Charged
} else {
enums::AttemptStatus::Authorized
}
}
Shift4PaymentStatus::Failed => enums::AttemptStatus::Failure,
Shift4PaymentStatus::Pending => match next_action {
Some(NextAction::Redirect) => enums::AttemptStatus::AuthenticationPending,
Some(NextAction::Wait) | Some(NextAction::None) | None => enums::AttemptStatus::Pending,
},
}
}
#[derive(Debug, Deserialize)]
pub struct Shift4WebhookObjectEventType {
#[serde(rename = "type")]
pub event_type: Shift4WebhookEvent,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum Shift4WebhookEvent {
ChargeSucceeded,
ChargeFailed,
ChargeUpdated,
ChargeCaptured,
ChargeRefunded,
#[serde(other)]
Unknown,
}
#[derive(Debug, Deserialize)]
pub struct Shift4WebhookObjectData {
pub id: String,
pub refunds: Option<Vec<RefundIdObject>>,
}
#[derive(Debug, Deserialize)]
pub struct RefundIdObject {
pub id: String,
}
#[derive(Debug, Deserialize)]
pub struct Shift4WebhookObjectId {
#[serde(rename = "type")]
pub event_type: Shift4WebhookEvent,
pub data: Shift4WebhookObjectData,
}
#[derive(Debug, Deserialize)]
pub struct Shift4WebhookObjectResource {
pub data: serde_json::Value,
}
#[derive(Default, Debug, Deserialize, Serialize)]
pub struct Shift4NonThreeDsResponse {
pub id: String,
pub currency: String,
pub amount: u32,
pub status: Shift4PaymentStatus,
pub captured: bool,
pub refunded: bool,
pub flow: Option<FlowResponse>,
}
#[derive(Default, Debug, Deserialize, Serialize)]
pub struct Shift4ThreeDsResponse {
pub enrolled: bool,
pub version: Option<String>,
#[serde(rename = "redirectUrl")]
pub redirect_url: Option<Url>,
pub token: Token,
}
#[derive(Default, Debug, Deserialize, Serialize)]
pub struct Token {
pub id: Secret<String>,
pub created: i64,
#[serde(rename = "objectType")]
pub object_type: String,
pub first6: String,
pub last4: String,
pub fingerprint: Secret<String>,
pub brand: String,
#[serde(rename = "type")]
pub token_type: String,
pub country: String,
pub used: bool,
#[serde(rename = "threeDSecureInfo")]
pub three_d_secure_info: ThreeDSecureInfo,
}
#[derive(Default, Debug, Deserialize, Serialize)]
pub struct ThreeDSecureInfo {
pub amount: MinorUnit,
pub currency: String,
pub enrolled: bool,
#[serde(rename = "liabilityShift")]
pub liability_shift: Option<String>,
pub version: String,
#[serde(rename = "authenticationFlow")]
pub authentication_flow: Option<SecretSerdeValue>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FlowResponse {
pub next_action: Option<NextAction>,
pub redirect: Option<Redirect>,
pub return_url: Option<Url>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Redirect {
pub redirect_url: Option<Url>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum NextAction {
Redirect,
Wait,
None,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Shift4CardToken {
pub id: Secret<String>,
}
impl TryFrom<PaymentsPreprocessingResponseRouterData<Shift4ThreeDsResponse>>
for PaymentsPreProcessingRouterData
{
type Error = Error;
fn try_from(
item: PaymentsPreprocessingResponseRouterData<Shift4ThreeDsResponse>,
) -> Result<Self, Self::Error> {
let redirection_data = item
.response
.redirect_url
.map(|url| RedirectForm::from((url, Method::Get)));
Ok(Self {
status: if redirection_data.is_some() {
enums::AttemptStatus::AuthenticationPending
} else {
enums::AttemptStatus::Pending
},
request: PaymentsPreProcessingData {
enrolled_for_3ds: item.response.enrolled,
..item.data.request
},
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(None),
connector_metadata: Some(
serde_json::to_value(Shift4CardToken {
id: item.response.token.id,
})
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?,
),
network_txn_id: None,
| 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/elavon/transformers.rs | crates/hyperswitch_connectors/src/connectors/elavon/transformers.rs | use cards::CardNumber;
use common_enums::{enums, Currency};
use common_utils::{pii::Email, types::StringMajorUnit};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{ConnectorAuthType, ErrorResponse},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{MandateReference, PaymentsResponseData, RefundsResponseData},
types::{
PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData,
RefundSyncRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::{consts::NO_ERROR_CODE, errors};
use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Deserializer, Serialize};
use crate::{
types::{
PaymentsCaptureResponseRouterData, PaymentsResponseRouterData,
PaymentsSyncResponseRouterData, RefundsResponseRouterData,
},
utils::{CardData, PaymentsAuthorizeRequestData, RefundsRequestData, RouterData as _},
};
pub struct ElavonRouterData<T> {
pub amount: StringMajorUnit,
pub router_data: T,
}
impl<T> From<(StringMajorUnit, T)> for ElavonRouterData<T> {
fn from((amount, item): (StringMajorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "lowercase")]
pub enum TransactionType {
CcSale,
CcAuthOnly,
CcComplete,
CcReturn,
TxnQuery,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "UPPERCASE")]
pub enum SyncTransactionType {
Sale,
AuthOnly,
Return,
}
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum ElavonPaymentsRequest {
Card(CardPaymentRequest),
MandatePayment(MandatePaymentRequest),
}
#[derive(Debug, Serialize)]
pub struct CardPaymentRequest {
pub ssl_transaction_type: TransactionType,
pub ssl_account_id: Secret<String>,
pub ssl_user_id: Secret<String>,
pub ssl_pin: Secret<String>,
pub ssl_amount: StringMajorUnit,
pub ssl_card_number: CardNumber,
pub ssl_exp_date: Secret<String>,
pub ssl_cvv2cvc2: Secret<String>,
pub ssl_email: Email,
#[serde(skip_serializing_if = "Option::is_none")]
pub ssl_add_token: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub ssl_get_token: Option<String>,
pub ssl_transaction_currency: Currency,
}
#[derive(Debug, Serialize)]
pub struct MandatePaymentRequest {
pub ssl_transaction_type: TransactionType,
pub ssl_account_id: Secret<String>,
pub ssl_user_id: Secret<String>,
pub ssl_pin: Secret<String>,
pub ssl_amount: StringMajorUnit,
pub ssl_email: Email,
pub ssl_token: Secret<String>,
}
impl TryFrom<&ElavonRouterData<&PaymentsAuthorizeRouterData>> for ElavonPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &ElavonRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let auth = ElavonAuthType::try_from(&item.router_data.connector_auth_type)?;
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(req_card) => {
if item.router_data.is_three_ds() {
Err(errors::ConnectorError::NotSupported {
message: "Card 3DS".to_string(),
connector: "Elavon",
})?
};
Ok(Self::Card(CardPaymentRequest {
ssl_transaction_type: match item.router_data.request.is_auto_capture()? {
true => TransactionType::CcSale,
false => TransactionType::CcAuthOnly,
},
ssl_account_id: auth.account_id.clone(),
ssl_user_id: auth.user_id.clone(),
ssl_pin: auth.pin.clone(),
ssl_amount: item.amount.clone(),
ssl_card_number: req_card.card_number.clone(),
ssl_exp_date: req_card.get_expiry_date_as_mmyy()?,
ssl_cvv2cvc2: req_card.card_cvc,
ssl_email: item.router_data.get_billing_email()?,
ssl_add_token: match item.router_data.request.is_mandate_payment() {
true => Some("Y".to_string()),
false => None,
},
ssl_get_token: match item.router_data.request.is_mandate_payment() {
true => Some("Y".to_string()),
false => None,
},
ssl_transaction_currency: item.router_data.request.currency,
}))
}
PaymentMethodData::MandatePayment => Ok(Self::MandatePayment(MandatePaymentRequest {
ssl_transaction_type: match item.router_data.request.is_auto_capture()? {
true => TransactionType::CcSale,
false => TransactionType::CcAuthOnly,
},
ssl_account_id: auth.account_id.clone(),
ssl_user_id: auth.user_id.clone(),
ssl_pin: auth.pin.clone(),
ssl_amount: item.amount.clone(),
ssl_email: item.router_data.get_billing_email()?,
ssl_token: Secret::new(item.router_data.request.get_connector_mandate_id()?),
})),
_ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()),
}
}
}
pub struct ElavonAuthType {
pub(super) account_id: Secret<String>,
pub(super) user_id: Secret<String>,
pub(super) pin: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for ElavonAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} => Ok(Self {
account_id: api_key.to_owned(),
user_id: key1.to_owned(),
pin: api_secret.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
enum SslResult {
#[serde(rename = "0")]
ImportedBatchFile,
#[serde(other)]
DeclineOrUnauthorized,
}
#[derive(Debug, Clone, Serialize)]
pub struct ElavonPaymentsResponse {
pub result: ElavonResult,
}
#[derive(Debug, Clone, Serialize)]
pub enum ElavonResult {
Success(PaymentResponse),
Error(ElavonErrorResponse),
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ElavonErrorResponse {
error_code: Option<String>,
error_message: String,
error_name: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PaymentResponse {
ssl_result: SslResult,
ssl_txn_id: String,
ssl_result_message: String,
ssl_token: Option<Secret<String>>,
}
impl<'de> Deserialize<'de> for ElavonPaymentsResponse {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
#[derive(Deserialize, Debug)]
#[serde(rename = "txn")]
struct XmlResponse {
// Error fields
#[serde(rename = "errorCode", default)]
error_code: Option<String>,
#[serde(rename = "errorMessage", default)]
error_message: Option<String>,
#[serde(rename = "errorName", default)]
error_name: Option<String>,
// Success fields
#[serde(rename = "ssl_result", default)]
ssl_result: Option<SslResult>,
#[serde(rename = "ssl_txn_id", default)]
ssl_txn_id: Option<String>,
#[serde(rename = "ssl_result_message", default)]
ssl_result_message: Option<String>,
#[serde(rename = "ssl_token", default)]
ssl_token: Option<Secret<String>>,
}
let xml_res = XmlResponse::deserialize(deserializer)?;
let result = match (xml_res.error_message.clone(), xml_res.error_name.clone()) {
(Some(error_message), Some(error_name)) => ElavonResult::Error(ElavonErrorResponse {
error_code: xml_res.error_code.clone(),
error_message,
error_name,
}),
_ => {
if let (Some(ssl_result), Some(ssl_txn_id), Some(ssl_result_message)) = (
xml_res.ssl_result.clone(),
xml_res.ssl_txn_id.clone(),
xml_res.ssl_result_message.clone(),
) {
ElavonResult::Success(PaymentResponse {
ssl_result,
ssl_txn_id,
ssl_result_message,
ssl_token: xml_res.ssl_token.clone(),
})
} else {
return Err(serde::de::Error::custom(
"Invalid Response XML structure - neither error nor success",
));
}
}
};
Ok(Self { result })
}
}
impl TryFrom<PaymentsResponseRouterData<ElavonPaymentsResponse>> for PaymentsAuthorizeRouterData {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsResponseRouterData<ElavonPaymentsResponse>,
) -> Result<Self, Self::Error> {
let status =
get_payment_status(&item.response.result, item.data.request.is_auto_capture()?);
let response = match &item.response.result {
ElavonResult::Error(error) => Err(ErrorResponse {
code: error
.error_code
.clone()
.unwrap_or(NO_ERROR_CODE.to_string()),
message: error.error_message.clone(),
reason: Some(error.error_message.clone()),
attempt_status: None,
connector_transaction_id: None,
status_code: item.http_code,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
ElavonResult::Success(response) => {
if status == enums::AttemptStatus::Failure {
Err(ErrorResponse {
code: response.ssl_result_message.clone(),
message: response.ssl_result_message.clone(),
reason: Some(response.ssl_result_message.clone()),
attempt_status: None,
connector_transaction_id: Some(response.ssl_txn_id.clone()),
status_code: item.http_code,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
response.ssl_txn_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(Some(MandateReference {
connector_mandate_id: response
.ssl_token
.as_ref()
.map(|secret| secret.clone().expose()),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
})),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(response.ssl_txn_id.clone()),
incremental_authorization_allowed: None,
charges: None,
})
}
}
};
Ok(Self {
status,
response,
..item.data
})
}
}
#[derive(Debug, Serialize, Deserialize)]
pub enum TransactionSyncStatus {
PEN, // Pended
OPN, // Unpended / release / open
REV, // Review
STL, // Settled
PST, // Failed due to post-auth rule
FPR, // Failed due to fraud prevention rules
PRE, // Failed due to pre-auth rule
}
#[derive(Debug, Serialize)]
#[serde(rename = "txn")]
pub struct PaymentsCaptureRequest {
pub ssl_transaction_type: TransactionType,
pub ssl_account_id: Secret<String>,
pub ssl_user_id: Secret<String>,
pub ssl_pin: Secret<String>,
pub ssl_amount: StringMajorUnit,
pub ssl_txn_id: String,
}
#[derive(Debug, Serialize)]
#[serde(rename = "txn")]
pub struct PaymentsVoidRequest {
pub ssl_transaction_type: TransactionType,
pub ssl_account_id: Secret<String>,
pub ssl_user_id: Secret<String>,
pub ssl_pin: Secret<String>,
pub ssl_txn_id: String,
}
#[derive(Debug, Serialize)]
#[serde(rename = "txn")]
pub struct ElavonRefundRequest {
pub ssl_transaction_type: TransactionType,
pub ssl_account_id: Secret<String>,
pub ssl_user_id: Secret<String>,
pub ssl_pin: Secret<String>,
pub ssl_amount: StringMajorUnit,
pub ssl_txn_id: String,
}
#[derive(Debug, Serialize)]
#[serde(rename = "txn")]
pub struct SyncRequest {
pub ssl_transaction_type: TransactionType,
pub ssl_account_id: Secret<String>,
pub ssl_user_id: Secret<String>,
pub ssl_pin: Secret<String>,
pub ssl_txn_id: String,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename = "txn")]
pub struct ElavonSyncResponse {
pub ssl_trans_status: TransactionSyncStatus,
pub ssl_transaction_type: SyncTransactionType,
pub ssl_txn_id: String,
}
impl TryFrom<&RefundSyncRouterData> for SyncRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &RefundSyncRouterData) -> Result<Self, Self::Error> {
let auth = ElavonAuthType::try_from(&item.connector_auth_type)?;
Ok(Self {
ssl_txn_id: item.request.get_connector_refund_id()?,
ssl_transaction_type: TransactionType::TxnQuery,
ssl_account_id: auth.account_id.clone(),
ssl_user_id: auth.user_id.clone(),
ssl_pin: auth.pin.clone(),
})
}
}
impl TryFrom<&PaymentsSyncRouterData> for SyncRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsSyncRouterData) -> Result<Self, Self::Error> {
let auth = ElavonAuthType::try_from(&item.connector_auth_type)?;
Ok(Self {
ssl_txn_id: item
.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?,
ssl_transaction_type: TransactionType::TxnQuery,
ssl_account_id: auth.account_id.clone(),
ssl_user_id: auth.user_id.clone(),
ssl_pin: auth.pin.clone(),
})
}
}
impl<F> TryFrom<&ElavonRouterData<&RefundsRouterData<F>>> for ElavonRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &ElavonRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
let auth = ElavonAuthType::try_from(&item.router_data.connector_auth_type)?;
Ok(Self {
ssl_txn_id: item.router_data.request.connector_transaction_id.clone(),
ssl_amount: item.amount.clone(),
ssl_transaction_type: TransactionType::CcReturn,
ssl_account_id: auth.account_id.clone(),
ssl_user_id: auth.user_id.clone(),
ssl_pin: auth.pin.clone(),
})
}
}
impl TryFrom<&ElavonRouterData<&PaymentsCaptureRouterData>> for PaymentsCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &ElavonRouterData<&PaymentsCaptureRouterData>) -> Result<Self, Self::Error> {
let auth = ElavonAuthType::try_from(&item.router_data.connector_auth_type)?;
Ok(Self {
ssl_txn_id: item.router_data.request.connector_transaction_id.clone(),
ssl_amount: item.amount.clone(),
ssl_transaction_type: TransactionType::CcComplete,
ssl_account_id: auth.account_id.clone(),
ssl_user_id: auth.user_id.clone(),
ssl_pin: auth.pin.clone(),
})
}
}
impl TryFrom<PaymentsSyncResponseRouterData<ElavonSyncResponse>> for PaymentsSyncRouterData {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsSyncResponseRouterData<ElavonSyncResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: get_sync_status(item.data.status, &item.response),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.ssl_txn_id),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, ElavonSyncResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, ElavonSyncResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.ssl_txn_id.clone(),
refund_status: get_refund_status(item.data.request.refund_status, &item.response),
}),
..item.data
})
}
}
impl TryFrom<PaymentsCaptureResponseRouterData<ElavonPaymentsResponse>>
for PaymentsCaptureRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsCaptureResponseRouterData<ElavonPaymentsResponse>,
) -> Result<Self, Self::Error> {
let status = map_payment_status(&item.response.result, enums::AttemptStatus::Charged);
let response = match &item.response.result {
ElavonResult::Error(error) => Err(ErrorResponse {
code: error
.error_code
.clone()
.unwrap_or(NO_ERROR_CODE.to_string()),
message: error.error_message.clone(),
reason: Some(error.error_message.clone()),
attempt_status: None,
connector_transaction_id: None,
status_code: item.http_code,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
ElavonResult::Success(response) => {
if status == enums::AttemptStatus::Failure {
Err(ErrorResponse {
code: response.ssl_result_message.clone(),
message: response.ssl_result_message.clone(),
reason: Some(response.ssl_result_message.clone()),
attempt_status: None,
connector_transaction_id: None,
status_code: item.http_code,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
response.ssl_txn_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(response.ssl_txn_id.clone()),
incremental_authorization_allowed: None,
charges: None,
})
}
}
};
Ok(Self {
status,
response,
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<Execute, ElavonPaymentsResponse>>
for RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, ElavonPaymentsResponse>,
) -> Result<Self, Self::Error> {
let status = enums::RefundStatus::from(&item.response.result);
let response = match &item.response.result {
ElavonResult::Error(error) => Err(ErrorResponse {
code: error
.error_code
.clone()
.unwrap_or(NO_ERROR_CODE.to_string()),
message: error.error_message.clone(),
reason: Some(error.error_message.clone()),
attempt_status: None,
connector_transaction_id: None,
status_code: item.http_code,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
ElavonResult::Success(response) => {
if status == enums::RefundStatus::Failure {
Err(ErrorResponse {
code: response.ssl_result_message.clone(),
message: response.ssl_result_message.clone(),
reason: Some(response.ssl_result_message.clone()),
attempt_status: None,
connector_transaction_id: None,
status_code: item.http_code,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(RefundsResponseData {
connector_refund_id: response.ssl_txn_id.clone(),
refund_status: enums::RefundStatus::from(&item.response.result),
})
}
}
};
Ok(Self {
response,
..item.data
})
}
}
trait ElavonResponseValidator {
fn is_successful(&self) -> bool;
}
impl ElavonResponseValidator for ElavonResult {
fn is_successful(&self) -> bool {
matches!(self, Self::Success(response) if response.ssl_result == SslResult::ImportedBatchFile)
}
}
fn map_payment_status(
item: &ElavonResult,
success_status: enums::AttemptStatus,
) -> enums::AttemptStatus {
if item.is_successful() {
success_status
} else {
enums::AttemptStatus::Failure
}
}
impl From<&ElavonResult> for enums::RefundStatus {
fn from(item: &ElavonResult) -> Self {
if item.is_successful() {
Self::Success
} else {
Self::Failure
}
}
}
fn get_refund_status(
prev_status: enums::RefundStatus,
item: &ElavonSyncResponse,
) -> enums::RefundStatus {
match item.ssl_trans_status {
TransactionSyncStatus::REV | TransactionSyncStatus::OPN | TransactionSyncStatus::PEN => {
prev_status
}
TransactionSyncStatus::STL => enums::RefundStatus::Success,
TransactionSyncStatus::PST | TransactionSyncStatus::FPR | TransactionSyncStatus::PRE => {
enums::RefundStatus::Failure
}
}
}
impl From<&ElavonSyncResponse> for enums::AttemptStatus {
fn from(item: &ElavonSyncResponse) -> Self {
match item.ssl_trans_status {
TransactionSyncStatus::REV
| TransactionSyncStatus::OPN
| TransactionSyncStatus::PEN => Self::Pending,
TransactionSyncStatus::STL => match item.ssl_transaction_type {
SyncTransactionType::Sale => Self::Charged,
SyncTransactionType::AuthOnly => Self::Authorized,
SyncTransactionType::Return => Self::Pending,
},
TransactionSyncStatus::PST
| TransactionSyncStatus::FPR
| TransactionSyncStatus::PRE => Self::Failure,
}
}
}
fn get_sync_status(
prev_status: enums::AttemptStatus,
item: &ElavonSyncResponse,
) -> enums::AttemptStatus {
match item.ssl_trans_status {
TransactionSyncStatus::REV | TransactionSyncStatus::OPN | TransactionSyncStatus::PEN => {
prev_status
}
TransactionSyncStatus::STL => match item.ssl_transaction_type {
SyncTransactionType::Sale => enums::AttemptStatus::Charged,
SyncTransactionType::AuthOnly => enums::AttemptStatus::Authorized,
SyncTransactionType::Return => enums::AttemptStatus::Pending,
},
TransactionSyncStatus::PST | TransactionSyncStatus::FPR | TransactionSyncStatus::PRE => {
enums::AttemptStatus::Failure
}
}
}
fn get_payment_status(item: &ElavonResult, is_auto_capture: bool) -> enums::AttemptStatus {
if item.is_successful() {
if is_auto_capture {
enums::AttemptStatus::Charged
} else {
enums::AttemptStatus::Authorized
}
} else {
enums::AttemptStatus::Failure
}
}
| 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/payu/transformers.rs | crates/hyperswitch_connectors/src/connectors/payu/transformers.rs | use base64::Engine;
use common_enums::enums;
use common_utils::{
consts::BASE64_ENGINE,
pii::{Email, IpAddress},
types::MinorUnit,
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{PaymentMethodData, WalletData},
router_data::{AccessToken, ConnectorAuthType, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RefundsResponseData},
types,
};
use hyperswitch_interfaces::errors;
use masking::Secret;
use serde::{Deserialize, Serialize};
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::AccessTokenRequestInfo as _,
};
const WALLET_IDENTIFIER: &str = "PBL";
#[derive(Debug, Serialize)]
pub struct PayuRouterData<T> {
pub amount: MinorUnit,
pub router_data: T,
}
impl<T> TryFrom<(MinorUnit, T)> for PayuRouterData<T> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from((amount, item): (MinorUnit, T)) -> Result<Self, Self::Error> {
Ok(Self {
amount,
router_data: item,
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PayuPaymentsRequest {
customer_ip: Secret<String, IpAddress>,
merchant_pos_id: Secret<String>,
total_amount: MinorUnit,
currency_code: enums::Currency,
description: String,
pay_methods: PayuPaymentMethod,
continue_url: Option<String>,
ext_order_id: Option<String>,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PayuPaymentMethod {
pay_method: PayuPaymentMethodData,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
#[serde(untagged)]
pub enum PayuPaymentMethodData {
Card(PayuCard),
Wallet(PayuWallet),
}
#[derive(Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum PayuCard {
#[serde(rename_all = "camelCase")]
Card {
number: cards::CardNumber,
expiration_month: Secret<String>,
expiration_year: Secret<String>,
cvv: Secret<String>,
},
}
#[derive(Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PayuWallet {
pub value: PayuWalletCode,
#[serde(rename = "type")]
pub wallet_type: String,
pub authorization_code: Secret<String>,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum PayuWalletCode {
Ap,
Jp,
}
impl TryFrom<&PayuRouterData<&types::PaymentsAuthorizeRouterData>> for PayuPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &PayuRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let auth_type = PayuAuthType::try_from(&item.router_data.connector_auth_type)?;
let payment_method = match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(ccard) => Ok(PayuPaymentMethod {
pay_method: PayuPaymentMethodData::Card(PayuCard::Card {
number: ccard.card_number,
expiration_month: ccard.card_exp_month,
expiration_year: ccard.card_exp_year,
cvv: ccard.card_cvc,
}),
}),
PaymentMethodData::Wallet(wallet_data) => match wallet_data {
WalletData::GooglePay(data) => Ok(PayuPaymentMethod {
pay_method: PayuPaymentMethodData::Wallet({
PayuWallet {
value: PayuWalletCode::Ap,
wallet_type: WALLET_IDENTIFIER.to_string(),
authorization_code: Secret::new(
BASE64_ENGINE.encode(
data.tokenization_data
.get_encrypted_google_pay_token()
.change_context(
errors::ConnectorError::MissingRequiredField {
field_name: "gpay wallet_token",
},
)?,
),
),
}
}),
}),
WalletData::ApplePay(apple_pay_data) => {
let apple_pay_encrypted_data = apple_pay_data
.payment_data
.get_encrypted_apple_pay_payment_data_mandatory()
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "Apple pay encrypted data",
})?;
Ok(PayuPaymentMethod {
pay_method: PayuPaymentMethodData::Wallet({
PayuWallet {
value: PayuWalletCode::Jp,
wallet_type: WALLET_IDENTIFIER.to_string(),
authorization_code: Secret::new(
apple_pay_encrypted_data.to_string(),
),
}
}),
})
}
_ => Err(errors::ConnectorError::NotImplemented(
"Unknown Wallet in Payment Method".to_string(),
)),
},
_ => Err(errors::ConnectorError::NotImplemented(
"Unknown payment method".to_string(),
)),
}?;
let browser_info = item.router_data.request.browser_info.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "browser_info",
},
)?;
Ok(Self {
customer_ip: Secret::new(
browser_info
.ip_address
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "browser_info.ip_address",
})?
.to_string(),
),
merchant_pos_id: auth_type.merchant_pos_id,
ext_order_id: Some(item.router_data.connector_request_reference_id.clone()),
total_amount: item.amount.to_owned(),
currency_code: item.router_data.request.currency,
description: item.router_data.description.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "item.description",
},
)?,
pay_methods: payment_method,
continue_url: None,
})
}
}
pub struct PayuAuthType {
pub(super) api_key: Secret<String>,
pub(super) merchant_pos_id: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for PayuAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
api_key: api_key.to_owned(),
merchant_pos_id: key1.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType)?,
}
}
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PayuPaymentStatus {
Success,
WarningContinueRedirect,
#[serde(rename = "WARNING_CONTINUE_3DS")]
WarningContinue3ds,
WarningContinueCvv,
#[default]
Pending,
}
impl From<PayuPaymentStatus> for enums::AttemptStatus {
fn from(item: PayuPaymentStatus) -> Self {
match item {
PayuPaymentStatus::Success => Self::Pending,
PayuPaymentStatus::WarningContinue3ds => Self::Pending,
PayuPaymentStatus::WarningContinueCvv => Self::Pending,
PayuPaymentStatus::WarningContinueRedirect => Self::Pending,
PayuPaymentStatus::Pending => Self::Pending,
}
}
}
#[derive(Debug, Clone, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PayuPaymentsResponse {
pub status: PayuPaymentStatusData,
pub redirect_uri: String,
pub iframe_allowed: Option<bool>,
pub three_ds_protocol_version: Option<String>,
pub order_id: String,
pub ext_order_id: Option<String>,
}
impl<F, T> TryFrom<ResponseRouterData<F, PayuPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, PayuPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: enums::AttemptStatus::from(item.response.status.status_code),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.order_id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: item
.response
.ext_order_id
.or(Some(item.response.order_id)),
incremental_authorization_allowed: None,
charges: None,
}),
amount_captured: None,
..item.data
})
}
}
#[derive(Default, Debug, Clone, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct PayuPaymentsCaptureRequest {
order_id: String,
order_status: OrderStatus,
}
impl TryFrom<&types::PaymentsCaptureRouterData> for PayuPaymentsCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::PaymentsCaptureRouterData) -> Result<Self, Self::Error> {
Ok(Self {
order_id: item.request.connector_transaction_id.clone(),
order_status: OrderStatus::Completed,
})
}
}
#[derive(Default, Debug, Clone, Deserialize, PartialEq, Serialize)]
pub struct PayuPaymentsCaptureResponse {
status: PayuPaymentStatusData,
}
impl<F, T> TryFrom<ResponseRouterData<F, PayuPaymentsCaptureResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, PayuPaymentsCaptureResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: enums::AttemptStatus::from(item.response.status.status_code.clone()),
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,
}),
amount_captured: None,
..item.data
})
}
}
#[derive(Debug, Clone, Serialize, PartialEq)]
pub struct PayuAuthUpdateRequest {
grant_type: String,
client_id: Secret<String>,
client_secret: Secret<String>,
}
impl TryFrom<&types::RefreshTokenRouterData> for PayuAuthUpdateRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::RefreshTokenRouterData) -> Result<Self, Self::Error> {
Ok(Self {
grant_type: "client_credentials".to_string(),
client_id: item.get_request_id()?,
client_secret: item.request.app_id.clone(),
})
}
}
#[derive(Default, Debug, Clone, Deserialize, PartialEq, Serialize)]
pub struct PayuAuthUpdateResponse {
pub access_token: Secret<String>,
pub token_type: String,
pub expires_in: i64,
pub grant_type: String,
}
impl<F, T> TryFrom<ResponseRouterData<F, PayuAuthUpdateResponse, T, AccessToken>>
for RouterData<F, T, AccessToken>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, PayuAuthUpdateResponse, T, AccessToken>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(AccessToken {
token: item.response.access_token,
expires: item.response.expires_in,
}),
..item.data
})
}
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct PayuPaymentsCancelResponse {
pub order_id: String,
pub ext_order_id: Option<String>,
pub status: PayuPaymentStatusData,
}
impl<F, T> TryFrom<ResponseRouterData<F, PayuPaymentsCancelResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, PayuPaymentsCancelResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: enums::AttemptStatus::from(item.response.status.status_code.clone()),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.order_id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: item
.response
.ext_order_id
.or(Some(item.response.order_id)),
incremental_authorization_allowed: None,
charges: None,
}),
amount_captured: None,
..item.data
})
}
}
#[allow(dead_code)]
#[derive(Debug, Serialize, Eq, PartialEq, Default, Deserialize, Clone)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum OrderStatus {
New,
Canceled,
Completed,
WaitingForConfirmation,
#[default]
Pending,
}
impl From<OrderStatus> for enums::AttemptStatus {
fn from(item: OrderStatus) -> Self {
match item {
OrderStatus::New => Self::PaymentMethodAwaited,
OrderStatus::Canceled => Self::Voided,
OrderStatus::Completed => Self::Charged,
OrderStatus::Pending => Self::Pending,
OrderStatus::WaitingForConfirmation => Self::Authorized,
}
}
}
#[derive(Debug, Serialize, Default, Deserialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct PayuPaymentStatusData {
status_code: PayuPaymentStatus,
severity: Option<String>,
status_desc: Option<String>,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct PayuProductData {
name: String,
unit_price: String,
quantity: String,
#[serde(rename = "virtual")]
virtually: Option<bool>,
listing_date: Option<String>,
}
#[derive(Debug, Clone, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PayuOrderResponseData {
order_id: String,
ext_order_id: Option<String>,
order_create_date: String,
notify_url: Option<String>,
customer_ip: Secret<String, IpAddress>,
merchant_pos_id: Secret<String>,
description: String,
validity_time: Option<String>,
currency_code: enums::Currency,
total_amount: String,
buyer: Option<PayuOrderResponseBuyerData>,
pay_method: Option<PayuOrderResponsePayMethod>,
products: Option<Vec<PayuProductData>>,
status: OrderStatus,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct PayuOrderResponseBuyerData {
ext_customer_id: Option<String>,
email: Option<Email>,
phone: Option<Secret<String>>,
first_name: Option<Secret<String>>,
last_name: Option<Secret<String>>,
#[serde(rename = "nin")]
national_identification_number: Option<Secret<String>>,
language: Option<String>,
delivery: Option<String>,
customer_id: Option<String>,
}
#[derive(Debug, Clone, Deserialize, PartialEq, Serialize)]
#[serde(tag = "type", rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PayuOrderResponsePayMethod {
CardToken,
Pbl,
Installemnts,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct PayuOrderResponseProperty {
name: String,
value: String,
}
#[derive(Default, Debug, Clone, Deserialize, PartialEq, Serialize)]
pub struct PayuPaymentsSyncResponse {
orders: Vec<PayuOrderResponseData>,
status: PayuPaymentStatusData,
properties: Option<Vec<PayuOrderResponseProperty>>,
}
impl<F, T> TryFrom<ResponseRouterData<F, PayuPaymentsSyncResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, PayuPaymentsSyncResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let order = match item.response.orders.first() {
Some(order) => order,
_ => Err(errors::ConnectorError::ResponseHandlingFailed)?,
};
Ok(Self {
status: enums::AttemptStatus::from(order.status.clone()),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(order.order_id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: order
.ext_order_id
.clone()
.or(Some(order.order_id.clone())),
incremental_authorization_allowed: None,
charges: None,
}),
amount_captured: Some(
order
.total_amount
.parse::<i64>()
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?,
),
..item.data
})
}
}
#[derive(Default, Debug, Serialize)]
pub struct PayuRefundRequestData {
description: String,
amount: Option<MinorUnit>,
}
#[derive(Default, Debug, Serialize)]
pub struct PayuRefundRequest {
refund: PayuRefundRequestData,
}
impl<F> TryFrom<&PayuRouterData<&types::RefundsRouterData<F>>> for PayuRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PayuRouterData<&types::RefundsRouterData<F>>) -> Result<Self, Self::Error> {
Ok(Self {
refund: PayuRefundRequestData {
description: item.router_data.request.reason.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "item.request.reason",
},
)?,
amount: None,
},
})
}
}
// Type definition for Refund Response
#[allow(dead_code)]
#[derive(Debug, Serialize, Eq, PartialEq, Default, Deserialize, Clone)]
#[serde(rename_all = "UPPERCASE")]
pub enum RefundStatus {
Finalized,
Completed,
Canceled,
#[default]
Pending,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Finalized | RefundStatus::Completed => Self::Success,
RefundStatus::Canceled => Self::Failure,
RefundStatus::Pending => Self::Pending,
}
}
}
#[derive(Default, Debug, Clone, Eq, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PayuRefundResponseData {
refund_id: String,
ext_refund_id: String,
amount: String,
currency_code: enums::Currency,
description: String,
creation_date_time: String,
status: RefundStatus,
status_date_time: Option<String>,
}
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RefundResponse {
refund: PayuRefundResponseData,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>>
for types::RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
let refund_status = enums::RefundStatus::from(item.response.refund.status);
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.refund.refund_id,
refund_status,
}),
..item.data
})
}
}
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
pub struct RefundSyncResponse {
refunds: Vec<PayuRefundResponseData>,
}
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> {
let refund = match item.response.refunds.first() {
Some(refund) => refund,
_ => Err(errors::ConnectorError::ResponseHandlingFailed)?,
};
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: refund.refund_id.clone(),
refund_status: enums::RefundStatus::from(refund.status.clone()),
}),
..item.data
})
}
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct PayuErrorData {
pub status_code: String,
pub code: Option<String>,
pub code_literal: Option<String>,
pub status_desc: String,
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct PayuErrorResponse {
pub status: PayuErrorData,
}
#[derive(Deserialize, Debug, Serialize)]
pub struct PayuAccessTokenErrorResponse {
pub error: String,
pub error_description: 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/barclaycard/transformers.rs | crates/hyperswitch_connectors/src/connectors/barclaycard/transformers.rs | use base64::Engine;
use common_enums::enums;
use common_types::payments::ApplePayPredecryptData;
use common_utils::{
consts, date_time,
ext_traits::ValueExt,
pii,
types::{SemanticVersion, StringMajorUnit},
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{ApplePayWalletData, GooglePayWalletData, PaymentMethodData, WalletData},
router_data::{
AdditionalPaymentMethodConnectorResponse, ConnectorAuthType, ConnectorResponseData,
ErrorResponse, PaymentMethodToken, RouterData,
},
router_flow_types::refunds::{Execute, RSync},
router_request_types::{
authentication::MessageExtensionAttribute, CompleteAuthorizeData, ResponseId,
},
router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsCompleteAuthorizeRouterData, PaymentsPreProcessingRouterData,
PaymentsSyncRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::errors;
use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::{
constants,
types::{
PaymentsCancelResponseRouterData, PaymentsCaptureResponseRouterData,
PaymentsPreprocessingResponseRouterData, PaymentsResponseRouterData,
PaymentsSyncResponseRouterData, RefundsResponseRouterData, ResponseRouterData,
},
unimplemented_payment_method,
utils::{
self, AddressDetailsData, CardData, PaymentsAuthorizeRequestData,
PaymentsCompleteAuthorizeRequestData, PaymentsPreProcessingRequestData,
PaymentsSyncRequestData, RouterData as OtherRouterData,
},
};
pub struct BarclaycardAuthType {
pub(super) api_key: Secret<String>,
pub(super) merchant_account: Secret<String>,
pub(super) api_secret: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for BarclaycardAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
if let ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} = auth_type
{
Ok(Self {
api_key: api_key.to_owned(),
merchant_account: key1.to_owned(),
api_secret: api_secret.to_owned(),
})
} else {
Err(errors::ConnectorError::FailedToObtainAuthType)?
}
}
}
pub struct BarclaycardRouterData<T> {
pub amount: StringMajorUnit,
pub router_data: T,
}
impl<T> TryFrom<(StringMajorUnit, T)> for BarclaycardRouterData<T> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from((amount, item): (StringMajorUnit, T)) -> Result<Self, Self::Error> {
Ok(Self {
amount,
router_data: item,
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BarclaycardPaymentsRequest {
processing_information: ProcessingInformation,
payment_information: PaymentInformation,
order_information: OrderInformationWithBill,
client_reference_information: ClientReferenceInformation,
#[serde(skip_serializing_if = "Option::is_none")]
consumer_authentication_information: Option<BarclaycardConsumerAuthInformation>,
#[serde(skip_serializing_if = "Option::is_none")]
merchant_defined_information: Option<Vec<MerchantDefinedInformation>>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ProcessingInformation {
commerce_indicator: String,
capture: Option<bool>,
payment_solution: Option<String>,
cavv_algorithm: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MerchantDefinedInformation {
key: u8,
value: String,
}
#[derive(Debug, Serialize)]
pub enum BarclaycardParesStatus {
#[serde(rename = "Y")]
AuthenticationSuccessful,
#[serde(rename = "A")]
AuthenticationAttempted,
#[serde(rename = "N")]
AuthenticationFailed,
#[serde(rename = "U")]
AuthenticationNotCompleted,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BarclaycardConsumerAuthInformation {
ucaf_collection_indicator: Option<String>,
cavv: Option<Secret<String>>,
ucaf_authentication_data: Option<Secret<String>>,
xid: Option<String>,
directory_server_transaction_id: Option<Secret<String>>,
specification_version: Option<SemanticVersion>,
/// This field specifies the 3ds version
pa_specification_version: Option<SemanticVersion>,
/// Verification response enrollment status.
///
/// This field is supported only on Asia, Middle East, and Africa Gateway.
///
/// For external authentication, this field will always be "Y"
veres_enrolled: Option<String>,
/// Raw electronic commerce indicator (ECI)
eci_raw: Option<String>,
/// This field is supported only on Asia, Middle East, and Africa Gateway
/// Also needed for Credit Mutuel-CIC in France and Mastercard Identity Check transactions
/// This field is only applicable for Mastercard and Visa Transactions
pares_status: Option<BarclaycardParesStatus>,
//This field is used to send the authentication date in yyyyMMDDHHMMSS format
authentication_date: Option<String>,
/// This field indicates the 3D Secure transaction flow. It is only supported for secure transactions in France.
/// The possible values are - CH (Challenge), FD (Frictionless with delegation), FR (Frictionless)
effective_authentication_type: Option<EffectiveAuthenticationType>,
/// This field indicates the authentication type or challenge presented to the cardholder at checkout.
challenge_code: Option<String>,
/// This field indicates the reason for payer authentication response status. It is only supported for secure transactions in France.
pares_status_reason: Option<String>,
/// This field indicates the reason why strong authentication was cancelled. It is only supported for secure transactions in France.
challenge_cancel_code: Option<String>,
/// This field indicates the score calculated by the 3D Securing platform. It is only supported for secure transactions in France.
network_score: Option<u32>,
/// This is the transaction ID generated by the access control server. This field is supported only for secure transactions in France.
acs_transaction_id: Option<String>,
}
#[derive(Debug, Serialize)]
pub enum EffectiveAuthenticationType {
CH,
FR,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CardPaymentInformation {
card: Card,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GooglePayPaymentInformation {
fluid_data: FluidData,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TokenizedCard {
number: cards::CardNumber,
expiration_month: Secret<String>,
expiration_year: Secret<String>,
cryptogram: Option<Secret<String>>,
transaction_type: TransactionType,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ApplePayTokenizedCard {
transaction_type: TransactionType,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ApplePayTokenPaymentInformation {
fluid_data: FluidData,
tokenized_card: ApplePayTokenizedCard,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ApplePayPaymentInformation {
tokenized_card: TokenizedCard,
}
pub const FLUID_DATA_DESCRIPTOR: &str = "RklEPUNPTU1PTi5BUFBMRS5JTkFQUC5QQVlNRU5U";
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum PaymentInformation {
Cards(Box<CardPaymentInformation>),
GooglePay(Box<GooglePayPaymentInformation>),
ApplePay(Box<ApplePayPaymentInformation>),
ApplePayToken(Box<ApplePayTokenPaymentInformation>),
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Card {
number: cards::CardNumber,
expiration_month: Secret<String>,
expiration_year: Secret<String>,
security_code: Secret<String>,
#[serde(rename = "type")]
card_type: Option<String>,
type_selection_indicator: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FluidData {
value: Secret<String>,
#[serde(skip_serializing_if = "Option::is_none")]
descriptor: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct OrderInformationWithBill {
amount_details: Amount,
bill_to: Option<BillTo>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Amount {
total_amount: StringMajorUnit,
currency: api_models::enums::Currency,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BillTo {
first_name: Secret<String>,
last_name: Secret<String>,
address1: Secret<String>,
locality: String,
administrative_area: Secret<String>,
postal_code: Secret<String>,
country: enums::CountryAlpha2,
email: pii::Email,
}
fn truncate_string(state: &Secret<String>, max_len: usize) -> Secret<String> {
let exposed = state.clone().expose();
let truncated = exposed.get(..max_len).unwrap_or(&exposed);
Secret::new(truncated.to_string())
}
fn build_bill_to(
address_details: &hyperswitch_domain_models::address::AddressDetails,
email: pii::Email,
) -> Result<BillTo, error_stack::Report<errors::ConnectorError>> {
let administrative_area = address_details
.to_state_code_as_optional()
.unwrap_or_else(|_| {
address_details
.get_state()
.ok()
.map(|state| truncate_string(state, 20))
})
.ok_or_else(|| errors::ConnectorError::MissingRequiredField {
field_name: "billing_address.state",
})?;
Ok(BillTo {
first_name: address_details.get_first_name()?.clone(),
last_name: address_details.get_last_name()?.clone(),
address1: address_details.get_line1()?.clone(),
locality: address_details.get_city()?.clone(),
administrative_area,
postal_code: address_details.get_zip()?.clone(),
country: address_details.get_country()?.to_owned(),
email,
})
}
fn get_barclaycard_card_type(card_network: common_enums::CardNetwork) -> Option<&'static str> {
match card_network {
common_enums::CardNetwork::Visa => Some("001"),
common_enums::CardNetwork::Mastercard => Some("002"),
common_enums::CardNetwork::AmericanExpress => Some("003"),
common_enums::CardNetwork::JCB => Some("007"),
common_enums::CardNetwork::DinersClub => Some("005"),
common_enums::CardNetwork::Discover => Some("004"),
common_enums::CardNetwork::CartesBancaires => Some("006"),
common_enums::CardNetwork::UnionPay => Some("062"),
//"042" is the type code for Masetro Cards(International). For Maestro Cards(UK-Domestic) the mapping should be "024"
common_enums::CardNetwork::Maestro => Some("042"),
common_enums::CardNetwork::Interac
| common_enums::CardNetwork::RuPay
| common_enums::CardNetwork::Star
| common_enums::CardNetwork::Accel
| common_enums::CardNetwork::Pulse
| common_enums::CardNetwork::Nyce => None,
}
}
#[derive(Debug, Serialize)]
pub enum PaymentSolution {
GooglePay,
ApplePay,
}
#[derive(Debug, Serialize)]
pub enum TransactionType {
#[serde(rename = "1")]
InApp,
}
impl From<PaymentSolution> for String {
fn from(solution: PaymentSolution) -> Self {
let payment_solution = match solution {
PaymentSolution::GooglePay => "012",
PaymentSolution::ApplePay => "001",
};
payment_solution.to_string()
}
}
impl
From<(
&BarclaycardRouterData<&PaymentsAuthorizeRouterData>,
Option<BillTo>,
)> for OrderInformationWithBill
{
fn from(
(item, bill_to): (
&BarclaycardRouterData<&PaymentsAuthorizeRouterData>,
Option<BillTo>,
),
) -> Self {
Self {
amount_details: Amount {
total_amount: item.amount.clone(),
currency: item.router_data.request.currency,
},
bill_to,
}
}
}
impl
TryFrom<(
&BarclaycardRouterData<&PaymentsAuthorizeRouterData>,
Option<PaymentSolution>,
Option<String>,
)> for ProcessingInformation
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, solution, network): (
&BarclaycardRouterData<&PaymentsAuthorizeRouterData>,
Option<PaymentSolution>,
Option<String>,
),
) -> Result<Self, Self::Error> {
let commerce_indicator = solution
.as_ref()
.map(|pm_solution| match pm_solution {
PaymentSolution::ApplePay => network
.as_ref()
.map(|card_network| match card_network.to_lowercase().as_str() {
"amex" => "internet",
"discover" => "internet",
"mastercard" => "spa",
"visa" => "internet",
_ => "internet",
})
.unwrap_or("internet"),
PaymentSolution::GooglePay => "internet",
})
.unwrap_or("internet")
.to_string();
let cavv_algorithm = Some("2".to_string());
Ok(Self {
capture: Some(matches!(
item.router_data.request.capture_method,
Some(enums::CaptureMethod::Automatic) | None
)),
payment_solution: solution.map(String::from),
commerce_indicator,
cavv_algorithm,
})
}
}
impl
TryFrom<(
&BarclaycardRouterData<&PaymentsCompleteAuthorizeRouterData>,
Option<PaymentSolution>,
Option<String>,
)> for ProcessingInformation
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, solution, network): (
&BarclaycardRouterData<&PaymentsCompleteAuthorizeRouterData>,
Option<PaymentSolution>,
Option<String>,
),
) -> Result<Self, Self::Error> {
let commerce_indicator = get_commerce_indicator(network);
let cavv_algorithm = Some("2".to_string());
Ok(Self {
capture: Some(matches!(
item.router_data.request.capture_method,
Some(enums::CaptureMethod::Automatic) | None
)),
payment_solution: solution.map(String::from),
commerce_indicator,
cavv_algorithm,
})
}
}
impl From<&BarclaycardRouterData<&PaymentsCompleteAuthorizeRouterData>>
for ClientReferenceInformation
{
fn from(item: &BarclaycardRouterData<&PaymentsCompleteAuthorizeRouterData>) -> Self {
Self {
code: Some(item.router_data.connector_request_reference_id.clone()),
}
}
}
impl From<&BarclaycardRouterData<&PaymentsAuthorizeRouterData>> for ClientReferenceInformation {
fn from(item: &BarclaycardRouterData<&PaymentsAuthorizeRouterData>) -> Self {
Self {
code: Some(item.router_data.connector_request_reference_id.clone()),
}
}
}
impl
From<(
&BarclaycardRouterData<&PaymentsCompleteAuthorizeRouterData>,
BillTo,
)> for OrderInformationWithBill
{
fn from(
(item, bill_to): (
&BarclaycardRouterData<&PaymentsCompleteAuthorizeRouterData>,
BillTo,
),
) -> Self {
Self {
amount_details: Amount {
total_amount: item.amount.clone(),
currency: item.router_data.request.currency,
},
bill_to: Some(bill_to),
}
}
}
impl From<BarclaycardAuthEnrollmentStatus> for enums::AttemptStatus {
fn from(item: BarclaycardAuthEnrollmentStatus) -> Self {
match item {
BarclaycardAuthEnrollmentStatus::PendingAuthentication => Self::AuthenticationPending,
BarclaycardAuthEnrollmentStatus::AuthenticationSuccessful => {
Self::AuthenticationSuccessful
}
BarclaycardAuthEnrollmentStatus::AuthenticationFailed => Self::AuthenticationFailed,
}
}
}
impl From<common_enums::DecoupledAuthenticationType> for EffectiveAuthenticationType {
fn from(auth_type: common_enums::DecoupledAuthenticationType) -> Self {
match auth_type {
common_enums::DecoupledAuthenticationType::Challenge => Self::CH,
common_enums::DecoupledAuthenticationType::Frictionless => Self::FR,
}
}
}
fn convert_metadata_to_merchant_defined_info(metadata: Value) -> Vec<MerchantDefinedInformation> {
let hashmap: std::collections::BTreeMap<String, Value> =
serde_json::from_str(&metadata.to_string()).unwrap_or(std::collections::BTreeMap::new());
let mut vector = Vec::new();
let mut iter = 1;
for (key, value) in hashmap {
vector.push(MerchantDefinedInformation {
key: iter,
value: format!("{key}={value}"),
});
iter += 1;
}
vector
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ClientReferenceInformation {
code: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ClientProcessorInformation {
avs: Option<Avs>,
card_verification: Option<CardVerification>,
processor: Option<ProcessorResponse>,
network_transaction_id: Option<Secret<String>>,
approval_code: Option<String>,
merchant_advice: Option<MerchantAdvice>,
response_code: Option<String>,
ach_verification: Option<AchVerification>,
system_trace_audit_number: Option<String>,
event_status: Option<String>,
retrieval_reference_number: Option<String>,
consumer_authentication_response: Option<ConsumerAuthenticationResponse>,
response_details: Option<String>,
transaction_id: Option<Secret<String>>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MerchantAdvice {
code: Option<String>,
code_raw: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ConsumerAuthenticationResponse {
code: Option<String>,
code_raw: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AchVerification {
result_code_raw: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ProcessorResponse {
name: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CardVerification {
result_code: Option<String>,
result_code_raw: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ClientRiskInformation {
rules: Option<Vec<ClientRiskInformationRules>>,
profile: Option<Profile>,
score: Option<Score>,
info_codes: Option<InfoCodes>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct InfoCodes {
address: Option<Vec<String>>,
identity_change: Option<Vec<String>>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Score {
factor_codes: Option<Vec<String>>,
result: Option<RiskResult>,
model_used: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(untagged)]
pub enum RiskResult {
StringVariant(String),
IntVariant(u64),
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Profile {
early_decision: Option<String>,
name: Option<String>,
decision: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ClientRiskInformationRules {
name: Option<Secret<String>>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Avs {
code: Option<String>,
code_raw: Option<String>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BarclaycardConsumerAuthValidateResponse {
ucaf_collection_indicator: Option<String>,
cavv: Option<Secret<String>>,
ucaf_authentication_data: Option<Secret<String>>,
xid: Option<String>,
specification_version: Option<SemanticVersion>,
directory_server_transaction_id: Option<Secret<String>>,
indicator: Option<String>,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct BarclaycardThreeDSMetadata {
three_ds_data: BarclaycardConsumerAuthValidateResponse,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BarclaycardConsumerAuthInformationEnrollmentResponse {
access_token: Option<Secret<String>>,
step_up_url: Option<String>,
//Added to segregate the three_ds_data in a separate struct
#[serde(flatten)]
validate_response: BarclaycardConsumerAuthValidateResponse,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum BarclaycardAuthEnrollmentStatus {
PendingAuthentication,
AuthenticationSuccessful,
AuthenticationFailed,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ClientAuthCheckInfoResponse {
id: String,
client_reference_information: ClientReferenceInformation,
consumer_authentication_information: BarclaycardConsumerAuthInformationEnrollmentResponse,
status: BarclaycardAuthEnrollmentStatus,
error_information: Option<BarclaycardErrorInformation>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BarclaycardConsumerAuthInformationValidateRequest {
authentication_transaction_id: String,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum BarclaycardPreProcessingResponse {
ClientAuthCheckInfo(Box<ClientAuthCheckInfoResponse>),
ErrorInformation(Box<BarclaycardErrorInformationResponse>),
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BarclaycardAuthSetupRequest {
payment_information: PaymentInformation,
client_reference_information: ClientReferenceInformation,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BarclaycardAuthValidateRequest {
payment_information: PaymentInformation,
client_reference_information: ClientReferenceInformation,
consumer_authentication_information: BarclaycardConsumerAuthInformationValidateRequest,
order_information: OrderInformation,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BarclaycardAuthEnrollmentRequest {
payment_information: PaymentInformation,
client_reference_information: ClientReferenceInformation,
consumer_authentication_information: BarclaycardConsumerAuthInformationRequest,
order_information: OrderInformationWithBill,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct BarclaycardRedirectionAuthResponse {
pub transaction_id: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BarclaycardConsumerAuthInformationRequest {
return_url: String,
reference_id: String,
}
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum BarclaycardPreProcessingRequest {
AuthEnrollment(Box<BarclaycardAuthEnrollmentRequest>),
AuthValidate(Box<BarclaycardAuthValidateRequest>),
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BarclaycardConsumerAuthInformationResponse {
access_token: String,
device_data_collection_url: String,
reference_id: String,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ClientAuthSetupInfoResponse {
id: String,
client_reference_information: ClientReferenceInformation,
consumer_authentication_information: BarclaycardConsumerAuthInformationResponse,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum BarclaycardAuthSetupResponse {
ClientAuthSetupInfo(Box<ClientAuthSetupInfoResponse>),
ErrorInformation(Box<BarclaycardErrorInformationResponse>),
}
impl TryFrom<&BarclaycardRouterData<&PaymentsPreProcessingRouterData>>
for BarclaycardPreProcessingRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &BarclaycardRouterData<&PaymentsPreProcessingRouterData>,
) -> Result<Self, Self::Error> {
let client_reference_information = ClientReferenceInformation {
code: Some(item.router_data.connector_request_reference_id.clone()),
};
let payment_method_data = item.router_data.request.payment_method_data.clone().ok_or(
errors::ConnectorError::MissingConnectorRedirectionPayload {
field_name: "payment_method_data",
},
)?;
let payment_information = match payment_method_data {
PaymentMethodData::Card(ccard) => {
let card_type = match ccard
.card_network
.clone()
.and_then(get_barclaycard_card_type)
{
Some(card_network) => Some(card_network.to_string()),
None => ccard.get_card_issuer().ok().map(String::from),
};
Ok(PaymentInformation::Cards(Box::new(
CardPaymentInformation {
card: Card {
number: ccard.card_number,
expiration_month: ccard.card_exp_month,
expiration_year: ccard.card_exp_year,
security_code: ccard.card_cvc,
card_type,
type_selection_indicator: Some("1".to_owned()),
},
},
)))
}
PaymentMethodData::Wallet(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Barclaycard"),
))
}
}?;
let redirect_response = item.router_data.request.redirect_response.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "redirect_response",
},
)?;
let amount_details = Amount {
total_amount: item.amount.clone(),
currency: item.router_data.request.currency.ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "currency",
},
)?,
};
match redirect_response.params {
Some(param) if !param.clone().peek().is_empty() => {
let reference_id = param
.clone()
.peek()
.split_once('=')
.ok_or(errors::ConnectorError::MissingConnectorRedirectionPayload {
field_name: "request.redirect_response.params.reference_id",
})?
.1
.to_string();
let email = item
.router_data
.get_billing_email()
.or(item.router_data.request.get_email())?;
let bill_to = build_bill_to(item.router_data.get_billing_address()?, email)?;
let order_information = OrderInformationWithBill {
amount_details,
bill_to: Some(bill_to),
};
Ok(Self::AuthEnrollment(Box::new(
BarclaycardAuthEnrollmentRequest {
payment_information,
client_reference_information,
consumer_authentication_information:
BarclaycardConsumerAuthInformationRequest {
return_url: item
.router_data
.request
.get_complete_authorize_url()?,
reference_id,
},
order_information,
},
)))
}
Some(_) | None => {
let redirect_payload: BarclaycardRedirectionAuthResponse = redirect_response
.payload
.ok_or(errors::ConnectorError::MissingConnectorRedirectionPayload {
field_name: "request.redirect_response.payload",
})?
.peek()
.clone()
.parse_value("BarclaycardRedirectionAuthResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
let order_information = OrderInformation { amount_details };
Ok(Self::AuthValidate(Box::new(
BarclaycardAuthValidateRequest {
payment_information,
client_reference_information,
consumer_authentication_information:
BarclaycardConsumerAuthInformationValidateRequest {
authentication_transaction_id: redirect_payload.transaction_id,
},
order_information,
},
)))
}
}
}
}
impl TryFrom<PaymentsPreprocessingResponseRouterData<BarclaycardPreProcessingResponse>>
for PaymentsPreProcessingRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsPreprocessingResponseRouterData<BarclaycardPreProcessingResponse>,
) -> Result<Self, Self::Error> {
match item.response {
BarclaycardPreProcessingResponse::ClientAuthCheckInfo(info_response) => {
let status = enums::AttemptStatus::from(info_response.status);
let risk_info: Option<ClientRiskInformation> = None;
if utils::is_payment_failure(status) {
let response = Err(get_error_response(
&info_response.error_information,
&None,
&risk_info,
Some(status),
item.http_code,
info_response.id.clone(),
));
Ok(Self {
status,
response,
..item.data
})
} else {
let connector_response_reference_id = Some(
info_response
.client_reference_information
.code
.unwrap_or(info_response.id.clone()),
);
let redirection_data = match (
info_response
.consumer_authentication_information
.access_token,
info_response
.consumer_authentication_information
.step_up_url,
| 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/novalnet/transformers.rs | crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs | use std::collections::HashMap;
use api_models::webhooks::IncomingWebhookEvent;
use cards::CardNumber;
use common_enums::{enums, enums as api_enums};
use common_utils::{
consts,
ext_traits::OptionExt,
pii::Email,
request::Method,
types::{MinorUnit, StringMinorUnit},
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{
BankDebitData, PaymentMethodData, WalletData as WalletDataPaymentMethod,
},
router_data::{ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::{PaymentsSyncData, ResponseId},
router_response_types::{
MandateReference, PaymentsResponseData, RedirectForm, RefundsResponseData,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, SetupMandateRouterData,
},
};
use hyperswitch_interfaces::errors;
use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use strum::Display;
use crate::{
types::{
PaymentsCancelResponseRouterData, PaymentsCaptureResponseRouterData,
RefundsResponseRouterData, ResponseRouterData,
},
utils::{
self, AddressData, AddressDetailsData, ApplePay, PaymentsAuthorizeRequestData,
PaymentsCancelRequestData, PaymentsCaptureRequestData, PaymentsSetupMandateRequestData,
PaymentsSyncRequestData, RefundsRequestData, RouterData as _,
},
};
pub struct NovalnetRouterData<T> {
pub amount: StringMinorUnit,
pub router_data: T,
}
impl<T> From<(StringMinorUnit, T)> for NovalnetRouterData<T> {
fn from((amount, item): (StringMinorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
const MINIMAL_CUSTOMER_DATA_PASSED: i64 = 1;
const CREATE_TOKEN_REQUIRED: i8 = 1;
const TEST_MODE_ENABLED: i8 = 1;
const TEST_MODE_DISABLED: i8 = 0;
fn get_test_mode(item: Option<bool>) -> i8 {
match item {
Some(true) => TEST_MODE_ENABLED,
Some(false) | None => TEST_MODE_DISABLED,
}
}
#[derive(Debug, Copy, Serialize, Deserialize, Clone)]
pub enum NovalNetPaymentTypes {
CREDITCARD,
PAYPAL,
GOOGLEPAY,
APPLEPAY,
#[serde(rename = "DIRECT_DEBIT_SEPA")]
DirectDebitSepa,
#[serde(rename = "GUARANTEED_DIRECT_DEBIT_SEPA")]
GuaranteedDirectDebitSepa,
#[serde(rename = "RETURN_DEBIT_SEPA")]
ReturnDebitSepa,
}
#[derive(Default, Debug, Serialize, Clone)]
pub struct NovalnetPaymentsRequestMerchant {
signature: Secret<String>,
tariff: Secret<String>,
}
#[derive(Default, Debug, Serialize, Clone)]
pub struct NovalnetPaymentsRequestBilling {
house_no: Option<Secret<String>>,
street: Option<Secret<String>>,
city: Option<Secret<String>>,
zip: Option<Secret<String>>,
country_code: Option<api_enums::CountryAlpha2>,
}
#[derive(Default, Debug, Serialize, Clone)]
pub struct NovalnetPaymentsRequestCustomer {
first_name: Option<Secret<String>>,
last_name: Option<Secret<String>>,
email: Email,
mobile: Option<Secret<String>>,
billing: Option<NovalnetPaymentsRequestBilling>,
no_nc: i64,
birth_date: Option<String>, // Mandatory for SEPA Guarentee Payment
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct NovalnetCard {
card_number: CardNumber,
card_expiry_month: Secret<String>,
card_expiry_year: Secret<String>,
card_cvc: Secret<String>,
card_holder: Secret<String>,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct NovalnetRawCardDetails {
card_number: CardNumber,
card_expiry_month: Secret<String>,
card_expiry_year: Secret<String>,
scheme_tid: Secret<String>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct NovalnetMandate {
token: Secret<String>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct NovalnetSepaDebit {
account_holder: Secret<String>,
iban: Secret<String>,
birth_date: Option<String>, // Mandatory for SEPA Guarantee Payment
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct NovalnetGooglePay {
wallet_data: Secret<String>,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct NovalnetApplePay {
wallet_data: Secret<String>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(untagged)]
pub enum NovalNetPaymentData {
Card(NovalnetCard),
RawCardForNTI(NovalnetRawCardDetails),
GooglePay(NovalnetGooglePay),
ApplePay(NovalnetApplePay),
MandatePayment(NovalnetMandate),
Sepa(NovalnetSepaDebit),
}
#[derive(Default, Debug, Serialize, Clone)]
pub struct NovalnetCustom {
lang: String,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(untagged)]
pub enum NovalNetAmount {
StringMinor(StringMinorUnit),
Int(i64),
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct NovalnetPaymentsRequestTransaction {
test_mode: i8,
payment_type: NovalNetPaymentTypes,
amount: NovalNetAmount,
currency: common_enums::Currency,
order_no: String,
payment_data: Option<NovalNetPaymentData>,
hook_url: Option<String>,
return_url: Option<String>,
error_return_url: Option<String>,
enforce_3d: Option<i8>, //NOTE: Needed for CREDITCARD, GOOGLEPAY
create_token: Option<i8>,
}
#[derive(Debug, Serialize, Clone)]
pub struct NovalnetPaymentsRequest {
merchant: NovalnetPaymentsRequestMerchant,
customer: NovalnetPaymentsRequestCustomer,
transaction: NovalnetPaymentsRequestTransaction,
custom: NovalnetCustom,
}
impl TryFrom<&api_enums::PaymentMethodType> for NovalNetPaymentTypes {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &api_enums::PaymentMethodType) -> Result<Self, Self::Error> {
match item {
api_enums::PaymentMethodType::ApplePay => Ok(Self::APPLEPAY),
api_enums::PaymentMethodType::Credit | api_enums::PaymentMethodType::Debit => {
Ok(Self::CREDITCARD)
}
api_enums::PaymentMethodType::GooglePay => Ok(Self::GOOGLEPAY),
api_enums::PaymentMethodType::Paypal => Ok(Self::PAYPAL),
api_enums::PaymentMethodType::Sepa => Ok(Self::DirectDebitSepa),
api_enums::PaymentMethodType::SepaGuarenteedDebit => {
Ok(Self::GuaranteedDirectDebitSepa)
}
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Novalnet"),
)
.into()),
}
}
}
impl TryFrom<&NovalnetRouterData<&PaymentsAuthorizeRouterData>> for NovalnetPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &NovalnetRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let auth = NovalnetAuthType::try_from(&item.router_data.connector_auth_type)?;
let merchant = NovalnetPaymentsRequestMerchant {
signature: auth.product_activation_key,
tariff: auth.tariff_id,
};
let enforce_3d = match item.router_data.auth_type {
enums::AuthenticationType::ThreeDs => Some(1),
enums::AuthenticationType::NoThreeDs => None,
};
let test_mode = get_test_mode(item.router_data.test_mode);
let billing = NovalnetPaymentsRequestBilling {
house_no: item.router_data.get_optional_billing_line1(),
street: item.router_data.get_optional_billing_line2(),
city: item
.router_data
.get_optional_billing_city()
.map(Secret::new),
zip: item.router_data.get_optional_billing_zip(),
country_code: item.router_data.get_optional_billing_country(),
};
let customer = NovalnetPaymentsRequestCustomer {
first_name: item.router_data.get_optional_billing_first_name(),
last_name: item.router_data.get_optional_billing_last_name(),
email: item
.router_data
.get_billing_email()
.or(item.router_data.request.get_email())?,
mobile: item.router_data.get_optional_billing_phone_number(),
billing: Some(billing),
// no_nc is used to indicate if minimal customer data is passed or not
no_nc: MINIMAL_CUSTOMER_DATA_PASSED,
birth_date: Some(String::from("1992-06-10")),
};
let lang = item
.router_data
.request
.get_optional_language_from_browser_info()
.unwrap_or(consts::DEFAULT_LOCALE.to_string().to_string());
let custom = NovalnetCustom { lang };
let hook_url = item.router_data.request.get_webhook_url()?;
let return_url = item.router_data.request.get_router_return_url()?;
let create_token = if item.router_data.request.is_mandate_payment() {
Some(CREATE_TOKEN_REQUIRED)
} else {
None
};
match item
.router_data
.request
.mandate_id
.clone()
.and_then(|mandate_id| mandate_id.mandate_reference_id)
{
None => match &item.router_data.request.payment_method_data {
PaymentMethodData::Card(ref req_card) => {
let novalnet_card = NovalNetPaymentData::Card(NovalnetCard {
card_number: req_card.card_number.clone(),
card_expiry_month: req_card.card_exp_month.clone(),
card_expiry_year: req_card.card_exp_year.clone(),
card_cvc: req_card.card_cvc.clone(),
card_holder: item.router_data.get_billing_full_name()?,
});
let transaction = NovalnetPaymentsRequestTransaction {
test_mode,
payment_type: NovalNetPaymentTypes::CREDITCARD,
amount: NovalNetAmount::StringMinor(item.amount.clone()),
currency: item.router_data.request.currency,
order_no: item.router_data.connector_request_reference_id.clone(),
hook_url: Some(hook_url),
return_url: Some(return_url.clone()),
error_return_url: Some(return_url.clone()),
payment_data: Some(novalnet_card),
enforce_3d,
create_token,
};
Ok(Self {
merchant,
transaction,
customer,
custom,
})
}
PaymentMethodData::Wallet(ref wallet_data) => match wallet_data {
WalletDataPaymentMethod::GooglePay(ref req_wallet) => {
let novalnet_google_pay: NovalNetPaymentData =
NovalNetPaymentData::GooglePay(NovalnetGooglePay {
wallet_data: Secret::new(
req_wallet
.tokenization_data
.get_encrypted_google_pay_token()
.change_context(
errors::ConnectorError::MissingRequiredField {
field_name: "gpay wallet_token",
},
)?
.clone(),
),
});
let transaction = NovalnetPaymentsRequestTransaction {
test_mode,
payment_type: NovalNetPaymentTypes::GOOGLEPAY,
amount: NovalNetAmount::StringMinor(item.amount.clone()),
currency: item.router_data.request.currency,
order_no: item.router_data.connector_request_reference_id.clone(),
hook_url: Some(hook_url),
return_url: None,
error_return_url: None,
payment_data: Some(novalnet_google_pay),
enforce_3d,
create_token,
};
Ok(Self {
merchant,
transaction,
customer,
custom,
})
}
WalletDataPaymentMethod::ApplePay(payment_method_data) => {
let transaction = NovalnetPaymentsRequestTransaction {
test_mode,
payment_type: NovalNetPaymentTypes::APPLEPAY,
amount: NovalNetAmount::StringMinor(item.amount.clone()),
currency: item.router_data.request.currency,
order_no: item.router_data.connector_request_reference_id.clone(),
hook_url: Some(hook_url),
return_url: None,
error_return_url: None,
payment_data: Some(NovalNetPaymentData::ApplePay(NovalnetApplePay {
wallet_data: payment_method_data
.get_applepay_decoded_payment_data()?,
})),
enforce_3d: None,
create_token,
};
Ok(Self {
merchant,
transaction,
customer,
custom,
})
}
WalletDataPaymentMethod::AliPayQr(_)
| WalletDataPaymentMethod::AliPayRedirect(_)
| WalletDataPaymentMethod::AliPayHkRedirect(_)
| WalletDataPaymentMethod::AmazonPay(_)
| WalletDataPaymentMethod::AmazonPayRedirect(_)
| WalletDataPaymentMethod::Paysera(_)
| WalletDataPaymentMethod::Skrill(_)
| WalletDataPaymentMethod::BluecodeRedirect {}
| WalletDataPaymentMethod::MomoRedirect(_)
| WalletDataPaymentMethod::KakaoPayRedirect(_)
| WalletDataPaymentMethod::GoPayRedirect(_)
| WalletDataPaymentMethod::GcashRedirect(_)
| WalletDataPaymentMethod::ApplePayRedirect(_)
| WalletDataPaymentMethod::ApplePayThirdPartySdk(_)
| WalletDataPaymentMethod::DanaRedirect {}
| WalletDataPaymentMethod::GooglePayRedirect(_)
| WalletDataPaymentMethod::GooglePayThirdPartySdk(_)
| WalletDataPaymentMethod::MbWayRedirect(_)
| WalletDataPaymentMethod::MobilePayRedirect(_)
| WalletDataPaymentMethod::RevolutPay(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("novalnet"),
)
.into())
}
WalletDataPaymentMethod::PaypalRedirect(_) => {
let transaction = NovalnetPaymentsRequestTransaction {
test_mode,
payment_type: NovalNetPaymentTypes::PAYPAL,
amount: NovalNetAmount::StringMinor(item.amount.clone()),
currency: item.router_data.request.currency,
order_no: item.router_data.connector_request_reference_id.clone(),
hook_url: Some(hook_url),
return_url: Some(return_url.clone()),
error_return_url: Some(return_url.clone()),
payment_data: None,
enforce_3d: None,
create_token,
};
Ok(Self {
merchant,
transaction,
customer,
custom,
})
}
WalletDataPaymentMethod::PaypalSdk(_)
| WalletDataPaymentMethod::Paze(_)
| WalletDataPaymentMethod::SamsungPay(_)
| WalletDataPaymentMethod::TwintRedirect {}
| WalletDataPaymentMethod::VippsRedirect {}
| WalletDataPaymentMethod::TouchNGoRedirect(_)
| WalletDataPaymentMethod::WeChatPayRedirect(_)
| WalletDataPaymentMethod::CashappQr(_)
| WalletDataPaymentMethod::SwishQr(_)
| WalletDataPaymentMethod::WeChatPayQr(_)
| WalletDataPaymentMethod::Mifinity(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("novalnet"),
)
.into())
}
},
PaymentMethodData::BankDebit(bank_debit_data) => {
let payment_type = NovalNetPaymentTypes::try_from(
&item
.router_data
.request
.payment_method_type
.ok_or(errors::ConnectorError::MissingPaymentMethodType)?,
)?;
let (iban, account_holder, dob) = match bank_debit_data {
BankDebitData::SepaBankDebit {
iban,
bank_account_holder_name,
} => {
let account_holder = match bank_account_holder_name {
Some(name) => name.clone(),
None => item.router_data.get_billing_full_name()?,
};
(iban, account_holder, None)
}
BankDebitData::SepaGuarenteedBankDebit {
iban,
bank_account_holder_name,
} => {
let account_holder = match bank_account_holder_name {
Some(name) => name.clone(),
None => item.router_data.get_billing_full_name()?,
};
(iban, account_holder, Some(String::from("1992-06-10")))
}
_ => {
return Err(
errors::ConnectorError::NotImplemented("SEPA".to_string()).into()
);
}
};
let transaction = NovalnetPaymentsRequestTransaction {
test_mode,
payment_type,
amount: NovalNetAmount::StringMinor(item.amount.clone()),
currency: item.router_data.request.currency,
order_no: item.router_data.connector_request_reference_id.clone(),
hook_url: Some(hook_url),
return_url: Some(return_url.clone()),
error_return_url: Some(return_url.clone()),
payment_data: Some(NovalNetPaymentData::Sepa(NovalnetSepaDebit {
account_holder: account_holder.clone(),
iban: iban.clone(),
birth_date: dob,
})),
enforce_3d,
create_token,
};
Ok(Self {
merchant,
transaction,
customer,
custom,
})
}
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("novalnet"),
)
.into()),
},
Some(api_models::payments::MandateReferenceId::ConnectorMandateId(mandate_data)) => {
let connector_mandate_id = mandate_data.get_connector_mandate_id().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "connector_mandate_id",
},
)?;
let novalnet_mandate_data = NovalNetPaymentData::MandatePayment(NovalnetMandate {
token: Secret::new(connector_mandate_id),
});
let payment_type = match item.router_data.request.payment_method_type {
Some(pm_type) => NovalNetPaymentTypes::try_from(&pm_type)?,
None => NovalNetPaymentTypes::CREDITCARD,
};
let transaction = NovalnetPaymentsRequestTransaction {
test_mode,
payment_type,
amount: NovalNetAmount::StringMinor(item.amount.clone()),
currency: item.router_data.request.currency,
order_no: item.router_data.connector_request_reference_id.clone(),
hook_url: Some(hook_url),
return_url: None,
error_return_url: None,
payment_data: Some(novalnet_mandate_data),
enforce_3d,
create_token: None,
};
Ok(Self {
merchant,
transaction,
customer,
custom,
})
}
Some(api_models::payments::MandateReferenceId::NetworkMandateId(
network_transaction_id,
)) => match item.router_data.request.payment_method_data {
PaymentMethodData::CardDetailsForNetworkTransactionId(ref raw_card_details) => {
let novalnet_card =
NovalNetPaymentData::RawCardForNTI(NovalnetRawCardDetails {
card_number: raw_card_details.card_number.clone(),
card_expiry_month: raw_card_details.card_exp_month.clone(),
card_expiry_year: raw_card_details.card_exp_year.clone(),
scheme_tid: network_transaction_id.into(),
});
let transaction = NovalnetPaymentsRequestTransaction {
test_mode,
payment_type: NovalNetPaymentTypes::CREDITCARD,
amount: NovalNetAmount::StringMinor(item.amount.clone()),
currency: item.router_data.request.currency,
order_no: item.router_data.connector_request_reference_id.clone(),
hook_url: Some(hook_url),
return_url: Some(return_url.clone()),
error_return_url: Some(return_url.clone()),
payment_data: Some(novalnet_card),
enforce_3d,
create_token,
};
Ok(Self {
merchant,
transaction,
customer,
custom,
})
}
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("novalnet"),
)
.into()),
},
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("novalnet"),
)
.into()),
}
}
}
// Auth Struct
pub struct NovalnetAuthType {
pub(super) product_activation_key: Secret<String>,
pub(super) payment_access_key: Secret<String>,
pub(super) tariff_id: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for NovalnetAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} => Ok(Self {
product_activation_key: api_key.to_owned(),
payment_access_key: key1.to_owned(),
tariff_id: api_secret.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
// PaymentsResponse
#[derive(Debug, Display, Copy, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum NovalnetTransactionStatus {
Success,
Failure,
Confirmed,
OnHold,
Pending,
Deactivated,
Progress,
Error,
}
#[derive(Debug, Copy, Display, Clone, Serialize, Deserialize, PartialEq)]
#[strum(serialize_all = "UPPERCASE")]
#[serde(rename_all = "UPPERCASE")]
pub enum NovalnetAPIStatus {
Success,
Failure,
}
impl From<NovalnetTransactionStatus> for common_enums::AttemptStatus {
fn from(item: NovalnetTransactionStatus) -> Self {
match item {
NovalnetTransactionStatus::Success | NovalnetTransactionStatus::Confirmed => {
Self::Charged
}
NovalnetTransactionStatus::OnHold => Self::Authorized,
NovalnetTransactionStatus::Pending => Self::Pending,
NovalnetTransactionStatus::Progress => Self::AuthenticationPending,
NovalnetTransactionStatus::Deactivated => Self::Voided,
NovalnetTransactionStatus::Failure | NovalnetTransactionStatus::Error => Self::Failure,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResultData {
pub redirect_url: Option<Secret<url::Url>>,
pub status: NovalnetAPIStatus,
pub status_code: u64,
pub status_text: String,
pub additional_message: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NovalnetPaymentsResponseTransactionData {
pub amount: Option<MinorUnit>,
pub currency: Option<common_enums::Currency>,
pub date: Option<String>,
pub order_no: Option<String>,
pub payment_data: Option<NovalnetResponsePaymentData>,
pub payment_type: Option<String>,
pub status_code: Option<u64>,
pub txn_secret: Option<Secret<String>>,
pub tid: Option<Secret<i64>>,
pub test_mode: Option<i8>,
pub status: Option<NovalnetTransactionStatus>,
pub authorization: Option<NovalnetAuthorizationResponse>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NovalnetPaymentsResponse {
result: ResultData,
transaction: Option<NovalnetPaymentsResponseTransactionData>,
}
pub fn get_error_response(result: ResultData, status_code: u16) -> ErrorResponse {
let error_code = result.status;
let error_reason = result.status_text.clone();
ErrorResponse {
code: error_code.to_string(),
message: error_reason.clone(),
reason: Some(error_reason),
status_code,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}
}
impl NovalnetPaymentsResponseTransactionData {
pub fn get_token(transaction_data: Option<&Self>) -> Option<String> {
if let Some(data) = transaction_data {
match &data.payment_data {
Some(NovalnetResponsePaymentData::Card(card_data)) => {
card_data.token.clone().map(|token| token.expose())
}
Some(NovalnetResponsePaymentData::Paypal(paypal_data)) => {
paypal_data.token.clone().map(|token| token.expose())
}
None => None,
}
} else {
None
}
}
}
impl<F, T> TryFrom<ResponseRouterData<F, NovalnetPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, NovalnetPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
match item.response.result.status {
NovalnetAPIStatus::Success => {
let redirection_data: Option<RedirectForm> =
item.response
.result
.redirect_url
.map(|url| RedirectForm::Form {
endpoint: url.expose().to_string(),
method: Method::Get,
form_fields: HashMap::new(),
});
let transaction_id = item
.response
.transaction
.clone()
.and_then(|data| data.tid.map(|tid| tid.expose().to_string()));
let mandate_reference_id = NovalnetPaymentsResponseTransactionData::get_token(
item.response.transaction.clone().as_ref(),
);
let transaction_status = item
.response
.transaction
.as_ref()
.and_then(|transaction_data| transaction_data.status)
.unwrap_or(if redirection_data.is_some() {
NovalnetTransactionStatus::Progress
// NOTE: Novalnet does not send us the transaction.status for redirection flow
// so status is mapped to Progress if flow has redirection data
} else {
NovalnetTransactionStatus::Pending
});
Ok(Self {
status: common_enums::AttemptStatus::from(transaction_status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: transaction_id
.clone()
.map(ResponseId::ConnectorTransactionId)
.unwrap_or(ResponseId::NoResponseId),
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(mandate_reference_id.as_ref().map(|id| {
MandateReference {
connector_mandate_id: Some(id.clone()),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
}
})),
connector_metadata: None,
network_txn_id: item.response.transaction.and_then(|data| {
data.payment_data
.and_then(|payment_data| match payment_data {
NovalnetResponsePaymentData::Card(card) => {
card.scheme_tid.map(|tid| tid.expose())
}
NovalnetResponsePaymentData::Paypal(_) => None,
})
}),
connector_response_reference_id: transaction_id.clone(),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
NovalnetAPIStatus::Failure => {
| 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/datatrans/transformers.rs | crates/hyperswitch_connectors/src/connectors/datatrans/transformers.rs | use std::collections::HashMap;
use api_models::payments::{self, AdditionalPaymentData};
use common_enums::enums;
use common_utils::{pii::Email, request::Method, types::MinorUnit};
use hyperswitch_domain_models::{
payment_method_data::{Card, PaymentMethodData},
router_data::{ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::{PaymentsAuthorizeData, ResponseId, SetupMandateRequestData},
router_response_types::{
MandateReference, PaymentsResponseData, RedirectForm, RefundsResponseData,
},
types,
};
use hyperswitch_interfaces::{
consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE},
errors,
};
use masking::Secret;
use serde::{Deserialize, Serialize};
use crate::{
types::{
PaymentsCancelResponseRouterData, PaymentsCaptureResponseRouterData,
PaymentsSyncResponseRouterData, RefundsResponseRouterData, ResponseRouterData,
},
utils::{
get_unimplemented_payment_method_error_message, AdditionalCardInfo, CardData as _,
PaymentsAuthorizeRequestData, RouterData as _,
},
};
const TRANSACTION_ALREADY_CANCELLED: &str = "transaction already canceled";
const TRANSACTION_ALREADY_SETTLED: &str = "already settled";
const REDIRECTION_SBX_URL: &str = "https://pay.sandbox.datatrans.com";
const REDIRECTION_PROD_URL: &str = "https://pay.datatrans.com";
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct DatatransErrorResponse {
pub error: DatatransError,
}
pub struct DatatransAuthType {
pub(super) merchant_id: Secret<String>,
pub(super) passcode: Secret<String>,
}
pub struct DatatransRouterData<T> {
pub amount: MinorUnit,
pub router_data: T,
}
#[derive(Debug, Serialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct DatatransPaymentsRequest {
pub amount: Option<MinorUnit>,
pub currency: enums::Currency,
pub card: DataTransPaymentDetails,
pub refno: String,
pub auto_settle: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub redirect: Option<RedirectUrls>,
pub option: Option<DataTransCreateAlias>,
}
#[derive(Debug, Serialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct DataTransCreateAlias {
pub create_alias: bool,
}
#[derive(Debug, Serialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct RedirectUrls {
pub success_url: Option<String>,
pub cancel_url: Option<String>,
pub error_url: Option<String>,
}
#[derive(Debug, Deserialize, Clone, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum TransactionType {
Payment,
Credit,
CardCheck,
}
#[derive(Debug, Deserialize, Clone, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum TransactionStatus {
Initialized,
Authenticated,
Authorized,
Settled,
Canceled,
Transmitted,
Failed,
ChallengeOngoing,
ChallengeRequired,
}
#[derive(Debug, Deserialize, Clone, Serialize)]
#[serde(untagged)]
pub enum DatatransSyncResponse {
Error(DatatransError),
Response(SyncResponse),
}
#[derive(Debug, Deserialize, Serialize)]
pub enum DataTransCaptureResponse {
Error(DatatransError),
Empty,
}
#[derive(Debug, Deserialize, Serialize)]
pub enum DataTransCancelResponse {
Error(DatatransError),
Empty,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
pub struct SyncResponse {
pub transaction_id: String,
#[serde(rename = "type")]
pub res_type: TransactionType,
pub status: TransactionStatus,
pub detail: SyncDetails,
pub card: Option<SyncCardDetails>,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
pub struct SyncCardDetails {
pub alias: Option<String>,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
pub struct SyncDetails {
fail: Option<FailDetails>,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
pub struct FailDetails {
reason: Option<String>,
message: Option<String>,
}
#[derive(Serialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
#[serde(untagged)]
pub enum DataTransPaymentDetails {
Cards(PlainCardDetails),
Mandate(MandateDetails),
}
#[derive(Serialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
pub struct PlainCardDetails {
#[serde(rename = "type")]
pub res_type: String,
pub number: cards::CardNumber,
pub expiry_month: Secret<String>,
pub expiry_year: Secret<String>,
pub cvv: Secret<String>,
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(rename = "3D")]
pub three_ds: Option<ThreeDSecureData>,
}
#[derive(Serialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
pub struct MandateDetails {
#[serde(rename = "type")]
pub res_type: String,
pub alias: String,
pub expiry_month: Secret<String>,
pub expiry_year: Secret<String>,
}
#[derive(Serialize, Clone, Debug)]
pub struct ThreedsInfo {
cardholder: CardHolder,
}
#[derive(Serialize, Clone, Debug)]
#[serde(untagged)]
pub enum ThreeDSecureData {
Cardholder(ThreedsInfo),
Authentication(ThreeDSData),
}
#[derive(Debug, Serialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct ThreeDSData {
#[serde(rename = "threeDSTransactionId")]
pub three_ds_transaction_id: Option<Secret<String>>,
pub cavv: Secret<String>,
pub eci: Option<String>,
pub xid: Option<Secret<String>>,
#[serde(rename = "threeDSVersion")]
pub three_ds_version: Option<String>,
#[serde(rename = "authenticationResponse")]
pub authentication_response: String,
}
#[derive(Debug, Serialize, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CardHolder {
cardholder_name: Secret<String>,
email: Email,
}
#[derive(Debug, Clone, Serialize, Default, Deserialize)]
pub struct DatatransError {
pub code: String,
pub message: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum DatatransResponse {
TransactionResponse(DatatransSuccessResponse),
ErrorResponse(DatatransError),
ThreeDSResponse(Datatrans3DSResponse),
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DatatransSuccessResponse {
pub transaction_id: String,
pub acquirer_authorization_code: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum DatatransRefundsResponse {
Success(DatatransSuccessResponse),
Error(DatatransError),
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Datatrans3DSResponse {
pub transaction_id: String,
#[serde(rename = "3D")]
pub three_ds_enrolled: ThreeDSEnolled,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ThreeDSEnolled {
pub enrolled: bool,
}
#[derive(Default, Debug, Serialize)]
pub struct DatatransRefundRequest {
pub amount: MinorUnit,
pub currency: enums::Currency,
pub refno: String,
}
#[derive(Debug, Serialize, Clone)]
pub struct DataPaymentCaptureRequest {
pub amount: MinorUnit,
pub currency: enums::Currency,
pub refno: String,
}
impl<T> TryFrom<(MinorUnit, T)> for DatatransRouterData<T> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from((amount, item): (MinorUnit, T)) -> Result<Self, Self::Error> {
Ok(Self {
amount,
router_data: item,
})
}
}
impl TryFrom<&types::SetupMandateRouterData> for DatatransPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::SetupMandateRouterData) -> Result<Self, Self::Error> {
match item.request.payment_method_data.clone() {
PaymentMethodData::Card(req_card) => Ok(Self {
amount: None,
currency: item.request.currency,
card: DataTransPaymentDetails::Cards(PlainCardDetails {
res_type: "PLAIN".to_string(),
number: req_card.card_number.clone(),
expiry_month: req_card.card_exp_month.clone(),
expiry_year: req_card.get_card_expiry_year_2_digit()?,
cvv: req_card.card_cvc.clone(),
three_ds: Some(ThreeDSecureData::Cardholder(ThreedsInfo {
cardholder: CardHolder {
cardholder_name: item.get_billing_full_name()?,
email: item.get_billing_email()?,
},
})),
}),
refno: item.connector_request_reference_id.clone(),
auto_settle: true, // zero auth doesn't support manual capture
option: Some(DataTransCreateAlias { create_alias: true }),
redirect: Some(RedirectUrls {
success_url: item.request.router_return_url.clone(),
cancel_url: item.request.router_return_url.clone(),
error_url: item.request.router_return_url.clone(),
}),
}),
PaymentMethodData::Wallet(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Crypto(_)
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("Datatrans"),
))?
}
}
}
}
impl TryFrom<&DatatransRouterData<&types::PaymentsAuthorizeRouterData>>
for DatatransPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &DatatransRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(req_card) => {
let is_mandate_payment = item.router_data.request.is_mandate_payment();
let option =
is_mandate_payment.then_some(DataTransCreateAlias { create_alias: true });
// provides return url for only mandate payment(CIT) or 3ds through datatrans
let redirect = if is_mandate_payment
|| (item.router_data.is_three_ds()
&& item.router_data.request.authentication_data.is_none())
{
Some(RedirectUrls {
success_url: item.router_data.request.router_return_url.clone(),
cancel_url: item.router_data.request.router_return_url.clone(),
error_url: item.router_data.request.router_return_url.clone(),
})
} else {
None
};
Ok(Self {
amount: Some(item.amount),
currency: item.router_data.request.currency,
card: create_card_details(item, &req_card)?,
refno: item.router_data.connector_request_reference_id.clone(),
auto_settle: item.router_data.request.is_auto_capture()?,
option,
redirect,
})
}
PaymentMethodData::MandatePayment => {
let additional_payment_data = match item
.router_data
.request
.additional_payment_method_data
.clone()
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "additional_payment_method_data",
})? {
AdditionalPaymentData::Card(card) => *card,
_ => Err(errors::ConnectorError::NotSupported {
message: "Payment Method Not Supported".to_string(),
connector: "DataTrans",
})?,
};
Ok(Self {
amount: Some(item.amount),
currency: item.router_data.request.currency,
card: create_mandate_details(item, &additional_payment_data)?,
refno: item.router_data.connector_request_reference_id.clone(),
auto_settle: item.router_data.request.is_auto_capture()?,
option: None,
redirect: None,
})
}
PaymentMethodData::Wallet(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("Datatrans"),
))?
}
}
}
}
impl TryFrom<&ConnectorAuthType> for DatatransAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
merchant_id: key1.clone(),
passcode: api_key.clone(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
fn get_status(item: &DatatransResponse, is_auto_capture: bool) -> enums::AttemptStatus {
match item {
DatatransResponse::ErrorResponse(_) => enums::AttemptStatus::Failure,
DatatransResponse::TransactionResponse(_) => {
if is_auto_capture {
enums::AttemptStatus::Charged
} else {
enums::AttemptStatus::Authorized
}
}
DatatransResponse::ThreeDSResponse(_) => enums::AttemptStatus::AuthenticationPending,
}
}
fn create_card_details(
item: &DatatransRouterData<&types::PaymentsAuthorizeRouterData>,
card: &Card,
) -> Result<DataTransPaymentDetails, error_stack::Report<errors::ConnectorError>> {
let mut details = PlainCardDetails {
res_type: "PLAIN".to_string(),
number: card.card_number.clone(),
expiry_month: card.card_exp_month.clone(),
expiry_year: card.get_card_expiry_year_2_digit()?,
cvv: card.card_cvc.clone(),
three_ds: None,
};
if let Some(auth_data) = &item.router_data.request.authentication_data {
details.three_ds = Some(ThreeDSecureData::Authentication(ThreeDSData {
three_ds_transaction_id: auth_data
.threeds_server_transaction_id
.clone()
.map(Secret::new),
cavv: auth_data.cavv.clone(),
eci: auth_data.eci.clone(),
xid: auth_data.ds_trans_id.clone().map(Secret::new),
three_ds_version: auth_data
.message_version
.clone()
.map(|version| version.to_string()),
authentication_response: "Y".to_string(),
}));
} else if item.router_data.is_three_ds() {
details.three_ds = Some(ThreeDSecureData::Cardholder(ThreedsInfo {
cardholder: CardHolder {
cardholder_name: item.router_data.get_billing_full_name()?,
email: item.router_data.get_billing_email()?,
},
}));
}
Ok(DataTransPaymentDetails::Cards(details))
}
fn create_mandate_details(
item: &DatatransRouterData<&types::PaymentsAuthorizeRouterData>,
additional_card_details: &payments::AdditionalCardInfo,
) -> Result<DataTransPaymentDetails, error_stack::Report<errors::ConnectorError>> {
let alias = item.router_data.request.get_connector_mandate_id()?;
Ok(DataTransPaymentDetails::Mandate(MandateDetails {
res_type: "ALIAS".to_string(),
alias,
expiry_month: additional_card_details.card_exp_month.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "card_exp_month",
},
)?,
expiry_year: additional_card_details.get_card_expiry_year_2_digit()?,
}))
}
impl From<SyncResponse> for enums::AttemptStatus {
fn from(item: SyncResponse) -> Self {
match item.res_type {
TransactionType::Payment => match item.status {
TransactionStatus::Authorized => Self::Authorized,
TransactionStatus::Settled | TransactionStatus::Transmitted => Self::Charged,
TransactionStatus::ChallengeOngoing | TransactionStatus::ChallengeRequired => {
Self::AuthenticationPending
}
TransactionStatus::Canceled => Self::Voided,
TransactionStatus::Failed => Self::Failure,
TransactionStatus::Initialized | TransactionStatus::Authenticated => Self::Pending,
},
TransactionType::CardCheck => match item.status {
TransactionStatus::Settled
| TransactionStatus::Transmitted
| TransactionStatus::Authorized => Self::Charged,
TransactionStatus::ChallengeOngoing | TransactionStatus::ChallengeRequired => {
Self::AuthenticationPending
}
TransactionStatus::Canceled => Self::Voided,
TransactionStatus::Failed => Self::Failure,
TransactionStatus::Initialized | TransactionStatus::Authenticated => Self::Pending,
},
TransactionType::Credit => Self::Failure,
}
}
}
impl From<SyncResponse> for enums::RefundStatus {
fn from(item: SyncResponse) -> Self {
match item.res_type {
TransactionType::Credit => match item.status {
TransactionStatus::Settled | TransactionStatus::Transmitted => Self::Success,
TransactionStatus::ChallengeOngoing | TransactionStatus::ChallengeRequired => {
Self::Pending
}
TransactionStatus::Initialized
| TransactionStatus::Authenticated
| TransactionStatus::Authorized
| TransactionStatus::Canceled
| TransactionStatus::Failed => Self::Failure,
},
TransactionType::Payment | TransactionType::CardCheck => Self::Failure,
}
}
}
impl<F>
TryFrom<ResponseRouterData<F, DatatransResponse, PaymentsAuthorizeData, PaymentsResponseData>>
for RouterData<F, PaymentsAuthorizeData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, DatatransResponse, PaymentsAuthorizeData, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let status = get_status(&item.response, item.data.request.is_auto_capture()?);
let response = match &item.response {
DatatransResponse::ErrorResponse(error) => Err(ErrorResponse {
code: error.code.clone(),
message: error.message.clone(),
reason: Some(error.message.clone()),
attempt_status: None,
connector_transaction_id: None,
status_code: item.http_code,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
DatatransResponse::TransactionResponse(response) => {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
response.transaction_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
})
}
DatatransResponse::ThreeDSResponse(response) => {
let redirection_link = match item.data.test_mode {
Some(true) => format!("{REDIRECTION_SBX_URL}/v1/start"),
Some(false) | None => format!("{REDIRECTION_PROD_URL}/v1/start"),
};
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
response.transaction_id.clone(),
),
redirection_data: Box::new(Some(RedirectForm::Form {
endpoint: format!("{}/{}", redirection_link, response.transaction_id),
method: Method::Get,
form_fields: HashMap::new(),
})),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
})
}
};
Ok(Self {
status,
response,
..item.data
})
}
}
impl<F>
TryFrom<ResponseRouterData<F, DatatransResponse, SetupMandateRequestData, PaymentsResponseData>>
for RouterData<F, SetupMandateRequestData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
DatatransResponse,
SetupMandateRequestData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
// zero auth doesn't support manual capture
let status = get_status(&item.response, true);
let response = match &item.response {
DatatransResponse::ErrorResponse(error) => Err(ErrorResponse {
code: error.code.clone(),
message: error.message.clone(),
reason: Some(error.message.clone()),
attempt_status: None,
connector_transaction_id: None,
status_code: item.http_code,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
DatatransResponse::TransactionResponse(response) => {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
response.transaction_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
})
}
DatatransResponse::ThreeDSResponse(response) => {
let redirection_link = match item.data.test_mode {
Some(true) => format!("{REDIRECTION_SBX_URL}/v1/start"),
Some(false) | None => format!("{REDIRECTION_PROD_URL}/v1/start"),
};
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
response.transaction_id.clone(),
),
redirection_data: Box::new(Some(RedirectForm::Form {
endpoint: format!("{}/{}", redirection_link, response.transaction_id),
method: Method::Get,
form_fields: HashMap::new(),
})),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
})
}
};
Ok(Self {
status,
response,
..item.data
})
}
}
impl<F> TryFrom<&DatatransRouterData<&types::RefundsRouterData<F>>> for DatatransRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &DatatransRouterData<&types::RefundsRouterData<F>>,
) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.amount.to_owned(),
currency: item.router_data.request.currency,
refno: item.router_data.request.refund_id.clone(),
})
}
}
impl TryFrom<RefundsResponseRouterData<Execute, DatatransRefundsResponse>>
for types::RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, DatatransRefundsResponse>,
) -> Result<Self, Self::Error> {
match item.response {
DatatransRefundsResponse::Error(error) => Ok(Self {
response: Err(ErrorResponse {
code: error.code.clone(),
message: error.message.clone(),
reason: Some(error.message),
attempt_status: None,
connector_transaction_id: None,
status_code: item.http_code,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
}),
DatatransRefundsResponse::Success(response) => Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: response.transaction_id,
refund_status: enums::RefundStatus::Success,
}),
..item.data
}),
}
}
}
impl TryFrom<RefundsResponseRouterData<RSync, DatatransSyncResponse>>
for types::RefundsRouterData<RSync>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, DatatransSyncResponse>,
) -> Result<Self, Self::Error> {
let response = match item.response {
DatatransSyncResponse::Error(error) => Err(ErrorResponse {
code: error.code.clone(),
message: error.message.clone(),
reason: Some(error.message),
attempt_status: None,
connector_transaction_id: None,
status_code: item.http_code,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
DatatransSyncResponse::Response(response) => Ok(RefundsResponseData {
connector_refund_id: response.transaction_id.to_string(),
refund_status: enums::RefundStatus::from(response),
}),
};
Ok(Self {
response,
..item.data
})
}
}
impl TryFrom<PaymentsSyncResponseRouterData<DatatransSyncResponse>>
for types::PaymentsSyncRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsSyncResponseRouterData<DatatransSyncResponse>,
) -> Result<Self, Self::Error> {
match item.response {
DatatransSyncResponse::Error(error) => {
let response = Err(ErrorResponse {
code: error.code.clone(),
message: error.message.clone(),
reason: Some(error.message),
attempt_status: None,
connector_transaction_id: None,
status_code: item.http_code,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
});
Ok(Self {
response,
..item.data
})
}
DatatransSyncResponse::Response(sync_response) => {
let status = enums::AttemptStatus::from(sync_response.clone());
let response = if status == enums::AttemptStatus::Failure {
let (code, message) = match sync_response.detail.fail {
Some(fail_details) => (
fail_details.reason.unwrap_or(NO_ERROR_CODE.to_string()),
fail_details.message.unwrap_or(NO_ERROR_MESSAGE.to_string()),
),
None => (NO_ERROR_CODE.to_string(), NO_ERROR_MESSAGE.to_string()),
};
Err(ErrorResponse {
code,
message: message.clone(),
reason: Some(message),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
let mandate_reference = sync_response
.card
.as_ref()
.and_then(|card| card.alias.as_ref())
.map(|alias| MandateReference {
connector_mandate_id: Some(alias.clone()),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
});
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
sync_response.transaction_id.to_string(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(mandate_reference),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
})
};
Ok(Self {
status,
response,
..item.data
})
}
}
}
}
impl TryFrom<&DatatransRouterData<&types::PaymentsCaptureRouterData>>
for DataPaymentCaptureRequest
{
| 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/deutschebank/transformers.rs | crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs | use std::collections::HashMap;
use cards::CardNumber;
use common_enums::{enums, PaymentMethod};
use common_utils::{ext_traits::ValueExt, pii::Email, types::MinorUnit};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{BankDebitData, PaymentMethodData},
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{
payments::{Authorize, Capture, CompleteAuthorize, PSync},
refunds::{Execute, RSync},
},
router_request_types::{
CompleteAuthorizeData, PaymentsAuthorizeData, PaymentsCaptureData, PaymentsSyncData,
ResponseId,
},
router_response_types::{
MandateReference, PaymentsResponseData, RedirectForm, RefundsResponseData,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsCompleteAuthorizeRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::{consts, errors};
use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
types::{PaymentsCancelResponseRouterData, RefundsResponseRouterData, ResponseRouterData},
utils::{
self, AddressDetailsData, CardData, PaymentsAuthorizeRequestData,
PaymentsCompleteAuthorizeRequestData, RefundsRequestData, RouterData as OtherRouterData,
},
};
pub struct DeutschebankRouterData<T> {
pub amount: MinorUnit,
pub router_data: T,
}
impl<T> From<(MinorUnit, T)> for DeutschebankRouterData<T> {
fn from((amount, item): (MinorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
pub struct DeutschebankAuthType {
pub(super) client_id: Secret<String>,
pub(super) merchant_id: Secret<String>,
pub(super) client_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for DeutschebankAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} => Ok(Self {
client_id: api_key.to_owned(),
merchant_id: key1.to_owned(),
client_key: api_secret.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Default, Debug, Serialize, PartialEq)]
pub struct DeutschebankAccessTokenRequest {
pub grant_type: String,
pub client_id: Secret<String>,
pub client_secret: Secret<String>,
pub scope: String,
}
#[derive(Default, Debug, Clone, Deserialize, PartialEq, Serialize)]
pub struct DeutschebankAccessTokenResponse {
pub access_token: Secret<String>,
pub expires_in: i64,
pub expires_on: i64,
pub scope: String,
pub token_type: String,
}
impl<F, T> TryFrom<ResponseRouterData<F, DeutschebankAccessTokenResponse, T, AccessToken>>
for RouterData<F, T, AccessToken>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, DeutschebankAccessTokenResponse, T, AccessToken>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(AccessToken {
token: item.response.access_token,
expires: item.response.expires_in,
}),
..item.data
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "UPPERCASE")]
pub enum DeutschebankSEPAApproval {
Click,
Email,
Sms,
Dynamic,
}
#[derive(Debug, Serialize, PartialEq)]
pub struct DeutschebankMandatePostRequest {
approval_by: DeutschebankSEPAApproval,
email_address: Email,
iban: Secret<String>,
first_name: Secret<String>,
last_name: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum DeutschebankPaymentsRequest {
MandatePost(DeutschebankMandatePostRequest),
DirectDebit(DeutschebankDirectDebitRequest),
CreditCard(Box<DeutschebankThreeDSInitializeRequest>),
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct DeutschebankThreeDSInitializeRequest {
means_of_payment: DeutschebankThreeDSInitializeRequestMeansOfPayment,
tds_20_data: DeutschebankThreeDSInitializeRequestTds20Data,
amount_total: DeutschebankThreeDSInitializeRequestAmountTotal,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct DeutschebankThreeDSInitializeRequestMeansOfPayment {
credit_card: DeutschebankThreeDSInitializeRequestCreditCard,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct DeutschebankThreeDSInitializeRequestCreditCard {
number: CardNumber,
expiry_date: DeutschebankThreeDSInitializeRequestCreditCardExpiry,
code: Secret<String>,
cardholder: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct DeutschebankThreeDSInitializeRequestCreditCardExpiry {
year: Secret<String>,
month: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct DeutschebankThreeDSInitializeRequestAmountTotal {
amount: MinorUnit,
currency: api_models::enums::Currency,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct DeutschebankThreeDSInitializeRequestTds20Data {
communication_data: DeutschebankThreeDSInitializeRequestCommunicationData,
customer_data: DeutschebankThreeDSInitializeRequestCustomerData,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct DeutschebankThreeDSInitializeRequestCommunicationData {
method_notification_url: String,
cres_notification_url: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct DeutschebankThreeDSInitializeRequestCustomerData {
billing_address: DeutschebankThreeDSInitializeRequestCustomerBillingData,
cardholder_email: Email,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct DeutschebankThreeDSInitializeRequestCustomerBillingData {
street: Secret<String>,
postal_code: Secret<String>,
city: String,
state: Secret<String>,
country: String,
}
impl TryFrom<&DeutschebankRouterData<&PaymentsAuthorizeRouterData>>
for DeutschebankPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &DeutschebankRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item
.router_data
.request
.mandate_id
.clone()
.and_then(|mandate_id| mandate_id.mandate_reference_id)
{
None => {
// To facilitate one-off payments via SEPA with Deutsche Bank, we are considering not storing the connector mandate ID in our system if future usage is on-session.
// We will only check for customer acceptance to make a one-off payment. we will be storing the connector mandate details only when setup future usage is off-session.
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::BankDebit(BankDebitData::SepaBankDebit { iban, .. }) => {
if item.router_data.request.customer_acceptance.is_some() {
let billing_address = item.router_data.get_billing_address()?;
Ok(Self::MandatePost(DeutschebankMandatePostRequest {
approval_by: DeutschebankSEPAApproval::Click,
email_address: item.router_data.request.get_email()?,
iban: Secret::from(iban.peek().replace(" ", "")),
first_name: billing_address.get_first_name()?.clone(),
last_name: billing_address.get_last_name()?.clone(),
}))
} else {
Err(errors::ConnectorError::MissingRequiredField {
field_name: "customer_acceptance",
}
.into())
}
}
PaymentMethodData::Card(ccard) => {
if !item.router_data.clone().is_three_ds() {
Err(errors::ConnectorError::NotSupported {
message: "Non-ThreeDs".to_owned(),
connector: "deutschebank",
}
.into())
} else {
let billing_address = item.router_data.get_billing_address()?;
Ok(Self::CreditCard(Box::new(DeutschebankThreeDSInitializeRequest {
means_of_payment: DeutschebankThreeDSInitializeRequestMeansOfPayment {
credit_card: DeutschebankThreeDSInitializeRequestCreditCard {
number: ccard.clone().card_number,
expiry_date: DeutschebankThreeDSInitializeRequestCreditCardExpiry {
year: ccard.get_expiry_year_4_digit(),
month: ccard.card_exp_month,
},
code: ccard.card_cvc,
cardholder: item.router_data.get_billing_full_name()?,
}},
amount_total: DeutschebankThreeDSInitializeRequestAmountTotal {
amount: item.amount,
currency: item.router_data.request.currency,
},
tds_20_data: DeutschebankThreeDSInitializeRequestTds20Data {
communication_data: DeutschebankThreeDSInitializeRequestCommunicationData {
method_notification_url: item.router_data.request.get_complete_authorize_url()?,
cres_notification_url: item.router_data.request.get_complete_authorize_url()?,
},
customer_data: DeutschebankThreeDSInitializeRequestCustomerData {
billing_address: DeutschebankThreeDSInitializeRequestCustomerBillingData {
street: billing_address.get_line1()?.clone(),
postal_code: billing_address.get_zip()?.clone(),
city: billing_address.get_city()?.to_string(),
state: billing_address.get_state()?.clone(),
country: item.router_data.get_billing_country()?.to_string(),
},
cardholder_email: item.router_data.request.get_email()?,
}
}
})))
}
}
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("deutschebank"),
)
.into()),
}
}
Some(api_models::payments::MandateReferenceId::ConnectorMandateId(mandate_data)) => {
let mandate_metadata: DeutschebankMandateMetadata = mandate_data
.get_mandate_metadata()
.ok_or(errors::ConnectorError::MissingConnectorMandateMetadata)?
.clone()
.parse_value("DeutschebankMandateMetadata")
.change_context(errors::ConnectorError::ParsingFailed)?;
Ok(Self::DirectDebit(DeutschebankDirectDebitRequest {
amount_total: DeutschebankAmount {
amount: item.amount,
currency: item.router_data.request.currency,
},
means_of_payment: DeutschebankMeansOfPayment {
bank_account: DeutschebankBankAccount {
account_holder: mandate_metadata.account_holder,
iban: mandate_metadata.iban,
},
},
mandate: DeutschebankMandate {
reference: mandate_metadata.reference,
signed_on: mandate_metadata.signed_on,
},
}))
}
Some(api_models::payments::MandateReferenceId::NetworkTokenWithNTI(_))
| Some(api_models::payments::MandateReferenceId::NetworkMandateId(_)) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("deutschebank"),
)
.into())
}
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct DeutschebankThreeDSInitializeResponse {
outcome: DeutschebankThreeDSInitializeResponseOutcome,
challenge_required: Option<DeutschebankThreeDSInitializeResponseChallengeRequired>,
processed: Option<DeutschebankThreeDSInitializeResponseProcessed>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct DeutschebankThreeDSInitializeResponseProcessed {
rc: String,
message: String,
tx_id: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum DeutschebankThreeDSInitializeResponseOutcome {
Processed,
ChallengeRequired,
MethodRequired,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct DeutschebankThreeDSInitializeResponseChallengeRequired {
acs_url: String,
creq: String,
}
impl
TryFrom<
ResponseRouterData<
Authorize,
DeutschebankThreeDSInitializeResponse,
PaymentsAuthorizeData,
PaymentsResponseData,
>,
> for RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
Authorize,
DeutschebankThreeDSInitializeResponse,
PaymentsAuthorizeData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
match item.response.outcome {
DeutschebankThreeDSInitializeResponseOutcome::Processed => {
match item.response.processed {
Some(processed) => Ok(Self {
status: if is_response_success(&processed.rc) {
match item.data.request.is_auto_capture()? {
true => common_enums::AttemptStatus::Charged,
false => common_enums::AttemptStatus::Authorized,
}
} else {
common_enums::AttemptStatus::AuthenticationFailed
},
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
processed.tx_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(processed.tx_id.clone()),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
}),
None => {
let response_string = format!("{:?}", item.response);
Err(
errors::ConnectorError::UnexpectedResponseError(bytes::Bytes::from(
response_string,
))
.into(),
)
}
}
}
DeutschebankThreeDSInitializeResponseOutcome::ChallengeRequired => {
match item.response.challenge_required {
Some(challenge) => Ok(Self {
status: common_enums::AttemptStatus::AuthenticationPending,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(Some(
RedirectForm::DeutschebankThreeDSChallengeFlow {
acs_url: challenge.acs_url,
creq: challenge.creq,
},
)),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
}),
None => {
let response_string = format!("{:?}", item.response);
Err(
errors::ConnectorError::UnexpectedResponseError(bytes::Bytes::from(
response_string,
))
.into(),
)
}
}
}
DeutschebankThreeDSInitializeResponseOutcome::MethodRequired => Ok(Self {
status: common_enums::AttemptStatus::Failure,
response: Err(ErrorResponse {
code: consts::NO_ERROR_CODE.to_owned(),
message: "METHOD_REQUIRED Flow not supported for deutschebank 3ds payments".to_owned(),
reason: Some("METHOD_REQUIRED Flow is not currently supported for deutschebank 3ds payments".to_owned()),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: None,network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
}),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum DeutschebankSEPAMandateStatus {
Created,
PendingApproval,
PendingSecondaryApproval,
PendingReview,
PendingSubmission,
Submitted,
Active,
Failed,
Discarded,
Expired,
Replaced,
}
impl From<DeutschebankSEPAMandateStatus> for common_enums::AttemptStatus {
fn from(item: DeutschebankSEPAMandateStatus) -> Self {
match item {
DeutschebankSEPAMandateStatus::Active
| DeutschebankSEPAMandateStatus::Created
| DeutschebankSEPAMandateStatus::PendingApproval
| DeutschebankSEPAMandateStatus::PendingSecondaryApproval
| DeutschebankSEPAMandateStatus::PendingReview
| DeutschebankSEPAMandateStatus::PendingSubmission
| DeutschebankSEPAMandateStatus::Submitted => Self::AuthenticationPending,
DeutschebankSEPAMandateStatus::Failed
| DeutschebankSEPAMandateStatus::Discarded
| DeutschebankSEPAMandateStatus::Expired
| DeutschebankSEPAMandateStatus::Replaced => Self::Failure,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct DeutschebankMandateMetadata {
account_holder: Secret<String>,
iban: Secret<String>,
reference: Secret<String>,
signed_on: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct DeutschebankMandatePostResponse {
rc: String,
message: String,
mandate_id: Option<String>,
reference: Option<String>,
approval_date: Option<String>,
language: Option<String>,
approval_by: Option<DeutschebankSEPAApproval>,
state: Option<DeutschebankSEPAMandateStatus>,
}
fn get_error_response(error_code: String, error_reason: String, status_code: u16) -> ErrorResponse {
ErrorResponse {
code: error_code.to_string(),
message: error_reason.clone(),
reason: Some(error_reason),
status_code,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}
}
fn is_response_success(rc: &String) -> bool {
rc == "0"
}
impl
TryFrom<
ResponseRouterData<
Authorize,
DeutschebankMandatePostResponse,
PaymentsAuthorizeData,
PaymentsResponseData,
>,
> for RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
Authorize,
DeutschebankMandatePostResponse,
PaymentsAuthorizeData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let signed_on = match item.response.approval_date.clone() {
Some(date) => date.chars().take(10).collect(),
None => time::OffsetDateTime::now_utc().date().to_string(),
};
let response_code = item.response.rc.clone();
let is_response_success = is_response_success(&response_code);
match (
item.response.reference.clone(),
item.response.state.clone(),
is_response_success,
) {
(Some(reference), Some(state), true) => Ok(Self {
status: common_enums::AttemptStatus::from(state),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(Some(RedirectForm::Form {
endpoint: item.data.request.get_complete_authorize_url()?,
method: common_utils::request::Method::Get,
form_fields: HashMap::from([
("reference".to_string(), reference.clone()),
("signed_on".to_string(), signed_on.clone()),
]),
})),
mandate_reference: if item.data.request.is_mandate_payment() {
Box::new(Some(MandateReference {
connector_mandate_id: item.response.mandate_id,
payment_method_id: None,
mandate_metadata: Some(Secret::new(
serde_json::json!(DeutschebankMandateMetadata {
account_holder: item.data.get_billing_address()?.get_full_name()?,
iban: match item.data.request.payment_method_data.clone() {
PaymentMethodData::BankDebit(BankDebitData::SepaBankDebit {
iban,
..
}) => Ok(Secret::from(iban.peek().replace(" ", ""))),
_ => Err(errors::ConnectorError::MissingRequiredField {
field_name:
"payment_method_data.bank_debit.sepa_bank_debit.iban"
}),
}?,
reference: Secret::from(reference.clone()),
signed_on,
}),
)),
connector_mandate_request_reference_id: None,
}))
} else {
Box::new(None)
},
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
}),
_ => Ok(Self {
status: common_enums::AttemptStatus::Failure,
response: Err(get_error_response(
response_code.clone(),
item.response.message.clone(),
item.http_code,
)),
..item.data
}),
}
}
}
impl
TryFrom<
ResponseRouterData<
Authorize,
DeutschebankPaymentsResponse,
PaymentsAuthorizeData,
PaymentsResponseData,
>,
> for RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
Authorize,
DeutschebankPaymentsResponse,
PaymentsAuthorizeData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let response_code = item.response.rc.clone();
if is_response_success(&response_code) {
Ok(Self {
status: match item.data.request.is_auto_capture()? {
true => common_enums::AttemptStatus::Charged,
false => common_enums::AttemptStatus::Authorized,
},
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.tx_id),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
} else {
Ok(Self {
status: common_enums::AttemptStatus::Failure,
response: Err(get_error_response(
response_code.clone(),
item.response.message.clone(),
item.http_code,
)),
..item.data
})
}
}
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct DeutschebankAmount {
amount: MinorUnit,
currency: api_models::enums::Currency,
}
#[derive(Debug, Serialize, PartialEq)]
pub struct DeutschebankMeansOfPayment {
bank_account: DeutschebankBankAccount,
}
#[derive(Debug, Serialize, PartialEq)]
pub struct DeutschebankBankAccount {
account_holder: Secret<String>,
iban: Secret<String>,
}
#[derive(Debug, Serialize, PartialEq)]
pub struct DeutschebankMandate {
reference: Secret<String>,
signed_on: String,
}
#[derive(Debug, Serialize, PartialEq)]
pub struct DeutschebankDirectDebitRequest {
amount_total: DeutschebankAmount,
means_of_payment: DeutschebankMeansOfPayment,
mandate: DeutschebankMandate,
}
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum DeutschebankCompleteAuthorizeRequest {
DeutschebankDirectDebitRequest(DeutschebankDirectDebitRequest),
DeutschebankThreeDSCompleteAuthorizeRequest(DeutschebankThreeDSCompleteAuthorizeRequest),
}
#[derive(Debug, Serialize, PartialEq)]
pub struct DeutschebankThreeDSCompleteAuthorizeRequest {
cres: String,
}
impl TryFrom<&DeutschebankRouterData<&PaymentsCompleteAuthorizeRouterData>>
for DeutschebankCompleteAuthorizeRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &DeutschebankRouterData<&PaymentsCompleteAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
if matches!(item.router_data.payment_method, PaymentMethod::Card) {
let redirect_response_payload = item
.router_data
.request
.get_redirect_response_payload()?
.expose();
let cres = redirect_response_payload
.get("cres")
.and_then(|v| v.as_str())
.map(String::from)
.ok_or(errors::ConnectorError::MissingRequiredField { field_name: "cres" })?;
Ok(Self::DeutschebankThreeDSCompleteAuthorizeRequest(
DeutschebankThreeDSCompleteAuthorizeRequest { cres },
))
} else {
match item.router_data.request.payment_method_data.clone() {
Some(PaymentMethodData::BankDebit(BankDebitData::SepaBankDebit {
iban, ..
})) => {
let account_holder = item.router_data.get_billing_address()?.get_full_name()?;
let redirect_response =
item.router_data.request.redirect_response.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "redirect_response",
},
)?;
let queries_params = redirect_response
.params
.map(|param| {
let mut queries = HashMap::<String, String>::new();
let values = param.peek().split('&').collect::<Vec<&str>>();
for value in values {
let pair = value.split('=').collect::<Vec<&str>>();
queries.insert(
pair.first()
.ok_or(
errors::ConnectorError::ResponseDeserializationFailed,
)?
.to_string(),
pair.get(1)
.ok_or(
errors::ConnectorError::ResponseDeserializationFailed,
)?
.to_string(),
);
}
Ok::<_, errors::ConnectorError>(queries)
})
.transpose()?
.ok_or(errors::ConnectorError::ResponseDeserializationFailed)?;
let reference = Secret::from(
queries_params
.get("reference")
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "reference",
})?
.to_owned(),
);
let signed_on = queries_params
.get("signed_on")
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "signed_on",
})?
.to_owned();
Ok(Self::DeutschebankDirectDebitRequest(
DeutschebankDirectDebitRequest {
amount_total: DeutschebankAmount {
amount: item.amount,
currency: item.router_data.request.currency,
},
| 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/checkbook/transformers.rs | crates/hyperswitch_connectors/src/connectors/checkbook/transformers.rs | use api_models::webhooks::IncomingWebhookEvent;
use common_utils::{pii, types::FloatMajorUnit};
use hyperswitch_domain_models::{
payment_method_data::{BankTransferData, PaymentMethodData},
router_data::{ConnectorAuthType, RouterData},
router_request_types::ResponseId,
router_response_types::PaymentsResponseData,
types::PaymentsAuthorizeRouterData,
};
use hyperswitch_interfaces::errors::ConnectorError;
use masking::Secret;
use serde::{Deserialize, Serialize};
use crate::{
types::ResponseRouterData,
utils::{get_unimplemented_payment_method_error_message, RouterData as _},
};
#[derive(Debug, Serialize)]
pub struct CheckbookPaymentsRequest {
name: Secret<String>,
recipient: pii::Email,
amount: FloatMajorUnit,
description: String,
}
impl TryFrom<(FloatMajorUnit, &PaymentsAuthorizeRouterData)> for CheckbookPaymentsRequest {
type Error = error_stack::Report<ConnectorError>;
fn try_from(
(amount, item): (FloatMajorUnit, &PaymentsAuthorizeRouterData),
) -> Result<Self, Self::Error> {
match item.request.payment_method_data.clone() {
PaymentMethodData::BankTransfer(bank_transfer_data) => match *bank_transfer_data {
BankTransferData::AchBankTransfer {} => Ok(Self {
name: item.get_billing_full_name()?,
recipient: item.get_billing_email()?,
amount,
description: item.get_description()?,
}),
_ => Err(ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("Checkbook"),
)
.into()),
},
_ => Err(ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("Checkbook"),
)
.into()),
}
}
}
pub struct CheckbookAuthType {
pub(super) publishable_key: Secret<String>,
pub(super) secret_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for CheckbookAuthType {
type Error = error_stack::Report<ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::BodyKey { key1, api_key } => Ok(Self {
publishable_key: key1.to_owned(),
secret_key: api_key.to_owned(),
}),
_ => Err(ConnectorError::FailedToObtainAuthType.into()),
}
}
}
// PaymentsResponse
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum CheckbookPaymentStatus {
Unpaid,
InProcess,
Paid,
Mailed,
Printed,
Failed,
Expired,
Void,
#[default]
Processing,
}
impl From<CheckbookPaymentStatus> for common_enums::AttemptStatus {
fn from(item: CheckbookPaymentStatus) -> Self {
match item {
CheckbookPaymentStatus::Paid
| CheckbookPaymentStatus::Mailed
| CheckbookPaymentStatus::Printed => Self::Charged,
CheckbookPaymentStatus::Failed | CheckbookPaymentStatus::Expired => Self::Failure,
CheckbookPaymentStatus::Unpaid => Self::AuthenticationPending,
CheckbookPaymentStatus::InProcess | CheckbookPaymentStatus::Processing => Self::Pending,
CheckbookPaymentStatus::Void => Self::Voided,
}
}
}
impl From<CheckbookPaymentStatus> for IncomingWebhookEvent {
fn from(status: CheckbookPaymentStatus) -> Self {
match status {
CheckbookPaymentStatus::Mailed
| CheckbookPaymentStatus::Printed
| CheckbookPaymentStatus::Paid => Self::PaymentIntentSuccess,
CheckbookPaymentStatus::Failed | CheckbookPaymentStatus::Expired => {
Self::PaymentIntentFailure
}
CheckbookPaymentStatus::Unpaid
| CheckbookPaymentStatus::InProcess
| CheckbookPaymentStatus::Processing => Self::PaymentIntentProcessing,
CheckbookPaymentStatus::Void => Self::PaymentIntentCancelled,
}
}
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct CheckbookPaymentsResponse {
pub status: CheckbookPaymentStatus,
pub id: String,
pub amount: Option<FloatMajorUnit>,
pub description: Option<String>,
pub name: Option<String>,
pub recipient: Option<String>,
}
impl<F, T> TryFrom<ResponseRouterData<F, CheckbookPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<F, CheckbookPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: common_enums::AttemptStatus::from(item.response.status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct CheckbookErrorResponse {
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/katapult/transformers.rs | crates/hyperswitch_connectors/src/connectors/katapult/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 KatapultRouterData<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 KatapultRouterData<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 KatapultPaymentsRequest {
amount: StringMinorUnit,
card: KatapultCard,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct KatapultCard {
number: cards::CardNumber,
expiry_month: Secret<String>,
expiry_year: Secret<String>,
cvc: Secret<String>,
complete: bool,
}
impl TryFrom<&KatapultRouterData<&PaymentsAuthorizeRouterData>> for KatapultPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &KatapultRouterData<&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 KatapultAuthType {
pub(super) api_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for KatapultAuthType {
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 KatapultPaymentStatus {
Succeeded,
Failed,
#[default]
Processing,
}
impl From<KatapultPaymentStatus> for common_enums::AttemptStatus {
fn from(item: KatapultPaymentStatus) -> Self {
match item {
KatapultPaymentStatus::Succeeded => Self::Charged,
KatapultPaymentStatus::Failed => Self::Failure,
KatapultPaymentStatus::Processing => Self::Authorizing,
}
}
}
//TODO: Fill the struct with respective fields
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct KatapultPaymentsResponse {
status: KatapultPaymentStatus,
id: String,
}
impl<F, T> TryFrom<ResponseRouterData<F, KatapultPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, KatapultPaymentsResponse, 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 KatapultRefundRequest {
pub amount: StringMinorUnit,
}
impl<F> TryFrom<&KatapultRouterData<&RefundsRouterData<F>>> for KatapultRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &KatapultRouterData<&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 KatapultErrorResponse {
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/taxjar/transformers.rs | crates/hyperswitch_connectors/src/connectors/taxjar/transformers.rs | use common_enums::enums;
use common_utils::types::{FloatMajorUnit, FloatMajorUnitForConnector};
use error_stack::report;
use hyperswitch_domain_models::{
router_data::{ConnectorAuthType, RouterData},
router_request_types::PaymentsTaxCalculationData,
router_response_types::TaxCalculationResponseData,
types,
};
use hyperswitch_interfaces::errors;
use masking::Secret;
use serde::{Deserialize, Serialize};
use crate::{
types::ResponseRouterData,
utils::{self, AddressDetailsData},
};
pub struct TaxjarRouterData<T> {
pub amount: FloatMajorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc.
pub order_amount: FloatMajorUnit,
pub shipping: FloatMajorUnit,
pub router_data: T,
}
impl<T> From<(FloatMajorUnit, FloatMajorUnit, FloatMajorUnit, T)> for TaxjarRouterData<T> {
fn from(
(amount, order_amount, shipping, item): (FloatMajorUnit, FloatMajorUnit, FloatMajorUnit, T),
) -> Self {
Self {
amount,
order_amount,
shipping,
router_data: item,
}
}
}
#[derive(Default, Debug, Serialize, PartialEq)]
pub struct TaxjarPaymentsRequest {
to_country: enums::CountryAlpha2,
to_zip: Secret<String>,
to_state: Secret<String>,
to_city: Option<String>,
to_street: Option<Secret<String>>,
amount: FloatMajorUnit,
shipping: FloatMajorUnit,
line_items: Vec<LineItem>,
}
#[derive(Serialize, Deserialize, Debug, PartialEq)]
pub struct LineItem {
id: Option<String>,
quantity: Option<u16>,
product_tax_code: Option<String>,
unit_price: Option<FloatMajorUnit>,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct TaxjarCard {
number: cards::CardNumber,
expiry_month: Secret<String>,
expiry_year: Secret<String>,
cvc: Secret<String>,
complete: bool,
}
impl TryFrom<&TaxjarRouterData<&types::PaymentsTaxCalculationRouterData>>
for TaxjarPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &TaxjarRouterData<&types::PaymentsTaxCalculationRouterData>,
) -> Result<Self, Self::Error> {
let request = &item.router_data.request;
let shipping = &item
.router_data
.request
.shipping_address
.address
.clone()
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "address",
})?;
match request.order_details.clone() {
Some(order_details) => {
let line_items: Result<Vec<LineItem>, error_stack::Report<errors::ConnectorError>> =
order_details
.iter()
.map(|line_item| {
Ok(LineItem {
id: line_item.product_id.clone(),
quantity: Some(line_item.quantity),
product_tax_code: line_item.product_tax_code.clone(),
unit_price: Some(item.order_amount),
})
})
.collect();
Ok(Self {
to_country: shipping.get_country()?.to_owned(),
to_zip: shipping.get_zip()?.to_owned(),
to_state: shipping.to_state_code()?.to_owned(),
to_city: shipping.get_optional_city(),
to_street: shipping.get_optional_line1(),
amount: item.amount,
shipping: item.shipping,
line_items: line_items?,
})
}
None => Err(report!(errors::ConnectorError::MissingRequiredField {
field_name: "order_details"
})),
}
}
}
pub struct TaxjarAuthType {
pub(super) api_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for TaxjarAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
api_key: api_key.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct TaxjarPaymentsResponse {
tax: Tax,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Tax {
amount_to_collect: FloatMajorUnit, //calculated_tax_amount
}
impl<F>
TryFrom<
ResponseRouterData<
F,
TaxjarPaymentsResponse,
PaymentsTaxCalculationData,
TaxCalculationResponseData,
>,
> for RouterData<F, PaymentsTaxCalculationData, TaxCalculationResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
TaxjarPaymentsResponse,
PaymentsTaxCalculationData,
TaxCalculationResponseData,
>,
) -> Result<Self, Self::Error> {
let currency = item.data.request.currency;
let amount_to_collect = item.response.tax.amount_to_collect;
let calculated_tax = utils::convert_back_amount_to_minor_units(
&FloatMajorUnitForConnector,
amount_to_collect,
currency,
)?;
Ok(Self {
response: Ok(TaxCalculationResponseData {
order_tax_amount: calculated_tax,
}),
..item.data
})
}
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct TaxjarErrorResponse {
pub status: i64,
pub error: String,
pub detail: 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/moneris/transformers.rs | crates/hyperswitch_connectors/src/connectors/moneris/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::{AccessToken, ConnectorAuthType, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{MandateReference, PaymentsResponseData, RefundsResponseData},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
RefundsRouterData,
},
};
use hyperswitch_interfaces::errors;
use masking::{PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
types::{RefreshTokenRouterData, RefundsResponseRouterData, ResponseRouterData},
utils::{CardData as _, PaymentsAuthorizeRequestData, RouterData as OtherRouterData},
};
const CLIENT_CREDENTIALS: &str = "client_credentials";
pub struct MonerisRouterData<T> {
pub amount: MinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc.
pub router_data: T,
}
impl<T> From<(MinorUnit, T)> for MonerisRouterData<T> {
fn from((amount, item): (MinorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
pub mod auth_headers {
pub const X_MERCHANT_ID: &str = "X-Merchant-Id";
pub const API_VERSION: &str = "Api-Version";
}
#[derive(Debug, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct MonerisPaymentsRequest {
idempotency_key: String,
amount: Amount,
payment_method: PaymentMethod,
automatic_capture: bool,
}
#[derive(Default, Debug, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Amount {
currency: enums::Currency,
amount: MinorUnit,
}
#[derive(Debug, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
#[serde(untagged)]
pub enum PaymentMethod {
Card(PaymentMethodCard),
PaymentMethodId(PaymentMethodId),
}
#[derive(Debug, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct PaymentMethodCard {
payment_method_source: PaymentMethodSource,
card: MonerisCard,
store_payment_method: StorePaymentMethod,
}
#[derive(Debug, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct PaymentMethodId {
payment_method_source: PaymentMethodSource,
payment_method_id: Secret<String>,
}
#[derive(Debug, Serialize, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PaymentMethodSource {
Card,
PaymentMethodId,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct MonerisCard {
card_number: cards::CardNumber,
expiry_month: Secret<i64>,
expiry_year: Secret<i64>,
card_security_code: Secret<String>,
}
#[derive(Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum StorePaymentMethod {
DoNotStore,
CardholderInitiated,
MerchantInitiated,
}
impl TryFrom<&MonerisRouterData<&PaymentsAuthorizeRouterData>> for MonerisPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &MonerisRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(ref req_card) => {
if item.router_data.is_three_ds() {
Err(errors::ConnectorError::NotSupported {
message: "Card 3DS".to_string(),
connector: "Moneris",
})?
};
let idempotency_key = uuid::Uuid::new_v4().to_string();
let amount = Amount {
currency: item.router_data.request.currency,
amount: item.amount,
};
let payment_method = PaymentMethod::Card(PaymentMethodCard {
payment_method_source: PaymentMethodSource::Card,
card: MonerisCard {
card_number: req_card.card_number.clone(),
expiry_month: Secret::new(
req_card
.card_exp_month
.peek()
.parse::<i64>()
.change_context(errors::ConnectorError::ParsingFailed)?,
),
expiry_year: Secret::new(
req_card
.get_expiry_year_4_digit()
.peek()
.parse::<i64>()
.change_context(errors::ConnectorError::ParsingFailed)?,
),
card_security_code: req_card.card_cvc.clone(),
},
store_payment_method: if item
.router_data
.request
.is_customer_initiated_mandate_payment()
{
StorePaymentMethod::CardholderInitiated
} else {
StorePaymentMethod::DoNotStore
},
});
let automatic_capture = item.router_data.request.is_auto_capture()?;
Ok(Self {
idempotency_key,
amount,
payment_method,
automatic_capture,
})
}
PaymentMethodData::MandatePayment => {
let idempotency_key = uuid::Uuid::new_v4().to_string();
let amount = Amount {
currency: item.router_data.request.currency,
amount: item.amount,
};
let automatic_capture = item.router_data.request.is_auto_capture()?;
let payment_method = PaymentMethod::PaymentMethodId(PaymentMethodId {
payment_method_source: PaymentMethodSource::PaymentMethodId,
payment_method_id: item
.router_data
.request
.connector_mandate_id()
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "connector_mandate_id",
})?
.into(),
});
Ok(Self {
idempotency_key,
amount,
payment_method,
automatic_capture,
})
}
_ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()),
}
}
}
pub struct MonerisAuthType {
pub(super) client_id: Secret<String>,
pub(super) client_secret: Secret<String>,
pub(super) merchant_id: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for MonerisAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} => Ok(Self {
client_id: key1.to_owned(),
client_secret: api_key.to_owned(),
merchant_id: api_secret.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Debug, Clone, Serialize, PartialEq)]
pub struct MonerisAuthRequest {
client_id: Secret<String>,
client_secret: Secret<String>,
grant_type: String,
}
impl TryFrom<&RefreshTokenRouterData> for MonerisAuthRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &RefreshTokenRouterData) -> Result<Self, Self::Error> {
let auth = MonerisAuthType::try_from(&item.connector_auth_type)?;
Ok(Self {
client_id: auth.client_id.clone(),
client_secret: auth.client_secret.clone(),
grant_type: CLIENT_CREDENTIALS.to_string(),
})
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct MonerisAuthResponse {
access_token: Secret<String>,
token_type: String,
expires_in: String,
}
impl<F, T> TryFrom<ResponseRouterData<F, MonerisAuthResponse, T, AccessToken>>
for RouterData<F, T, AccessToken>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, MonerisAuthResponse, T, AccessToken>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(AccessToken {
token: item.response.access_token,
expires: item
.response
.expires_in
.parse::<i64>()
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?,
}),
..item.data
})
}
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum MonerisPaymentStatus {
Succeeded,
#[default]
Processing,
Canceled,
Declined,
DeclinedRetry,
Authorized,
}
impl From<MonerisPaymentStatus> for common_enums::AttemptStatus {
fn from(item: MonerisPaymentStatus) -> Self {
match item {
MonerisPaymentStatus::Succeeded => Self::Charged,
MonerisPaymentStatus::Authorized => Self::Authorized,
MonerisPaymentStatus::Canceled => Self::Voided,
MonerisPaymentStatus::Declined | MonerisPaymentStatus::DeclinedRetry => Self::Failure,
MonerisPaymentStatus::Processing => Self::Pending,
}
}
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct MonerisPaymentsResponse {
payment_status: MonerisPaymentStatus,
payment_id: String,
payment_method: MonerisPaymentMethodData,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct MonerisPaymentMethodData {
payment_method_id: Secret<String>,
}
impl<F, T> TryFrom<ResponseRouterData<F, MonerisPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, MonerisPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: common_enums::AttemptStatus::from(item.response.payment_status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.payment_id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(Some(MandateReference {
connector_mandate_id: Some(
item.response
.payment_method
.payment_method_id
.peek()
.to_string(),
),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
})),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.payment_id),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MonerisPaymentsCaptureRequest {
amount: Amount,
idempotency_key: String,
}
impl TryFrom<&MonerisRouterData<&PaymentsCaptureRouterData>> for MonerisPaymentsCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &MonerisRouterData<&PaymentsCaptureRouterData>) -> Result<Self, Self::Error> {
let amount = Amount {
currency: item.router_data.request.currency,
amount: item.amount,
};
let idempotency_key = uuid::Uuid::new_v4().to_string();
Ok(Self {
amount,
idempotency_key,
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MonerisCancelRequest {
idempotency_key: String,
reason: Option<String>,
}
impl TryFrom<&PaymentsCancelRouterData> for MonerisCancelRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> {
let idempotency_key = uuid::Uuid::new_v4().to_string();
let reason = item.request.cancellation_reason.clone();
Ok(Self {
idempotency_key,
reason,
})
}
}
#[derive(Default, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MonerisRefundRequest {
pub refund_amount: Amount,
pub idempotency_key: String,
pub reason: Option<String>,
pub payment_id: String,
}
impl<F> TryFrom<&MonerisRouterData<&RefundsRouterData<F>>> for MonerisRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &MonerisRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
let refund_amount = Amount {
currency: item.router_data.request.currency,
amount: item.amount,
};
let idempotency_key = uuid::Uuid::new_v4().to_string();
let reason = item.router_data.request.reason.clone();
let payment_id = item.router_data.request.connector_transaction_id.clone();
Ok(Self {
refund_amount,
idempotency_key,
reason,
payment_id,
})
}
}
#[allow(dead_code)]
#[derive(Debug, Serialize, Default, Deserialize, Clone)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum RefundStatus {
Succeeded,
#[default]
Processing,
Declined,
DeclinedRetry,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Succeeded => Self::Success,
RefundStatus::Declined | RefundStatus::DeclinedRetry => Self::Failure,
RefundStatus::Processing => Self::Pending,
}
}
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RefundResponse {
refund_id: String,
refund_status: RefundStatus,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.refund_id.to_string(),
refund_status: enums::RefundStatus::from(item.response.refund_status),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.refund_id.to_string(),
refund_status: enums::RefundStatus::from(item.response.refund_status),
}),
..item.data
})
}
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct MonerisErrorResponse {
pub status: u16,
pub category: String,
pub title: String,
pub errors: Option<Vec<MonerisError>>,
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct MonerisError {
pub reason_code: String,
pub parameter_name: String,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct MonerisAuthErrorResponse {
pub error: String,
pub error_description: Option<String>,
}
| 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/paytm/transformers.rs | crates/hyperswitch_connectors/src/connectors/paytm/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 PaytmRouterData<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 PaytmRouterData<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 PaytmPaymentsRequest {
amount: StringMinorUnit,
card: PaytmCard,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct PaytmCard {
number: cards::CardNumber,
expiry_month: Secret<String>,
expiry_year: Secret<String>,
cvc: Secret<String>,
complete: bool,
}
impl TryFrom<&PaytmRouterData<&PaymentsAuthorizeRouterData>> for PaytmPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaytmRouterData<&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 PaytmAuthType {
pub merchant_id: Secret<String>,
pub merchant_key: Secret<String>,
pub website: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for PaytmAuthType {
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 {
merchant_id: key1.to_owned(), // merchant_id
merchant_key: api_key.to_owned(), // signing key
website: api_secret.to_owned(), // website name
}),
_ => 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 PaytmPaymentStatus {
Succeeded,
Failed,
#[default]
Processing,
}
impl From<PaytmPaymentStatus> for common_enums::AttemptStatus {
fn from(item: PaytmPaymentStatus) -> Self {
match item {
PaytmPaymentStatus::Succeeded => Self::Charged,
PaytmPaymentStatus::Failed => Self::Failure,
PaytmPaymentStatus::Processing => Self::Authorizing,
}
}
}
//TODO: Fill the struct with respective fields
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct PaytmPaymentsResponse {
status: PaytmPaymentStatus,
id: String,
}
impl<F, T> TryFrom<ResponseRouterData<F, PaytmPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, PaytmPaymentsResponse, 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 PaytmRefundRequest {
pub amount: StringMinorUnit,
}
impl<F> TryFrom<&PaytmRouterData<&RefundsRouterData<F>>> for PaytmRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaytmRouterData<&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 PaytmErrorResponse {
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/adyenplatform/transformers.rs | crates/hyperswitch_connectors/src/connectors/adyenplatform/transformers.rs | use common_utils::types::MinorUnit;
use error_stack::Report;
use hyperswitch_domain_models::router_data::ConnectorAuthType;
use hyperswitch_interfaces::errors::ConnectorError;
use masking::Secret;
use serde::Serialize;
#[cfg(feature = "payouts")]
pub mod payouts;
#[cfg(feature = "payouts")]
pub use payouts::*;
// Error signature
type Error = Report<ConnectorError>;
// Auth Struct
pub struct AdyenplatformAuthType {
pub(super) api_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for AdyenplatformAuthType {
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(),
}),
_ => Err(ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Debug, Serialize)]
pub struct AdyenPlatformRouterData<T> {
pub amount: MinorUnit,
pub router_data: T,
}
impl<T> TryFrom<(MinorUnit, T)> for AdyenPlatformRouterData<T> {
type Error = Report<ConnectorError>;
fn try_from((amount, item): (MinorUnit, T)) -> Result<Self, Self::Error> {
Ok(Self {
amount,
router_data: item,
})
}
}
| 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/adyenplatform/transformers/payouts.rs | crates/hyperswitch_connectors/src/connectors/adyenplatform/transformers/payouts.rs | use api_models::{payouts, webhooks};
use common_enums::enums;
use common_utils::pii;
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::types::{self, PayoutsRouterData};
use hyperswitch_interfaces::errors::ConnectorError;
use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use super::{AdyenPlatformRouterData, Error};
use crate::{
connectors::adyen::transformers as adyen,
types::PayoutsResponseRouterData,
utils::{
self, AdditionalPayoutMethodData as _, AddressDetailsData, CardData,
PayoutFulfillRequestData, PayoutsData as _, RouterData as _,
},
};
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct AdyenPlatformConnectorMetadataObject {
source_balance_account: Option<Secret<String>>,
}
impl TryFrom<&Option<pii::SecretSerdeValue>> for AdyenPlatformConnectorMetadataObject {
type Error = Error;
fn try_from(meta_data: &Option<pii::SecretSerdeValue>) -> Result<Self, Self::Error> {
let metadata: Self = utils::to_connector_meta_from_secret::<Self>(meta_data.clone())
.change_context(ConnectorError::InvalidConnectorConfig { config: "metadata" })?;
Ok(metadata)
}
}
#[serde_with::skip_serializing_none]
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AdyenTransferRequest {
amount: adyen::Amount,
balance_account_id: Secret<String>,
category: AdyenPayoutMethod,
counterparty: AdyenPayoutMethodDetails,
priority: Option<AdyenPayoutPriority>,
reference: String,
reference_for_beneficiary: String,
description: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum AdyenPayoutMethod {
Bank,
Card,
PlatformPayment,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum AdyenPayoutMethodDetails {
BankAccount(AdyenBankAccountDetails),
Card(AdyenCardDetails),
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AdyenBankAccountDetails {
account_holder: AdyenAccountHolder,
account_identification: AdyenBankAccountIdentification,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AdyenAccountHolder {
address: Option<AdyenAddress>,
first_name: Option<Secret<String>>,
last_name: Option<Secret<String>>,
full_name: Option<Secret<String>>,
email: Option<pii::Email>,
#[serde(rename = "reference")]
customer_id: Option<String>,
#[serde(rename = "type")]
entity_type: Option<EntityType>,
}
#[serde_with::skip_serializing_none]
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AdyenAddress {
line1: Secret<String>,
line2: Secret<String>,
postal_code: Option<Secret<String>>,
state_or_province: Option<Secret<String>>,
city: String,
country: enums::CountryAlpha2,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct AdyenBankAccountIdentification {
#[serde(rename = "type")]
bank_type: String,
#[serde(flatten)]
account_details: AdyenBankAccountIdentificationDetails,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum AdyenBankAccountIdentificationDetails {
Sepa(SepaDetails),
}
#[derive(Debug, Serialize, Deserialize)]
pub struct SepaDetails {
iban: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AdyenCardDetails {
card_holder: AdyenAccountHolder,
card_identification: AdyenCardIdentification,
}
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum AdyenCardIdentification {
Card(AdyenRawCardIdentification),
Stored(AdyenStoredCardIdentification),
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AdyenRawCardIdentification {
#[serde(rename = "number")]
card_number: cards::CardNumber,
expiry_month: Secret<String>,
expiry_year: Secret<String>,
issue_number: Option<String>,
start_month: Option<String>,
start_year: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AdyenStoredCardIdentification {
stored_payment_method_id: Secret<String>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum AdyenPayoutPriority {
Instant,
Fast,
Regular,
Wire,
CrossBorder,
Internal,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum EntityType {
Individual,
Organization,
Unknown,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AdyenTransferResponse {
id: String,
account_holder: AdyenPlatformAccountHolder,
amount: adyen::Amount,
balance_account: AdyenBalanceAccount,
category: AdyenPayoutMethod,
category_data: Option<AdyenCategoryData>,
direction: AdyenTransactionDirection,
reference: String,
reference_for_beneficiary: String,
status: AdyenTransferStatus,
#[serde(rename = "type")]
transaction_type: AdyenTransactionType,
reason: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct AdyenPlatformAccountHolder {
description: String,
id: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct AdyenCategoryData {
priority: AdyenPayoutPriority,
#[serde(rename = "type")]
category: AdyenPayoutMethod,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct AdyenBalanceAccount {
description: String,
id: String,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum AdyenTransactionDirection {
Incoming,
Outgoing,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, strum::Display)]
#[serde(rename_all = "lowercase")]
pub enum AdyenTransferStatus {
Authorised,
Refused,
Error,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum AdyenTransactionType {
BankTransfer,
CardTransfer,
InternalTransfer,
Payment,
Refund,
}
impl TryFrom<&hyperswitch_domain_models::address::AddressDetails> for AdyenAddress {
type Error = Error;
fn try_from(
address: &hyperswitch_domain_models::address::AddressDetails,
) -> Result<Self, Self::Error> {
let line1 = address
.get_line1()
.change_context(ConnectorError::MissingRequiredField {
field_name: "billing.address.line1",
})?
.clone();
let line2 = address
.get_line2()
.change_context(ConnectorError::MissingRequiredField {
field_name: "billing.address.line2",
})?
.clone();
Ok(Self {
line1,
line2,
postal_code: address.get_optional_zip(),
state_or_province: address.get_optional_state(),
city: address.get_city()?.to_owned(),
country: address.get_country()?.to_owned(),
})
}
}
impl<F> TryFrom<(&PayoutsRouterData<F>, &payouts::CardPayout)> for AdyenAccountHolder {
type Error = Error;
fn try_from(
(router_data, card): (&PayoutsRouterData<F>, &payouts::CardPayout),
) -> Result<Self, Self::Error> {
let billing_address = router_data.get_optional_billing();
let address = billing_address
.and_then(|billing| billing.address.as_ref().map(|addr| addr.try_into()))
.transpose()?
.ok_or(ConnectorError::MissingRequiredField {
field_name: "address",
})?;
let (first_name, last_name) = if let Some(card_holder_name) = &card.card_holder_name {
let exposed_name = card_holder_name.clone().expose();
let name_parts: Vec<&str> = exposed_name.split_whitespace().collect();
let first_name = name_parts
.first()
.map(|s| Secret::new(s.to_string()))
.ok_or(ConnectorError::MissingRequiredField {
field_name: "card_holder_name.first_name",
})?;
let last_name = if name_parts.len() > 1 {
let remaining_names: Vec<&str> = name_parts.iter().skip(1).copied().collect();
Some(Secret::new(remaining_names.join(" ")))
} else {
return Err(ConnectorError::MissingRequiredField {
field_name: "card_holder_name.last_name",
}
.into());
};
(Some(first_name), last_name)
} else {
return Err(ConnectorError::MissingRequiredField {
field_name: "card_holder_name",
}
.into());
};
let customer_id_reference = router_data.get_connector_customer_id()?;
Ok(Self {
address: Some(address),
first_name,
last_name,
full_name: None,
email: router_data.get_optional_billing_email(),
customer_id: Some(customer_id_reference),
entity_type: Some(EntityType::from(router_data.request.entity_type)),
})
}
}
impl<F> TryFrom<(&PayoutsRouterData<F>, &payouts::Bank)> for AdyenAccountHolder {
type Error = Error;
fn try_from(
(router_data, _bank): (&PayoutsRouterData<F>, &payouts::Bank),
) -> Result<Self, Self::Error> {
let billing_address = router_data.get_optional_billing();
let address = billing_address
.and_then(|billing| billing.address.as_ref().map(|addr| addr.try_into()))
.transpose()?
.ok_or(ConnectorError::MissingRequiredField {
field_name: "address",
})?;
let full_name = router_data.get_billing_full_name()?;
let customer_id_reference = router_data.get_connector_customer_id()?;
Ok(Self {
address: Some(address),
first_name: None,
last_name: None,
full_name: Some(full_name),
email: router_data.get_optional_billing_email(),
customer_id: Some(customer_id_reference),
entity_type: Some(EntityType::from(router_data.request.entity_type)),
})
}
}
#[derive(Debug)]
pub struct StoredPaymentCounterparty<'a, F> {
pub item: &'a AdyenPlatformRouterData<&'a PayoutsRouterData<F>>,
pub stored_payment_method_id: String,
}
#[derive(Debug)]
pub struct RawPaymentCounterparty<'a, F> {
pub item: &'a AdyenPlatformRouterData<&'a PayoutsRouterData<F>>,
pub raw_payout_method_data: payouts::PayoutMethodData,
}
impl<F> TryFrom<StoredPaymentCounterparty<'_, F>>
for (AdyenPayoutMethodDetails, Option<AdyenPayoutPriority>)
{
type Error = Error;
fn try_from(stored_payment: StoredPaymentCounterparty<'_, F>) -> Result<Self, Self::Error> {
let request = &stored_payment.item.router_data.request;
let payout_type = request.get_payout_type()?;
match payout_type {
enums::PayoutType::Card => {
let billing_address = stored_payment.item.router_data.get_optional_billing();
let address = billing_address
.and_then(|billing| billing.address.as_ref())
.ok_or(ConnectorError::MissingRequiredField {
field_name: "address",
})?
.try_into()?;
let customer_id_reference = stored_payment
.item
.router_data
.get_connector_customer_id()?;
let required_name: Name = stored_payment.item.router_data.try_into()?;
let card_holder = AdyenAccountHolder {
address: Some(address),
first_name: Some(required_name.first_name.clone()),
last_name: Some(required_name.last_name.clone()),
full_name: Some(required_name.get_full_name()),
email: stored_payment.item.router_data.get_optional_billing_email(),
customer_id: Some(customer_id_reference),
entity_type: Some(EntityType::from(request.entity_type)),
};
let card_identification =
AdyenCardIdentification::Stored(AdyenStoredCardIdentification {
stored_payment_method_id: Secret::new(
stored_payment.stored_payment_method_id,
),
});
let counterparty = AdyenPayoutMethodDetails::Card(AdyenCardDetails {
card_holder,
card_identification,
});
Ok((counterparty, None))
}
_ => Err(ConnectorError::NotSupported {
message: "Stored payment method is only supported for card payouts".to_string(),
connector: "Adyenplatform",
}
.into()),
}
}
}
struct Name {
first_name: Secret<String>,
last_name: Secret<String>,
}
impl Name {
fn get_full_name(&self) -> Secret<String> {
Secret::new(format!(
"{} {}",
self.first_name.peek(),
self.last_name.peek()
))
}
}
impl<F> TryFrom<&PayoutsRouterData<F>> for Name {
type Error = Error;
fn try_from(router_data: &PayoutsRouterData<F>) -> Result<Self, Self::Error> {
let card_holder_name = router_data
.request
.get_optional_additional_payout_method_data()
.and_then(|additional_data| additional_data.get_optional_card_holder_name());
let billing_first_name = router_data
.get_optional_billing_first_name()
.map(|first_name| Secret::new(first_name.peek().trim().to_string()));
let billing_last_name = router_data
.get_optional_billing_last_name()
.map(|last_name| Secret::new(last_name.peek().trim().to_string()));
let mut should_fallback = billing_first_name.is_none() || billing_last_name.is_none();
//check for empty first name
billing_first_name.clone().inspect(|first_name| {
should_fallback = first_name.peek().is_empty() || should_fallback;
});
// check for empty last name
billing_last_name.clone().inspect(|last_name| {
should_fallback = last_name.peek().is_empty() || should_fallback;
});
// get first_name from the billing
// if not present in billing, get from card_holder_name
let first_name = if should_fallback {
card_holder_name.clone().and_then(|full_name| {
let mut name_collection = full_name.peek().split_whitespace();
name_collection
.next()
.map(|first_name| Secret::new(first_name.to_string()))
})
} else {
billing_first_name
};
// get last_name from the billing
// if not present in billing, get from card_holder_name
let last_name = if should_fallback {
card_holder_name.map(|full_name| {
let mut name_collection = full_name.peek().split_whitespace();
let _first_name = name_collection.next();
Secret::new(name_collection.collect::<Vec<_>>().join(" "))
})
} else {
billing_last_name
};
Ok(Self {
first_name: first_name.ok_or(ConnectorError::MissingRequiredField {
field_name: "first_name",
})?,
last_name: last_name.ok_or(ConnectorError::MissingRequiredField {
field_name: "first_name",
})?,
})
}
}
impl<F> TryFrom<RawPaymentCounterparty<'_, F>>
for (AdyenPayoutMethodDetails, Option<AdyenPayoutPriority>)
{
type Error = Error;
fn try_from(raw_payment: RawPaymentCounterparty<'_, F>) -> Result<Self, Self::Error> {
let request = &raw_payment.item.router_data.request;
match raw_payment.raw_payout_method_data {
payouts::PayoutMethodData::Wallet(_)
| payouts::PayoutMethodData::BankRedirect(_)
| payouts::PayoutMethodData::Passthrough(_) => Err(ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Adyenplatform"),
))?,
payouts::PayoutMethodData::Card(c) => {
let card_holder: AdyenAccountHolder =
(raw_payment.item.router_data, &c).try_into()?;
let card_identification =
AdyenCardIdentification::Card(AdyenRawCardIdentification {
expiry_year: c.get_expiry_year_4_digit(),
card_number: c.card_number,
expiry_month: c.expiry_month,
issue_number: None,
start_month: None,
start_year: None,
});
let counterparty = AdyenPayoutMethodDetails::Card(AdyenCardDetails {
card_holder,
card_identification,
});
Ok((counterparty, None))
}
payouts::PayoutMethodData::Bank(bd) => {
let account_holder: AdyenAccountHolder =
(raw_payment.item.router_data, &bd).try_into()?;
let bank_details = match bd {
payouts::Bank::Sepa(b) => AdyenBankAccountIdentification {
bank_type: "iban".to_string(),
account_details: AdyenBankAccountIdentificationDetails::Sepa(SepaDetails {
iban: b.iban,
}),
},
payouts::Bank::Ach(..) => Err(ConnectorError::NotSupported {
message: "Bank transfer via ACH is not supported".to_string(),
connector: "Adyenplatform",
})?,
payouts::Bank::Bacs(..) => Err(ConnectorError::NotSupported {
message: "Bank transfer via Bacs is not supported".to_string(),
connector: "Adyenplatform",
})?,
payouts::Bank::Pix(..) => Err(ConnectorError::NotSupported {
message: "Bank transfer via Pix is not supported".to_string(),
connector: "Adyenplatform",
})?,
};
let counterparty = AdyenPayoutMethodDetails::BankAccount(AdyenBankAccountDetails {
account_holder,
account_identification: bank_details,
});
let priority = request
.priority
.ok_or(ConnectorError::MissingRequiredField {
field_name: "priority",
})?;
Ok((counterparty, Some(AdyenPayoutPriority::from(priority))))
}
}
}
}
impl<F> TryFrom<&AdyenPlatformRouterData<&PayoutsRouterData<F>>> for AdyenTransferRequest {
type Error = Error;
fn try_from(
item: &AdyenPlatformRouterData<&PayoutsRouterData<F>>,
) -> Result<Self, Self::Error> {
let request = &item.router_data.request;
let stored_payment_method_result =
item.router_data.request.get_connector_transfer_method_id();
let raw_payout_method_result = item.router_data.get_payout_method_data();
let (counterparty, priority) =
if let Ok(stored_payment_method_id) = stored_payment_method_result {
StoredPaymentCounterparty {
item,
stored_payment_method_id,
}
.try_into()?
} else if let Ok(raw_payout_method_data) = raw_payout_method_result {
RawPaymentCounterparty {
item,
raw_payout_method_data,
}
.try_into()?
} else {
return Err(ConnectorError::MissingRequiredField {
field_name: "payout_method_data or stored_payment_method_id",
}
.into());
};
let adyen_connector_metadata_object =
AdyenPlatformConnectorMetadataObject::try_from(&item.router_data.connector_meta_data)?;
let balance_account_id = adyen_connector_metadata_object
.source_balance_account
.ok_or(ConnectorError::InvalidConnectorConfig {
config: "metadata.source_balance_account",
})?;
let payout_type = request.get_payout_type()?;
Ok(Self {
amount: adyen::Amount {
value: item.amount,
currency: request.destination_currency,
},
balance_account_id,
category: AdyenPayoutMethod::try_from(payout_type)?,
counterparty,
priority,
reference: item.router_data.connector_request_reference_id.clone(),
reference_for_beneficiary: item.router_data.connector_request_reference_id.clone(),
description: item.router_data.description.clone(),
})
}
}
impl<F> TryFrom<PayoutsResponseRouterData<F, AdyenTransferResponse>> for PayoutsRouterData<F> {
type Error = Error;
fn try_from(
item: PayoutsResponseRouterData<F, AdyenTransferResponse>,
) -> Result<Self, Self::Error> {
let response: AdyenTransferResponse = item.response;
let status = enums::PayoutStatus::from(response.status);
if matches!(status, enums::PayoutStatus::Failed) {
return Ok(Self {
response: Err(hyperswitch_domain_models::router_data::ErrorResponse {
code: response.status.to_string(),
message: if !response.reason.is_empty() {
response.reason
} else {
response.status.to_string()
},
reason: None,
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(response.id),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
});
}
Ok(Self {
response: Ok(types::PayoutsResponseData {
status: Some(status),
connector_payout_id: Some(response.id),
payout_eligible: None,
should_add_next_step_to_process_tracker: false,
error_code: None,
error_message: None,
payout_connector_metadata: None,
}),
..item.data
})
}
}
impl From<AdyenTransferStatus> for enums::PayoutStatus {
fn from(adyen_status: AdyenTransferStatus) -> Self {
match adyen_status {
AdyenTransferStatus::Authorised => Self::Initiated,
AdyenTransferStatus::Error | AdyenTransferStatus::Refused => Self::Failed,
}
}
}
impl From<enums::PayoutEntityType> for EntityType {
fn from(entity: enums::PayoutEntityType) -> Self {
match entity {
enums::PayoutEntityType::Individual
| enums::PayoutEntityType::Personal
| enums::PayoutEntityType::NaturalPerson => Self::Individual,
enums::PayoutEntityType::Company | enums::PayoutEntityType::Business => {
Self::Organization
}
_ => Self::Unknown,
}
}
}
impl From<enums::PayoutSendPriority> for AdyenPayoutPriority {
fn from(entity: enums::PayoutSendPriority) -> Self {
match entity {
enums::PayoutSendPriority::Instant => Self::Instant,
enums::PayoutSendPriority::Fast => Self::Fast,
enums::PayoutSendPriority::Regular => Self::Regular,
enums::PayoutSendPriority::Wire => Self::Wire,
enums::PayoutSendPriority::CrossBorder => Self::CrossBorder,
enums::PayoutSendPriority::Internal => Self::Internal,
}
}
}
impl TryFrom<enums::PayoutType> for AdyenPayoutMethod {
type Error = Error;
fn try_from(payout_type: enums::PayoutType) -> Result<Self, Self::Error> {
match payout_type {
enums::PayoutType::Bank => Ok(Self::Bank),
enums::PayoutType::Card => Ok(Self::Card),
enums::PayoutType::Wallet | enums::PayoutType::BankRedirect => {
Err(report!(ConnectorError::NotSupported {
message: "Bakredirect or wallet payouts".to_string(),
connector: "Adyenplatform",
}))
}
}
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AdyenplatformIncomingWebhook {
pub data: AdyenplatformIncomingWebhookData,
#[serde(rename = "type")]
pub webhook_type: AdyenplatformWebhookEventType,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AdyenplatformIncomingWebhookData {
pub status: AdyenplatformWebhookStatus,
pub reference: String,
pub tracking: Option<AdyenplatformTrackingData>,
pub reason: Option<String>,
pub category: Option<AdyenPayoutMethod>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AdyenplatformTrackingData {
pub status: TrackingStatus,
pub reason: Option<String>,
pub estimated_arrival_time: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum TrackingStatus {
Accepted,
Pending,
Credited,
}
#[derive(Debug, Serialize, Deserialize)]
pub enum AdyenplatformWebhookEventType {
#[serde(rename = "balancePlatform.transfer.created")]
PayoutCreated,
#[serde(rename = "balancePlatform.transfer.updated")]
PayoutUpdated,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum AdyenplatformWebhookStatus {
Authorised,
Booked,
Pending,
Failed,
Returned,
Received,
}
pub fn get_adyen_payout_webhook_event(
event_type: AdyenplatformWebhookEventType,
status: AdyenplatformWebhookStatus,
tracking_data: Option<AdyenplatformTrackingData>,
) -> webhooks::IncomingWebhookEvent {
match (event_type, status, tracking_data) {
(AdyenplatformWebhookEventType::PayoutCreated, _, _) => {
webhooks::IncomingWebhookEvent::PayoutCreated
}
(AdyenplatformWebhookEventType::PayoutUpdated, _, Some(tracking_data)) => {
match tracking_data.status {
TrackingStatus::Credited | TrackingStatus::Accepted => {
webhooks::IncomingWebhookEvent::PayoutSuccess
}
TrackingStatus::Pending => webhooks::IncomingWebhookEvent::PayoutProcessing,
}
}
(AdyenplatformWebhookEventType::PayoutUpdated, status, _) => match status {
AdyenplatformWebhookStatus::Authorised | AdyenplatformWebhookStatus::Received => {
webhooks::IncomingWebhookEvent::PayoutCreated
}
AdyenplatformWebhookStatus::Booked | AdyenplatformWebhookStatus::Pending => {
webhooks::IncomingWebhookEvent::PayoutProcessing
}
AdyenplatformWebhookStatus::Failed => webhooks::IncomingWebhookEvent::PayoutFailure,
AdyenplatformWebhookStatus::Returned => webhooks::IncomingWebhookEvent::PayoutReversed,
},
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AdyenTransferErrorResponse {
pub error_code: String,
#[serde(rename = "type")]
pub error_type: String,
pub status: u16,
pub title: String,
pub detail: Option<String>,
pub request_id: Option<String>,
pub invalid_fields: Option<Vec<AdyenInvalidField>>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AdyenInvalidField {
pub name: Option<String>,
pub value: Option<String>,
pub message: Option<String>,
}
| 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/authorizedotnet/transformers.rs | crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs | use std::collections::BTreeMap;
use api_models::{payments::AdditionalPaymentData, webhooks::IncomingWebhookEvent};
use common_enums::enums;
use common_utils::{
errors::CustomResult,
ext_traits::{Encode, OptionExt, ValueExt},
id_type::CustomerId,
pii::Email,
request::Method,
types::FloatMajorUnit,
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{Card, PaymentMethodData, WalletData},
router_data::{
AdditionalPaymentMethodConnectorResponse, ConnectorAuthType, ConnectorResponseData,
ErrorResponse, RouterData,
},
router_flow_types::RSync,
router_request_types::ResponseId,
router_response_types::{
ConnectorCustomerResponseData, MandateReference, PaymentsResponseData, RedirectForm,
RefundsResponseData,
},
types::{
ConnectorCustomerRouterData, PaymentsAuthorizeRouterData, PaymentsCancelRouterData,
PaymentsCaptureRouterData, PaymentsCompleteAuthorizeRouterData, PaymentsSyncRouterData,
RefundsRouterData, SetupMandateRouterData,
},
};
use hyperswitch_interfaces::errors;
use masking::{ExposeInterface, PeekInterface, Secret, StrongSecret};
use rand::distributions::{Alphanumeric, DistString};
use regex::Regex;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{
self, CardData, ForeignTryFrom, PaymentsAuthorizeRequestData, PaymentsSyncRequestData,
RefundsRequestData, RouterData as OtherRouterData, WalletData as OtherWalletData,
},
};
const MAX_ID_LENGTH: usize = 20;
const ADDRESS_MAX_LENGTH: usize = 60;
fn get_random_string() -> String {
Alphanumeric.sample_string(&mut rand::thread_rng(), MAX_ID_LENGTH)
}
#[derive(Debug, Serialize)]
pub enum TransactionType {
#[serde(rename = "authCaptureTransaction")]
Payment,
#[serde(rename = "authOnlyTransaction")]
Authorization,
#[serde(rename = "priorAuthCaptureTransaction")]
Capture,
#[serde(rename = "refundTransaction")]
Refund,
#[serde(rename = "voidTransaction")]
Void,
#[serde(rename = "authOnlyContinueTransaction")]
ContinueAuthorization,
#[serde(rename = "authCaptureContinueTransaction")]
ContinueCapture,
}
#[derive(Debug, Serialize)]
pub struct AuthorizedotnetRouterData<T> {
pub amount: FloatMajorUnit,
pub router_data: T,
}
impl<T> TryFrom<(FloatMajorUnit, T)> for AuthorizedotnetRouterData<T> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from((amount, item): (FloatMajorUnit, T)) -> Result<Self, Self::Error> {
Ok(Self {
amount,
router_data: item,
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthorizedotnetAuthType {
name: Secret<String>,
transaction_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for AuthorizedotnetAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
if let ConnectorAuthType::BodyKey { api_key, key1 } = auth_type {
Ok(Self {
name: api_key.to_owned(),
transaction_key: key1.to_owned(),
})
} else {
Err(errors::ConnectorError::FailedToObtainAuthType)?
}
}
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
struct CreditCardDetails {
card_number: StrongSecret<String, cards::CardNumberStrategy>,
expiration_date: Secret<String>,
#[serde(skip_serializing_if = "Option::is_none")]
card_code: Option<Secret<String>>,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
enum PaymentDetails {
CreditCard(CreditCardDetails),
OpaqueData(WalletDetails),
PayPal(PayPalDetails),
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct PayPalDetails {
pub success_url: Option<String>,
pub cancel_url: Option<String>,
}
#[derive(Serialize, Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct WalletDetails {
pub data_descriptor: WalletMethod,
pub data_value: Secret<String>,
}
#[derive(Serialize, Debug, Deserialize)]
pub enum WalletMethod {
#[serde(rename = "COMMON.GOOGLE.INAPP.PAYMENT")]
Googlepay,
#[serde(rename = "COMMON.APPLE.INAPP.PAYMENT")]
Applepay,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct TransactionRequest {
transaction_type: TransactionType,
amount: FloatMajorUnit,
currency_code: common_enums::Currency,
#[serde(skip_serializing_if = "Option::is_none")]
payment: Option<PaymentDetails>,
#[serde(skip_serializing_if = "Option::is_none")]
profile: Option<ProfileDetails>,
order: Order,
#[serde(skip_serializing_if = "Option::is_none")]
customer: Option<CustomerDetails>,
#[serde(skip_serializing_if = "Option::is_none")]
bill_to: Option<BillTo>,
#[serde(skip_serializing_if = "Option::is_none")]
user_fields: Option<UserFields>,
#[serde(skip_serializing_if = "Option::is_none")]
processing_options: Option<ProcessingOptions>,
#[serde(skip_serializing_if = "Option::is_none")]
subsequent_auth_information: Option<SubsequentAuthInformation>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct UserFields {
user_field: Vec<UserField>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct UserField {
name: String,
value: String,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(untagged)]
enum ProfileDetails {
CreateProfileDetails(CreateProfileDetails),
CustomerProfileDetails(CustomerProfileDetails),
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct CreateProfileDetails {
create_profile: bool,
#[serde(skip_serializing_if = "Option::is_none")]
customer_profile_id: Option<Secret<String>>,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
struct CustomerProfileDetails {
customer_profile_id: Secret<String>,
payment_profile: PaymentProfileDetails,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
struct PaymentProfileDetails {
payment_profile_id: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CustomerDetails {
id: String,
email: Option<Email>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ProcessingOptions {
is_subsequent_auth: bool,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BillTo {
first_name: Option<Secret<String>>,
last_name: Option<Secret<String>>,
address: Option<Secret<String>>,
city: Option<String>,
state: Option<Secret<String>>,
zip: Option<Secret<String>>,
country: Option<enums::CountryAlpha2>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Order {
invoice_number: String,
description: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SubsequentAuthInformation {
original_network_trans_id: Secret<String>,
// original_auth_amount: String, Required for Discover, Diners Club, JCB, and China Union Pay transactions.
reason: Reason,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Reason {
Resubmission,
#[serde(rename = "delayedCharge")]
DelayedCharge,
Reauthorization,
#[serde(rename = "noShow")]
NoShow,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct TransactionVoidOrCaptureRequest {
transaction_type: TransactionType,
#[serde(skip_serializing_if = "Option::is_none")]
amount: Option<FloatMajorUnit>,
ref_trans_id: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthorizedotnetPaymentsRequest {
merchant_authentication: AuthorizedotnetAuthType,
ref_id: Option<String>,
transaction_request: TransactionRequest,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthorizedotnetPaymentCancelOrCaptureRequest {
merchant_authentication: AuthorizedotnetAuthType,
transaction_request: TransactionVoidOrCaptureRequest,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
// The connector enforces field ordering, it expects fields to be in the same order as in their API documentation
pub struct CustomerRequest {
create_customer_profile_request: CreateCustomerRequest,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CreateCustomerRequest {
merchant_authentication: AuthorizedotnetAuthType,
profile: Profile,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CreateCustomerPaymentProfileRequest {
create_customer_payment_profile_request: AuthorizedotnetPaymentProfileRequest,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthorizedotnetPaymentProfileRequest {
merchant_authentication: AuthorizedotnetAuthType,
customer_profile_id: Secret<String>,
payment_profile: PaymentProfile,
validation_mode: ValidationMode,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ShipToList {
#[serde(skip_serializing_if = "Option::is_none")]
first_name: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
last_name: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
address: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
city: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
state: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
zip: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
country: Option<enums::CountryAlpha2>,
#[serde(skip_serializing_if = "Option::is_none")]
phone_number: Option<Secret<String>>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct Profile {
#[serde(skip_serializing_if = "Option::is_none")]
merchant_customer_id: Option<CustomerId>,
#[serde(skip_serializing_if = "Option::is_none")]
description: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
email: Option<Email>,
#[serde(skip_serializing_if = "Option::is_none")]
payment_profiles: Option<PaymentProfiles>,
#[serde(skip_serializing_if = "Option::is_none")]
ship_to_list: Option<Vec<ShipToList>>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct PaymentProfiles {
customer_type: CustomerType,
#[serde(skip_serializing_if = "Option::is_none")]
bill_to: Option<BillTo>,
payment: PaymentDetails,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct PaymentProfile {
#[serde(skip_serializing_if = "Option::is_none")]
bill_to: Option<BillTo>,
payment: PaymentDetails,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum CustomerType {
Individual,
Business,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum ValidationMode {
// testMode performs a Luhn mod-10 check on the card number, without further validation at connector.
TestMode,
// liveMode submits a zero-dollar or one-cent transaction (depending on card type and processor support) to confirm that the card number belongs to an active credit or debit account.
LiveMode,
}
impl ForeignTryFrom<Value> for Vec<UserField> {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(metadata: Value) -> Result<Self, Self::Error> {
let hashmap: BTreeMap<String, Value> = serde_json::from_str(&metadata.to_string())
.change_context(errors::ConnectorError::RequestEncodingFailedWithReason(
"Failed to serialize request metadata".to_owned(),
))
.attach_printable("")?;
let mut vector: Self = Self::new();
for (key, value) in hashmap {
let string_value = match value {
Value::Bool(boolean) => boolean.to_string(),
Value::Number(number) => number.to_string(),
Value::String(string) => string.to_string(),
_ => value.to_string(),
};
vector.push(UserField {
name: key,
value: string_value,
});
}
Ok(vector)
}
}
impl TryFrom<&ConnectorCustomerRouterData> for CustomerRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &ConnectorCustomerRouterData) -> Result<Self, Self::Error> {
let merchant_authentication = AuthorizedotnetAuthType::try_from(&item.connector_auth_type)?;
let ship_to_list = item.get_optional_shipping().and_then(|shipping| {
shipping.address.as_ref().map(|address| {
vec![ShipToList {
first_name: address.first_name.clone(),
last_name: address.last_name.clone(),
address: address.line1.clone(),
city: address.city.clone(),
state: address.state.clone(),
zip: address.zip.clone(),
country: address.country,
phone_number: shipping
.phone
.as_ref()
.and_then(|phone| phone.number.as_ref().map(|number| number.to_owned())),
}]
})
});
let merchant_customer_id = match item.customer_id.as_ref() {
Some(cid) if cid.get_string_repr().len() <= MAX_ID_LENGTH => Some(cid.clone()),
_ => None,
};
Ok(Self {
create_customer_profile_request: CreateCustomerRequest {
merchant_authentication,
profile: Profile {
merchant_customer_id,
description: None,
email: item.request.email.clone(),
payment_profiles: None,
ship_to_list,
},
},
})
}
}
impl TryFrom<&SetupMandateRouterData> for CreateCustomerPaymentProfileRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &SetupMandateRouterData) -> Result<Self, Self::Error> {
let merchant_authentication = AuthorizedotnetAuthType::try_from(&item.connector_auth_type)?;
let validation_mode = match item.test_mode {
Some(true) | None => ValidationMode::TestMode,
Some(false) => ValidationMode::LiveMode,
};
let customer_profile_id = item.get_connector_customer_id()?.into();
let bill_to = item
.get_optional_billing()
.and_then(|billing_address| billing_address.address.as_ref())
.map(|address| BillTo {
first_name: address.first_name.clone(),
last_name: address.last_name.clone(),
address: get_address_line(&address.line1, &address.line2, &address.line3),
city: address.city.clone(),
state: address.state.clone(),
zip: address.zip.clone(),
country: address.country,
});
let payment_profile = match item.request.payment_method_data.clone() {
PaymentMethodData::Card(ccard) => Ok(PaymentProfile {
bill_to,
payment: PaymentDetails::CreditCard(CreditCardDetails {
card_number: (*ccard.card_number).clone(),
expiration_date: ccard.get_expiry_date_as_yyyymm("-"),
card_code: Some(ccard.card_cvc.clone()),
}),
}),
PaymentMethodData::Wallet(wallet_data) => match wallet_data {
WalletData::GooglePay(_) => Ok(PaymentProfile {
bill_to,
payment: PaymentDetails::OpaqueData(WalletDetails {
data_descriptor: WalletMethod::Googlepay,
data_value: Secret::new(wallet_data.get_encoded_wallet_token()?),
}),
}),
WalletData::ApplePay(applepay_token) => {
let apple_pay_encrypted_data = applepay_token
.payment_data
.get_encrypted_apple_pay_payment_data_mandatory()
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "Apple pay encrypted data",
})?;
Ok(PaymentProfile {
bill_to,
payment: PaymentDetails::OpaqueData(WalletDetails {
data_descriptor: WalletMethod::Applepay,
data_value: Secret::new(apple_pay_encrypted_data.clone()),
}),
})
}
WalletData::AliPayQr(_)
| WalletData::AliPayRedirect(_)
| WalletData::AliPayHkRedirect(_)
| WalletData::AmazonPayRedirect(_)
| WalletData::Paysera(_)
| WalletData::BluecodeRedirect {}
| WalletData::Skrill(_)
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
| WalletData::GcashRedirect(_)
| WalletData::ApplePayRedirect(_)
| WalletData::ApplePayThirdPartySdk(_)
| WalletData::DanaRedirect {}
| WalletData::GooglePayRedirect(_)
| WalletData::GooglePayThirdPartySdk(_)
| WalletData::MbWayRedirect(_)
| WalletData::MobilePayRedirect(_)
| WalletData::PaypalRedirect(_)
| WalletData::AmazonPay(_)
| WalletData::PaypalSdk(_)
| WalletData::Paze(_)
| WalletData::SamsungPay(_)
| WalletData::TwintRedirect {}
| WalletData::VippsRedirect {}
| WalletData::TouchNGoRedirect(_)
| WalletData::WeChatPayRedirect(_)
| WalletData::WeChatPayQr(_)
| WalletData::CashappQr(_)
| WalletData::SwishQr(_)
| WalletData::Mifinity(_)
| WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("authorizedotnet"),
)),
},
PaymentMethodData::CardRedirect(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("authorizedotnet"),
))
}
}?;
Ok(Self {
create_customer_payment_profile_request: AuthorizedotnetPaymentProfileRequest {
merchant_authentication,
customer_profile_id,
payment_profile,
validation_mode,
},
})
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthorizedotnetSetupMandateResponse {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
customer_payment_profile_id_list: Vec<String>,
customer_profile_id: Option<String>,
#[serde(rename = "customerPaymentProfileId")]
customer_payment_profile_id: Option<String>,
validation_direct_response_list: Option<Vec<Secret<String>>>,
pub messages: ResponseMessages,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthorizedotnetCustomerResponse {
customer_profile_id: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
customer_payment_profile_id_list: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
customer_shipping_address_id_list: Vec<String>,
pub messages: ResponseMessages,
}
fn extract_customer_id(text: &str) -> Option<String> {
let re = Regex::new(r"ID (\d+)").ok()?;
re.captures(text)
.and_then(|captures| captures.get(1))
.map(|capture_match| capture_match.as_str().to_string())
}
impl<F, T> TryFrom<ResponseRouterData<F, AuthorizedotnetCustomerResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, AuthorizedotnetCustomerResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
match item.response.messages.result_code {
ResultCode::Ok => match item.response.customer_profile_id.clone() {
Some(connector_customer_id) => Ok(Self {
response: Ok(PaymentsResponseData::ConnectorCustomerResponse(
ConnectorCustomerResponseData::new_with_customer_id(connector_customer_id),
)),
..item.data
}),
None => Err(
errors::ConnectorError::UnexpectedResponseError(bytes::Bytes::from(
"Missing customer profile id from Authorizedotnet".to_string(),
))
.into(),
),
},
ResultCode::Error => {
let error_message = item.response.messages.message.first();
if let Some(connector_customer_id) =
error_message.and_then(|error| extract_customer_id(&error.text))
{
Ok(Self {
response: Ok(PaymentsResponseData::ConnectorCustomerResponse(
ConnectorCustomerResponseData::new_with_customer_id(
connector_customer_id,
),
)),
..item.data
})
} else {
let error_code = error_message.map(|error| error.code.clone());
let error_code = error_code.unwrap_or_else(|| {
hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()
});
let error_reason = item
.response
.messages
.message
.iter()
.map(|error: &ResponseMessage| error.text.clone())
.collect::<Vec<String>>()
.join(" ");
let response = Err(ErrorResponse {
code: error_code,
message: item.response.messages.result_code.to_string(),
reason: Some(error_reason),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
});
Ok(Self {
response,
status: enums::AttemptStatus::Failure,
..item.data
})
}
}
}
}
}
// zero dollar response
impl<F, T>
TryFrom<ResponseRouterData<F, AuthorizedotnetSetupMandateResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, AuthorizedotnetSetupMandateResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let connector_customer_id = item.data.get_connector_customer_id()?;
if item.response.customer_profile_id.is_some() {
Ok(Self {
status: enums::AttemptStatus::Charged,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(None),
mandate_reference: Box::new(Some(MandateReference {
connector_mandate_id: item
.response
.customer_payment_profile_id_list
.first()
.or(item.response.customer_payment_profile_id.as_ref())
.map(|payment_profile_id| {
format!("{connector_customer_id}-{payment_profile_id}")
}),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
})),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
} else {
let error_message = item.response.messages.message.first();
let error_code = error_message.map(|error| error.code.clone());
let error_code = error_code
.unwrap_or_else(|| hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string());
let error_reason = item
.response
.messages
.message
.iter()
.map(|error: &ResponseMessage| error.text.clone())
.collect::<Vec<String>>()
.join(" ");
let response = Err(ErrorResponse {
code: error_code,
message: item.response.messages.result_code.to_string(),
reason: Some(error_reason),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
});
Ok(Self {
response,
status: enums::AttemptStatus::Failure,
..item.data
})
}
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
// The connector enforces field ordering, it expects fields to be in the same order as in their API documentation
pub struct CreateTransactionRequest {
create_transaction_request: AuthorizedotnetPaymentsRequest,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CancelOrCaptureTransactionRequest {
create_transaction_request: AuthorizedotnetPaymentCancelOrCaptureRequest,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum AuthorizationType {
Final,
Pre,
}
impl TryFrom<enums::CaptureMethod> for AuthorizationType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(capture_method: enums::CaptureMethod) -> Result<Self, Self::Error> {
match capture_method {
enums::CaptureMethod::Manual => Ok(Self::Pre),
enums::CaptureMethod::SequentialAutomatic | enums::CaptureMethod::Automatic => {
Ok(Self::Final)
}
enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => Err(
utils::construct_not_supported_error_report(capture_method, "authorizedotnet"),
)?,
}
}
}
impl TryFrom<&AuthorizedotnetRouterData<&PaymentsAuthorizeRouterData>>
for CreateTransactionRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &AuthorizedotnetRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let merchant_authentication =
AuthorizedotnetAuthType::try_from(&item.router_data.connector_auth_type)?;
let ref_id = if item.router_data.connector_request_reference_id.len() <= MAX_ID_LENGTH {
Some(item.router_data.connector_request_reference_id.clone())
} else {
None
};
let transaction_request = match item
.router_data
.request
.mandate_id
.clone()
.and_then(|mandate_ids| mandate_ids.mandate_reference_id)
{
Some(api_models::payments::MandateReferenceId::NetworkMandateId(network_trans_id)) => {
TransactionRequest::try_from((item, network_trans_id))?
}
Some(api_models::payments::MandateReferenceId::ConnectorMandateId(
connector_mandate_id,
)) => TransactionRequest::try_from((item, connector_mandate_id))?,
Some(api_models::payments::MandateReferenceId::NetworkTokenWithNTI(_)) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("authorizedotnet"),
))?
}
None => {
match &item.router_data.request.payment_method_data {
PaymentMethodData::Card(ccard) => TransactionRequest::try_from((item, ccard)),
PaymentMethodData::Wallet(wallet_data) => {
TransactionRequest::try_from((item, wallet_data))
}
PaymentMethodData::CardRedirect(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message(
"authorizedotnet",
),
))?
}
}
}?,
};
Ok(Self {
create_transaction_request: AuthorizedotnetPaymentsRequest {
merchant_authentication,
ref_id,
transaction_request,
},
})
}
}
impl
TryFrom<(
&AuthorizedotnetRouterData<&PaymentsAuthorizeRouterData>,
String,
)> for TransactionRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, network_trans_id): (
&AuthorizedotnetRouterData<&PaymentsAuthorizeRouterData>,
String,
),
| 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/riskified/transformers.rs | crates/hyperswitch_connectors/src/connectors/riskified/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/riskified/transformers/api.rs | crates/hyperswitch_connectors/src/connectors/riskified/transformers/api.rs | use api_models::{payments::AdditionalPaymentData, webhooks::IncomingWebhookEvent};
use common_enums::{Currency, FraudCheckStatus};
use common_utils::{
ext_traits::ValueExt,
id_type,
pii::Email,
types::{AmountConvertor, StringMajorUnit, StringMajorUnitForConnector},
};
use error_stack::{self, ResultExt};
use hyperswitch_domain_models::{
router_data::RouterData,
router_flow_types::Fulfillment,
router_request_types::{
fraud_check::{FraudCheckFulfillmentData, FulfillmentStatus},
BrowserInformation, ResponseId,
},
router_response_types::fraud_check::FraudCheckResponseData,
};
use hyperswitch_interfaces::errors::ConnectorError;
use masking::Secret;
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
use crate::{
types::{
FrmCheckoutRouterData, FrmFulfillmentRouterData, FrmTransactionRouterData,
ResponseRouterData,
},
utils::{
convert_amount, AddressDetailsData as _, FraudCheckCheckoutRequest,
FraudCheckTransactionRequest, RouterData as _,
},
};
type Error = error_stack::Report<ConnectorError>;
pub struct RiskifiedRouterData<T> {
pub amount: StringMajorUnit,
pub router_data: T,
amount_converter: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync),
}
impl<T> From<(StringMajorUnit, T)> for RiskifiedRouterData<T> {
fn from((amount, router_data): (StringMajorUnit, T)) -> Self {
Self {
amount,
router_data,
amount_converter: &StringMajorUnitForConnector,
}
}
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
pub struct RiskifiedPaymentsCheckoutRequest {
order: CheckoutRequest,
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
pub struct CheckoutRequest {
id: String,
note: Option<String>,
email: Option<Email>,
#[serde(with = "common_utils::custom_serde::iso8601")]
created_at: PrimitiveDateTime,
currency: Option<Currency>,
#[serde(with = "common_utils::custom_serde::iso8601")]
updated_at: PrimitiveDateTime,
gateway: Option<String>,
browser_ip: Option<std::net::IpAddr>,
total_price: StringMajorUnit,
total_discounts: i64,
cart_token: String,
referring_site: String,
line_items: Vec<LineItem>,
discount_codes: Vec<DiscountCodes>,
shipping_lines: Vec<ShippingLines>,
payment_details: Option<PaymentDetails>,
customer: RiskifiedCustomer,
billing_address: Option<OrderAddress>,
shipping_address: Option<OrderAddress>,
source: Source,
client_details: ClientDetails,
vendor_name: String,
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
pub struct PaymentDetails {
credit_card_bin: Option<Secret<String>>,
credit_card_number: Option<Secret<String>>,
credit_card_company: Option<api_models::enums::CardNetwork>,
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
pub struct ShippingLines {
price: StringMajorUnit,
title: Option<String>,
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
pub struct DiscountCodes {
amount: StringMajorUnit,
code: Option<String>,
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
pub struct ClientDetails {
user_agent: Option<String>,
accept_language: Option<String>,
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
pub struct RiskifiedCustomer {
email: Option<Email>,
first_name: Option<Secret<String>>,
last_name: Option<Secret<String>>,
#[serde(with = "common_utils::custom_serde::iso8601")]
created_at: PrimitiveDateTime,
verified_email: bool,
id: id_type::CustomerId,
account_type: CustomerAccountType,
orders_count: i32,
phone: Option<Secret<String>>,
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
#[serde(rename_all = "lowercase")]
pub enum CustomerAccountType {
Guest,
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
pub struct OrderAddress {
first_name: Option<Secret<String>>,
last_name: Option<Secret<String>>,
address1: Option<Secret<String>>,
country_code: Option<common_enums::CountryAlpha2>,
city: Option<String>,
province: Option<Secret<String>>,
phone: Option<Secret<String>>,
zip: Option<Secret<String>>,
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
pub struct LineItem {
price: StringMajorUnit,
quantity: i32,
title: String,
product_type: Option<common_enums::ProductType>,
requires_shipping: Option<bool>,
product_id: Option<String>,
category: Option<String>,
brand: Option<String>,
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
#[serde(rename_all = "snake_case")]
pub enum Source {
DesktopWeb,
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
pub struct RiskifiedMetadata {
vendor_name: String,
shipping_lines: Vec<ShippingLines>,
}
impl TryFrom<&RiskifiedRouterData<&FrmCheckoutRouterData>> for RiskifiedPaymentsCheckoutRequest {
type Error = Error;
fn try_from(
payment: &RiskifiedRouterData<&FrmCheckoutRouterData>,
) -> Result<Self, Self::Error> {
let payment_data = payment.router_data.clone();
let metadata: RiskifiedMetadata = payment_data
.frm_metadata
.clone()
.ok_or(ConnectorError::MissingRequiredField {
field_name: "frm_metadata",
})?
.parse_value("Riskified Metadata")
.change_context(ConnectorError::InvalidDataFormat {
field_name: "frm_metadata",
})?;
let billing_address = payment_data.get_billing()?;
let shipping_address = payment_data.get_shipping_address_with_phone_number()?;
let address = payment_data.get_billing_address()?;
let line_items = payment_data
.request
.get_order_details()?
.iter()
.map(|order_detail| {
let price = convert_amount(
payment.amount_converter,
order_detail.amount,
payment_data.request.currency.ok_or_else(|| {
ConnectorError::MissingRequiredField {
field_name: "currency",
}
})?,
)?;
Ok(LineItem {
price,
quantity: i32::from(order_detail.quantity),
title: order_detail.product_name.clone(),
product_type: order_detail.product_type.clone(),
requires_shipping: order_detail.requires_shipping,
product_id: order_detail.product_id.clone(),
category: order_detail.category.clone(),
brand: order_detail.brand.clone(),
})
})
.collect::<Result<Vec<_>, Self::Error>>()?;
Ok(Self {
order: CheckoutRequest {
id: payment_data.attempt_id.clone(),
email: payment_data.request.email.clone(),
created_at: common_utils::date_time::now(),
updated_at: common_utils::date_time::now(),
gateway: payment_data.request.gateway.clone(),
total_price: payment.amount.clone(),
cart_token: payment_data.attempt_id.clone(),
line_items,
source: Source::DesktopWeb,
billing_address: OrderAddress::try_from(billing_address).ok(),
shipping_address: OrderAddress::try_from(shipping_address).ok(),
total_discounts: 0,
currency: payment_data.request.currency,
referring_site: "hyperswitch.io".to_owned(),
discount_codes: Vec::new(),
shipping_lines: metadata.shipping_lines,
customer: RiskifiedCustomer {
email: payment_data.request.email.clone(),
first_name: address.get_first_name().ok().cloned(),
last_name: address.get_last_name().ok().cloned(),
created_at: common_utils::date_time::now(),
verified_email: false,
id: payment_data.get_customer_id()?,
account_type: CustomerAccountType::Guest,
orders_count: 0,
phone: billing_address
.clone()
.phone
.and_then(|phone_data| phone_data.number),
},
browser_ip: payment_data
.request
.browser_info
.as_ref()
.and_then(|browser_info| browser_info.ip_address),
client_details: ClientDetails {
user_agent: payment_data
.request
.browser_info
.as_ref()
.and_then(|browser_info| browser_info.user_agent.clone()),
accept_language: payment_data.request.browser_info.as_ref().and_then(
|browser_info: &BrowserInformation| browser_info.language.clone(),
),
},
note: payment_data.description.clone(),
vendor_name: metadata.vendor_name,
payment_details: match payment_data.request.payment_method_data.as_ref() {
Some(AdditionalPaymentData::Card(card_info)) => Some(PaymentDetails {
credit_card_bin: card_info.card_isin.clone().map(Secret::new),
credit_card_number: card_info
.last4
.clone()
.map(|last_four| format!("XXXX-XXXX-XXXX-{last_four}"))
.map(Secret::new),
credit_card_company: card_info.card_network.clone(),
}),
Some(_) | None => None,
},
},
})
}
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
pub struct RiskifiedPaymentsResponse {
order: OrderResponse,
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
pub struct OrderResponse {
id: String,
status: PaymentStatus,
description: Option<String>,
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
pub struct RiskifiedFulfilmentResponse {
order: OrderFulfilmentResponse,
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
pub struct OrderFulfilmentResponse {
id: String,
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
#[serde(rename_all = "lowercase")]
pub enum FulfilmentStatus {
Fulfilled,
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
#[serde(rename_all = "lowercase")]
pub enum PaymentStatus {
Captured,
Created,
Submitted,
Approved,
Declined,
Processing,
}
impl<F, T> TryFrom<ResponseRouterData<F, RiskifiedPaymentsResponse, T, FraudCheckResponseData>>
for RouterData<F, T, FraudCheckResponseData>
{
type Error = Error;
fn try_from(
item: ResponseRouterData<F, RiskifiedPaymentsResponse, 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.order.status),
connector_metadata: None,
score: None,
reason: item.response.order.description.map(serde_json::Value::from),
}),
..item.data
})
}
}
impl From<PaymentStatus> for FraudCheckStatus {
fn from(item: PaymentStatus) -> Self {
match item {
PaymentStatus::Approved => Self::Legit,
PaymentStatus::Declined => Self::Fraud,
_ => Self::Pending,
}
}
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
pub struct TransactionFailedRequest {
checkout: FailedTransactionData,
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
pub struct FailedTransactionData {
id: String,
payment_details: Vec<DeclinedPaymentDetails>,
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
pub struct DeclinedPaymentDetails {
authorization_error: AuthorizationError,
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
pub struct AuthorizationError {
#[serde(with = "common_utils::custom_serde::iso8601")]
created_at: PrimitiveDateTime,
error_code: Option<String>,
message: Option<String>,
}
impl TryFrom<&FrmTransactionRouterData> for TransactionFailedRequest {
type Error = Error;
fn try_from(item: &FrmTransactionRouterData) -> Result<Self, Self::Error> {
Ok(Self {
checkout: FailedTransactionData {
id: item.attempt_id.clone(),
payment_details: [DeclinedPaymentDetails {
authorization_error: AuthorizationError {
created_at: common_utils::date_time::now(),
error_code: item.request.error_code.clone(),
message: item.request.error_message.clone(),
},
}]
.to_vec(),
},
})
}
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
pub struct RiskifiedFailedTransactionResponse {
checkout: OrderResponse,
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
#[serde(untagged)]
pub enum RiskifiedTransactionResponse {
FailedResponse(RiskifiedFailedTransactionResponse),
SuccessResponse(RiskifiedPaymentsResponse),
}
impl<F, T>
TryFrom<ResponseRouterData<F, RiskifiedFailedTransactionResponse, T, FraudCheckResponseData>>
for RouterData<F, T, FraudCheckResponseData>
{
type Error = Error;
fn try_from(
item: ResponseRouterData<F, RiskifiedFailedTransactionResponse, T, FraudCheckResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(FraudCheckResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.checkout.id),
status: FraudCheckStatus::from(item.response.checkout.status),
connector_metadata: None,
score: None,
reason: item
.response
.checkout
.description
.map(serde_json::Value::from),
}),
..item.data
})
}
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
pub struct TransactionSuccessRequest {
order: SuccessfulTransactionData,
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
pub struct SuccessfulTransactionData {
id: String,
decision: TransactionDecisionData,
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
pub struct TransactionDecisionData {
external_status: TransactionStatus,
reason: Option<String>,
amount: StringMajorUnit,
currency: Currency,
#[serde(with = "common_utils::custom_serde::iso8601")]
decided_at: PrimitiveDateTime,
payment_details: Vec<TransactionPaymentDetails>,
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
pub struct TransactionPaymentDetails {
authorization_id: Option<String>,
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
#[serde(rename_all = "lowercase")]
pub enum TransactionStatus {
Approved,
}
impl TryFrom<&RiskifiedRouterData<&FrmTransactionRouterData>> for TransactionSuccessRequest {
type Error = Error;
fn try_from(
item_data: &RiskifiedRouterData<&FrmTransactionRouterData>,
) -> Result<Self, Self::Error> {
let item = item_data.router_data.clone();
Ok(Self {
order: SuccessfulTransactionData {
id: item.attempt_id.clone(),
decision: TransactionDecisionData {
external_status: TransactionStatus::Approved,
reason: None,
amount: item_data.amount.clone(),
currency: item.request.get_currency()?,
decided_at: common_utils::date_time::now(),
payment_details: [TransactionPaymentDetails {
authorization_id: item.request.connector_transaction_id.clone(),
}]
.to_vec(),
},
},
})
}
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
pub struct RiskifiedFulfillmentRequest {
order: OrderFulfillment,
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
#[serde(rename_all = "lowercase")]
pub enum FulfillmentRequestStatus {
Success,
Cancelled,
Error,
Failure,
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
pub struct OrderFulfillment {
id: String,
fulfillments: FulfilmentData,
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
pub struct FulfilmentData {
fulfillment_id: String,
#[serde(with = "common_utils::custom_serde::iso8601")]
created_at: PrimitiveDateTime,
status: Option<FulfillmentRequestStatus>,
tracking_company: String,
tracking_number: String,
tracking_url: Option<String>,
}
impl TryFrom<&FrmFulfillmentRouterData> for RiskifiedFulfillmentRequest {
type Error = Error;
fn try_from(item: &FrmFulfillmentRouterData) -> Result<Self, Self::Error> {
let tracking_number = item
.request
.fulfillment_req
.tracking_numbers
.as_ref()
.and_then(|numbers| numbers.first().cloned())
.ok_or(ConnectorError::MissingRequiredField {
field_name: "tracking_number",
})?;
let tracking_url = item
.request
.fulfillment_req
.tracking_urls
.as_ref()
.and_then(|urls| urls.first().cloned().map(|url| url.to_string()));
Ok(Self {
order: OrderFulfillment {
id: item.attempt_id.clone(),
fulfillments: FulfilmentData {
fulfillment_id: item.payment_id.clone(),
created_at: common_utils::date_time::now(),
status: item
.request
.fulfillment_req
.fulfillment_status
.clone()
.and_then(get_fulfillment_status),
tracking_company: item
.request
.fulfillment_req
.tracking_company
.clone()
.ok_or(ConnectorError::MissingRequiredField {
field_name: "tracking_company",
})?,
tracking_number,
tracking_url,
},
},
})
}
}
impl
TryFrom<
ResponseRouterData<
Fulfillment,
RiskifiedFulfilmentResponse,
FraudCheckFulfillmentData,
FraudCheckResponseData,
>,
> for RouterData<Fulfillment, FraudCheckFulfillmentData, FraudCheckResponseData>
{
type Error = Error;
fn try_from(
item: ResponseRouterData<
Fulfillment,
RiskifiedFulfilmentResponse,
FraudCheckFulfillmentData,
FraudCheckResponseData,
>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(FraudCheckResponseData::FulfillmentResponse {
order_id: item.response.order.id,
shipment_ids: Vec::new(),
}),
..item.data
})
}
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
pub struct ErrorResponse {
pub error: ErrorData,
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
pub struct ErrorData {
pub message: String,
}
impl TryFrom<&hyperswitch_domain_models::address::Address> for OrderAddress {
type Error = Error;
fn try_from(
address_info: &hyperswitch_domain_models::address::Address,
) -> Result<Self, Self::Error> {
let address = address_info
.clone()
.address
.ok_or(ConnectorError::MissingRequiredField {
field_name: "address",
})?;
Ok(Self {
first_name: address.first_name.clone(),
last_name: address.last_name.clone(),
address1: address.line1.clone(),
country_code: address.country,
city: address.city.clone(),
province: address.state.clone(),
zip: address.zip.clone(),
phone: address_info
.phone
.clone()
.and_then(|phone_data| phone_data.number),
})
}
}
fn get_fulfillment_status(status: FulfillmentStatus) -> Option<FulfillmentRequestStatus> {
match status {
FulfillmentStatus::COMPLETE => Some(FulfillmentRequestStatus::Success),
FulfillmentStatus::CANCELED => Some(FulfillmentRequestStatus::Cancelled),
FulfillmentStatus::PARTIAL | FulfillmentStatus::REPLACEMENT => None,
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct RiskifiedWebhookBody {
pub id: String,
pub status: RiskifiedWebhookStatus,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub enum RiskifiedWebhookStatus {
Approved,
Declined,
}
impl From<RiskifiedWebhookStatus> for IncomingWebhookEvent {
fn from(value: RiskifiedWebhookStatus) -> Self {
match value {
RiskifiedWebhookStatus::Declined => Self::FrmRejected,
RiskifiedWebhookStatus::Approved => 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/riskified/transformers/auth.rs | crates/hyperswitch_connectors/src/connectors/riskified/transformers/auth.rs | use hyperswitch_domain_models::router_data::ConnectorAuthType;
use hyperswitch_interfaces::errors::ConnectorError;
use masking::{ExposeInterface, Secret};
pub struct RiskifiedAuthType {
pub secret_token: Secret<String>,
pub domain_name: String,
}
impl TryFrom<&ConnectorAuthType> for RiskifiedAuthType {
type Error = error_stack::Report<ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
secret_token: api_key.to_owned(),
domain_name: key1.to_owned().expose(),
}),
_ => 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/getnet/transformers.rs | crates/hyperswitch_connectors/src/connectors/getnet/transformers.rs | use api_models::webhooks::IncomingWebhookEvent;
use base64::Engine;
use cards::CardNumber;
use common_enums::{enums, AttemptStatus, CaptureMethod, CountryAlpha2};
use common_utils::{
consts::BASE64_ENGINE,
errors::CustomResult,
pii::{Email, IpAddress},
types::FloatMajorUnit,
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::ConnectorAuthType,
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RefundsResponseData},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsSyncRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::errors;
use masking::{PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
connectors::paybox::transformers::parse_url_encoded_to_struct,
types::{
PaymentsCancelResponseRouterData, PaymentsCaptureResponseRouterData,
PaymentsResponseRouterData, PaymentsSyncResponseRouterData, RefundsResponseRouterData,
},
utils::{
BrowserInformationData, PaymentsAuthorizeRequestData, PaymentsSyncRequestData,
RouterData as _,
},
};
pub struct GetnetRouterData<T> {
pub amount: FloatMajorUnit,
pub router_data: T,
}
impl<T> From<(FloatMajorUnit, T)> for GetnetRouterData<T> {
fn from((amount, item): (FloatMajorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
#[derive(Default, Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct Amount {
pub value: FloatMajorUnit,
pub currency: enums::Currency,
}
#[derive(Default, Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct Address {
#[serde(rename = "street1")]
pub street1: Option<Secret<String>>,
pub city: Option<String>,
pub state: Option<Secret<String>>,
pub country: Option<CountryAlpha2>,
}
#[derive(Default, Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct AccountHolder {
#[serde(rename = "first-name")]
pub first_name: Option<Secret<String>>,
#[serde(rename = "last-name")]
pub last_name: Option<Secret<String>>,
pub email: Option<Email>,
pub phone: Option<Secret<String>>,
pub address: Option<Address>,
}
#[derive(Default, Debug, Serialize, PartialEq)]
pub struct Card {
#[serde(rename = "account-number")]
pub account_number: CardNumber,
#[serde(rename = "expiration-month")]
pub expiration_month: Secret<String>,
#[serde(rename = "expiration-year")]
pub expiration_year: Secret<String>,
#[serde(rename = "card-security-code")]
pub card_security_code: Secret<String>,
#[serde(rename = "card-type")]
pub card_type: String,
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum GetnetPaymentMethods {
CreditCard,
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct PaymentMethod {
pub name: GetnetPaymentMethods,
}
#[derive(Default, Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct Notification {
pub url: Option<String>,
}
#[derive(Default, Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct PaymentMethodContainer {
#[serde(rename = "payment-method")]
pub payment_method: Vec<PaymentMethod>,
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum NotificationFormat {
#[serde(rename = "application/json-signed")]
JsonSigned,
#[serde(rename = "application/json")]
Json,
#[serde(rename = "application/xml")]
Xml,
#[serde(rename = "application/html")]
Html,
#[serde(rename = "application/x-www-form-urlencoded")]
Urlencoded,
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct NotificationContainer {
pub notification: Vec<Notification>,
pub format: NotificationFormat,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
pub struct MerchantAccountId {
pub value: Secret<String>,
}
#[derive(Debug, Serialize, PartialEq)]
pub struct PaymentData {
#[serde(rename = "merchant-account-id")]
pub merchant_account_id: MerchantAccountId,
#[serde(rename = "request-id")]
pub request_id: String,
#[serde(rename = "transaction-type")]
pub transaction_type: GetnetTransactionType,
#[serde(rename = "requested-amount")]
pub requested_amount: Amount,
#[serde(rename = "account-holder")]
pub account_holder: Option<AccountHolder>,
pub card: Card,
#[serde(rename = "ip-address")]
pub ip_address: Option<Secret<String, IpAddress>>,
#[serde(rename = "payment-methods")]
pub payment_methods: PaymentMethodContainer,
pub notifications: Option<NotificationContainer>,
}
#[derive(Debug, Serialize)]
pub struct GetnetPaymentsRequest {
payment: PaymentData,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct GetnetCard {
number: CardNumber,
expiry_month: Secret<String>,
expiry_year: Secret<String>,
cvc: Secret<String>,
complete: bool,
}
impl TryFrom<enums::PaymentMethodType> for PaymentMethodContainer {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(payment_method_type: enums::PaymentMethodType) -> Result<Self, Self::Error> {
match payment_method_type {
enums::PaymentMethodType::Credit => Ok(Self {
payment_method: vec![PaymentMethod {
name: GetnetPaymentMethods::CreditCard,
}],
}),
_ => Err(errors::ConnectorError::NotSupported {
message: "Payment method type not supported".to_string(),
connector: "Getnet",
}
.into()),
}
}
}
impl TryFrom<&GetnetRouterData<&PaymentsAuthorizeRouterData>> for GetnetPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &GetnetRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(ref req_card) => {
if item.router_data.is_three_ds() {
return Err(errors::ConnectorError::NotSupported {
message: "3DS payments".to_string(),
connector: "Getnet",
}
.into());
}
let request = &item.router_data.request;
let auth_type = GetnetAuthType::try_from(&item.router_data.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let merchant_account_id = MerchantAccountId {
value: auth_type.merchant_id,
};
let requested_amount = Amount {
value: item.amount,
currency: request.currency,
};
let account_holder = AccountHolder {
first_name: item.router_data.get_optional_billing_first_name(),
last_name: item.router_data.get_optional_billing_last_name(),
email: item.router_data.request.get_optional_email(),
phone: item.router_data.get_optional_billing_phone_number(),
address: Some(Address {
street1: item.router_data.get_optional_billing_line2(),
city: item.router_data.get_optional_billing_city(),
state: item.router_data.get_optional_billing_state(),
country: item.router_data.get_optional_billing_country(),
}),
};
let card = Card {
account_number: req_card.card_number.clone(),
expiration_month: req_card.card_exp_month.clone(),
expiration_year: req_card.card_exp_year.clone(),
card_security_code: req_card.card_cvc.clone(),
card_type: req_card
.card_network
.as_ref()
.map(|network| network.to_string().to_lowercase())
.unwrap_or_default(),
};
let pmt = item.router_data.request.get_payment_method_type()?;
let payment_method = PaymentMethodContainer::try_from(pmt)?;
let notifications: NotificationContainer = NotificationContainer {
format: NotificationFormat::JsonSigned,
notification: vec![Notification {
url: Some(item.router_data.request.get_webhook_url()?),
}],
};
let transaction_type = if request.is_auto_capture()? {
GetnetTransactionType::Purchase
} else {
GetnetTransactionType::Authorization
};
let payment_data = PaymentData {
merchant_account_id,
request_id: item.router_data.payment_id.clone(),
transaction_type,
requested_amount,
account_holder: Some(account_holder),
card,
ip_address: Some(request.get_browser_info()?.get_ip_address()?),
payment_methods: payment_method,
notifications: Some(notifications),
};
Ok(Self {
payment: payment_data,
})
}
_ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()),
}
}
}
pub struct GetnetAuthType {
pub username: Secret<String>,
pub password: Secret<String>,
pub merchant_id: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for GetnetAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} => Ok(Self {
username: key1.to_owned(),
password: api_key.to_owned(),
merchant_id: api_secret.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum GetnetPaymentStatus {
Success,
Failed,
#[default]
InProgress,
}
impl From<GetnetPaymentStatus> for AttemptStatus {
fn from(item: GetnetPaymentStatus) -> Self {
match item {
GetnetPaymentStatus::Success => Self::Charged,
GetnetPaymentStatus::Failed => Self::Failure,
GetnetPaymentStatus::InProgress => Self::Pending,
}
}
}
#[derive(Default, Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct Status {
pub code: String,
pub description: String,
pub severity: String,
}
#[derive(Default, Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct Statuses {
pub status: Vec<Status>,
}
#[derive(Default, Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct CardToken {
#[serde(rename = "token-id")]
pub token_id: Secret<String>,
#[serde(rename = "masked-account-number")]
pub masked_account_number: Secret<String>,
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct PaymentResponseData {
pub statuses: Statuses,
pub descriptor: Option<String>,
pub notifications: NotificationContainer,
#[serde(rename = "merchant-account-id")]
pub merchant_account_id: MerchantAccountId,
#[serde(rename = "transaction-id")]
pub transaction_id: String,
#[serde(rename = "request-id")]
pub request_id: String,
#[serde(rename = "transaction-type")]
pub transaction_type: GetnetTransactionType,
#[serde(rename = "transaction-state")]
pub transaction_state: GetnetPaymentStatus,
#[serde(rename = "completion-time-stamp")]
pub completion_time_stamp: Option<i64>,
#[serde(rename = "requested-amount")]
pub requested_amount: Amount,
#[serde(rename = "account-holder")]
pub account_holder: Option<AccountHolder>,
#[serde(rename = "card-token")]
pub card_token: CardToken,
#[serde(rename = "ip-address")]
pub ip_address: Option<Secret<String, IpAddress>>,
#[serde(rename = "payment-methods")]
pub payment_methods: PaymentMethodContainer,
#[serde(rename = "api-id")]
pub api_id: String,
#[serde(rename = "self")]
pub self_url: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PaymentsResponse {
payment: PaymentResponseData,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum GetnetPaymentsResponse {
PaymentsResponse(Box<PaymentsResponse>),
GetnetWebhookNotificationResponse(Box<GetnetWebhookNotificationResponseBody>),
}
pub fn authorization_attempt_status_from_transaction_state(
getnet_status: GetnetPaymentStatus,
is_auto_capture: bool,
) -> AttemptStatus {
match getnet_status {
GetnetPaymentStatus::Success => {
if is_auto_capture {
AttemptStatus::Charged
} else {
AttemptStatus::Authorized
}
}
GetnetPaymentStatus::InProgress => AttemptStatus::Pending,
GetnetPaymentStatus::Failed => AttemptStatus::Failure,
}
}
impl TryFrom<PaymentsResponseRouterData<GetnetPaymentsResponse>> for PaymentsAuthorizeRouterData {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsResponseRouterData<GetnetPaymentsResponse>,
) -> Result<Self, Self::Error> {
match item.response {
GetnetPaymentsResponse::PaymentsResponse(ref payment_response) => Ok(Self {
status: authorization_attempt_status_from_transaction_state(
payment_response.payment.transaction_state.clone(),
item.data.request.is_auto_capture()?,
),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
payment_response.payment.transaction_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
}),
_ => Err(error_stack::Report::new(
errors::ConnectorError::ResponseHandlingFailed,
)),
}
}
}
pub fn psync_attempt_status_from_transaction_state(
getnet_status: GetnetPaymentStatus,
is_auto_capture: bool,
transaction_type: GetnetTransactionType,
) -> AttemptStatus {
match getnet_status {
GetnetPaymentStatus::Success => {
if is_auto_capture && transaction_type == GetnetTransactionType::CaptureAuthorization {
AttemptStatus::Charged
} else {
AttemptStatus::Authorized
}
}
GetnetPaymentStatus::InProgress => AttemptStatus::Pending,
GetnetPaymentStatus::Failed => AttemptStatus::Failure,
}
}
impl TryFrom<PaymentsSyncResponseRouterData<GetnetPaymentsResponse>> for PaymentsSyncRouterData {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsSyncResponseRouterData<GetnetPaymentsResponse>,
) -> Result<Self, Self::Error> {
match item.response {
GetnetPaymentsResponse::PaymentsResponse(ref payment_response) => Ok(Self {
status: authorization_attempt_status_from_transaction_state(
payment_response.payment.transaction_state.clone(),
item.data.request.is_auto_capture()?,
),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
payment_response.payment.transaction_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
}),
GetnetPaymentsResponse::GetnetWebhookNotificationResponse(ref webhook_response) => {
Ok(Self {
status: psync_attempt_status_from_transaction_state(
webhook_response.payment.transaction_state.clone(),
item.data.request.is_auto_capture()?,
webhook_response.payment.transaction_type.clone(),
),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
webhook_response.payment.transaction_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
}
}
#[derive(Debug, Serialize, PartialEq)]
pub struct CapturePaymentData {
#[serde(rename = "merchant-account-id")]
pub merchant_account_id: MerchantAccountId,
#[serde(rename = "request-id")]
pub request_id: String,
#[serde(rename = "transaction-type")]
pub transaction_type: GetnetTransactionType,
#[serde(rename = "parent-transaction-id")]
pub parent_transaction_id: String,
#[serde(rename = "requested-amount")]
pub requested_amount: Amount,
pub notifications: NotificationContainer,
#[serde(rename = "ip-address")]
pub ip_address: Option<Secret<String, IpAddress>>,
}
#[derive(Debug, Serialize)]
pub struct GetnetCaptureRequest {
pub payment: CapturePaymentData,
}
impl TryFrom<&GetnetRouterData<&PaymentsCaptureRouterData>> for GetnetCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &GetnetRouterData<&PaymentsCaptureRouterData>) -> Result<Self, Self::Error> {
let request = &item.router_data.request;
let auth_type = GetnetAuthType::try_from(&item.router_data.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let merchant_account_id = MerchantAccountId {
value: auth_type.merchant_id,
};
let requested_amount = Amount {
value: item.amount,
currency: request.currency,
};
let req = &item.router_data.request;
let webhook_url = &req.webhook_url;
let notifications = NotificationContainer {
format: NotificationFormat::JsonSigned,
notification: vec![Notification {
url: webhook_url.clone(),
}],
};
let transaction_type = GetnetTransactionType::CaptureAuthorization;
let ip_address = req
.browser_info
.as_ref()
.and_then(|info| info.ip_address.as_ref())
.map(|ip| Secret::new(ip.to_string()));
let request_id = item.router_data.connector_request_reference_id.clone();
let parent_transaction_id = item.router_data.request.connector_transaction_id.clone();
let capture_payment_data = CapturePaymentData {
merchant_account_id,
request_id,
transaction_type,
parent_transaction_id,
requested_amount,
notifications,
ip_address,
};
Ok(Self {
payment: capture_payment_data,
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct CaptureResponseData {
pub statuses: Statuses,
pub descriptor: String,
pub notifications: NotificationContainer,
#[serde(rename = "merchant-account-id")]
pub merchant_account_id: MerchantAccountId,
#[serde(rename = "transaction-id")]
pub transaction_id: String,
#[serde(rename = "request-id")]
pub request_id: String,
#[serde(rename = "transaction-type")]
pub transaction_type: GetnetTransactionType,
#[serde(rename = "transaction-state")]
pub transaction_state: GetnetPaymentStatus,
#[serde(rename = "completion-time-stamp")]
pub completion_time_stamp: Option<i64>,
#[serde(rename = "requested-amount")]
pub requested_amount: Amount,
#[serde(rename = "parent-transaction-id")]
pub parent_transaction_id: String,
#[serde(rename = "account-holder")]
pub account_holder: Option<AccountHolder>,
#[serde(rename = "card-token")]
pub card_token: CardToken,
#[serde(rename = "ip-address")]
pub ip_address: Option<Secret<String, IpAddress>>,
#[serde(rename = "payment-methods")]
pub payment_methods: PaymentMethodContainer,
#[serde(rename = "parent-transaction-amount")]
pub parent_transaction_amount: Amount,
#[serde(rename = "authorization-code")]
pub authorization_code: String,
#[serde(rename = "api-id")]
pub api_id: String,
#[serde(rename = "self")]
pub self_url: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GetnetCaptureResponse {
payment: CaptureResponseData,
}
pub fn capture_status_from_transaction_state(getnet_status: GetnetPaymentStatus) -> AttemptStatus {
match getnet_status {
GetnetPaymentStatus::Success => AttemptStatus::Charged,
GetnetPaymentStatus::InProgress => AttemptStatus::Pending,
GetnetPaymentStatus::Failed => AttemptStatus::Authorized,
}
}
impl TryFrom<PaymentsCaptureResponseRouterData<GetnetCaptureResponse>>
for PaymentsCaptureRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsCaptureResponseRouterData<GetnetCaptureResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: capture_status_from_transaction_state(item.response.payment.transaction_state),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.payment.transaction_id,
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Debug, Serialize, PartialEq)]
pub struct RefundPaymentData {
#[serde(rename = "merchant-account-id")]
pub merchant_account_id: MerchantAccountId,
#[serde(rename = "request-id")]
pub request_id: String,
#[serde(rename = "transaction-type")]
pub transaction_type: GetnetTransactionType,
#[serde(rename = "parent-transaction-id")]
pub parent_transaction_id: String,
pub notifications: NotificationContainer,
#[serde(rename = "ip-address")]
pub ip_address: Option<Secret<String, IpAddress>>,
}
#[derive(Debug, Serialize)]
pub struct GetnetRefundRequest {
pub payment: RefundPaymentData,
}
impl<F> TryFrom<&GetnetRouterData<&RefundsRouterData<F>>> for GetnetRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &GetnetRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
let request = &item.router_data.request;
let auth_type = GetnetAuthType::try_from(&item.router_data.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let url = request.webhook_url.clone();
let merchant_account_id = MerchantAccountId {
value: auth_type.merchant_id,
};
let notifications = NotificationContainer {
format: NotificationFormat::JsonSigned,
notification: vec![Notification { url }],
};
let capture_method = request.capture_method;
let transaction_type = match capture_method {
Some(CaptureMethod::Automatic) => GetnetTransactionType::RefundPurchase,
Some(CaptureMethod::Manual) => GetnetTransactionType::RefundCapture,
Some(CaptureMethod::ManualMultiple)
| Some(CaptureMethod::Scheduled)
| Some(CaptureMethod::SequentialAutomatic)
| None => {
return Err(errors::ConnectorError::CaptureMethodNotSupported {}.into());
}
};
let ip_address = request
.browser_info
.as_ref()
.and_then(|browser_info| browser_info.ip_address.as_ref())
.map(|ip| Secret::new(ip.to_string()));
let request_id = item
.router_data
.refund_id
.clone()
.ok_or(errors::ConnectorError::MissingConnectorRefundID)?;
let parent_transaction_id = item.router_data.request.connector_transaction_id.clone();
let refund_payment_data = RefundPaymentData {
merchant_account_id,
request_id,
transaction_type,
parent_transaction_id,
notifications,
ip_address,
};
Ok(Self {
payment: refund_payment_data,
})
}
}
#[allow(dead_code)]
#[derive(Debug, Serialize, Default, Deserialize, Clone, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum RefundStatus {
Success,
Failed,
#[default]
InProgress,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Success => Self::Success,
RefundStatus::Failed => Self::Failure,
RefundStatus::InProgress => Self::Pending,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct RefundResponseData {
pub statuses: Statuses,
pub descriptor: String,
pub notifications: NotificationContainer,
#[serde(rename = "merchant-account-id")]
pub merchant_account_id: MerchantAccountId,
#[serde(rename = "transaction-id")]
pub transaction_id: String,
#[serde(rename = "request-id")]
pub request_id: String,
#[serde(rename = "transaction-type")]
pub transaction_type: GetnetTransactionType,
#[serde(rename = "transaction-state")]
pub transaction_state: RefundStatus,
#[serde(rename = "completion-time-stamp")]
pub completion_time_stamp: Option<i64>,
#[serde(rename = "requested-amount")]
pub requested_amount: Amount,
#[serde(rename = "parent-transaction-id")]
#[serde(skip_serializing_if = "Option::is_none")]
pub parent_transaction_id: Option<String>,
#[serde(rename = "account-holder")]
pub account_holder: Option<AccountHolder>,
#[serde(rename = "card-token")]
pub card_token: CardToken,
#[serde(rename = "ip-address")]
pub ip_address: Option<Secret<String, IpAddress>>,
#[serde(rename = "payment-methods")]
pub payment_methods: PaymentMethodContainer,
#[serde(rename = "parent-transaction-amount")]
#[serde(skip_serializing_if = "Option::is_none")]
pub parent_transaction_amount: Option<Amount>,
#[serde(rename = "api-id")]
pub api_id: String,
#[serde(rename = "self")]
pub self_url: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RefundResponse {
payment: RefundResponseData,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.payment.transaction_id,
refund_status: enums::RefundStatus::from(item.response.payment.transaction_state),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.payment.transaction_id,
refund_status: enums::RefundStatus::from(item.response.payment.transaction_state),
}),
..item.data
})
}
}
#[derive(Debug, Serialize, PartialEq)]
pub struct CancelPaymentData {
#[serde(rename = "merchant-account-id")]
pub merchant_account_id: MerchantAccountId,
#[serde(rename = "request-id")]
pub request_id: String,
#[serde(rename = "transaction-type")]
pub transaction_type: GetnetTransactionType,
#[serde(rename = "parent-transaction-id")]
pub parent_transaction_id: String,
pub notifications: NotificationContainer,
#[serde(rename = "ip-address")]
pub ip_address: Option<Secret<String, IpAddress>>,
}
#[derive(Debug, Serialize)]
pub struct GetnetCancelRequest {
pub payment: CancelPaymentData,
}
impl TryFrom<&PaymentsCancelRouterData> for GetnetCancelRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> {
let request = &item.request;
let auth_type = GetnetAuthType::try_from(&item.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let merchant_account_id = MerchantAccountId {
value: auth_type.merchant_id,
};
let webhook_url = &item.request.webhook_url;
let notifications = NotificationContainer {
format: NotificationFormat::JsonSigned,
notification: vec![Notification {
url: webhook_url.clone(),
}],
};
let capture_method = &item.request.capture_method;
let transaction_type = match capture_method {
Some(CaptureMethod::Automatic) => GetnetTransactionType::VoidPurchase,
Some(CaptureMethod::Manual) => GetnetTransactionType::VoidAuthorization,
Some(CaptureMethod::ManualMultiple)
| Some(CaptureMethod::Scheduled)
| Some(CaptureMethod::SequentialAutomatic) => {
return Err(errors::ConnectorError::CaptureMethodNotSupported {}.into());
}
None => {
return Err(errors::ConnectorError::CaptureMethodNotSupported {}.into());
}
};
let ip_address = request
.browser_info
.as_ref()
.and_then(|browser_info| browser_info.ip_address.as_ref())
.map(|ip| Secret::new(ip.to_string()));
let request_id = &item.connector_request_reference_id.clone();
let parent_transaction_id = item.request.connector_transaction_id.clone();
let cancel_payment_data = CancelPaymentData {
merchant_account_id,
request_id: request_id.to_string(),
transaction_type,
parent_transaction_id,
notifications,
ip_address,
};
Ok(Self {
payment: cancel_payment_data,
})
}
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum GetnetTransactionType {
Purchase,
| 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/zsl/transformers.rs | crates/hyperswitch_connectors/src/connectors/zsl/transformers.rs | use std::collections::HashMap;
use base64::Engine;
use common_enums::enums;
use common_utils::{crypto::GenerateDigest, date_time, pii::Email, request::Method};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{BankTransferData, PaymentMethodData},
router_data::{ConnectorAuthType, ErrorResponse, RouterData},
router_request_types::{PaymentsSyncData, ResponseId},
router_response_types::{PaymentsResponseData, RedirectForm},
types,
};
use hyperswitch_interfaces::{api, consts::NO_ERROR_CODE, errors};
use masking::{ExposeInterface, Secret};
use ring::digest;
use serde::{Deserialize, Serialize};
use crate::{
types::ResponseRouterData,
utils::{
get_amount_as_string, get_unimplemented_payment_method_error_message,
PaymentsAuthorizeRequestData, RouterData as _,
},
};
mod auth_error {
pub const INVALID_SIGNATURE: &str = "INVALID_SIGNATURE";
}
mod zsl_version {
pub const VERSION_1: &str = "1";
}
pub struct ZslRouterData<T> {
pub amount: String,
pub router_data: T,
}
impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for ZslRouterData<T> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(currency_unit, currency, txn_amount, item): (&api::CurrencyUnit, enums::Currency, i64, T),
) -> Result<Self, Self::Error> {
let amount = get_amount_as_string(currency_unit, txn_amount, currency)?;
Ok(Self {
amount,
router_data: item,
})
}
}
pub struct ZslAuthType {
pub(super) api_key: Secret<String>,
pub(super) merchant_id: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for ZslAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
api_key: api_key.to_owned(),
merchant_id: key1.clone(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ZslPaymentsRequest {
process_type: ProcessType,
process_code: ProcessCode,
txn_amt: String,
ccy: api_models::enums::Currency,
mer_ref: String,
mer_txn_date: String,
mer_id: Secret<String>,
lang: String,
success_url: String,
failure_url: String,
success_s2s_url: String,
failure_s2s_url: String,
enctype: EncodingType,
signature: Secret<String>,
country: api_models::enums::CountryAlpha2,
verno: String,
service_code: ServiceCode,
cust_tag: String,
#[serde(flatten)]
payment_method: ZslPaymentMethods,
name: Option<Secret<String>>,
family_name: Option<Secret<String>>,
tel_phone: Option<Secret<String>>,
email: Option<Email>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ZslPaymentMethods {
LocalBankTransfer(LocalBankTransaferRequest),
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LocalBankTransaferRequest {
bank_code: Option<String>,
pay_method: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ProcessType {
#[serde(rename = "0200")]
PaymentRequest,
#[serde(rename = "0208")]
PaymentResponse,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ProcessCode {
#[serde(rename = "200002")]
API,
#[serde(rename = "200003")]
CallBack,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum EncodingType {
#[serde(rename = "1")]
MD5,
#[serde(rename = "2")]
Sha1,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum ServiceCode {
MPG,
}
impl TryFrom<&ZslRouterData<&types::PaymentsAuthorizeRouterData>> for ZslPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &ZslRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let payment_method = match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::BankTransfer(bank_transfer_data) => match *bank_transfer_data {
BankTransferData::LocalBankTransfer { bank_code } => Ok(
ZslPaymentMethods::LocalBankTransfer(LocalBankTransaferRequest {
bank_code,
pay_method: None,
}),
),
BankTransferData::AchBankTransfer { .. }
| BankTransferData::SepaBankTransfer { .. }
| BankTransferData::BacsBankTransfer { .. }
| BankTransferData::MultibancoBankTransfer { .. }
| BankTransferData::PermataBankTransfer { .. }
| BankTransferData::BcaBankTransfer { .. }
| BankTransferData::BniVaBankTransfer { .. }
| BankTransferData::BriVaBankTransfer { .. }
| BankTransferData::CimbVaBankTransfer { .. }
| BankTransferData::DanamonVaBankTransfer { .. }
| BankTransferData::MandiriVaBankTransfer { .. }
| BankTransferData::Pix { .. }
| BankTransferData::Pse {}
| BankTransferData::InstantBankTransferFinland {}
| BankTransferData::InstantBankTransferPoland {}
| BankTransferData::IndonesianBankTransfer { .. }
| BankTransferData::InstantBankTransfer {} => {
Err(errors::ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message(
item.router_data.connector.as_str(),
),
))
}
},
PaymentMethodData::Card(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Wallet(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_)
| PaymentMethodData::OpenBanking(_) => Err(errors::ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message(item.router_data.connector.as_str()),
)),
}?;
let auth_type = ZslAuthType::try_from(&item.router_data.connector_auth_type)?;
let key: Secret<String> = auth_type.api_key;
let mer_id = auth_type.merchant_id;
let mer_txn_date =
date_time::format_date(date_time::now(), date_time::DateFormat::YYYYMMDDHHmmss)
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
let txn_amt = item.amount.clone();
let ccy = item.router_data.request.currency;
let mer_ref = item.router_data.connector_request_reference_id.clone();
let signature = calculate_signature(
EncodingType::MD5,
ZslSignatureType::RequestSignature {
txn_amt: txn_amt.clone(),
ccy: ccy.to_string(),
mer_ref: mer_ref.clone(),
mer_id: mer_id.clone().expose(),
mer_txn_date: mer_txn_date.clone(),
key: key.expose(),
},
)?;
let tel_phone = item.router_data.get_optional_billing_phone_number();
let email = item.router_data.get_optional_billing_email();
let name = item.router_data.get_optional_billing_first_name();
let family_name = item.router_data.get_optional_billing_last_name();
let router_url = item.router_data.request.get_router_return_url()?;
let webhook_url = item.router_data.request.get_webhook_url()?;
let billing_country = item.router_data.get_billing_country()?;
let lang = item
.router_data
.request
.browser_info
.as_ref()
.and_then(|browser_data| {
browser_data.language.as_ref().map(|language| {
language
.split_once('-')
.map_or(language.to_uppercase(), |(lang, _)| lang.to_uppercase())
})
})
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "browser_info.language",
})?;
let cust_tag = item
.router_data
.customer_id
.clone()
.and_then(|customer_id| {
let cust_id = customer_id.get_string_repr().replace(['_', '-'], "");
let id_len = cust_id.len();
if id_len > 10 {
cust_id.get(id_len - 10..id_len).map(|id| id.to_string())
} else {
Some(cust_id)
}
})
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "customer_id",
})?;
Ok(Self {
process_type: ProcessType::PaymentRequest,
process_code: ProcessCode::API,
txn_amt,
ccy,
mer_ref,
mer_txn_date,
mer_id,
lang,
success_url: router_url.clone(),
failure_url: router_url.clone(),
success_s2s_url: webhook_url.clone(),
failure_s2s_url: webhook_url.clone(),
enctype: EncodingType::MD5,
signature,
verno: zsl_version::VERSION_1.to_owned(),
service_code: ServiceCode::MPG,
country: billing_country,
payment_method,
name,
family_name,
tel_phone,
email,
cust_tag,
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ZslPaymentsResponse {
process_type: ProcessType,
process_code: ProcessCode,
status: String,
mer_ref: String,
mer_id: String,
enctype: EncodingType,
txn_url: String,
signature: Secret<String>,
}
impl<F, T> TryFrom<ResponseRouterData<F, ZslPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, ZslPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
if item.response.status.eq("0") && !item.response.txn_url.is_empty() {
let auth_type = ZslAuthType::try_from(&item.data.connector_auth_type)?;
let key: Secret<String> = auth_type.api_key;
let mer_id = auth_type.merchant_id;
let calculated_signature = calculate_signature(
item.response.enctype,
ZslSignatureType::ResponseSignature {
status: item.response.status.clone(),
txn_url: item.response.txn_url.clone(),
mer_ref: item.response.mer_ref.clone(),
mer_id: mer_id.clone().expose(),
key: key.expose(),
},
)?;
if calculated_signature.clone().eq(&item.response.signature) {
let decoded_redirect_url_bytes: Vec<u8> = base64::engine::general_purpose::STANDARD
.decode(item.response.txn_url.clone())
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
let redirect_url = String::from_utf8(decoded_redirect_url_bytes)
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
Ok(Self {
status: enums::AttemptStatus::AuthenticationPending, // Redirect is always expected after success response
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(Some(RedirectForm::Form {
endpoint: redirect_url,
method: Method::Get,
form_fields: HashMap::new(),
})),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.mer_ref.clone()),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
} else {
// When the signature check fails
Ok(Self {
status: enums::AttemptStatus::Failure,
response: Err(ErrorResponse {
code: NO_ERROR_CODE.to_string(),
message: auth_error::INVALID_SIGNATURE.to_string(),
reason: Some(auth_error::INVALID_SIGNATURE.to_string()),
status_code: item.http_code,
attempt_status: Some(enums::AttemptStatus::Failure),
connector_transaction_id: Some(item.response.mer_ref.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
})
}
} else {
let error_reason =
ZslResponseStatus::try_from(item.response.status.clone())?.to_string();
Ok(Self {
status: enums::AttemptStatus::Failure,
response: Err(ErrorResponse {
code: item.response.status.clone(),
message: error_reason.clone(),
reason: Some(error_reason.clone()),
status_code: item.http_code,
attempt_status: Some(enums::AttemptStatus::Failure),
connector_transaction_id: Some(item.response.mer_ref.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
})
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ZslWebhookResponse {
pub process_type: ProcessType,
pub process_code: ProcessCode,
pub status: String,
pub txn_id: String,
pub txn_date: String,
pub paid_ccy: api_models::enums::Currency,
pub paid_amt: String,
pub consr_paid_ccy: Option<api_models::enums::Currency>,
pub consr_paid_amt: String,
pub service_fee_ccy: Option<api_models::enums::Currency>,
pub service_fee: Option<String>,
pub txn_amt: String,
pub ccy: String,
pub mer_ref: String,
pub mer_txn_date: String,
pub mer_id: String,
pub enctype: EncodingType,
pub signature: Secret<String>,
}
pub(crate) fn get_status(status: String) -> api_models::webhooks::IncomingWebhookEvent {
match status.as_str() {
//any response with status != 0 are a failed deposit transaction
"0" => api_models::webhooks::IncomingWebhookEvent::PaymentIntentSuccess,
_ => api_models::webhooks::IncomingWebhookEvent::PaymentIntentFailure,
}
}
impl<F> TryFrom<ResponseRouterData<F, ZslWebhookResponse, PaymentsSyncData, PaymentsResponseData>>
for RouterData<F, PaymentsSyncData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, ZslWebhookResponse, PaymentsSyncData, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let paid_amount = item
.response
.consr_paid_amt
.parse::<i64>()
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
if item.response.status == "0" {
Ok(Self {
status: enums::AttemptStatus::Charged,
amount_captured: Some(paid_amount),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.txn_id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.mer_ref.clone()),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
} else {
let error_reason =
ZslResponseStatus::try_from(item.response.status.clone())?.to_string();
Ok(Self {
status: enums::AttemptStatus::Failure,
response: Err(ErrorResponse {
code: item.response.status.clone(),
message: error_reason.clone(),
reason: Some(error_reason.clone()),
status_code: item.http_code,
attempt_status: Some(enums::AttemptStatus::Failure),
connector_transaction_id: Some(item.response.mer_ref.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
})
}
}
}
impl TryFrom<String> for ZslResponseStatus {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(status: String) -> Result<Self, Self::Error> {
match status.as_str() {
"0" => Ok(Self::Normal),
"1000" => Ok(Self::InternalError),
"1001" => Ok(Self::BreakDownMessageError),
"1002" => Ok(Self::FormatError),
"1004" => Ok(Self::InvalidTransaction),
"1005" => Ok(Self::TransactionCountryNotFound),
"1006" => Ok(Self::MerchantIdNotFound),
"1007" => Ok(Self::AccountDisabled),
"1008" => Ok(Self::DuplicateMerchantReference),
"1009" => Ok(Self::InvalidPayAmount),
"1010" => Ok(Self::PayAmountNotFound),
"1011" => Ok(Self::InvalidCurrencyCode),
"1012" => Ok(Self::CurrencyCodeNotFound),
"1013" => Ok(Self::ReferenceNotFound),
"1014" => Ok(Self::TransmissionTimeNotFound),
"1015" => Ok(Self::PayMethodNotFound),
"1016" => Ok(Self::BankCodeNotFound),
"1017" => Ok(Self::InvalidShowPayPage),
"1018" => Ok(Self::ShowPayPageNotFound),
"1019" => Ok(Self::SuccessUrlNotFound),
"1020" => Ok(Self::SuccessCallbackUrlNotFound),
"1021" => Ok(Self::FailUrlNotFound),
"1022" => Ok(Self::FailCallbackUrlNotFound),
"1023" => Ok(Self::MacNotFound),
"1025" => Ok(Self::OriginalTransactionNotFound),
"1026" => Ok(Self::DeblockDataError),
"1028" => Ok(Self::PspAckNotYetReturn),
"1029" => Ok(Self::BankBranchNameNotFound),
"1030" => Ok(Self::BankAccountIDNotFound),
"1031" => Ok(Self::BankAccountNameNotFound),
"1032" => Ok(Self::IdentityIDNotFound),
"1033" => Ok(Self::ErrorConnectingToPsp),
"1034" => Ok(Self::CountryPspNotAvailable),
"1035" => Ok(Self::UnsupportedPayAmount),
"1036" => Ok(Self::RecordMismatch),
"1037" => Ok(Self::NoRecord),
"1038" => Ok(Self::PspError),
"1039" => Ok(Self::UnsupportedEncryptionType),
"1040" => Ok(Self::ExceedTransactionLimitCount),
"1041" => Ok(Self::ExceedTransactionLimitAmount),
"1042" => Ok(Self::ExceedTransactionAccountLimitCount),
"1043" => Ok(Self::ExceedTransactionAccountLimitAmount),
"1044" => Ok(Self::ExchangeRateError),
"1045" => Ok(Self::InvalidEncoding),
"1046" => Ok(Self::CustomerNameNotFound),
"1047" => Ok(Self::CustomerFamilyNameNotFound),
"1048" => Ok(Self::CustomerTelPhoneNotFound),
"1049" => Ok(Self::InsufficientFund),
"1050" => Ok(Self::ServiceCodeIsMissing),
"1051" => Ok(Self::CurrencyIdNotMatch),
"1052" => Ok(Self::NoPendingRecord),
"1053" => Ok(Self::NoLoadBalancerRuleDefineForTransaction),
"1054" => Ok(Self::NoPaymentProviderAvailable),
"1055" => Ok(Self::UnsupportedPayMethod),
"1056" => Ok(Self::PendingTransaction),
"1057" => Ok(Self::OtherError1059),
"1058" => Ok(Self::OtherError1058),
"1059" => Ok(Self::OtherError1059),
"1084" => Ok(Self::InvalidRequestId),
"5043" => Ok(Self::BeneficiaryBankAccountIsNotAvailable),
"5053" => Ok(Self::BaidNotFound),
"5057" => Ok(Self::InvalidBaid),
"5059" => Ok(Self::InvalidBaidStatus),
"5107" => Ok(Self::AutoUploadBankDisabled),
"5108" => Ok(Self::InvalidNature),
"5109" => Ok(Self::SmsCreateDateNotFound),
"5110" => Ok(Self::InvalidSmsCreateDate),
"5111" => Ok(Self::RecordNotFound),
"5112" => Ok(Self::InsufficientBaidAvailableBalance),
"5113" => Ok(Self::ExceedTxnAmountLimit),
"5114" => Ok(Self::BaidBalanceNotFound),
"5115" => Ok(Self::AutoUploadIndicatorNotFound),
"5116" => Ok(Self::InvalidBankAcctStatus),
"5117" => Ok(Self::InvalidAutoUploadIndicator),
"5118" => Ok(Self::InvalidPidStatus),
"5119" => Ok(Self::InvalidProviderStatus),
"5120" => Ok(Self::InvalidBankAccountSystemSwitchEnabled),
"5121" => Ok(Self::AutoUploadProviderDisabled),
"5122" => Ok(Self::AutoUploadBankNotFound),
"5123" => Ok(Self::AutoUploadBankAcctNotFound),
"5124" => Ok(Self::AutoUploadProviderNotFound),
"5125" => Ok(Self::UnsupportedBankCode),
"5126" => Ok(Self::BalanceOverrideIndicatorNotFound),
"5127" => Ok(Self::InvalidBalanceOverrideIndicator),
"10000" => Ok(Self::VernoInvalid),
"10001" => Ok(Self::ServiceCodeInvalid),
"10002" => Ok(Self::PspResponseSignatureIsNotValid),
"10003" => Ok(Self::ProcessTypeNotFound),
"10004" => Ok(Self::ProcessCodeNotFound),
"10005" => Ok(Self::EnctypeNotFound),
"10006" => Ok(Self::VernoNotFound),
"10007" => Ok(Self::DepositBankNotFound),
"10008" => Ok(Self::DepositFlowNotFound),
"10009" => Ok(Self::CustDepositDateNotFound),
"10010" => Ok(Self::CustTagNotFound),
"10011" => Ok(Self::CountryValueInvalid),
"10012" => Ok(Self::CurrencyCodeValueInvalid),
"10013" => Ok(Self::MerTxnDateInvalid),
"10014" => Ok(Self::CustDepositDateInvalid),
"10015" => Ok(Self::TxnAmtInvalid),
"10016" => Ok(Self::SuccessCallbackUrlInvalid),
"10017" => Ok(Self::DepositFlowInvalid),
"10018" => Ok(Self::ProcessTypeInvalid),
"10019" => Ok(Self::ProcessCodeInvalid),
"10020" => Ok(Self::UnsupportedMerRefLength),
"10021" => Ok(Self::DepositBankLengthOverLimit),
"10022" => Ok(Self::CustTagLengthOverLimit),
"10023" => Ok(Self::SignatureLengthOverLimit),
"10024" => Ok(Self::RequestContainInvalidTag),
"10025" => Ok(Self::RequestSignatureNotMatch),
"10026" => Ok(Self::InvalidCustomer),
"10027" => Ok(Self::SchemeNotFound),
"10028" => Ok(Self::PspResponseFieldsMissing),
"10029" => Ok(Self::PspResponseMerRefNotMatchWithRequestMerRef),
"10030" => Ok(Self::PspResponseMerIdNotMatchWithRequestMerId),
"10031" => Ok(Self::UpdateDepositFailAfterResponse),
"10032" => Ok(Self::UpdateUsedLimitTransactionCountFailAfterSuccessResponse),
"10033" => Ok(Self::UpdateCustomerLastDepositRecordAfterSuccessResponse),
"10034" => Ok(Self::CreateDepositFail),
"10035" => Ok(Self::CreateDepositMsgFail),
"10036" => Ok(Self::UpdateStatusSubStatusFail),
"10037" => Ok(Self::AddDepositRecordToSchemeAccount),
"10038" => Ok(Self::EmptyResponse),
"10039" => Ok(Self::AubConfirmErrorFromPh),
"10040" => Ok(Self::ProviderEmailAddressNotFound),
"10041" => Ok(Self::AubConnectionTimeout),
"10042" => Ok(Self::AubConnectionIssue),
"10043" => Ok(Self::AubMsgTypeMissing),
"10044" => Ok(Self::AubMsgCodeMissing),
"10045" => Ok(Self::AubVersionMissing),
"10046" => Ok(Self::AubEncTypeMissing),
"10047" => Ok(Self::AubSignMissing),
"10048" => Ok(Self::AubInfoMissing),
"10049" => Ok(Self::AubErrorCodeMissing),
"10050" => Ok(Self::AubMsgTypeInvalid),
"10051" => Ok(Self::AubMsgCodeInvalid),
"10052" => Ok(Self::AubBaidMissing),
"10053" => Ok(Self::AubResponseSignNotMatch),
"10054" => Ok(Self::SmsConnectionTimeout),
"10055" => Ok(Self::SmsConnectionIssue),
"10056" => Ok(Self::SmsConfirmErrorFromPh),
"10057" => Ok(Self::SmsMsgTypeMissing),
"10058" => Ok(Self::SmsMsgCodeMissing),
"10059" => Ok(Self::SmsVersionMissing),
"10060" => Ok(Self::SmsEncTypeMissing),
"10061" => Ok(Self::SmsSignMissing),
"10062" => Ok(Self::SmsInfoMissing),
"10063" => Ok(Self::SmsErrorCodeMissing),
"10064" => Ok(Self::SmsMsgTypeInvalid),
"10065" => Ok(Self::SmsMsgCodeInvalid),
"10066" => Ok(Self::SmsResponseSignNotMatch),
"10067" => Ok(Self::SmsRequestReachMaximumLimit),
"10068" => Ok(Self::SyncConnectionTimeout),
"10069" => Ok(Self::SyncConnectionIssue),
"10070" => Ok(Self::SyncConfirmErrorFromPh),
"10071" => Ok(Self::SyncMsgTypeMissing),
"10072" => Ok(Self::SyncMsgCodeMissing),
"10073" => Ok(Self::SyncVersionMissing),
"10074" => Ok(Self::SyncEncTypeMissing),
"10075" => Ok(Self::SyncSignMissing),
"10076" => Ok(Self::SyncInfoMissing),
"10077" => Ok(Self::SyncErrorCodeMissing),
"10078" => Ok(Self::SyncMsgTypeInvalid),
"10079" => Ok(Self::SyncMsgCodeInvalid),
"10080" => Ok(Self::SyncResponseSignNotMatch),
"10081" => Ok(Self::AccountExpired),
"10082" => Ok(Self::ExceedMaxMinAmount),
"10083" => Ok(Self::WholeNumberAmountLessThanOne),
"10084" => Ok(Self::AddDepositRecordToSchemeChannel),
"10085" => Ok(Self::UpdateUtilizedAmountFailAfterSuccessResponse),
"10086" => Ok(Self::PidResponseInvalidFormat),
"10087" => Ok(Self::PspNameNotFound),
"10088" => Ok(Self::LangIsMissing),
"10089" => Ok(Self::FailureCallbackUrlInvalid),
"10090" => Ok(Self::SuccessRedirectUrlInvalid),
"10091" => Ok(Self::FailureRedirectUrlInvalid),
"10092" => Ok(Self::LangValueInvalid),
"10093" => Ok(Self::OnlineDepositSessionTimeout),
"10094" => Ok(Self::AccessPaymentPageRouteFieldMissing),
"10095" => Ok(Self::AmountNotMatch),
"10096" => Ok(Self::PidCallbackFieldsMissing),
"10097" => Ok(Self::TokenNotMatch),
"10098" => Ok(Self::OperationDuplicated),
"10099" => Ok(Self::PayPageDomainNotAvailable),
"10100" => Ok(Self::PayPageConfirmSignatureNotMatch),
"10101" => Ok(Self::PaymentPageConfirmationFieldMissing),
"10102" => Ok(Self::MultipleCallbackFromPsp),
"10103" => Ok(Self::PidNotAvailable),
"10104" => Ok(Self::PidDepositUrlNotValidOrEmp),
"10105" => Ok(Self::PspSelfRedirectTagNotValid),
"20000" => Ok(Self::InternalError20000),
"20001" => Ok(Self::DepositTimeout),
_ => Err(errors::ConnectorError::ResponseHandlingFailed.into()),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, strum::Display)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum ZslResponseStatus {
Normal,
InternalError,
BreakDownMessageError,
FormatError,
InvalidTransaction,
TransactionCountryNotFound,
MerchantIdNotFound,
AccountDisabled,
DuplicateMerchantReference,
InvalidPayAmount,
PayAmountNotFound,
InvalidCurrencyCode,
CurrencyCodeNotFound,
ReferenceNotFound,
TransmissionTimeNotFound,
PayMethodNotFound,
BankCodeNotFound,
InvalidShowPayPage,
ShowPayPageNotFound,
SuccessUrlNotFound,
SuccessCallbackUrlNotFound,
FailUrlNotFound,
FailCallbackUrlNotFound,
MacNotFound,
OriginalTransactionNotFound,
DeblockDataError,
PspAckNotYetReturn,
BankBranchNameNotFound,
BankAccountIDNotFound,
BankAccountNameNotFound,
IdentityIDNotFound,
ErrorConnectingToPsp,
CountryPspNotAvailable,
UnsupportedPayAmount,
RecordMismatch,
NoRecord,
PspError,
UnsupportedEncryptionType,
ExceedTransactionLimitCount,
ExceedTransactionLimitAmount,
ExceedTransactionAccountLimitCount,
ExceedTransactionAccountLimitAmount,
ExchangeRateError,
InvalidEncoding,
CustomerNameNotFound,
CustomerFamilyNameNotFound,
CustomerTelPhoneNotFound,
InsufficientFund,
ServiceCodeIsMissing,
CurrencyIdNotMatch,
NoPendingRecord,
NoLoadBalancerRuleDefineForTransaction,
NoPaymentProviderAvailable,
UnsupportedPayMethod,
PendingTransaction,
OtherError1059,
OtherError1058,
InvalidRequestId,
BeneficiaryBankAccountIsNotAvailable,
BaidNotFound,
InvalidBaid,
InvalidBaidStatus,
AutoUploadBankDisabled,
InvalidNature,
SmsCreateDateNotFound,
InvalidSmsCreateDate,
RecordNotFound,
InsufficientBaidAvailableBalance,
ExceedTxnAmountLimit,
BaidBalanceNotFound,
AutoUploadIndicatorNotFound,
InvalidBankAcctStatus,
InvalidAutoUploadIndicator,
InvalidPidStatus,
InvalidProviderStatus,
InvalidBankAccountSystemSwitchEnabled,
AutoUploadProviderDisabled,
AutoUploadBankNotFound,
AutoUploadBankAcctNotFound,
AutoUploadProviderNotFound,
UnsupportedBankCode,
BalanceOverrideIndicatorNotFound,
InvalidBalanceOverrideIndicator,
VernoInvalid,
ServiceCodeInvalid,
PspResponseSignatureIsNotValid,
ProcessTypeNotFound,
ProcessCodeNotFound,
EnctypeNotFound,
VernoNotFound,
DepositBankNotFound,
DepositFlowNotFound,
CustDepositDateNotFound,
CustTagNotFound,
CountryValueInvalid,
CurrencyCodeValueInvalid,
MerTxnDateInvalid,
CustDepositDateInvalid,
TxnAmtInvalid,
SuccessCallbackUrlInvalid,
DepositFlowInvalid,
ProcessTypeInvalid,
ProcessCodeInvalid,
UnsupportedMerRefLength,
DepositBankLengthOverLimit,
CustTagLengthOverLimit,
SignatureLengthOverLimit,
RequestContainInvalidTag,
RequestSignatureNotMatch,
InvalidCustomer,
SchemeNotFound,
PspResponseFieldsMissing,
PspResponseMerRefNotMatchWithRequestMerRef,
PspResponseMerIdNotMatchWithRequestMerId,
UpdateDepositFailAfterResponse,
UpdateUsedLimitTransactionCountFailAfterSuccessResponse,
UpdateCustomerLastDepositRecordAfterSuccessResponse,
CreateDepositFail,
CreateDepositMsgFail,
UpdateStatusSubStatusFail,
AddDepositRecordToSchemeAccount,
EmptyResponse,
| 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/payone/transformers.rs | crates/hyperswitch_connectors/src/connectors/payone/transformers.rs | #[cfg(feature = "payouts")]
use api_models::payouts::PayoutMethodData;
#[cfg(feature = "payouts")]
use cards::CardNumber;
#[cfg(feature = "payouts")]
use common_enums::{PayoutStatus, PayoutType};
use common_utils::types::MinorUnit;
#[cfg(feature = "payouts")]
use common_utils::{ext_traits::OptionExt, transformers::ForeignFrom};
#[cfg(feature = "payouts")]
use error_stack::ResultExt;
use hyperswitch_domain_models::router_data::ConnectorAuthType;
#[cfg(feature = "payouts")]
use hyperswitch_domain_models::{
router_flow_types::PoFulfill,
types::{PayoutsResponseData, PayoutsRouterData},
};
use hyperswitch_interfaces::errors::ConnectorError;
use masking::Secret;
use serde::{Deserialize, Serialize};
#[cfg(feature = "payouts")]
use crate::utils::CardData as _;
use crate::utils::{
get_unimplemented_payment_method_error_message, CardIssuer, ErrorCodeAndMessage,
};
#[cfg(feature = "payouts")]
use crate::{
types::PayoutsResponseRouterData,
utils::{PayoutsData, RouterData},
};
#[cfg(feature = "payouts")]
type Error = error_stack::Report<ConnectorError>;
use serde_repr::{Deserialize_repr, Serialize_repr};
pub struct PayoneRouterData<T> {
pub amount: MinorUnit,
pub router_data: T,
}
impl<T> From<(MinorUnit, T)> for PayoneRouterData<T> {
fn from((amount, item): (MinorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct ErrorResponse {
pub errors: Option<Vec<SubError>>,
pub error_id: Option<i32>,
}
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct SubError {
pub code: String,
pub message: String,
pub http_status_code: u16,
}
impl From<SubError> for ErrorCodeAndMessage {
fn from(error: SubError) -> Self {
Self {
error_code: error.code.to_string(),
error_message: error.code.to_string(),
}
}
}
// Auth Struct
pub struct PayoneAuthType {
pub(super) api_key: Secret<String>,
pub merchant_account: Secret<String>,
pub api_secret: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for PayoneAuthType {
type Error = error_stack::Report<ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} => Ok(Self {
api_key: api_key.to_owned(),
merchant_account: key1.to_owned(),
api_secret: api_secret.to_owned(),
}),
_ => Err(ConnectorError::FailedToObtainAuthType)?,
}
}
}
#[cfg(feature = "payouts")]
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PayonePayoutFulfillRequest {
amount_of_money: AmountOfMoney,
card_payout_method_specific_input: CardPayoutMethodSpecificInput,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AmountOfMoney {
amount: MinorUnit,
currency_code: String,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CardPayoutMethodSpecificInput {
card: Card,
payment_product_id: PaymentProductId,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Card {
card_holder_name: Secret<String>,
card_number: CardNumber,
expiry_date: Secret<String>,
}
#[cfg(feature = "payouts")]
impl TryFrom<PayoneRouterData<&PayoutsRouterData<PoFulfill>>> for PayonePayoutFulfillRequest {
type Error = Error;
fn try_from(
item: PayoneRouterData<&PayoutsRouterData<PoFulfill>>,
) -> Result<Self, Self::Error> {
let request = item.router_data.request.to_owned();
let payout_type = request.get_payout_type()?;
match payout_type {
PayoutType::Card => {
let amount_of_money: AmountOfMoney = AmountOfMoney {
amount: item.amount,
currency_code: item.router_data.request.destination_currency.to_string(),
};
let card_payout_method_specific_input =
match item.router_data.get_payout_method_data()? {
PayoutMethodData::Card(card_data) => CardPayoutMethodSpecificInput {
card: Card {
card_number: card_data.card_number.clone(),
card_holder_name: card_data
.card_holder_name
.clone()
.get_required_value("card_holder_name")
.change_context(ConnectorError::MissingRequiredField {
field_name: "payout_method_data.card.holder_name",
})?,
expiry_date: card_data
.get_card_expiry_month_year_2_digit_with_delimiter(
"".to_string(),
)?,
},
payment_product_id: PaymentProductId::try_from(
card_data.get_card_issuer()?,
)?,
},
PayoutMethodData::Bank(_)
| PayoutMethodData::Wallet(_)
| PayoutMethodData::BankRedirect(_)
| PayoutMethodData::Passthrough(_) => Err(ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("Payone"),
))?,
};
Ok(Self {
amount_of_money,
card_payout_method_specific_input,
})
}
PayoutType::Wallet | PayoutType::Bank | PayoutType::BankRedirect => {
Err(ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("Payone"),
))?
}
}
}
}
#[derive(Clone, Debug, Eq, Hash, PartialEq, Serialize_repr, Deserialize_repr)]
#[repr(i32)]
pub enum PaymentProductId {
Visa = 1,
MasterCard = 3,
}
impl TryFrom<CardIssuer> for PaymentProductId {
type Error = error_stack::Report<ConnectorError>;
fn try_from(issuer: CardIssuer) -> Result<Self, Self::Error> {
match issuer {
CardIssuer::Master => Ok(Self::MasterCard),
CardIssuer::Visa => Ok(Self::Visa),
CardIssuer::AmericanExpress
| CardIssuer::Maestro
| CardIssuer::Discover
| CardIssuer::DinersClub
| CardIssuer::JCB
| CardIssuer::CarteBlanche
| CardIssuer::UnionPay
| CardIssuer::CartesBancaires => Err(ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("payone"),
)
.into()),
}
}
}
#[cfg(feature = "payouts")]
#[derive(Debug, Default, Clone, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PayoneStatus {
Created,
#[default]
PendingApproval,
Rejected,
PayoutRequested,
AccountCredited,
RejectedCredit,
Cancelled,
Reversed,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PayonePayoutFulfillResponse {
id: String,
payout_output: PayoutOutput,
status: PayoneStatus,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PayoutOutput {
amount_of_money: AmountOfMoney,
}
#[cfg(feature = "payouts")]
impl ForeignFrom<PayoneStatus> for PayoutStatus {
fn foreign_from(payone_status: PayoneStatus) -> Self {
match payone_status {
PayoneStatus::AccountCredited => Self::Success,
PayoneStatus::RejectedCredit | PayoneStatus::Rejected => Self::Failed,
PayoneStatus::Cancelled | PayoneStatus::Reversed => Self::Cancelled,
PayoneStatus::Created
| PayoneStatus::PendingApproval
| PayoneStatus::PayoutRequested => Self::Pending,
}
}
}
#[cfg(feature = "payouts")]
impl<F> TryFrom<PayoutsResponseRouterData<F, PayonePayoutFulfillResponse>>
for PayoutsRouterData<F>
{
type Error = Error;
fn try_from(
item: PayoutsResponseRouterData<F, PayonePayoutFulfillResponse>,
) -> Result<Self, Self::Error> {
let response: PayonePayoutFulfillResponse = item.response;
Ok(Self {
response: Ok(PayoutsResponseData {
status: Some(PayoutStatus::foreign_from(response.status)),
connector_payout_id: Some(response.id),
payout_eligible: None,
should_add_next_step_to_process_tracker: false,
error_code: None,
error_message: None,
payout_connector_metadata: None,
}),
..item.data
})
}
}
| 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/globepay/transformers.rs | crates/hyperswitch_connectors/src/connectors/globepay/transformers.rs | use common_enums::enums;
use common_utils::{ext_traits::Encode, types::MinorUnit};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{PaymentMethodData, WalletData},
router_data::{ConnectorAuthType, ErrorResponse, RouterData},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RefundsResponseData},
types::{self, RefundsRouterData},
};
use hyperswitch_interfaces::{consts, errors};
use masking::Secret;
use serde::{Deserialize, Serialize};
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{get_unimplemented_payment_method_error_message, RouterData as _},
};
type Error = error_stack::Report<errors::ConnectorError>;
#[derive(Debug, Serialize)]
pub struct GlobepayRouterData<T> {
pub amount: MinorUnit,
pub router_data: T,
}
impl<T> From<(MinorUnit, T)> for GlobepayRouterData<T> {
fn from((amount, router_data): (MinorUnit, T)) -> Self {
Self {
amount,
router_data,
}
}
}
#[derive(Debug, Serialize)]
pub struct GlobepayPaymentsRequest {
price: MinorUnit,
description: String,
currency: enums::Currency,
channel: GlobepayChannel,
}
#[derive(Debug, Serialize)]
pub enum GlobepayChannel {
Alipay,
Wechat,
}
impl TryFrom<&GlobepayRouterData<&types::PaymentsAuthorizeRouterData>> for GlobepayPaymentsRequest {
type Error = Error;
fn try_from(
item_data: &GlobepayRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let item = item_data.router_data.clone();
let channel: GlobepayChannel = match &item.request.payment_method_data {
PaymentMethodData::Wallet(ref wallet_data) => match wallet_data {
WalletData::AliPayQr(_) => GlobepayChannel::Alipay,
WalletData::WeChatPayQr(_) => GlobepayChannel::Wechat,
WalletData::AliPayRedirect(_)
| WalletData::AliPayHkRedirect(_)
| WalletData::AmazonPay(_)
| WalletData::AmazonPayRedirect(_)
| WalletData::Paysera(_)
| WalletData::Skrill(_)
| WalletData::BluecodeRedirect {}
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
| WalletData::GcashRedirect(_)
| WalletData::ApplePay(_)
| WalletData::ApplePayRedirect(_)
| WalletData::ApplePayThirdPartySdk(_)
| WalletData::DanaRedirect {}
| WalletData::GooglePay(_)
| WalletData::GooglePayRedirect(_)
| WalletData::GooglePayThirdPartySdk(_)
| WalletData::MbWayRedirect(_)
| WalletData::MobilePayRedirect(_)
| WalletData::PaypalRedirect(_)
| WalletData::PaypalSdk(_)
| WalletData::Paze(_)
| WalletData::SamsungPay(_)
| WalletData::TwintRedirect {}
| WalletData::VippsRedirect {}
| WalletData::TouchNGoRedirect(_)
| WalletData::WeChatPayRedirect(_)
| WalletData::CashappQr(_)
| WalletData::SwishQr(_)
| WalletData::Mifinity(_)
| WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("globepay"),
))?,
},
PaymentMethodData::Card(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("globepay"),
))?
}
};
let description = item.get_description()?;
Ok(Self {
price: item_data.amount,
description,
currency: item.request.currency,
channel,
})
}
}
pub struct GlobepayAuthType {
pub(super) partner_code: Secret<String>,
pub(super) credential_code: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for GlobepayAuthType {
type Error = Error;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
partner_code: api_key.to_owned(),
credential_code: key1.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum GlobepayPaymentStatus {
Success,
Exists,
}
impl From<GlobepayPaymentStatus> for enums::AttemptStatus {
fn from(item: GlobepayPaymentStatus) -> Self {
match item {
GlobepayPaymentStatus::Success => Self::AuthenticationPending, // this connector only have redirection flows so "Success" is mapped to authenticatoin pending ,ref = "https://pay.globepay.co/docs/en/#api-QRCode-NewQRCode"
GlobepayPaymentStatus::Exists => Self::Failure,
}
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct GlobepayConnectorMetadata {
image_data_url: url::Url,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct GlobepayPaymentsResponse {
result_code: Option<GlobepayPaymentStatus>,
order_id: Option<String>,
qrcode_img: Option<url::Url>,
return_code: GlobepayReturnCode, //Execution result
return_msg: Option<String>,
}
#[derive(Debug, Deserialize, PartialEq, strum::Display, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum GlobepayReturnCode {
Success,
OrderNotExist,
OrderMismatch,
Systemerror,
InvalidShortId,
SignTimeout,
InvalidSign,
ParamInvalid,
NotPermitted,
InvalidChannel,
DuplicateOrderId,
OrderNotPaid,
}
impl<F, T> TryFrom<ResponseRouterData<F, GlobepayPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = Error;
fn try_from(
item: ResponseRouterData<F, GlobepayPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
if item.response.return_code == GlobepayReturnCode::Success {
let globepay_metadata = GlobepayConnectorMetadata {
image_data_url: item
.response
.qrcode_img
.ok_or(errors::ConnectorError::ResponseHandlingFailed)?,
};
let connector_metadata = Some(globepay_metadata.encode_to_value())
.transpose()
.change_context(errors::ConnectorError::ResponseHandlingFailed)?;
let globepay_status = item
.response
.result_code
.ok_or(errors::ConnectorError::ResponseHandlingFailed)?;
Ok(Self {
status: enums::AttemptStatus::from(globepay_status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response
.order_id
.ok_or(errors::ConnectorError::ResponseHandlingFailed)?,
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
} else {
Ok(Self {
status: enums::AttemptStatus::Failure, //As this connector gives 200 in failed scenarios . if return_code is not success status is mapped to failure. ref = "https://pay.globepay.co/docs/en/#api-QRCode-NewQRCode"
response: Err(get_error_response(
item.response.return_code,
item.response.return_msg,
item.http_code,
)),
..item.data
})
}
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct GlobepaySyncResponse {
pub result_code: Option<GlobepayPaymentPsyncStatus>,
pub order_id: Option<String>,
pub return_code: GlobepayReturnCode,
pub return_msg: Option<String>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum GlobepayPaymentPsyncStatus {
Paying,
CreateFail,
Closed,
PayFail,
PaySuccess,
}
impl From<GlobepayPaymentPsyncStatus> for enums::AttemptStatus {
fn from(item: GlobepayPaymentPsyncStatus) -> Self {
match item {
GlobepayPaymentPsyncStatus::PaySuccess => Self::Charged,
GlobepayPaymentPsyncStatus::PayFail
| GlobepayPaymentPsyncStatus::CreateFail
| GlobepayPaymentPsyncStatus::Closed => Self::Failure,
GlobepayPaymentPsyncStatus::Paying => Self::AuthenticationPending,
}
}
}
impl<F, T> TryFrom<ResponseRouterData<F, GlobepaySyncResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = Error;
fn try_from(
item: ResponseRouterData<F, GlobepaySyncResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
if item.response.return_code == GlobepayReturnCode::Success {
let globepay_status = item
.response
.result_code
.ok_or(errors::ConnectorError::ResponseHandlingFailed)?;
let globepay_id = item
.response
.order_id
.ok_or(errors::ConnectorError::ResponseHandlingFailed)?;
Ok(Self {
status: enums::AttemptStatus::from(globepay_status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(globepay_id),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
} else {
Ok(Self {
status: enums::AttemptStatus::Failure, //As this connector gives 200 in failed scenarios . if return_code is not success status is mapped to failure. ref = "https://pay.globepay.co/docs/en/#api-QRCode-NewQRCode"
response: Err(get_error_response(
item.response.return_code,
item.response.return_msg,
item.http_code,
)),
..item.data
})
}
}
}
fn get_error_response(
return_code: GlobepayReturnCode,
return_msg: Option<String>,
status_code: u16,
) -> ErrorResponse {
ErrorResponse {
code: return_code.to_string(),
message: consts::NO_ERROR_MESSAGE.to_string(),
reason: return_msg,
status_code,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}
}
#[derive(Debug, Serialize)]
pub struct GlobepayRefundRequest {
pub fee: MinorUnit,
}
impl<F> TryFrom<&GlobepayRouterData<&RefundsRouterData<F>>> for GlobepayRefundRequest {
type Error = Error;
fn try_from(item: &GlobepayRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
Ok(Self { fee: item.amount })
}
}
#[derive(Debug, Deserialize, Serialize)]
pub enum GlobepayRefundStatus {
Waiting,
CreateFailed,
Failed,
Success,
Finished,
Change,
}
impl From<GlobepayRefundStatus> for enums::RefundStatus {
fn from(item: GlobepayRefundStatus) -> Self {
match item {
GlobepayRefundStatus::Finished => Self::Success, //FINISHED: Refund success(funds has already been returned to user's account)
GlobepayRefundStatus::Failed
| GlobepayRefundStatus::CreateFailed
| GlobepayRefundStatus::Change => Self::Failure, //CHANGE: Refund can not return to user's account. Manual operation is required
GlobepayRefundStatus::Waiting | GlobepayRefundStatus::Success => Self::Pending, // SUCCESS: Submission succeeded, but refund is not yet complete. Waiting = Submission succeeded, but refund is not yet complete.
}
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct GlobepayRefundResponse {
pub result_code: Option<GlobepayRefundStatus>,
pub refund_id: Option<String>,
pub return_code: GlobepayReturnCode,
pub return_msg: Option<String>,
}
impl<T> TryFrom<RefundsResponseRouterData<T, GlobepayRefundResponse>> for RefundsRouterData<T> {
type Error = Error;
fn try_from(
item: RefundsResponseRouterData<T, GlobepayRefundResponse>,
) -> Result<Self, Self::Error> {
if item.response.return_code == GlobepayReturnCode::Success {
let globepay_refund_id = item
.response
.refund_id
.ok_or(errors::ConnectorError::ResponseHandlingFailed)?;
let globepay_refund_status = item
.response
.result_code
.ok_or(errors::ConnectorError::ResponseHandlingFailed)?;
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: globepay_refund_id,
refund_status: enums::RefundStatus::from(globepay_refund_status),
}),
..item.data
})
} else {
Ok(Self {
response: Err(get_error_response(
item.response.return_code,
item.response.return_msg,
item.http_code,
)),
..item.data
})
}
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct GlobepayErrorResponse {
pub return_msg: String,
pub return_code: GlobepayReturnCode,
pub message: String,
}
| 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/worldpayvantiv/transformers.rs | crates/hyperswitch_connectors/src/connectors/worldpayvantiv/transformers.rs | use common_utils::{
ext_traits::Encode,
pii,
types::{MinorUnit, StringMajorUnit, StringMinorUnitForConnector},
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{
AdditionalPaymentMethodConnectorResponse, ConnectorAuthType, ConnectorResponseData,
ErrorResponse, RouterData,
},
router_flow_types::{
refunds::{Execute, RSync},
Dsync, Fetch, Retrieve, Upload,
},
router_request_types::{
DisputeSyncData, FetchDisputesRequestData, PaymentsAuthorizeData,
PaymentsCancelPostCaptureData, PaymentsSyncData, ResponseId, RetrieveFileRequestData,
SetupMandateRequestData, UploadFileRequestData,
},
router_response_types::{
DisputeSyncResponse, FetchDisputesResponse, MandateReference, PaymentsResponseData,
RefundsResponseData, RetrieveFileResponse, UploadFileResponse,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelPostCaptureRouterData, PaymentsCancelRouterData,
PaymentsCaptureRouterData, RefundsRouterData, SetupMandateRouterData,
},
};
use hyperswitch_interfaces::{consts, errors};
use masking::{ExposeInterface, PeekInterface, Secret};
use router_env::logger;
use serde::{Deserialize, Serialize};
use crate::{
types::{
AcceptDisputeRouterData, DisputeSyncRouterData, FetchDisputeRouterData,
PaymentsCancelResponseRouterData, PaymentsCaptureResponseRouterData,
RefundsResponseRouterData, ResponseRouterData, RetrieveFileRouterData,
SubmitEvidenceRouterData,
},
utils::{
self as connector_utils, CardData, PaymentsAuthorizeRequestData,
PaymentsSetupMandateRequestData, RouterData as UtilsRouterData,
},
};
pub mod worldpayvantiv_constants {
pub const WORLDPAYVANTIV_VERSION: &str = "12.23";
pub const XML_VERSION: &str = "1.0";
pub const XML_ENCODING: &str = "UTF-8";
pub const XMLNS: &str = "http://www.vantivcnp.com/schema";
pub const MAX_PAYMENT_REFERENCE_ID_LENGTH: usize = 28;
pub const XML_STANDALONE: &str = "yes";
pub const XML_CHARGEBACK: &str = "http://www.vantivcnp.com/chargebacks";
pub const MAC_FIELD_NUMBER: &str = "39";
pub const CUSTOMER_ID_MAX_LENGTH: usize = 50;
pub const CUSTOMER_REFERENCE_MAX_LENGTH: usize = 17;
}
pub struct WorldpayvantivRouterData<T> {
pub amount: MinorUnit,
pub router_data: T,
}
impl<T> From<(MinorUnit, T)> for WorldpayvantivRouterData<T> {
fn from((amount, item): (MinorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
pub struct WorldpayvantivAuthType {
pub(super) user: Secret<String>,
pub(super) password: Secret<String>,
pub(super) merchant_id: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for WorldpayvantivAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::SignatureKey {
api_key,
api_secret,
key1,
} => Ok(Self {
user: api_key.to_owned(),
password: api_secret.to_owned(),
merchant_id: key1.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Debug, strum::Display, Serialize, Deserialize, PartialEq, Clone, Copy)]
#[strum(serialize_all = "lowercase")]
pub enum OperationId {
Sale,
Auth,
Capture,
Void,
// VoidPostCapture
VoidPC,
Refund,
}
// Represents the payment metadata for Worldpay Vantiv.
// The `report_group` field is an Option<String> to account for cases where the report group might not be provided in the metadata.
#[derive(Debug, Default, Serialize, Deserialize, Clone)]
pub struct WorldpayvantivPaymentMetadata {
pub report_group: Option<String>,
pub fraud_filter_override: Option<bool>,
}
// Represents the merchant connector account metadata for Worldpay Vantiv
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct WorldpayvantivMetadataObject {
pub report_group: String,
pub merchant_config_currency: common_enums::Currency,
pub fraud_filter_override: Option<bool>,
}
impl TryFrom<&Option<pii::SecretSerdeValue>> for WorldpayvantivMetadataObject {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(meta_data: &Option<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)]
#[serde(rename = "cnpOnlineRequest", rename_all = "camelCase")]
pub struct CnpOnlineRequest {
#[serde(rename = "@version")]
pub version: String,
#[serde(rename = "@xmlns")]
pub xmlns: String,
#[serde(rename = "@merchantId")]
pub merchant_id: Secret<String>,
pub authentication: Authentication,
#[serde(skip_serializing_if = "Option::is_none")]
pub authorization: Option<Authorization>,
#[serde(skip_serializing_if = "Option::is_none")]
pub sale: Option<Sale>,
#[serde(skip_serializing_if = "Option::is_none")]
pub capture: Option<Capture>,
#[serde(skip_serializing_if = "Option::is_none")]
pub auth_reversal: Option<AuthReversal>,
#[serde(skip_serializing_if = "Option::is_none")]
pub void: Option<Void>,
#[serde(skip_serializing_if = "Option::is_none")]
pub credit: Option<RefundRequest>,
}
#[derive(Debug, Serialize)]
pub struct Authentication {
pub user: Secret<String>,
pub password: Secret<String>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Void {
#[serde(rename = "@id")]
pub id: String,
#[serde(rename = "@reportGroup")]
pub report_group: String,
pub cnp_txn_id: String,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthReversal {
#[serde(rename = "@id")]
pub id: String,
#[serde(rename = "@reportGroup")]
pub report_group: String,
pub cnp_txn_id: String,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Capture {
#[serde(rename = "@id")]
pub id: String,
#[serde(rename = "@reportGroup")]
pub report_group: String,
pub cnp_txn_id: String,
pub amount: MinorUnit,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct VantivAddressData {
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub address_line1: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub address_line2: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub address_line3: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub city: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub state: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub zip: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub email: Option<pii::Email>,
#[serde(skip_serializing_if = "Option::is_none")]
pub country: Option<common_enums::CountryAlpha2>,
#[serde(skip_serializing_if = "Option::is_none")]
pub phone: Option<Secret<String>>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum VantivProcessingType {
InitialCOF,
MerchantInitiatedCOF,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Authorization {
#[serde(rename = "@id")]
pub id: String,
#[serde(rename = "@reportGroup")]
pub report_group: String,
#[serde(rename = "@customerId", skip_serializing_if = "Option::is_none")]
pub customer_id: Option<String>,
pub order_id: String,
pub amount: MinorUnit,
pub order_source: OrderSource,
#[serde(skip_serializing_if = "Option::is_none")]
pub bill_to_address: Option<VantivAddressData>,
#[serde(skip_serializing_if = "Option::is_none")]
pub ship_to_address: Option<VantivAddressData>,
#[serde(skip_serializing_if = "Option::is_none")]
pub card: Option<WorldpayvantivCardData>,
#[serde(skip_serializing_if = "Option::is_none")]
pub token: Option<TokenizationData>,
#[serde(skip_serializing_if = "Option::is_none")]
pub enhanced_data: Option<EnhancedData>,
#[serde(skip_serializing_if = "Option::is_none")]
pub processing_type: Option<VantivProcessingType>,
#[serde(skip_serializing_if = "Option::is_none")]
pub original_network_transaction_id: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub allow_partial_auth: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub fraud_filter_override: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub cardholder_authentication: Option<CardholderAuthentication>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CardholderAuthentication {
authentication_value: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Sale {
#[serde(rename = "@id")]
pub id: String,
#[serde(rename = "@reportGroup")]
pub report_group: String,
#[serde(rename = "@customerId", skip_serializing_if = "Option::is_none")]
pub customer_id: Option<String>,
pub order_id: String,
pub amount: MinorUnit,
pub order_source: OrderSource,
#[serde(skip_serializing_if = "Option::is_none")]
pub bill_to_address: Option<VantivAddressData>,
#[serde(skip_serializing_if = "Option::is_none")]
pub ship_to_address: Option<VantivAddressData>,
#[serde(skip_serializing_if = "Option::is_none")]
pub card: Option<WorldpayvantivCardData>,
#[serde(skip_serializing_if = "Option::is_none")]
pub token: Option<TokenizationData>,
#[serde(skip_serializing_if = "Option::is_none")]
pub enhanced_data: Option<EnhancedData>,
#[serde(skip_serializing_if = "Option::is_none")]
pub processing_type: Option<VantivProcessingType>,
#[serde(skip_serializing_if = "Option::is_none")]
pub original_network_transaction_id: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub allow_partial_auth: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub fraud_filter_override: Option<bool>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EnhancedData {
#[serde(skip_serializing_if = "Option::is_none")]
pub customer_reference: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub sales_tax: Option<MinorUnit>,
#[serde(skip_serializing_if = "Option::is_none")]
pub tax_exempt: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub discount_amount: Option<MinorUnit>,
#[serde(skip_serializing_if = "Option::is_none")]
pub shipping_amount: Option<MinorUnit>,
#[serde(skip_serializing_if = "Option::is_none")]
pub duty_amount: Option<MinorUnit>,
#[serde(skip_serializing_if = "Option::is_none")]
pub ship_from_postal_code: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub destination_postal_code: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub destination_country_code: Option<common_enums::CountryAlpha2>,
#[serde(skip_serializing_if = "Option::is_none")]
pub detail_tax: Option<DetailTax>,
#[serde(skip_serializing_if = "Option::is_none")]
pub line_item_data: Option<Vec<LineItemData>>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DetailTax {
#[serde(skip_serializing_if = "Option::is_none")]
pub tax_included_in_total: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub tax_amount: Option<MinorUnit>,
#[serde(skip_serializing_if = "Option::is_none")]
pub card_acceptor_tax_id: Option<Secret<String>>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct LineItemData {
#[serde(skip_serializing_if = "Option::is_none")]
pub item_sequence_number: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub item_description: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub product_code: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub quantity: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub unit_of_measure: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub tax_amount: Option<MinorUnit>,
#[serde(skip_serializing_if = "Option::is_none")]
pub line_item_total: Option<MinorUnit>,
#[serde(skip_serializing_if = "Option::is_none")]
pub line_item_total_with_tax: Option<MinorUnit>,
#[serde(skip_serializing_if = "Option::is_none")]
pub item_discount_amount: Option<MinorUnit>,
#[serde(skip_serializing_if = "Option::is_none")]
pub commodity_code: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub unit_cost: Option<MinorUnit>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RefundRequest {
#[serde(rename = "@reportGroup")]
pub report_group: String,
#[serde(rename = "@id")]
pub id: String,
#[serde(rename = "@customerId", skip_serializing_if = "Option::is_none")]
pub customer_id: Option<String>,
pub cnp_txn_id: String,
pub amount: MinorUnit,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum OrderSource {
Ecommerce,
ApplePay,
MailOrder,
Telephone,
AndroidPay,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TokenizationData {
cnp_token: Secret<String>,
exp_date: Secret<String>,
}
#[derive(Debug)]
struct VantivMandateDetail {
processing_type: Option<VantivProcessingType>,
network_transaction_id: Option<Secret<String>>,
token: Option<TokenizationData>,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct WorldpayvantivCardData {
#[serde(rename = "type")]
pub card_type: WorldpayvativCardType,
pub number: cards::CardNumber,
pub exp_date: Secret<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub card_validation_num: Option<Secret<String>>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum WorldpayvativCardType {
#[serde(rename = "VI")]
Visa,
#[serde(rename = "MC")]
MasterCard,
#[serde(rename = "AX")]
AmericanExpress,
#[serde(rename = "DI")]
Discover,
#[serde(rename = "DC")]
DinersClub,
#[serde(rename = "JC")]
JCB,
#[serde(rename = "")]
UnionPay,
}
#[derive(Debug, Clone, Serialize, strum::EnumString)]
pub enum WorldPayVativApplePayNetwork {
Visa,
MasterCard,
AmEx,
Discover,
DinersClub,
JCB,
UnionPay,
}
impl From<WorldPayVativApplePayNetwork> for WorldpayvativCardType {
fn from(network: WorldPayVativApplePayNetwork) -> Self {
match network {
WorldPayVativApplePayNetwork::Visa => Self::Visa,
WorldPayVativApplePayNetwork::MasterCard => Self::MasterCard,
WorldPayVativApplePayNetwork::AmEx => Self::AmericanExpress,
WorldPayVativApplePayNetwork::Discover => Self::Discover,
WorldPayVativApplePayNetwork::DinersClub => Self::DinersClub,
WorldPayVativApplePayNetwork::JCB => Self::JCB,
WorldPayVativApplePayNetwork::UnionPay => Self::UnionPay,
}
}
}
#[derive(Debug, Clone, Serialize, strum::EnumString)]
#[serde(rename_all = "UPPERCASE")]
#[strum(ascii_case_insensitive)]
pub enum WorldPayVativGooglePayNetwork {
Visa,
Mastercard,
Amex,
Discover,
Dinersclub,
Jcb,
Unionpay,
}
impl From<WorldPayVativGooglePayNetwork> for WorldpayvativCardType {
fn from(network: WorldPayVativGooglePayNetwork) -> Self {
match network {
WorldPayVativGooglePayNetwork::Visa => Self::Visa,
WorldPayVativGooglePayNetwork::Mastercard => Self::MasterCard,
WorldPayVativGooglePayNetwork::Amex => Self::AmericanExpress,
WorldPayVativGooglePayNetwork::Discover => Self::Discover,
WorldPayVativGooglePayNetwork::Dinersclub => Self::DinersClub,
WorldPayVativGooglePayNetwork::Jcb => Self::JCB,
WorldPayVativGooglePayNetwork::Unionpay => Self::UnionPay,
}
}
}
impl TryFrom<common_enums::CardNetwork> for WorldpayvativCardType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(card_network: common_enums::CardNetwork) -> Result<Self, Self::Error> {
match card_network {
common_enums::CardNetwork::Visa => Ok(Self::Visa),
common_enums::CardNetwork::Mastercard => Ok(Self::MasterCard),
common_enums::CardNetwork::AmericanExpress => Ok(Self::AmericanExpress),
common_enums::CardNetwork::Discover => Ok(Self::Discover),
common_enums::CardNetwork::DinersClub => Ok(Self::DinersClub),
common_enums::CardNetwork::JCB => Ok(Self::JCB),
common_enums::CardNetwork::UnionPay => Ok(Self::UnionPay),
_ => Err(errors::ConnectorError::NotSupported {
message: "Card network".to_string(),
connector: "worldpayvantiv",
}
.into()),
}
}
}
impl TryFrom<&connector_utils::CardIssuer> for WorldpayvativCardType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(card_issuer: &connector_utils::CardIssuer) -> Result<Self, Self::Error> {
match card_issuer {
connector_utils::CardIssuer::Visa => Ok(Self::Visa),
connector_utils::CardIssuer::Master => Ok(Self::MasterCard),
connector_utils::CardIssuer::AmericanExpress => Ok(Self::AmericanExpress),
connector_utils::CardIssuer::Discover => Ok(Self::Discover),
connector_utils::CardIssuer::DinersClub => Ok(Self::DinersClub),
connector_utils::CardIssuer::JCB => Ok(Self::JCB),
_ => Err(errors::ConnectorError::NotSupported {
message: "Card network".to_string(),
connector: "worldpayvantiv",
}
.into()),
}
}
}
impl<F> TryFrom<ResponseRouterData<F, VantivSyncResponse, PaymentsSyncData, PaymentsResponseData>>
for RouterData<F, PaymentsSyncData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, VantivSyncResponse, PaymentsSyncData, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let status = determine_attempt_status(&item)?;
if connector_utils::is_payment_failure(status) {
let error_code = item
.response
.payment_detail
.as_ref()
.and_then(|detail| detail.response_reason_code.clone())
.unwrap_or(consts::NO_ERROR_CODE.to_string());
let error_message = item
.response
.payment_detail
.as_ref()
.and_then(|detail| detail.response_reason_message.clone())
.unwrap_or(item.response.payment_status.to_string());
let connector_transaction_id = item
.response
.payment_detail
.as_ref()
.and_then(|detail| detail.payment_id.map(|id| id.to_string()));
Ok(Self {
status,
response: Err(ErrorResponse {
code: error_code.clone(),
message: error_message.clone(),
reason: Some(error_message.clone()),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
})
} else {
let required_conversion_type = common_utils::types::StringMajorUnitForConnector;
let minor_amount_captured: Option<MinorUnit> =
match connector_utils::is_successful_terminal_status(status) {
true => item
.response
.payment_detail
.and_then(|details| {
details.amount.map(|amount| {
common_utils::types::AmountConvertor::convert_back(
&required_conversion_type,
amount,
item.data.request.currency,
)
})
})
.transpose()
.change_context(errors::ConnectorError::ResponseHandlingFailed)?,
false => None,
};
Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.payment_id.to_string(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
minor_amount_captured,
..item.data
})
}
}
}
fn get_bill_to_address<T>(item: &T) -> Option<VantivAddressData>
where
T: UtilsRouterData,
{
let billing_address = item.get_optional_billing();
billing_address.and_then(|billing_address| {
billing_address
.address
.clone()
.map(|address| VantivAddressData {
name: address.get_optional_full_name(),
address_line1: item.get_optional_billing_line1(),
address_line2: item.get_optional_billing_line2(),
address_line3: item.get_optional_billing_line3(),
city: item.get_optional_billing_city(),
state: item.get_optional_billing_state(),
zip: item.get_optional_billing_zip(),
email: item.get_optional_billing_email(),
country: item.get_optional_billing_country(),
phone: item.get_optional_billing_phone_number(),
})
})
}
fn extract_customer_id<T>(item: &T) -> Option<String>
where
T: UtilsRouterData,
{
item.get_optional_customer_id().and_then(|customer_id| {
let customer_id_str = customer_id.get_string_repr().to_string();
if customer_id_str.len() <= worldpayvantiv_constants::CUSTOMER_ID_MAX_LENGTH {
Some(customer_id_str)
} else {
None
}
})
}
fn get_valid_transaction_id(
id: String,
error_field_name: &str,
) -> Result<String, error_stack::Report<errors::ConnectorError>> {
if id.len() <= worldpayvantiv_constants::MAX_PAYMENT_REFERENCE_ID_LENGTH {
Ok(id.clone())
} else {
Err(errors::ConnectorError::MaxFieldLengthViolated {
connector: "Worldpayvantiv".to_string(),
field_name: error_field_name.to_string(),
max_length: worldpayvantiv_constants::MAX_PAYMENT_REFERENCE_ID_LENGTH,
received_length: id.len(),
}
.into())
}
}
fn get_ship_to_address<T>(item: &T) -> Option<VantivAddressData>
where
T: UtilsRouterData,
{
let shipping_address = item.get_optional_shipping();
shipping_address.and_then(|shipping_address| {
shipping_address
.address
.clone()
.map(|address| VantivAddressData {
name: address.get_optional_full_name(),
address_line1: item.get_optional_shipping_line1(),
address_line2: item.get_optional_shipping_line2(),
address_line3: item.get_optional_shipping_line3(),
city: item.get_optional_shipping_city(),
state: item.get_optional_shipping_state(),
zip: item.get_optional_shipping_zip(),
email: item.get_optional_shipping_email(),
country: item.get_optional_shipping_country(),
phone: item.get_optional_shipping_phone_number(),
})
})
}
impl TryFrom<&WorldpayvantivRouterData<&PaymentsAuthorizeRouterData>> for CnpOnlineRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &WorldpayvantivRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
if item.router_data.is_three_ds()
&& matches!(
item.router_data.request.payment_method_data,
PaymentMethodData::Card(_)
)
{
Err(errors::ConnectorError::NotSupported {
message: "Card 3DS".to_string(),
connector: "Worldpayvantiv",
})?
}
let worldpayvantiv_metadata =
WorldpayvantivMetadataObject::try_from(&item.router_data.connector_meta_data)?;
if worldpayvantiv_metadata.merchant_config_currency != item.router_data.request.currency {
Err(errors::ConnectorError::CurrencyNotSupported {
message: item.router_data.request.currency.to_string(),
connector: "Worldpayvantiv",
})?
};
let (card, cardholder_authentication) = get_vantiv_card_data(
&item.router_data.request.payment_method_data,
item.router_data.payment_method_token.clone(),
)?;
let worldpayvantivmetadata = item
.router_data
.request
.metadata
.clone()
.map(|payment_metadata| {
connector_utils::to_connector_meta::<WorldpayvantivPaymentMetadata>(Some(
payment_metadata,
))
})
.transpose()?;
let report_group = worldpayvantivmetadata
.clone()
.and_then(|worldpayvantiv_metadata| worldpayvantiv_metadata.report_group)
.unwrap_or(worldpayvantiv_metadata.report_group);
let fraud_filter_override = worldpayvantivmetadata
.clone()
.and_then(|worldpayvantiv_metadata| worldpayvantiv_metadata.fraud_filter_override)
.or(worldpayvantiv_metadata.fraud_filter_override);
let worldpayvantiv_auth_type =
WorldpayvantivAuthType::try_from(&item.router_data.connector_auth_type)?;
let authentication = Authentication {
user: worldpayvantiv_auth_type.user,
password: worldpayvantiv_auth_type.password,
};
let customer_id = extract_customer_id(item.router_data);
let bill_to_address = get_bill_to_address(item.router_data);
let ship_to_address = get_ship_to_address(item.router_data);
let processing_info = get_processing_info(&item.router_data.request)?;
let enhanced_data = get_enhanced_data(item.router_data)?;
let order_source = OrderSource::from((
item.router_data.request.payment_method_data.clone(),
item.router_data.request.payment_channel.clone(),
));
let (authorization, sale) =
if item.router_data.request.is_auto_capture()? && item.amount != MinorUnit::zero() {
let merchant_txn_id = get_valid_transaction_id(
item.router_data.connector_request_reference_id.clone(),
"sale.id",
)?;
(
None,
Some(Sale {
id: format!("{}_{merchant_txn_id}", OperationId::Sale),
report_group: report_group.clone(),
fraud_filter_override,
customer_id,
order_id: item.router_data.connector_request_reference_id.clone(),
amount: item.amount,
order_source,
bill_to_address,
ship_to_address,
card: card.clone(),
token: processing_info.token,
processing_type: processing_info.processing_type,
original_network_transaction_id: processing_info.network_transaction_id,
enhanced_data,
allow_partial_auth: item
.router_data
.request
.enable_partial_authorization
.and_then(|enable_partial_authorization| {
enable_partial_authorization.then_some(true)
}),
}),
)
} else {
let operation_id = if item.router_data.request.is_auto_capture()? {
OperationId::Sale
} else {
OperationId::Auth
};
let merchant_txn_id = get_valid_transaction_id(
item.router_data.connector_request_reference_id.clone(),
"authorization.id",
)?;
(
Some(Authorization {
id: format!("{operation_id}_{merchant_txn_id}"),
report_group: report_group.clone(),
fraud_filter_override,
customer_id,
order_id: item.router_data.connector_request_reference_id.clone(),
amount: item.amount,
order_source,
bill_to_address,
ship_to_address,
card: card.clone(),
token: processing_info.token,
processing_type: processing_info.processing_type,
original_network_transaction_id: processing_info.network_transaction_id,
cardholder_authentication,
enhanced_data,
allow_partial_auth: item
.router_data
.request
.enable_partial_authorization
.and_then(|enable_partial_authorization| {
enable_partial_authorization.then_some(true)
}),
}),
None,
)
};
Ok(Self {
version: worldpayvantiv_constants::WORLDPAYVANTIV_VERSION.to_string(),
xmlns: worldpayvantiv_constants::XMLNS.to_string(),
merchant_id: worldpayvantiv_auth_type.merchant_id,
authentication,
authorization,
sale,
capture: None,
auth_reversal: None,
credit: None,
void: None,
})
}
}
impl TryFrom<&SetupMandateRouterData> for CnpOnlineRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &SetupMandateRouterData) -> Result<Self, Self::Error> {
if item.is_three_ds()
&& matches!(item.request.payment_method_data, PaymentMethodData::Card(_))
{
Err(errors::ConnectorError::NotSupported {
message: "Card 3DS".to_string(),
connector: "Worldpayvantiv",
})?
}
let worldpayvantiv_metadata =
WorldpayvantivMetadataObject::try_from(&item.connector_meta_data)?;
if worldpayvantiv_metadata.merchant_config_currency != item.request.currency {
| 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/tokenex/transformers.rs | crates/hyperswitch_connectors/src/connectors/tokenex/transformers.rs | use common_utils::types::StringMinorUnit;
use error_stack::ResultExt;
use hyperswitch_domain_models::{
router_data::{ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{ExternalVaultInsertFlow, ExternalVaultRetrieveFlow},
router_request_types::VaultRequestData,
router_response_types::{VaultIdType, VaultResponseData},
types::VaultRouterData,
vault::{PaymentMethodCustomVaultingData, PaymentMethodVaultingData},
};
use hyperswitch_interfaces::errors;
use masking::Secret;
use serde::{Deserialize, Serialize};
use crate::types::ResponseRouterData;
pub struct TokenexRouterData<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 TokenexRouterData<T> {
fn from((amount, item): (StringMinorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
#[derive(Default, Debug, Serialize, PartialEq)]
pub struct TokenexInsertRequest {
data: cards::CardNumber, //Currently only card number is tokenized. Data can be stringified and can be tokenized
}
impl<F> TryFrom<&VaultRouterData<F>> for TokenexInsertRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &VaultRouterData<F>) -> Result<Self, Self::Error> {
match item.request.payment_method_vaulting_data.clone() {
Some(PaymentMethodCustomVaultingData::CardData(req_card)) => Ok(Self {
data: req_card.card_number.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "card_number",
},
)?,
}),
_ => Err(errors::ConnectorError::NotImplemented(
"Payment method apart from card".to_string(),
)
.into()),
}
}
}
pub struct TokenexAuthType {
pub(super) api_key: Secret<String>,
pub(super) tokenex_id: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for TokenexAuthType {
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(),
tokenex_id: key1.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct TokenexInsertResponse {
token: Option<String>,
first_six: Option<String>,
last_four: Option<String>,
success: bool,
error: String,
message: Option<String>,
}
impl
TryFrom<
ResponseRouterData<
ExternalVaultInsertFlow,
TokenexInsertResponse,
VaultRequestData,
VaultResponseData,
>,
> for RouterData<ExternalVaultInsertFlow, VaultRequestData, VaultResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
ExternalVaultInsertFlow,
TokenexInsertResponse,
VaultRequestData,
VaultResponseData,
>,
) -> Result<Self, Self::Error> {
let resp = item.response;
match resp.success && resp.error.is_empty() {
true => {
let token = resp
.token
.clone()
.ok_or(errors::ConnectorError::ResponseDeserializationFailed)
.attach_printable("Token is missing in tokenex response")?;
Ok(Self {
status: common_enums::AttemptStatus::Started,
response: Ok(VaultResponseData::ExternalVaultInsertResponse {
connector_vault_id: VaultIdType::SingleVaultId(token.clone()),
//fingerprint is not provided by tokenex, using token as fingerprint
fingerprint_id: token.clone(),
}),
..item.data
})
}
false => {
let (code, message) = resp.error.split_once(':').unwrap_or(("", ""));
let response = Err(ErrorResponse {
code: code.to_string(),
message: message.to_string(),
reason: resp.message,
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: None,
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
connector_metadata: None,
});
Ok(Self {
response,
..item.data
})
}
}
}
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct TokenexRetrieveRequest {
token: Secret<String>, //Currently only card number is tokenized. Data can be stringified and can be tokenized
cache_cvv: bool,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct TokenexRetrieveResponse {
value: Option<cards::CardNumber>,
success: bool,
error: String,
message: Option<String>,
}
impl<F> TryFrom<&VaultRouterData<F>> for TokenexRetrieveRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &VaultRouterData<F>) -> Result<Self, Self::Error> {
let connector_vault_id = item.request.connector_vault_id.as_ref().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "connector_vault_id",
},
)?;
Ok(Self {
token: Secret::new(connector_vault_id.clone()),
cache_cvv: false, //since cvv is not stored at tokenex
})
}
}
impl
TryFrom<
ResponseRouterData<
ExternalVaultRetrieveFlow,
TokenexRetrieveResponse,
VaultRequestData,
VaultResponseData,
>,
> for RouterData<ExternalVaultRetrieveFlow, VaultRequestData, VaultResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
ExternalVaultRetrieveFlow,
TokenexRetrieveResponse,
VaultRequestData,
VaultResponseData,
>,
) -> Result<Self, Self::Error> {
let resp = item.response;
match resp.success && resp.error.is_empty() {
true => {
let data = resp
.value
.clone()
.ok_or(errors::ConnectorError::ResponseDeserializationFailed)
.attach_printable("Card number is missing in tokenex response")?;
Ok(Self {
status: common_enums::AttemptStatus::Started,
response: Ok(VaultResponseData::ExternalVaultRetrieveResponse {
vault_data: PaymentMethodVaultingData::CardNumber(data),
}),
..item.data
})
}
false => {
let (code, message) = resp.error.split_once(':').unwrap_or(("", ""));
let response = Err(ErrorResponse {
code: code.to_string(),
message: message.to_string(),
reason: resp.message,
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: None,
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
connector_metadata: None,
});
Ok(Self {
response,
..item.data
})
}
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct TokenexErrorResponse {
pub error: 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/checkout/transformers.rs | crates/hyperswitch_connectors/src/connectors/checkout/transformers.rs | use common_enums::{
enums::{self, AttemptStatus, PaymentChannel},
CountryAlpha2,
};
use common_utils::{
errors::{CustomResult, ParsingError},
ext_traits::ByteSliceExt,
request::{Method, RequestContent},
types::MinorUnit,
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{PaymentMethodData, WalletData},
payment_methods::storage_enums::MitCategory,
router_data::{
AdditionalPaymentMethodConnectorResponse, ConnectorAuthType, ConnectorResponseData,
ErrorResponse, PaymentMethodToken, RouterData,
},
router_flow_types::{Execute, RSync, SetupMandate},
router_request_types::{ResponseId, SetupMandateRequestData},
router_response_types::{
MandateReference, PaymentsResponseData, RedirectForm, RefundsResponseData,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsSyncRouterData, RefundsRouterData, TokenizationRouterData,
},
};
use hyperswitch_interfaces::{consts, errors, webhooks};
use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use serde_json::json;
use serde_with::skip_serializing_none;
use time::PrimitiveDateTime;
use url::Url;
use crate::{
types::{
PaymentsCancelResponseRouterData, PaymentsCaptureResponseRouterData,
PaymentsResponseRouterData, PaymentsSyncResponseRouterData, RefundsResponseRouterData,
ResponseRouterData, SubmitEvidenceRouterData, UploadFileRouterData,
},
unimplemented_payment_method,
utils::{
self, PaymentsAuthorizeRequestData, PaymentsCaptureRequestData, PaymentsSyncRequestData,
RouterData as OtherRouterData, WalletData as OtherWalletData,
},
};
#[derive(Debug, Serialize)]
pub struct CheckoutRouterData<T> {
pub amount: MinorUnit,
pub router_data: T,
}
impl<T> From<(MinorUnit, T)> for CheckoutRouterData<T> {
fn from((amount, item): (MinorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "lowercase")]
#[serde(tag = "type", content = "token_data")]
pub enum TokenRequest {
Googlepay(CheckoutGooglePayData),
Applepay(CheckoutApplePayData),
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "lowercase")]
#[serde(tag = "type", content = "token_data")]
pub enum PreDecryptedTokenRequest {
Applepay(Box<CheckoutApplePayData>),
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CheckoutGooglePayData {
protocol_version: Secret<String>,
signature: Secret<String>,
signed_message: Secret<String>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct CheckoutApplePayData {
version: Secret<String>,
data: Secret<String>,
signature: Secret<String>,
header: CheckoutApplePayHeader,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CheckoutApplePayHeader {
ephemeral_public_key: Secret<String>,
public_key_hash: Secret<String>,
transaction_id: Secret<String>,
}
impl TryFrom<&TokenizationRouterData> for TokenRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &TokenizationRouterData) -> Result<Self, Self::Error> {
match item.request.payment_method_data.clone() {
PaymentMethodData::Wallet(wallet_data) => match wallet_data.clone() {
WalletData::GooglePay(_data) => {
let json_wallet_data: CheckoutGooglePayData =
wallet_data.get_wallet_token_as_json("Google Pay".to_string())?;
Ok(Self::Googlepay(json_wallet_data))
}
WalletData::ApplePay(_data) => {
let json_wallet_data: CheckoutApplePayData =
wallet_data.get_wallet_token_as_json("Apple Pay".to_string())?;
Ok(Self::Applepay(json_wallet_data))
}
WalletData::AliPayQr(_)
| WalletData::AliPayRedirect(_)
| WalletData::AliPayHkRedirect(_)
| WalletData::AmazonPay(_)
| WalletData::AmazonPayRedirect(_)
| WalletData::Paysera(_)
| WalletData::Skrill(_)
| WalletData::BluecodeRedirect {}
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
| WalletData::GcashRedirect(_)
| WalletData::ApplePayRedirect(_)
| WalletData::ApplePayThirdPartySdk(_)
| WalletData::DanaRedirect {}
| WalletData::GooglePayRedirect(_)
| WalletData::GooglePayThirdPartySdk(_)
| WalletData::MbWayRedirect(_)
| WalletData::MobilePayRedirect(_)
| WalletData::PaypalRedirect(_)
| WalletData::PaypalSdk(_)
| WalletData::Paze(_)
| WalletData::SamsungPay(_)
| WalletData::TwintRedirect {}
| WalletData::VippsRedirect {}
| WalletData::TouchNGoRedirect(_)
| WalletData::WeChatPayRedirect(_)
| WalletData::CashappQr(_)
| WalletData::SwishQr(_)
| WalletData::WeChatPayQr(_)
| WalletData::Mifinity(_)
| WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("checkout"),
)
.into()),
},
PaymentMethodData::Card(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("checkout"),
)
.into())
}
}
}
}
#[derive(Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct CheckoutTokenResponse {
token: Secret<String>,
}
impl<F, T> TryFrom<ResponseRouterData<F, CheckoutTokenResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, CheckoutTokenResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(PaymentsResponseData::TokenizationResponse {
token: item.response.token.expose(),
}),
..item.data
})
}
}
#[skip_serializing_none]
#[derive(Debug, Serialize)]
pub struct CheckoutAddress {
pub address_line1: Option<Secret<String>>,
pub address_line2: Option<Secret<String>>,
pub city: Option<String>,
pub state: Option<Secret<String>>,
pub zip: Option<Secret<String>>,
pub country: Option<CountryAlpha2>,
}
#[skip_serializing_none]
#[derive(Debug, Serialize)]
pub struct CheckoutAccountHolderDetails {
pub first_name: Option<Secret<String>>,
pub last_name: Option<Secret<String>>,
}
#[derive(Debug, Serialize)]
pub struct CardSource {
#[serde(rename = "type")]
pub source_type: CheckoutSourceTypes,
pub number: cards::CardNumber,
pub expiry_month: Secret<String>,
pub expiry_year: Secret<String>,
pub cvv: Option<Secret<String>>,
pub billing_address: Option<CheckoutAddress>,
pub account_holder: Option<CheckoutAccountHolderDetails>,
}
#[derive(Debug, Serialize)]
pub struct WalletSource {
#[serde(rename = "type")]
pub source_type: CheckoutSourceTypes,
pub token: Secret<String>,
pub billing_address: Option<CheckoutAddress>,
}
#[derive(Debug, Serialize)]
pub struct MandateSource {
#[serde(rename = "type")]
pub source_type: CheckoutSourceTypes,
#[serde(rename = "id")]
pub source_id: Option<String>,
pub billing_address: Option<CheckoutAddress>,
}
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum PaymentSource {
Card(CardSource),
Wallets(WalletSource),
ApplePayPredecrypt(Box<ApplePayPredecrypt>),
MandatePayment(MandateSource),
GooglePayPredecrypt(Box<GooglePayPredecrypt>),
}
#[derive(Debug, Serialize)]
pub struct GooglePayPredecrypt {
#[serde(rename = "type")]
_type: String,
token: cards::CardNumber,
token_type: String,
expiry_month: Secret<String>,
expiry_year: Secret<String>,
eci: String,
cryptogram: Option<Secret<String>>,
pub billing_address: Option<CheckoutAddress>,
}
#[derive(Debug, Serialize)]
pub struct ApplePayPredecrypt {
token: cards::CardNumber,
#[serde(rename = "type")]
decrypt_type: String,
token_type: String,
expiry_month: Secret<String>,
expiry_year: Secret<String>,
eci: Option<String>,
cryptogram: Secret<String>,
pub billing_address: Option<CheckoutAddress>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum CheckoutSourceTypes {
Card,
Token,
#[serde(rename = "id")]
SourceId,
}
#[derive(Debug, Serialize)]
pub enum CheckoutPaymentType {
Regular,
Unscheduled,
#[serde(rename = "MOTO")]
Moto,
Installment,
Recurring,
}
pub struct CheckoutAuthType {
pub(super) api_key: Secret<String>,
pub(super) processing_channel_id: Secret<String>,
pub(super) api_secret: Secret<String>,
}
#[derive(Debug, Serialize)]
pub struct ReturnUrl {
pub success_url: Option<String>,
pub failure_url: Option<String>,
}
#[skip_serializing_none]
#[derive(Debug, Default, Serialize)]
pub struct CheckoutCustomer {
pub name: Option<Secret<String>>,
pub email: Option<common_utils::pii::Email>,
pub phone: Option<CheckoutPhoneDetails>,
pub tax_number: Option<Secret<String>>,
}
#[skip_serializing_none]
#[derive(Debug, Default, Serialize)]
pub struct CheckoutPhoneDetails {
pub country_code: Option<String>,
pub number: Option<Secret<String>>,
}
#[skip_serializing_none]
#[derive(Debug, Default, Serialize)]
pub struct CheckoutProcessing {
pub order_id: Option<String>,
pub tax_amount: Option<MinorUnit>,
pub discount_amount: Option<MinorUnit>,
pub duty_amount: Option<MinorUnit>,
pub shipping_amount: Option<MinorUnit>,
pub shipping_tax_amount: Option<MinorUnit>,
}
#[skip_serializing_none]
#[derive(Debug, Default, Serialize)]
pub struct CheckoutShipping {
pub address: Option<CheckoutAddress>,
pub from_address_zip: Option<String>,
}
#[skip_serializing_none]
#[derive(Debug, Default, Serialize)]
pub struct CheckoutLineItem {
pub commodity_code: Option<String>,
pub discount_amount: Option<MinorUnit>,
pub name: Option<String>,
pub quantity: Option<u16>,
pub reference: Option<String>,
pub tax_exempt: Option<bool>,
pub tax_amount: Option<MinorUnit>,
pub total_amount: Option<MinorUnit>,
pub unit_of_measure: Option<String>,
pub unit_price: Option<MinorUnit>,
}
#[skip_serializing_none]
#[derive(Debug, Default, Serialize)]
pub struct CheckoutBillingDescriptor {
pub name: Option<Secret<String>>,
pub city: Option<Secret<String>>,
pub reference: Option<String>,
}
#[skip_serializing_none]
#[derive(Debug, Serialize)]
pub struct PaymentsRequest {
pub source: PaymentSource,
pub amount: MinorUnit,
pub currency: String,
pub processing_channel_id: Secret<String>,
#[serde(rename = "3ds")]
pub three_ds: CheckoutThreeDS,
#[serde(flatten)]
pub return_url: ReturnUrl,
pub capture: bool,
pub reference: String,
#[serde(skip_serializing_if = "is_metadata_empty")]
pub metadata: Option<Secret<serde_json::Value>>,
pub payment_type: CheckoutPaymentType,
pub merchant_initiated: Option<bool>,
pub previous_payment_id: Option<String>,
pub store_for_future_use: Option<bool>,
pub billing_descriptor: Option<CheckoutBillingDescriptor>,
// Level 2/3 data fields
pub customer: Option<CheckoutCustomer>,
pub processing: Option<CheckoutProcessing>,
pub shipping: Option<CheckoutShipping>,
pub items: Option<Vec<CheckoutLineItem>>,
pub partial_authorization: Option<CheckoutPartialAuthorization>,
pub payment_ip: Option<Secret<String, common_utils::pii::IpAddress>>,
}
#[skip_serializing_none]
#[derive(Debug, Default, Serialize)]
pub struct CheckoutPartialAuthorization {
pub enabled: bool,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct CheckoutMeta {
pub psync_flow: CheckoutPaymentIntent,
}
#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq)]
pub enum CheckoutPaymentIntent {
Capture,
Authorize,
}
#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum CheckoutChallengeIndicator {
NoPreference,
ChallengeRequestedMandate,
ChallengeRequested,
NoChallengeRequested,
}
#[derive(Debug, Serialize)]
pub struct CheckoutThreeDS {
enabled: bool,
force_3ds: bool,
eci: Option<String>,
cryptogram: Option<Secret<String>>,
xid: Option<String>,
version: Option<String>,
challenge_indicator: CheckoutChallengeIndicator,
}
impl TryFrom<&ConnectorAuthType> for CheckoutAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
if let ConnectorAuthType::SignatureKey {
api_key,
api_secret,
key1,
} = auth_type
{
Ok(Self {
api_key: api_key.to_owned(),
api_secret: api_secret.to_owned(),
processing_channel_id: key1.to_owned(),
})
} else {
Err(errors::ConnectorError::FailedToObtainAuthType.into())
}
}
}
fn split_account_holder_name(
card_holder_name: Option<Secret<String>>,
) -> (Option<Secret<String>>, Option<Secret<String>>) {
let account_holder_name = card_holder_name
.as_ref()
.map(|name| name.clone().expose().trim().to_string());
match account_holder_name {
Some(name) if !name.is_empty() => match name.rsplit_once(' ') {
Some((first, last)) => (
Some(Secret::new(first.to_string())),
Some(Secret::new(last.to_string())),
),
None => (Some(Secret::new(name)), None),
},
_ => (None, None),
}
}
fn build_metadata(
item: &CheckoutRouterData<&PaymentsAuthorizeRouterData>,
) -> Option<Secret<serde_json::Value>> {
// get metadata or create empty json object
let mut metadata_json = item
.router_data
.request
.metadata
.clone()
.unwrap_or_else(|| json!({}));
// get udf5 value (name or integrator)
let udf5 = item
.router_data
.request
.partner_merchant_identifier_details
.as_ref()
.and_then(|p| p.partner_details.as_ref())
.and_then(|e| e.name.clone().or(e.integrator.clone()));
// insert udf5 if present
if let Some(v) = udf5 {
if let Some(obj) = metadata_json.as_object_mut() {
obj.insert("udf5".to_string(), json!(v));
} else {
metadata_json = json!({ "udf5": v });
}
}
Some(Secret::new(metadata_json))
}
fn is_metadata_empty(val: &Option<Secret<serde_json::Value>>) -> bool {
match val {
None => true,
Some(secret) => {
let inner = secret.clone().expose();
match inner {
serde_json::Value::Null => true,
serde_json::Value::Object(map) => map.is_empty(),
_ => false,
}
}
}
}
impl TryFrom<&CheckoutRouterData<&PaymentsAuthorizeRouterData>> for PaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &CheckoutRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let capture = matches!(
item.router_data.request.capture_method,
Some(enums::CaptureMethod::Automatic)
);
let payment_type = if matches!(
item.router_data.request.payment_channel,
Some(PaymentChannel::MailOrder | PaymentChannel::TelephoneOrder)
) {
CheckoutPaymentType::Moto
} else if item.router_data.request.is_mandate_payment() {
CheckoutPaymentType::Unscheduled
} else {
CheckoutPaymentType::Regular
};
let (challenge_indicator, store_for_future_use) =
if item.router_data.request.is_mandate_payment() {
(
CheckoutChallengeIndicator::ChallengeRequestedMandate,
Some(true),
)
} else {
(CheckoutChallengeIndicator::ChallengeRequested, None)
};
let billing_details = Some(CheckoutAddress {
city: item.router_data.get_optional_billing_city(),
address_line1: item.router_data.get_optional_billing_line1(),
address_line2: item.router_data.get_optional_billing_line2(),
state: item.router_data.get_optional_billing_state(),
zip: item.router_data.get_optional_billing_zip(),
country: item.router_data.get_optional_billing_country(),
});
let (
source_var,
previous_payment_id,
merchant_initiated,
payment_type,
store_for_future_use,
) = match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(ccard) => {
let (first_name, last_name) = split_account_holder_name(ccard.card_holder_name);
let payment_source = PaymentSource::Card(CardSource {
source_type: CheckoutSourceTypes::Card,
number: ccard.card_number.clone(),
expiry_month: ccard.card_exp_month.clone(),
expiry_year: ccard.card_exp_year.clone(),
cvv: Some(ccard.card_cvc),
billing_address: billing_details,
account_holder: Some(CheckoutAccountHolderDetails {
first_name,
last_name,
}),
});
Ok((
payment_source,
None,
Some(false),
payment_type,
store_for_future_use,
))
}
PaymentMethodData::Wallet(wallet_data) => match wallet_data {
WalletData::GooglePay(_) => {
let p_source = match item.router_data.get_payment_method_token()? {
PaymentMethodToken::Token(token) => PaymentSource::Wallets(WalletSource {
source_type: CheckoutSourceTypes::Token,
token,
billing_address: billing_details,
}),
PaymentMethodToken::ApplePayDecrypt(_) => Err(
unimplemented_payment_method!("Apple Pay", "Simplified", "Checkout"),
)?,
PaymentMethodToken::PazeDecrypt(_) => {
Err(unimplemented_payment_method!("Paze", "Checkout"))?
}
PaymentMethodToken::GooglePayDecrypt(google_pay_decrypted_data) => {
let token = google_pay_decrypted_data
.application_primary_account_number
.clone();
let expiry_month = google_pay_decrypted_data
.get_expiry_month()
.change_context(errors::ConnectorError::InvalidDataFormat {
field_name: "payment_method_data.card.card_exp_month",
})?;
let expiry_year = google_pay_decrypted_data
.get_four_digit_expiry_year()
.change_context(errors::ConnectorError::InvalidDataFormat {
field_name: "payment_method_data.card.card_exp_year",
})?;
let cryptogram = google_pay_decrypted_data.cryptogram.clone();
PaymentSource::GooglePayPredecrypt(Box::new(GooglePayPredecrypt {
_type: "network_token".to_string(),
token,
token_type: "googlepay".to_string(),
expiry_month,
expiry_year,
eci: "06".to_string(),
cryptogram,
billing_address: billing_details,
}))
}
};
Ok((
p_source,
None,
Some(false),
payment_type,
store_for_future_use,
))
}
WalletData::ApplePay(_) => {
let payment_method_token = item.router_data.get_payment_method_token()?;
match payment_method_token {
PaymentMethodToken::Token(apple_pay_payment_token) => {
let p_source = PaymentSource::Wallets(WalletSource {
source_type: CheckoutSourceTypes::Token,
token: apple_pay_payment_token,
billing_address: billing_details,
});
Ok((
p_source,
None,
Some(false),
payment_type,
store_for_future_use,
))
}
PaymentMethodToken::ApplePayDecrypt(decrypt_data) => {
let exp_month = decrypt_data.get_expiry_month().change_context(
errors::ConnectorError::InvalidDataFormat {
field_name: "expiration_month",
},
)?;
let expiry_year_4_digit = decrypt_data.get_four_digit_expiry_year();
let p_source =
PaymentSource::ApplePayPredecrypt(Box::new(ApplePayPredecrypt {
token: decrypt_data.application_primary_account_number,
decrypt_type: "network_token".to_string(),
token_type: "applepay".to_string(),
expiry_month: exp_month,
expiry_year: expiry_year_4_digit,
eci: decrypt_data.payment_data.eci_indicator,
cryptogram: decrypt_data.payment_data.online_payment_cryptogram,
billing_address: billing_details,
}));
Ok((
p_source,
None,
Some(false),
payment_type,
store_for_future_use,
))
}
PaymentMethodToken::PazeDecrypt(_) => {
Err(unimplemented_payment_method!("Paze", "Checkout"))?
}
PaymentMethodToken::GooglePayDecrypt(_) => {
Err(unimplemented_payment_method!("Google Pay", "Checkout"))?
}
}
}
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("checkout"),
)),
},
PaymentMethodData::MandatePayment => {
let mandate_source = PaymentSource::MandatePayment(MandateSource {
source_type: CheckoutSourceTypes::SourceId,
source_id: item.router_data.request.connector_mandate_id(),
billing_address: billing_details,
});
let previous_id = Some(
item.router_data
.request
.get_connector_mandate_request_reference_id()?,
);
let p_type = match item.router_data.request.mit_category {
Some(MitCategory::Installment) => CheckoutPaymentType::Installment,
Some(MitCategory::Recurring) => CheckoutPaymentType::Recurring,
Some(MitCategory::Unscheduled) | None => CheckoutPaymentType::Unscheduled,
_ => CheckoutPaymentType::Unscheduled,
};
Ok((mandate_source, previous_id, Some(true), p_type, None))
}
PaymentMethodData::CardDetailsForNetworkTransactionId(ccard) => {
let (first_name, last_name) = split_account_holder_name(ccard.card_holder_name);
let payment_source = PaymentSource::Card(CardSource {
source_type: CheckoutSourceTypes::Card,
number: ccard.card_number.clone(),
expiry_month: ccard.card_exp_month.clone(),
expiry_year: ccard.card_exp_year.clone(),
cvv: None,
billing_address: billing_details,
account_holder: Some(CheckoutAccountHolderDetails {
first_name,
last_name,
}),
});
let previous_id = Some(
item.router_data
.request
.get_optional_network_transaction_id()
.ok_or_else(utils::missing_field_err("network_transaction_id"))
.attach_printable("Checkout unable to find NTID for MIT")?,
);
let p_type = match item.router_data.request.mit_category {
Some(MitCategory::Installment) => CheckoutPaymentType::Installment,
Some(MitCategory::Recurring) => CheckoutPaymentType::Recurring,
Some(MitCategory::Unscheduled) | None => CheckoutPaymentType::Unscheduled,
_ => CheckoutPaymentType::Unscheduled,
};
Ok((payment_source, previous_id, Some(true), p_type, None))
}
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("checkout"),
)),
}?;
let authentication_data = item.router_data.request.authentication_data.as_ref();
let three_ds = match item.router_data.auth_type {
enums::AuthenticationType::ThreeDs => CheckoutThreeDS {
enabled: true,
force_3ds: true,
eci: authentication_data.and_then(|auth| auth.eci.clone()),
cryptogram: authentication_data.map(|auth| auth.cavv.clone()),
xid: authentication_data
.and_then(|auth| auth.threeds_server_transaction_id.clone()),
version: authentication_data.and_then(|auth| {
auth.message_version
.clone()
.map(|version| version.to_string())
}),
challenge_indicator,
},
enums::AuthenticationType::NoThreeDs => CheckoutThreeDS {
enabled: false,
force_3ds: false,
eci: None,
cryptogram: None,
xid: None,
version: None,
challenge_indicator: CheckoutChallengeIndicator::NoPreference,
},
};
let return_url = ReturnUrl {
success_url: item
.router_data
.request
.router_return_url
.as_ref()
.map(|return_url| format!("{return_url}?status=success")),
failure_url: item
.router_data
.request
.router_return_url
.as_ref()
.map(|return_url| format!("{return_url}?status=failure")),
};
let connector_auth = &item.router_data.connector_auth_type;
let auth_type: CheckoutAuthType = connector_auth.try_into()?;
let processing_channel_id = auth_type.processing_channel_id;
let metadata = build_metadata(item);
let (customer, processing, shipping, items) = if let Some(l2l3_data) =
&item.router_data.l2_l3_data
{
(
l2l3_data.customer_info.as_ref().map(|_| CheckoutCustomer {
name: l2l3_data.get_customer_name(),
email: l2l3_data.get_customer_email(),
phone: Some(CheckoutPhoneDetails {
country_code: l2l3_data.get_customer_phone_country_code(),
number: l2l3_data.get_customer_phone_number(),
}),
tax_number: l2l3_data.get_customer_tax_registration_id(),
}),
l2l3_data.order_info.as_ref().map(|_| CheckoutProcessing {
order_id: l2l3_data.get_merchant_order_reference_id(),
tax_amount: l2l3_data.get_order_tax_amount(),
discount_amount: l2l3_data.get_discount_amount(),
duty_amount: l2l3_data.get_duty_amount(),
shipping_amount: l2l3_data.get_shipping_cost(),
shipping_tax_amount: l2l3_data.get_shipping_amount_tax(),
}),
Some(CheckoutShipping {
address: Some(CheckoutAddress {
country: l2l3_data.get_shipping_country(),
address_line1: l2l3_data.get_shipping_address_line1(),
address_line2: l2l3_data.get_shipping_address_line2(),
city: l2l3_data.get_shipping_city(),
state: l2l3_data.get_shipping_state(),
zip: l2l3_data.get_shipping_zip(),
}),
from_address_zip: l2l3_data.get_shipping_origin_zip().map(|zip| zip.expose()),
}),
l2l3_data.get_order_details().map(|details| {
details
.iter()
.map(|item| CheckoutLineItem {
commodity_code: item.commodity_code.clone(),
discount_amount: item.unit_discount_amount,
name: Some(item.product_name.clone()),
quantity: Some(item.quantity),
reference: item.product_id.clone(),
tax_exempt: None,
tax_amount: item.total_tax_amount,
total_amount: item.total_amount,
unit_of_measure: item.unit_of_measure.clone(),
| 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/threedsecureio/transformers.rs | crates/hyperswitch_connectors/src/connectors/threedsecureio/transformers.rs | use std::str::FromStr;
use api_models::payments::{DeviceChannel, ThreeDsCompletionIndicator};
use base64::Engine;
use common_enums::enums;
use common_utils::{consts::BASE64_ENGINE, date_time, ext_traits::OptionExt as _};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
router_data::{ConnectorAuthType, ErrorResponse},
router_flow_types::authentication::{Authentication, PreAuthentication},
router_request_types::{
authentication::{
AuthNFlowType, ChallengeParams, ConnectorAuthenticationRequestData, MessageCategory,
PreAuthNRequestData,
},
BrowserInformation,
},
router_response_types::AuthenticationResponseData,
};
use hyperswitch_interfaces::{api::CurrencyUnit, consts::NO_ERROR_MESSAGE, errors};
use iso_currency::Currency;
use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use serde_json::{json, to_string};
use crate::{
types::{ConnectorAuthenticationRouterData, PreAuthNRouterData, ResponseRouterData},
utils::{get_card_details, to_connector_meta, AddressDetailsData, CardData as _},
};
pub struct ThreedsecureioRouterData<T> {
pub amount: String,
pub router_data: T,
}
impl<T> TryFrom<(&CurrencyUnit, enums::Currency, i64, T)> for ThreedsecureioRouterData<T> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(_currency_unit, _currency, amount, item): (&CurrencyUnit, enums::Currency, i64, T),
) -> Result<Self, Self::Error> {
Ok(Self {
amount: amount.to_string(),
router_data: item,
})
}
}
impl<T> TryFrom<(i64, T)> for ThreedsecureioRouterData<T> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from((amount, router_data): (i64, T)) -> Result<Self, Self::Error> {
Ok(Self {
amount: amount.to_string(),
router_data,
})
}
}
impl
TryFrom<
ResponseRouterData<
PreAuthentication,
ThreedsecureioPreAuthenticationResponse,
PreAuthNRequestData,
AuthenticationResponseData,
>,
> for PreAuthNRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
PreAuthentication,
ThreedsecureioPreAuthenticationResponse,
PreAuthNRequestData,
AuthenticationResponseData,
>,
) -> Result<Self, Self::Error> {
let response = match item.response {
ThreedsecureioPreAuthenticationResponse::Success(pre_authn_response) => {
let three_ds_method_data = json!({
"threeDSServerTransID": pre_authn_response.threeds_server_trans_id,
});
let three_ds_method_data_str = to_string(&three_ds_method_data)
.change_context(errors::ConnectorError::ResponseDeserializationFailed)
.attach_printable("error while constructing three_ds_method_data_str")?;
let three_ds_method_data_base64 = BASE64_ENGINE.encode(three_ds_method_data_str);
let connector_metadata = serde_json::json!(ThreeDSecureIoConnectorMetaData {
ds_start_protocol_version: pre_authn_response.ds_start_protocol_version,
ds_end_protocol_version: pre_authn_response.ds_end_protocol_version,
acs_start_protocol_version: pre_authn_response.acs_start_protocol_version,
acs_end_protocol_version: pre_authn_response.acs_end_protocol_version.clone(),
});
Ok(AuthenticationResponseData::PreAuthNResponse {
threeds_server_transaction_id: pre_authn_response
.threeds_server_trans_id
.clone(),
maximum_supported_3ds_version: common_utils::types::SemanticVersion::from_str(
&pre_authn_response.acs_end_protocol_version,
)
.change_context(errors::ConnectorError::ParsingFailed)?,
connector_authentication_id: pre_authn_response.threeds_server_trans_id,
three_ds_method_data: Some(three_ds_method_data_base64),
three_ds_method_url: pre_authn_response.threeds_method_url,
message_version: common_utils::types::SemanticVersion::from_str(
&pre_authn_response.acs_end_protocol_version,
)
.change_context(errors::ConnectorError::ParsingFailed)?,
connector_metadata: Some(connector_metadata),
directory_server_id: None,
scheme_id: pre_authn_response.scheme,
})
}
ThreedsecureioPreAuthenticationResponse::Failure(error_response) => {
Err(ErrorResponse {
code: error_response.error_code,
message: error_response
.error_description
.clone()
.unwrap_or(NO_ERROR_MESSAGE.to_owned()),
reason: error_response.error_description,
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
};
Ok(Self {
response,
..item.data.clone()
})
}
}
impl
TryFrom<
ResponseRouterData<
Authentication,
ThreedsecureioAuthenticationResponse,
ConnectorAuthenticationRequestData,
AuthenticationResponseData,
>,
> for ConnectorAuthenticationRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
Authentication,
ThreedsecureioAuthenticationResponse,
ConnectorAuthenticationRequestData,
AuthenticationResponseData,
>,
) -> Result<Self, Self::Error> {
let response = match item.response {
ThreedsecureioAuthenticationResponse::Success(response) => {
let creq = serde_json::json!({
"threeDSServerTransID": response.three_dsserver_trans_id,
"acsTransID": response.acs_trans_id,
"messageVersion": response.message_version,
"messageType": "CReq",
"challengeWindowSize": "01",
});
let creq_str = to_string(&creq)
.change_context(errors::ConnectorError::ResponseDeserializationFailed)
.attach_printable("error while constructing creq_str")?;
let creq_base64 = Engine::encode(&BASE64_ENGINE, creq_str)
.trim_end_matches('=')
.to_owned();
Ok(AuthenticationResponseData::AuthNResponse {
trans_status: response.trans_status.clone().into(),
authn_flow_type: if response.trans_status == ThreedsecureioTransStatus::C {
AuthNFlowType::Challenge(Box::new(ChallengeParams {
acs_url: response.acs_url,
challenge_request: Some(creq_base64),
acs_reference_number: Some(response.acs_reference_number.clone()),
acs_trans_id: Some(response.acs_trans_id.clone()),
three_dsserver_trans_id: Some(response.three_dsserver_trans_id),
acs_signed_content: response.acs_signed_content,
challenge_request_key: None,
}))
} else {
AuthNFlowType::Frictionless
},
authentication_value: response.authentication_value,
connector_metadata: None,
ds_trans_id: Some(response.ds_trans_id),
eci: None,
challenge_code: None,
challenge_cancel: None,
challenge_code_reason: None,
message_extension: None,
})
}
ThreedsecureioAuthenticationResponse::Error(err_response) => match *err_response {
ThreedsecureioErrorResponseWrapper::ErrorResponse(resp) => Err(ErrorResponse {
code: resp.error_code,
message: resp
.error_description
.clone()
.unwrap_or(NO_ERROR_MESSAGE.to_owned()),
reason: resp.error_description,
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
ThreedsecureioErrorResponseWrapper::ErrorString(error) => Err(ErrorResponse {
code: error.clone(),
message: error.clone(),
reason: Some(error),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
},
};
Ok(Self {
response,
..item.data.clone()
})
}
}
pub struct ThreedsecureioAuthType {
pub(super) api_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for ThreedsecureioAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
api_key: api_key.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
impl TryFrom<&ThreedsecureioRouterData<&ConnectorAuthenticationRouterData>>
for ThreedsecureioAuthenticationRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &ThreedsecureioRouterData<&ConnectorAuthenticationRouterData>,
) -> Result<Self, Self::Error> {
let request = &item.router_data.request;
//browser_details are mandatory for Browser flows
let browser_details = match request.browser_details.clone() {
Some(details) => Ok::<Option<BrowserInformation>, Self::Error>(Some(details)),
None => {
if request.device_channel == DeviceChannel::Browser {
Err(errors::ConnectorError::MissingRequiredField {
field_name: "browser_info",
})?
} else {
Ok(None)
}
}
}?;
let card_details = get_card_details(request.payment_method_data.clone(), "threedsecureio")?;
let currency = request
.currency
.map(|currency| currency.to_string())
.ok_or(errors::ConnectorError::RequestEncodingFailed)
.attach_printable("missing field currency")?;
let purchase_currency: Currency = Currency::from_code(¤cy)
.ok_or(errors::ConnectorError::RequestEncodingFailed)
.attach_printable("error while parsing Currency")?;
let billing_address = request.billing_address.address.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "billing_address.address",
},
)?;
let billing_state = billing_address.clone().to_state_code()?;
let billing_country = isocountry::CountryCode::for_alpha2(
&billing_address
.country
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "billing_address.address.country",
})?
.to_string(),
)
.change_context(errors::ConnectorError::RequestEncodingFailed)
.attach_printable("Error parsing billing_address.address.country")?;
let connector_meta_data: ThreeDSecureIoMetaData = item
.router_data
.connector_meta_data
.clone()
.parse_value("ThreeDSecureIoMetaData")
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
let pre_authentication_data = &request.pre_authentication_data;
let sdk_information = match request.device_channel {
DeviceChannel::App => Some(item.router_data.request.sdk_information.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "sdk_information",
},
)?),
DeviceChannel::Browser => None,
};
let (acquirer_bin, acquirer_merchant_id) = pre_authentication_data
.acquirer_bin
.clone()
.zip(pre_authentication_data.acquirer_merchant_id.clone())
.get_required_value("acquirer_details")
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "acquirer_details",
})?;
let meta: ThreeDSecureIoConnectorMetaData =
to_connector_meta(request.pre_authentication_data.connector_metadata.clone())?;
let card_holder_name = billing_address.get_optional_full_name();
Ok(Self {
ds_start_protocol_version: meta.ds_start_protocol_version.clone(),
ds_end_protocol_version: meta.ds_end_protocol_version.clone(),
acs_start_protocol_version: meta.acs_start_protocol_version.clone(),
acs_end_protocol_version: meta.acs_end_protocol_version.clone(),
three_dsserver_trans_id: pre_authentication_data
.threeds_server_transaction_id
.clone(),
acct_number: card_details.card_number.clone(),
notification_url: request
.return_url
.clone()
.ok_or(errors::ConnectorError::RequestEncodingFailed)
.attach_printable("missing return_url")?,
three_dscomp_ind: ThreeDSecureIoThreeDsCompletionIndicator::from(
request.threeds_method_comp_ind.clone(),
),
three_dsrequestor_url: request.three_ds_requestor_url.clone(),
acquirer_bin,
acquirer_merchant_id,
card_expiry_date: card_details.get_expiry_date_as_yymm()?.expose(),
bill_addr_city: billing_address
.city
.clone()
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "billing_address.address.city",
})?
.to_string(),
bill_addr_country: billing_country.numeric_id().to_string().into(),
bill_addr_line1: billing_address.line1.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "billing_address.address.line1",
},
)?,
bill_addr_post_code: billing_address.zip.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "billing_address.address.zip",
},
)?,
bill_addr_state: billing_state,
// Indicates the type of Authentication request, "01" for Payment transaction
three_dsrequestor_authentication_ind: "01".to_string(),
device_channel: match item.router_data.request.device_channel.clone() {
DeviceChannel::App => "01",
DeviceChannel::Browser => "02",
}
.to_string(),
message_category: match item.router_data.request.message_category.clone() {
MessageCategory::Payment => "01",
MessageCategory::NonPayment => "02",
}
.to_string(),
browser_javascript_enabled: browser_details
.as_ref()
.and_then(|details| details.java_script_enabled),
browser_accept_header: browser_details
.as_ref()
.and_then(|details| details.accept_header.clone()),
browser_ip: browser_details
.clone()
.and_then(|details| details.ip_address.map(|ip| Secret::new(ip.to_string()))),
browser_java_enabled: browser_details
.as_ref()
.and_then(|details| details.java_enabled),
browser_language: browser_details
.as_ref()
.and_then(|details| details.language.clone()),
browser_color_depth: browser_details
.as_ref()
.and_then(|details| details.color_depth.map(|a| a.to_string())),
browser_screen_height: browser_details
.as_ref()
.and_then(|details| details.screen_height.map(|a| a.to_string())),
browser_screen_width: browser_details
.as_ref()
.and_then(|details| details.screen_width.map(|a| a.to_string())),
browser_tz: browser_details
.as_ref()
.and_then(|details| details.time_zone.map(|a| a.to_string())),
browser_user_agent: browser_details
.as_ref()
.and_then(|details| details.user_agent.clone().map(|a| a.to_string())),
mcc: connector_meta_data.mcc,
merchant_country_code: connector_meta_data.merchant_country_code,
merchant_name: connector_meta_data.merchant_name,
message_type: "AReq".to_string(),
message_version: pre_authentication_data.message_version.to_string(),
purchase_amount: item.amount.clone(),
purchase_currency: purchase_currency.numeric().to_string(),
trans_type: "01".to_string(),
purchase_exponent: purchase_currency
.exponent()
.ok_or(errors::ConnectorError::RequestEncodingFailed)
.attach_printable("missing purchase_exponent")?
.to_string(),
purchase_date: date_time::DateTime::<date_time::YYYYMMDDHHmmss>::from(date_time::now())
.to_string(),
sdk_app_id: sdk_information
.as_ref()
.map(|sdk_info| sdk_info.sdk_app_id.clone()),
sdk_enc_data: sdk_information
.as_ref()
.map(|sdk_info| sdk_info.sdk_enc_data.clone()),
sdk_ephem_pub_key: sdk_information
.as_ref()
.map(|sdk_info| sdk_info.sdk_ephem_pub_key.clone()),
sdk_reference_number: sdk_information
.as_ref()
.map(|sdk_info| sdk_info.sdk_reference_number.clone()),
sdk_trans_id: sdk_information
.as_ref()
.map(|sdk_info| sdk_info.sdk_trans_id.clone()),
sdk_max_timeout: sdk_information
.as_ref()
.map(|sdk_info| sdk_info.sdk_max_timeout.to_string()),
device_render_options: match request.device_channel {
DeviceChannel::App => Some(DeviceRenderOptions {
// SDK Interface types that the device supports for displaying specific challenge user interfaces within the SDK, 01 for Native
sdk_interface: "01".to_string(),
// UI types that the device supports for displaying specific challenge user interfaces within the SDK, 01 for Text
sdk_ui_type: vec!["01".to_string()],
}),
DeviceChannel::Browser => None,
},
cardholder_name: card_holder_name,
email: request.email.clone(),
})
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ThreedsecureioErrorResponse {
pub error_code: String,
pub error_component: Option<String>,
pub error_description: Option<String>,
pub error_detail: Option<String>,
pub error_message_type: Option<String>,
pub message_type: Option<String>,
pub message_version: Option<String>,
pub three_dsserver_trans_id: Option<String>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum ThreedsecureioErrorResponseWrapper {
ErrorResponse(ThreedsecureioErrorResponse),
ErrorString(String),
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ThreedsecureioAuthenticationResponse {
Success(Box<ThreedsecureioAuthenticationSuccessResponse>),
Error(Box<ThreedsecureioErrorResponseWrapper>),
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ThreedsecureioAuthenticationSuccessResponse {
#[serde(rename = "acsChallengeMandated")]
pub acs_challenge_mandated: Option<String>,
#[serde(rename = "acsOperatorID")]
pub acs_operator_id: Option<String>,
#[serde(rename = "acsReferenceNumber")]
pub acs_reference_number: String,
#[serde(rename = "acsTransID")]
pub acs_trans_id: String,
#[serde(rename = "acsURL")]
pub acs_url: Option<url::Url>,
#[serde(rename = "authenticationType")]
pub authentication_type: Option<String>,
#[serde(rename = "dsReferenceNumber")]
pub ds_reference_number: String,
#[serde(rename = "dsTransID")]
pub ds_trans_id: String,
#[serde(rename = "messageType")]
pub message_type: Option<String>,
#[serde(rename = "messageVersion")]
pub message_version: String,
#[serde(rename = "threeDSServerTransID")]
pub three_dsserver_trans_id: String,
#[serde(rename = "transStatus")]
pub trans_status: ThreedsecureioTransStatus,
#[serde(rename = "acsSignedContent")]
pub acs_signed_content: Option<String>,
#[serde(rename = "authenticationValue")]
pub authentication_value: Option<Secret<String>>,
}
#[derive(Debug, Serialize, Deserialize)]
pub enum ThreeDSecureIoThreeDsCompletionIndicator {
Y,
N,
U,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ThreedsecureioAuthenticationRequest {
pub ds_start_protocol_version: String,
pub ds_end_protocol_version: String,
pub acs_start_protocol_version: String,
pub acs_end_protocol_version: String,
pub three_dsserver_trans_id: String,
pub acct_number: cards::CardNumber,
pub notification_url: String,
pub three_dscomp_ind: ThreeDSecureIoThreeDsCompletionIndicator,
pub three_dsrequestor_url: String,
pub acquirer_bin: String,
pub acquirer_merchant_id: String,
pub card_expiry_date: String,
pub bill_addr_city: String,
pub bill_addr_country: Secret<String>,
pub bill_addr_line1: Secret<String>,
pub bill_addr_post_code: Secret<String>,
pub bill_addr_state: Secret<String>,
pub email: Option<common_utils::pii::Email>,
pub three_dsrequestor_authentication_ind: String,
pub cardholder_name: Option<Secret<String>>,
pub device_channel: String,
pub browser_javascript_enabled: Option<bool>,
pub browser_accept_header: Option<String>,
pub browser_ip: Option<Secret<String, common_utils::pii::IpAddress>>,
pub browser_java_enabled: Option<bool>,
pub browser_language: Option<String>,
pub browser_color_depth: Option<String>,
pub browser_screen_height: Option<String>,
pub browser_screen_width: Option<String>,
pub browser_tz: Option<String>,
pub browser_user_agent: Option<String>,
pub sdk_app_id: Option<String>,
pub sdk_enc_data: Option<String>,
pub sdk_ephem_pub_key: Option<std::collections::HashMap<String, String>>,
pub sdk_reference_number: Option<String>,
pub sdk_trans_id: Option<String>,
pub mcc: String,
pub merchant_country_code: String,
pub merchant_name: String,
pub message_category: String,
pub message_type: String,
pub message_version: String,
pub purchase_amount: String,
pub purchase_currency: String,
pub purchase_exponent: String,
pub purchase_date: String,
pub trans_type: String,
pub sdk_max_timeout: Option<String>,
pub device_render_options: Option<DeviceRenderOptions>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct ThreeDSecureIoMetaData {
pub mcc: String,
pub merchant_country_code: String,
pub merchant_name: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct ThreeDSecureIoConnectorMetaData {
pub ds_start_protocol_version: String,
pub ds_end_protocol_version: String,
pub acs_start_protocol_version: String,
pub acs_end_protocol_version: String,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DeviceRenderOptions {
pub sdk_interface: String,
pub sdk_ui_type: Vec<String>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ThreedsecureioPreAuthenticationRequest {
acct_number: cards::CardNumber,
ds: Option<DirectoryServer>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ThreedsecureioPostAuthenticationRequest {
pub three_ds_server_trans_id: String,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ThreedsecureioPostAuthenticationResponse {
pub authentication_value: Option<Secret<String>>,
pub trans_status: ThreedsecureioTransStatus,
pub eci: Option<String>,
}
#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)]
pub enum ThreedsecureioTransStatus {
/// Authentication/ Account Verification Successful
Y,
/// Not Authenticated /Account Not Verified; Transaction denied
N,
/// Authentication/ Account Verification Could Not Be Performed; Technical or other problem, as indicated in ARes or RReq
U,
/// Attempts Processing Performed; Not Authenticated/Verified , but a proof of attempted authentication/verification is provided
A,
/// Authentication/ Account Verification Rejected; Issuer is rejecting authentication/verification and request that authorisation not be attempted.
R,
C,
}
impl From<ThreeDsCompletionIndicator> for ThreeDSecureIoThreeDsCompletionIndicator {
fn from(value: ThreeDsCompletionIndicator) -> Self {
match value {
ThreeDsCompletionIndicator::Success => Self::Y,
ThreeDsCompletionIndicator::Failure => Self::N,
ThreeDsCompletionIndicator::NotAvailable => Self::U,
}
}
}
impl From<ThreedsecureioTransStatus> for common_enums::TransactionStatus {
fn from(value: ThreedsecureioTransStatus) -> Self {
match value {
ThreedsecureioTransStatus::Y => Self::Success,
ThreedsecureioTransStatus::N => Self::Failure,
ThreedsecureioTransStatus::U => Self::VerificationNotPerformed,
ThreedsecureioTransStatus::A => Self::NotVerified,
ThreedsecureioTransStatus::R => Self::Rejected,
ThreedsecureioTransStatus::C => Self::ChallengeRequired,
}
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum DirectoryServer {
Standin,
Visa,
Mastercard,
Jcb,
Upi,
Amex,
Protectbuy,
Sbn,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum ThreedsecureioPreAuthenticationResponse {
Success(Box<ThreedsecureioPreAuthenticationResponseData>),
Failure(Box<ThreedsecureioErrorResponse>),
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ThreedsecureioPreAuthenticationResponseData {
pub ds_start_protocol_version: String,
pub ds_end_protocol_version: String,
pub acs_start_protocol_version: String,
pub acs_end_protocol_version: String,
#[serde(rename = "threeDSMethodURL")]
pub threeds_method_url: Option<String>,
#[serde(rename = "threeDSServerTransID")]
pub threeds_server_trans_id: String,
pub scheme: Option<String>,
pub message_type: Option<String>,
}
impl TryFrom<&ThreedsecureioRouterData<&PreAuthNRouterData>>
for ThreedsecureioPreAuthenticationRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
value: &ThreedsecureioRouterData<&PreAuthNRouterData>,
) -> Result<Self, Self::Error> {
let router_data = value.router_data;
Ok(Self {
acct_number: router_data.request.card.card_number.clone(),
ds: None,
})
}
}
| 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/dlocal/transformers.rs | crates/hyperswitch_connectors/src/connectors/dlocal/transformers.rs | use common_enums::enums;
use common_utils::{pii::Email, request::Method, types::FloatMajorUnit};
use hyperswitch_domain_models::{
payment_method_data::{PaymentMethodData, VoucherData},
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 url::Url;
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{AddressDetailsData, PaymentsAuthorizeRequestData, RouterData as _},
};
#[derive(Debug, Default, Eq, PartialEq, Serialize)]
pub struct Payer {
pub name: Secret<String>,
pub email: Email,
pub document: Secret<String>,
}
#[derive(Debug, Default, Eq, Clone, PartialEq, Serialize, Deserialize)]
pub struct Card {
pub holder_name: Option<Secret<String>>,
pub number: cards::CardNumber,
pub cvv: Secret<String>,
pub expiration_month: Secret<String>,
pub expiration_year: Secret<String>,
pub capture: String,
}
#[derive(Debug, Default, Eq, PartialEq, Serialize)]
pub struct ThreeDSecureReqData {
pub force: bool,
}
#[derive(Debug, Serialize, Default, Deserialize, Clone, Eq, PartialEq)]
#[serde(rename_all = "UPPERCASE")]
pub enum PaymentMethodId {
#[default]
Card,
#[serde(rename = "OX")]
Oxxo,
}
#[derive(Debug, Serialize, Default, Deserialize, Clone, Eq, PartialEq)]
#[serde(rename_all = "UPPERCASE")]
pub enum PaymentMethodFlow {
#[default]
Direct,
ReDirect,
}
#[derive(Debug, Serialize)]
pub struct DlocalRouterData<T> {
pub amount: FloatMajorUnit,
pub router_data: T,
}
impl<T> TryFrom<(FloatMajorUnit, T)> for DlocalRouterData<T> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from((amount, router_data): (FloatMajorUnit, T)) -> Result<Self, Self::Error> {
Ok(Self {
amount,
router_data,
})
}
}
#[derive(Default, Debug, Serialize, PartialEq)]
pub struct DlocalPaymentsRequest {
pub amount: FloatMajorUnit,
pub currency: enums::Currency,
pub country: enums::CountryAlpha2,
pub payment_method_id: PaymentMethodId,
pub payment_method_flow: PaymentMethodFlow,
pub payer: Payer,
#[serde(skip_serializing_if = "Option::is_none")]
pub card: Option<Card>,
pub order_id: String,
pub three_dsecure: Option<ThreeDSecureReqData>,
pub callback_url: Option<String>,
pub description: Option<String>,
}
impl TryFrom<&DlocalRouterData<&types::PaymentsAuthorizeRouterData>> for DlocalPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &DlocalRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let email = item.router_data.request.get_email()?;
let address = item.router_data.get_billing_address()?;
let country = *address.get_country()?;
let name = address.get_full_name()?;
let amount = item.amount;
let payer = Payer {
name,
email,
// [#589]: Allow securely collecting PII from customer in payments request
document: get_doc_from_currency(country.to_string()),
};
let order_id = item.router_data.connector_request_reference_id.clone();
let callback_url = item.router_data.request.get_router_return_url()?;
let description = item.router_data.description.clone();
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(ref ccard) => {
let should_capture = matches!(
item.router_data.request.capture_method,
Some(enums::CaptureMethod::Automatic)
| Some(enums::CaptureMethod::SequentialAutomatic)
);
let payment_request = Self {
amount,
currency: item.router_data.request.currency,
payment_method_id: PaymentMethodId::Card,
payment_method_flow: PaymentMethodFlow::Direct,
country,
payer,
card: Some(Card {
holder_name: ccard.card_holder_name.clone(),
number: ccard.card_number.clone(),
cvv: ccard.card_cvc.clone(),
expiration_month: ccard.card_exp_month.clone(),
expiration_year: ccard.card_exp_year.clone(),
capture: should_capture.to_string(),
}),
order_id,
three_dsecure: match item.router_data.auth_type {
enums::AuthenticationType::ThreeDs => {
Some(ThreeDSecureReqData { force: true })
}
enums::AuthenticationType::NoThreeDs => None,
},
callback_url: Some(callback_url),
description,
};
Ok(payment_request)
}
PaymentMethodData::Voucher(voucher_data) => match voucher_data {
VoucherData::Oxxo => {
let payment_request = Self {
amount: item.amount,
currency: item.router_data.request.currency,
payment_method_id: PaymentMethodId::Oxxo,
payment_method_flow: PaymentMethodFlow::Direct,
country,
payer,
card: None,
order_id,
three_dsecure: None,
callback_url: Some(callback_url),
description,
};
Ok(payment_request)
}
_ => Err(errors::ConnectorError::NotImplemented(
crate::utils::get_unimplemented_payment_method_error_message("Dlocal"),
))?,
},
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::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
crate::utils::get_unimplemented_payment_method_error_message("Dlocal"),
))?
}
}
}
}
#[derive(Default, Debug, Serialize, PartialEq)]
pub struct DlocalPaymentsCaptureRequest {
pub authorization_id: String,
pub amount: FloatMajorUnit,
pub currency: String,
pub order_id: String,
}
impl TryFrom<&DlocalRouterData<&types::PaymentsCaptureRouterData>>
for DlocalPaymentsCaptureRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &DlocalRouterData<&types::PaymentsCaptureRouterData>,
) -> Result<Self, Self::Error> {
Ok(Self {
authorization_id: item.router_data.request.connector_transaction_id.clone(),
amount: item.amount,
currency: item.router_data.request.currency.to_string(),
order_id: item.router_data.connector_request_reference_id.clone(),
})
}
}
// Auth Struct
pub struct DlocalAuthType {
pub(super) x_login: Secret<String>,
pub(super) x_trans_key: Secret<String>,
pub(super) secret: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for DlocalAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
if let ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} = auth_type
{
Ok(Self {
x_login: api_key.to_owned(),
x_trans_key: key1.to_owned(),
secret: api_secret.to_owned(),
})
} else {
Err(errors::ConnectorError::FailedToObtainAuthType.into())
}
}
}
#[derive(Debug, Clone, Eq, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "UPPERCASE")]
pub enum DlocalPaymentStatus {
Authorized,
Paid,
Cancelled,
#[default]
Pending,
Rejected,
}
impl From<DlocalPaymentStatus> for enums::AttemptStatus {
fn from(item: DlocalPaymentStatus) -> Self {
match item {
DlocalPaymentStatus::Authorized => Self::Authorized,
DlocalPaymentStatus::Paid => Self::Charged,
DlocalPaymentStatus::Pending => Self::Pending,
DlocalPaymentStatus::Cancelled => Self::Voided,
DlocalPaymentStatus::Rejected => Self::Failure,
}
}
}
fn map_dlocal_status_to_attempt_status(
status: DlocalPaymentStatus,
has_redirect: bool,
) -> enums::AttemptStatus {
match status {
DlocalPaymentStatus::Authorized => enums::AttemptStatus::Authorized,
DlocalPaymentStatus::Paid => enums::AttemptStatus::Charged,
DlocalPaymentStatus::Cancelled => enums::AttemptStatus::Voided,
DlocalPaymentStatus::Rejected => enums::AttemptStatus::Failure,
DlocalPaymentStatus::Pending => {
if has_redirect {
enums::AttemptStatus::AuthenticationPending
} else {
enums::AttemptStatus::Pending
}
}
}
}
#[derive(Eq, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ThreeDSecureResData {
pub redirect_url: Option<Url>,
}
#[derive(Debug, Default, Eq, Clone, PartialEq, Serialize, Deserialize)]
pub struct DlocalPaymentsResponse {
status: DlocalPaymentStatus,
id: String,
three_dsecure: Option<ThreeDSecureResData>,
order_id: Option<String>,
ticket: Option<TicketData>,
}
#[derive(Eq, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct TicketData {
pub image_url: Option<Url>,
}
impl<F, T> TryFrom<ResponseRouterData<F, DlocalPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, DlocalPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let payment_method = item.data.payment_method;
let redirection_data = match payment_method {
enums::PaymentMethod::Card => item
.response
.three_dsecure
.and_then(|three_secure_data| three_secure_data.redirect_url)
.map(|redirect_url| RedirectForm::from((redirect_url, Method::Get))),
enums::PaymentMethod::Voucher => item
.response
.ticket
.and_then(|ticket_data| ticket_data.image_url)
.map(|image_url| RedirectForm::from((image_url, Method::Get))),
_ => None,
};
let response = PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: Box::new(redirection_data.clone()),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: item.response.order_id.clone(),
incremental_authorization_allowed: None,
charges: None,
};
let status =
map_dlocal_status_to_attempt_status(item.response.status, redirection_data.is_some());
Ok(Self {
status,
response: Ok(response),
..item.data
})
}
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct DlocalPaymentsSyncResponse {
status: DlocalPaymentStatus,
id: String,
order_id: Option<String>,
}
impl<F, T> TryFrom<ResponseRouterData<F, DlocalPaymentsSyncResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, DlocalPaymentsSyncResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: enums::AttemptStatus::from(item.response.status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: item.response.order_id.clone(),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct DlocalPaymentsCaptureResponse {
status: DlocalPaymentStatus,
id: String,
order_id: Option<String>,
}
impl<F, T> TryFrom<ResponseRouterData<F, DlocalPaymentsCaptureResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, DlocalPaymentsCaptureResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: enums::AttemptStatus::from(item.response.status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: item.response.order_id.clone(),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
pub struct DlocalPaymentsCancelResponse {
status: DlocalPaymentStatus,
order_id: String,
}
impl<F, T> TryFrom<ResponseRouterData<F, DlocalPaymentsCancelResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, DlocalPaymentsCancelResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: enums::AttemptStatus::from(item.response.status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.order_id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.order_id.clone()),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
// REFUND :
#[derive(Default, Debug, Serialize)]
pub struct DlocalRefundRequest {
pub amount: FloatMajorUnit,
pub payment_id: String,
pub currency: enums::Currency,
pub id: String,
}
impl<F> TryFrom<&DlocalRouterData<&types::RefundsRouterData<F>>> for DlocalRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &DlocalRouterData<&types::RefundsRouterData<F>>,
) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.amount,
payment_id: item.router_data.request.connector_transaction_id.clone(),
currency: item.router_data.request.currency,
id: item.router_data.request.refund_id.clone(),
})
}
}
#[allow(dead_code)]
#[derive(Debug, Serialize, Default, Deserialize, Clone)]
#[serde(rename_all = "UPPERCASE")]
pub enum RefundStatus {
Success,
#[default]
Pending,
Rejected,
Cancelled,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Success => Self::Success,
RefundStatus::Pending => Self::Pending,
RefundStatus::Rejected | RefundStatus::Cancelled => Self::Failure,
}
}
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct RefundResponse {
pub id: String,
pub status: RefundStatus,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>>
for types::RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
let refund_status = enums::RefundStatus::from(item.response.status);
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id,
refund_status,
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for types::RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
let refund_status = enums::RefundStatus::from(item.response.status);
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id,
refund_status,
}),
..item.data
})
}
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct DlocalErrorResponse {
pub code: i32,
pub message: String,
pub param: Option<String>,
}
fn get_doc_from_currency(country: String) -> Secret<String> {
let doc = match country.as_str() {
"BR" => "91483309223",
"ZA" => "2001014800086",
"BD" | "GT" | "HN" | "PK" | "SN" | "TH" => "1234567890001",
"CR" | "SV" | "VN" => "123456789",
"DO" | "NG" => "12345678901",
"EG" => "12345678901112",
"GH" | "ID" | "RW" | "UG" => "1234567890111123",
"IN" => "NHSTP6374G",
"CI" => "CA124356789",
"JP" | "MY" | "PH" => "123456789012",
"NI" => "1234567890111A",
"TZ" => "12345678912345678900",
"MX" => "1234567890",
_ => "12345678",
};
Secret::new(doc.to_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/worldline/transformers.rs | crates/hyperswitch_connectors/src/connectors/worldline/transformers.rs | use common_enums::enums::{AttemptStatus, BankNames, CaptureMethod, CountryAlpha2, Currency};
use common_utils::{pii::Email, request::Method};
use hyperswitch_domain_models::{
payment_method_data::{BankRedirectData, PaymentMethodData},
router_data::{ConnectorAuthType, RouterData},
router_flow_types::{
payments::Authorize,
refunds::{Execute, RSync},
},
router_request_types::{PaymentsAuthorizeData, ResponseId},
router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
types::{PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, RefundsRouterData},
};
use hyperswitch_interfaces::{api::CurrencyUnit, errors};
use masking::{PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use url::Url;
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{self, CardData, RouterData as RouterDataUtils},
};
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Card {
pub card_number: cards::CardNumber,
pub cardholder_name: Secret<String>,
pub cvv: Secret<String>,
pub expiry_date: Secret<String>,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct CardPaymentMethod {
pub card: Card,
pub requires_approval: bool,
pub payment_product_id: u16,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct AmountOfMoney {
pub amount: i64,
pub currency_code: String,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct References {
pub merchant_reference: String,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Order {
pub amount_of_money: AmountOfMoney,
pub customer: Customer,
pub references: References,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct BillingAddress {
pub city: Option<String>,
pub country_code: Option<CountryAlpha2>,
pub house_number: Option<Secret<String>>,
pub state: Option<Secret<String>>,
pub state_code: Option<Secret<String>>,
pub street: Option<Secret<String>>,
pub zip: Option<Secret<String>>,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ContactDetails {
pub email_address: Option<Email>,
pub mobile_phone_number: Option<Secret<String>>,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Customer {
pub billing_address: BillingAddress,
pub contact_details: Option<ContactDetails>,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Name {
pub first_name: Option<Secret<String>>,
pub surname: Option<Secret<String>>,
pub surname_prefix: Option<Secret<String>>,
pub title: Option<Secret<String>>,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Shipping {
pub city: Option<String>,
pub country_code: Option<CountryAlpha2>,
pub house_number: Option<Secret<String>>,
pub name: Option<Name>,
pub state: Option<Secret<String>>,
pub state_code: Option<String>,
pub street: Option<Secret<String>>,
pub zip: Option<Secret<String>>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum WorldlinePaymentMethod {
CardPaymentMethodSpecificInput(Box<CardPaymentMethod>),
RedirectPaymentMethodSpecificInput(Box<RedirectPaymentMethod>),
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RedirectPaymentMethod {
pub payment_product_id: u16,
pub redirection_data: RedirectionData,
#[serde(flatten)]
pub payment_method_specific_data: PaymentMethodSpecificData,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RedirectionData {
pub return_url: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum PaymentMethodSpecificData {
PaymentProduct816SpecificInput(Box<Giropay>),
PaymentProduct809SpecificInput(Box<Ideal>),
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Giropay {
pub bank_account_iban: BankAccountIban,
}
#[derive(Debug, Serialize)]
pub struct Ideal {
#[serde(rename = "issuerId")]
pub issuer_id: Option<WorldlineBic>,
}
#[derive(Debug, Serialize)]
pub enum WorldlineBic {
#[serde(rename = "ABNANL2A")]
Abnamro,
#[serde(rename = "ASNBNL21")]
Asn,
#[serde(rename = "FRBKNL2L")]
Friesland,
#[serde(rename = "KNABNL2H")]
Knab,
#[serde(rename = "RABONL2U")]
Rabobank,
#[serde(rename = "RBRBNL21")]
Regiobank,
#[serde(rename = "SNSBNL2A")]
Sns,
#[serde(rename = "TRIONL2U")]
Triodos,
#[serde(rename = "FVLBNL22")]
Vanlanschot,
#[serde(rename = "INGBNL2A")]
Ing,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BankAccountIban {
pub account_holder_name: Secret<String>,
pub iban: Option<Secret<String>>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentsRequest {
#[serde(flatten)]
pub payment_data: WorldlinePaymentMethod,
pub order: Order,
pub shipping: Option<Shipping>,
}
#[derive(Debug, Serialize)]
pub struct WorldlineRouterData<T> {
amount: i64,
router_data: T,
}
impl<T> TryFrom<(&CurrencyUnit, Currency, i64, T)> for WorldlineRouterData<T> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(_currency_unit, _currency, amount, item): (&CurrencyUnit, Currency, i64, T),
) -> Result<Self, Self::Error> {
Ok(Self {
amount,
router_data: item,
})
}
}
impl
TryFrom<
&WorldlineRouterData<&RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData>>,
> for PaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &WorldlineRouterData<
&RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData>,
>,
) -> Result<Self, Self::Error> {
let payment_data =
match &item.router_data.request.payment_method_data {
PaymentMethodData::Card(card) => {
let card_holder_name = item.router_data.get_optional_billing_full_name();
WorldlinePaymentMethod::CardPaymentMethodSpecificInput(Box::new(
make_card_request(&item.router_data.request, card, card_holder_name)?,
))
}
PaymentMethodData::BankRedirect(bank_redirect) => {
WorldlinePaymentMethod::RedirectPaymentMethodSpecificInput(Box::new(
make_bank_redirect_request(item.router_data, bank_redirect)?,
))
}
PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Wallet(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("worldline"),
))?
}
};
let billing_address = item.router_data.get_billing()?;
let customer = build_customer_info(billing_address, &item.router_data.request.email)?;
let order = Order {
amount_of_money: AmountOfMoney {
amount: item.amount,
currency_code: item.router_data.request.currency.to_string().to_uppercase(),
},
customer,
references: References {
merchant_reference: item.router_data.connector_request_reference_id.clone(),
},
};
let shipping = item
.router_data
.get_optional_shipping()
.and_then(|shipping| shipping.address.clone())
.map(Shipping::from);
Ok(Self {
payment_data,
order,
shipping,
})
}
}
#[derive(Clone, Debug, Eq, Hash, PartialEq, Deserialize, Serialize)]
pub enum Gateway {
Amex = 2,
Discover = 128,
MasterCard = 3,
Visa = 1,
}
impl TryFrom<utils::CardIssuer> for Gateway {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(issuer: utils::CardIssuer) -> Result<Self, Self::Error> {
match issuer {
utils::CardIssuer::AmericanExpress => Ok(Self::Amex),
utils::CardIssuer::Master => Ok(Self::MasterCard),
utils::CardIssuer::Discover => Ok(Self::Discover),
utils::CardIssuer::Visa => Ok(Self::Visa),
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("worldline"),
)
.into()),
}
}
}
impl TryFrom<&BankNames> for WorldlineBic {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(bank: &BankNames) -> Result<Self, Self::Error> {
match bank {
BankNames::AbnAmro => Ok(Self::Abnamro),
BankNames::AsnBank => Ok(Self::Asn),
BankNames::Ing => Ok(Self::Ing),
BankNames::Knab => Ok(Self::Knab),
BankNames::Rabobank => Ok(Self::Rabobank),
BankNames::Regiobank => Ok(Self::Regiobank),
BankNames::SnsBank => Ok(Self::Sns),
BankNames::TriodosBank => Ok(Self::Triodos),
BankNames::VanLanschot => Ok(Self::Vanlanschot),
BankNames::FrieslandBank => Ok(Self::Friesland),
_ => Err(errors::ConnectorError::FlowNotSupported {
flow: bank.to_string(),
connector: "Worldline".to_string(),
}
.into()),
}
}
}
fn make_card_request(
req: &PaymentsAuthorizeData,
ccard: &hyperswitch_domain_models::payment_method_data::Card,
card_holder_name: Option<Secret<String>>,
) -> Result<CardPaymentMethod, error_stack::Report<errors::ConnectorError>> {
let expiry_year = ccard.card_exp_year.peek();
let secret_value = format!(
"{}{}",
ccard.card_exp_month.peek(),
&expiry_year
.get(expiry_year.len() - 2..)
.ok_or(errors::ConnectorError::RequestEncodingFailed)?
);
let expiry_date: Secret<String> = Secret::new(secret_value);
let card = Card {
card_number: ccard.card_number.clone(),
cardholder_name: card_holder_name.unwrap_or(Secret::new("".to_string())),
cvv: ccard.card_cvc.clone(),
expiry_date,
};
#[allow(clippy::as_conversions)]
let payment_product_id = Gateway::try_from(ccard.get_card_issuer()?)? as u16;
let card_payment_method_specific_input = CardPaymentMethod {
card,
requires_approval: matches!(req.capture_method, Some(CaptureMethod::Manual)),
payment_product_id,
};
Ok(card_payment_method_specific_input)
}
fn make_bank_redirect_request(
req: &PaymentsAuthorizeRouterData,
bank_redirect: &BankRedirectData,
) -> Result<RedirectPaymentMethod, error_stack::Report<errors::ConnectorError>> {
let return_url = req.request.router_return_url.clone();
let redirection_data = RedirectionData { return_url };
let (payment_method_specific_data, payment_product_id) = match bank_redirect {
BankRedirectData::Giropay {
bank_account_iban, ..
} => (
{
PaymentMethodSpecificData::PaymentProduct816SpecificInput(Box::new(Giropay {
bank_account_iban: BankAccountIban {
account_holder_name: req.get_billing_full_name()?.to_owned(),
iban: bank_account_iban.clone(),
},
}))
},
816,
),
BankRedirectData::Ideal { bank_name, .. } => (
{
PaymentMethodSpecificData::PaymentProduct809SpecificInput(Box::new(Ideal {
issuer_id: bank_name
.map(|bank_name| WorldlineBic::try_from(&bank_name))
.transpose()?,
}))
},
809,
),
BankRedirectData::BancontactCard { .. }
| BankRedirectData::Bizum {}
| BankRedirectData::Blik { .. }
| BankRedirectData::Eft { .. }
| BankRedirectData::Eps { .. }
| BankRedirectData::Interac { .. }
| BankRedirectData::OnlineBankingCzechRepublic { .. }
| BankRedirectData::OnlineBankingFinland { .. }
| BankRedirectData::OnlineBankingPoland { .. }
| BankRedirectData::OnlineBankingSlovakia { .. }
| BankRedirectData::OpenBankingUk { .. }
| BankRedirectData::Przelewy24 { .. }
| BankRedirectData::Sofort { .. }
| BankRedirectData::Trustly { .. }
| BankRedirectData::OnlineBankingFpx { .. }
| BankRedirectData::OnlineBankingThailand { .. }
| BankRedirectData::LocalBankRedirect {}
| BankRedirectData::OpenBanking { .. } => {
return Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("worldline"),
)
.into())
}
};
Ok(RedirectPaymentMethod {
payment_product_id,
redirection_data,
payment_method_specific_data,
})
}
fn get_address(
billing: &hyperswitch_domain_models::address::Address,
) -> Option<(
&hyperswitch_domain_models::address::Address,
&hyperswitch_domain_models::address::AddressDetails,
)> {
let address = billing.address.as_ref()?;
address.country.as_ref()?;
Some((billing, address))
}
fn build_customer_info(
billing_address: &hyperswitch_domain_models::address::Address,
email: &Option<Email>,
) -> Result<Customer, error_stack::Report<errors::ConnectorError>> {
let (billing, address) =
get_address(billing_address).ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "billing.address.country",
})?;
let number_with_country_code = billing.phone.as_ref().and_then(|phone| {
phone.number.as_ref().and_then(|number| {
phone
.country_code
.as_ref()
.map(|cc| Secret::new(format!("{}{}", cc, number.peek())))
})
});
Ok(Customer {
billing_address: BillingAddress {
..address.clone().into()
},
contact_details: Some(ContactDetails {
mobile_phone_number: number_with_country_code,
email_address: email.clone(),
}),
})
}
impl From<hyperswitch_domain_models::address::AddressDetails> for BillingAddress {
fn from(value: hyperswitch_domain_models::address::AddressDetails) -> Self {
Self {
city: value.city,
country_code: value.country,
state: value.state,
zip: value.zip,
..Default::default()
}
}
}
impl From<hyperswitch_domain_models::address::AddressDetails> for Shipping {
fn from(value: hyperswitch_domain_models::address::AddressDetails) -> Self {
Self {
city: value.city,
country_code: value.country,
name: Some(Name {
first_name: value.first_name,
surname: value.last_name,
..Default::default()
}),
state: value.state,
zip: value.zip,
..Default::default()
}
}
}
pub struct WorldlineAuthType {
pub api_key: Secret<String>,
pub api_secret: Secret<String>,
pub merchant_account_id: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for WorldlineAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
if let ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} = auth_type
{
Ok(Self {
api_key: api_key.to_owned(),
api_secret: api_secret.to_owned(),
merchant_account_id: key1.to_owned(),
})
} else {
Err(errors::ConnectorError::FailedToObtainAuthType)?
}
}
}
#[derive(Debug, Clone, Default, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PaymentStatus {
Captured,
Paid,
ChargebackNotification,
Cancelled,
Rejected,
RejectedCapture,
PendingApproval,
CaptureRequested,
#[default]
Processing,
Created,
Redirected,
}
fn get_status(item: (PaymentStatus, CaptureMethod)) -> AttemptStatus {
let (status, capture_method) = item;
match status {
PaymentStatus::Captured | PaymentStatus::Paid | PaymentStatus::ChargebackNotification => {
AttemptStatus::Charged
}
PaymentStatus::Cancelled => AttemptStatus::Voided,
PaymentStatus::Rejected => AttemptStatus::Failure,
PaymentStatus::RejectedCapture => AttemptStatus::CaptureFailed,
PaymentStatus::CaptureRequested => {
if matches!(
capture_method,
CaptureMethod::Automatic | CaptureMethod::SequentialAutomatic
) {
AttemptStatus::Pending
} else {
AttemptStatus::CaptureInitiated
}
}
PaymentStatus::PendingApproval => AttemptStatus::Authorized,
PaymentStatus::Created => AttemptStatus::Started,
PaymentStatus::Redirected => AttemptStatus::AuthenticationPending,
_ => AttemptStatus::Pending,
}
}
/// capture_method is not part of response from connector.
/// This is used to decide payment status while converting connector response to RouterData.
/// To keep this try_from logic generic in case of AUTHORIZE, SYNC and CAPTURE flows capture_method will be set from RouterData request.
#[derive(Default, Debug, Clone, Deserialize, PartialEq, Serialize)]
pub struct Payment {
pub id: String,
pub status: PaymentStatus,
#[serde(skip_deserializing)]
pub capture_method: CaptureMethod,
}
impl<F, T> TryFrom<ResponseRouterData<F, Payment, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, Payment, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: get_status((item.response.status, item.response.capture_method)),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.id),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentResponse {
pub payment: Payment,
pub merchant_action: Option<MerchantAction>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MerchantAction {
pub redirect_data: RedirectData,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct RedirectData {
#[serde(rename = "redirectURL")]
pub redirect_url: Url,
}
impl<F, T> TryFrom<ResponseRouterData<F, PaymentResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, PaymentResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let redirection_data = item
.response
.merchant_action
.map(|action| action.redirect_data.redirect_url)
.map(|redirect_url| RedirectForm::from((redirect_url, Method::Get)));
Ok(Self {
status: get_status((
item.response.payment.status,
item.response.payment.capture_method,
)),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.payment.id.clone()),
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.payment.id),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Default, Debug, Serialize)]
pub struct ApproveRequest {}
impl TryFrom<&PaymentsCaptureRouterData> for ApproveRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(_item: &PaymentsCaptureRouterData) -> Result<Self, Self::Error> {
Ok(Self {})
}
}
#[derive(Default, Debug, Serialize)]
pub struct WorldlineRefundRequest {
amount_of_money: AmountOfMoney,
}
impl<F> TryFrom<&RefundsRouterData<F>> for WorldlineRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &RefundsRouterData<F>) -> Result<Self, Self::Error> {
Ok(Self {
amount_of_money: AmountOfMoney {
amount: item.request.refund_amount,
currency_code: item.request.currency.to_string(),
},
})
}
}
#[allow(dead_code)]
#[derive(Debug, Default, Deserialize, Clone, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum RefundStatus {
Cancelled,
Rejected,
Refunded,
#[default]
Processing,
}
impl From<RefundStatus> for common_enums::enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Refunded => Self::Success,
RefundStatus::Cancelled | RefundStatus::Rejected => Self::Failure,
RefundStatus::Processing => Self::Pending,
}
}
}
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
pub struct RefundResponse {
id: String,
status: RefundStatus,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
let refund_status = common_enums::enums::RefundStatus::from(item.response.status);
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.clone(),
refund_status,
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
let refund_status = common_enums::enums::RefundStatus::from(item.response.status);
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.clone(),
refund_status,
}),
..item.data
})
}
}
#[derive(Default, Debug, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Error {
pub code: Option<String>,
pub property_name: Option<String>,
pub message: Option<String>,
}
#[derive(Default, Debug, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ErrorResponse {
pub error_id: Option<String>,
pub errors: Vec<Error>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct WebhookBody {
pub api_version: Option<String>,
pub id: String,
pub created: String,
pub merchant_id: common_utils::id_type::MerchantId,
#[serde(rename = "type")]
pub event_type: WebhookEvent,
pub payment: Option<serde_json::Value>,
pub refund: Option<serde_json::Value>,
pub payout: Option<serde_json::Value>,
pub token: Option<serde_json::Value>,
}
#[derive(Debug, Deserialize)]
pub enum WebhookEvent {
#[serde(rename = "payment.rejected")]
Rejected,
#[serde(rename = "payment.rejected_capture")]
RejectedCapture,
#[serde(rename = "payment.paid")]
Paid,
#[serde(other)]
Unknown,
}
| 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/nexinets/transformers.rs | crates/hyperswitch_connectors/src/connectors/nexinets/transformers.rs | use base64::Engine;
use cards::CardNumber;
use common_enums::{enums, AttemptStatus};
use common_utils::{consts, errors::CustomResult, request::Method};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{
ApplePayWalletData, BankRedirectData, Card, PaymentMethodData, WalletData,
},
router_data::{ConnectorAuthType, RouterData},
router_flow_types::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{
MandateReference, PaymentsResponseData, RedirectForm, RefundsResponseData,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
RefundsRouterData,
},
};
use hyperswitch_interfaces::errors;
use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use url::Url;
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{
self, CardData, PaymentsAuthorizeRequestData, PaymentsCancelRequestData, WalletData as _,
},
};
pub mod nexinets_constants {
pub const MAX_PAYMENT_REFERENCE_ID_LENGTH: usize = 30;
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NexinetsPaymentsRequest {
initial_amount: i64,
currency: enums::Currency,
channel: NexinetsChannel,
product: NexinetsProduct,
payment: Option<NexinetsPaymentDetails>,
#[serde(rename = "async")]
nexinets_async: NexinetsAsyncDetails,
merchant_order_id: Option<String>,
}
#[derive(Debug, Serialize, Default)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum NexinetsChannel {
#[default]
Ecom,
}
#[derive(Default, Debug, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum NexinetsProduct {
#[default]
Creditcard,
Paypal,
Giropay,
Sofort,
Eps,
Ideal,
Applepay,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
#[serde(untagged)]
pub enum NexinetsPaymentDetails {
Card(Box<NexiCardDetails>),
Wallet(Box<NexinetsWalletDetails>),
BankRedirects(Box<NexinetsBankRedirects>),
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NexiCardDetails {
#[serde(flatten)]
card_data: CardDataDetails,
cof_contract: Option<CofContract>,
}
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum CardDataDetails {
CardDetails(Box<CardDetails>),
PaymentInstrument(Box<PaymentInstrument>),
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CardDetails {
card_number: CardNumber,
expiry_month: Secret<String>,
expiry_year: Secret<String>,
verification: Secret<String>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentInstrument {
payment_instrument_id: Option<Secret<String>>,
}
#[derive(Debug, Serialize)]
pub struct CofContract {
#[serde(rename = "type")]
recurring_type: RecurringType,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum RecurringType {
Unscheduled,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NexinetsBankRedirects {
bic: Option<NexinetsBIC>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NexinetsAsyncDetails {
pub success_url: Option<String>,
pub cancel_url: Option<String>,
pub failure_url: Option<String>,
}
#[derive(Debug, Serialize)]
pub enum NexinetsBIC {
#[serde(rename = "ABNANL2A")]
AbnAmro,
#[serde(rename = "ASNBNL21")]
AsnBank,
#[serde(rename = "BUNQNL2A")]
Bunq,
#[serde(rename = "INGBNL2A")]
Ing,
#[serde(rename = "KNABNL2H")]
Knab,
#[serde(rename = "RABONL2U")]
Rabobank,
#[serde(rename = "RBRBNL21")]
Regiobank,
#[serde(rename = "SNSBNL2A")]
SnsBank,
#[serde(rename = "TRIONL2U")]
TriodosBank,
#[serde(rename = "FVLBNL22")]
VanLanschot,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum NexinetsWalletDetails {
ApplePayToken(Box<ApplePayDetails>),
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ApplePayDetails {
payment_data: serde_json::Value,
payment_method: ApplepayPaymentMethod,
transaction_identifier: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ApplepayPaymentMethod {
display_name: String,
network: String,
#[serde(rename = "type")]
token_type: String,
}
impl TryFrom<&PaymentsAuthorizeRouterData> for NexinetsPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> {
let return_url = item.request.router_return_url.clone();
let nexinets_async = NexinetsAsyncDetails {
success_url: return_url.clone(),
cancel_url: return_url.clone(),
failure_url: return_url,
};
let (payment, product) = get_payment_details_and_product(item)?;
let merchant_order_id = match item.payment_method {
// Merchant order id is sent only in case of card payment
enums::PaymentMethod::Card => {
if item.connector_request_reference_id.len()
<= nexinets_constants::MAX_PAYMENT_REFERENCE_ID_LENGTH
{
Ok(Some(item.connector_request_reference_id.clone()))
} else {
Err(errors::ConnectorError::MaxFieldLengthViolated {
connector: "Nexinets".to_string(),
field_name: "merchant_order_id".to_string(),
max_length: nexinets_constants::MAX_PAYMENT_REFERENCE_ID_LENGTH,
received_length: item.connector_request_reference_id.len(),
})
}
}?,
_ => None,
};
Ok(Self {
initial_amount: item.request.amount,
currency: item.request.currency,
channel: NexinetsChannel::Ecom,
product,
payment,
nexinets_async,
merchant_order_id,
})
}
}
// Auth Struct
pub struct NexinetsAuthType {
pub(super) api_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for NexinetsAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::BodyKey { api_key, key1 } => {
let auth_key = format!("{}:{}", key1.peek(), api_key.peek());
let auth_header = format!("Basic {}", consts::BASE64_ENGINE.encode(auth_key));
Ok(Self {
api_key: Secret::new(auth_header),
})
}
_ => Err(errors::ConnectorError::FailedToObtainAuthType)?,
}
}
}
// PaymentsResponse
#[derive(Debug, Deserialize, Clone, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum NexinetsPaymentStatus {
Success,
Pending,
Ok,
Failure,
Declined,
InProgress,
Expired,
Aborted,
}
fn get_status(status: NexinetsPaymentStatus, method: NexinetsTransactionType) -> AttemptStatus {
match status {
NexinetsPaymentStatus::Success => match method {
NexinetsTransactionType::Preauth => AttemptStatus::Authorized,
NexinetsTransactionType::Debit | NexinetsTransactionType::Capture => {
AttemptStatus::Charged
}
NexinetsTransactionType::Cancel => AttemptStatus::Voided,
},
NexinetsPaymentStatus::Declined
| NexinetsPaymentStatus::Failure
| NexinetsPaymentStatus::Expired
| NexinetsPaymentStatus::Aborted => match method {
NexinetsTransactionType::Preauth => AttemptStatus::AuthorizationFailed,
NexinetsTransactionType::Debit | NexinetsTransactionType::Capture => {
AttemptStatus::CaptureFailed
}
NexinetsTransactionType::Cancel => AttemptStatus::VoidFailed,
},
NexinetsPaymentStatus::Ok => match method {
NexinetsTransactionType::Preauth => AttemptStatus::Authorized,
_ => AttemptStatus::Pending,
},
NexinetsPaymentStatus::Pending => AttemptStatus::AuthenticationPending,
NexinetsPaymentStatus::InProgress => AttemptStatus::Pending,
}
}
impl TryFrom<&enums::BankNames> for NexinetsBIC {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(bank: &enums::BankNames) -> Result<Self, Self::Error> {
match bank {
enums::BankNames::AbnAmro => Ok(Self::AbnAmro),
enums::BankNames::AsnBank => Ok(Self::AsnBank),
enums::BankNames::Bunq => Ok(Self::Bunq),
enums::BankNames::Ing => Ok(Self::Ing),
enums::BankNames::Knab => Ok(Self::Knab),
enums::BankNames::Rabobank => Ok(Self::Rabobank),
enums::BankNames::Regiobank => Ok(Self::Regiobank),
enums::BankNames::SnsBank => Ok(Self::SnsBank),
enums::BankNames::TriodosBank => Ok(Self::TriodosBank),
enums::BankNames::VanLanschot => Ok(Self::VanLanschot),
_ => Err(errors::ConnectorError::FlowNotSupported {
flow: bank.to_string(),
connector: "Nexinets".to_string(),
}
.into()),
}
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NexinetsPreAuthOrDebitResponse {
order_id: String,
transaction_type: NexinetsTransactionType,
transactions: Vec<NexinetsTransaction>,
payment_instrument: PaymentInstrument,
redirect_url: Option<Url>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NexinetsTransaction {
pub transaction_id: String,
#[serde(rename = "type")]
pub transaction_type: NexinetsTransactionType,
pub currency: enums::Currency,
pub status: NexinetsPaymentStatus,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum NexinetsTransactionType {
Preauth,
Debit,
Capture,
Cancel,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct NexinetsPaymentsMetadata {
pub transaction_id: Option<String>,
pub order_id: Option<String>,
pub psync_flow: NexinetsTransactionType,
}
impl<F, T> TryFrom<ResponseRouterData<F, NexinetsPreAuthOrDebitResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, NexinetsPreAuthOrDebitResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let transaction = match item.response.transactions.first() {
Some(order) => order,
_ => Err(errors::ConnectorError::ResponseHandlingFailed)?,
};
let connector_metadata = serde_json::to_value(NexinetsPaymentsMetadata {
transaction_id: Some(transaction.transaction_id.clone()),
order_id: Some(item.response.order_id.clone()),
psync_flow: item.response.transaction_type.clone(),
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)?;
let redirection_data = item
.response
.redirect_url
.map(|url| RedirectForm::from((url, Method::Get)));
let resource_id = match item.response.transaction_type.clone() {
NexinetsTransactionType::Preauth => ResponseId::NoResponseId,
NexinetsTransactionType::Debit => {
ResponseId::ConnectorTransactionId(transaction.transaction_id.clone())
}
_ => Err(errors::ConnectorError::ResponseHandlingFailed)?,
};
let mandate_reference = item
.response
.payment_instrument
.payment_instrument_id
.map(|id| MandateReference {
connector_mandate_id: Some(id.expose()),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
});
Ok(Self {
status: get_status(transaction.status.clone(), item.response.transaction_type),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id,
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(mandate_reference),
connector_metadata: Some(connector_metadata),
network_txn_id: None,
connector_response_reference_id: Some(item.response.order_id),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NexinetsCaptureOrVoidRequest {
pub initial_amount: i64,
pub currency: enums::Currency,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NexinetsOrder {
pub order_id: String,
}
impl TryFrom<&PaymentsCaptureRouterData> for NexinetsCaptureOrVoidRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsCaptureRouterData) -> Result<Self, Self::Error> {
Ok(Self {
initial_amount: item.request.amount_to_capture,
currency: item.request.currency,
})
}
}
impl TryFrom<&PaymentsCancelRouterData> for NexinetsCaptureOrVoidRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> {
Ok(Self {
initial_amount: item.request.get_amount()?,
currency: item.request.get_currency()?,
})
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NexinetsPaymentResponse {
pub transaction_id: String,
pub status: NexinetsPaymentStatus,
pub order: NexinetsOrder,
#[serde(rename = "type")]
pub transaction_type: NexinetsTransactionType,
}
impl<F, T> TryFrom<ResponseRouterData<F, NexinetsPaymentResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, NexinetsPaymentResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let transaction_id = Some(item.response.transaction_id.clone());
let connector_metadata = serde_json::to_value(NexinetsPaymentsMetadata {
transaction_id,
order_id: Some(item.response.order.order_id.clone()),
psync_flow: item.response.transaction_type.clone(),
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)?;
let resource_id = match item.response.transaction_type.clone() {
NexinetsTransactionType::Debit | NexinetsTransactionType::Capture => {
ResponseId::ConnectorTransactionId(item.response.transaction_id)
}
_ => ResponseId::NoResponseId,
};
Ok(Self {
status: get_status(item.response.status, item.response.transaction_type),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id,
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: Some(connector_metadata),
network_txn_id: None,
connector_response_reference_id: Some(item.response.order.order_id),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
// REFUND :
// Type definition for RefundRequest
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NexinetsRefundRequest {
pub initial_amount: i64,
pub currency: enums::Currency,
}
impl<F> TryFrom<&RefundsRouterData<F>> for NexinetsRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &RefundsRouterData<F>) -> Result<Self, Self::Error> {
Ok(Self {
initial_amount: item.request.refund_amount,
currency: item.request.currency,
})
}
}
// Type definition for Refund Response
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NexinetsRefundResponse {
pub transaction_id: String,
pub status: RefundStatus,
pub order: NexinetsOrder,
#[serde(rename = "type")]
pub transaction_type: RefundType,
}
#[allow(dead_code)]
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum RefundStatus {
Success,
Ok,
Failure,
Declined,
InProgress,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum RefundType {
Refund,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Success => Self::Success,
RefundStatus::Failure | RefundStatus::Declined => Self::Failure,
RefundStatus::InProgress | RefundStatus::Ok => Self::Pending,
}
}
}
impl TryFrom<RefundsResponseRouterData<Execute, NexinetsRefundResponse>>
for RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, NexinetsRefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.transaction_id,
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, NexinetsRefundResponse>>
for RefundsRouterData<RSync>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, NexinetsRefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.transaction_id,
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct NexinetsErrorResponse {
pub status: u16,
pub code: u16,
pub message: String,
pub errors: Vec<OrderErrorDetails>,
}
#[derive(Debug, Deserialize, Clone, Serialize)]
pub struct OrderErrorDetails {
pub code: u16,
pub message: String,
pub field: Option<String>,
}
fn get_payment_details_and_product(
item: &PaymentsAuthorizeRouterData,
) -> Result<
(Option<NexinetsPaymentDetails>, NexinetsProduct),
error_stack::Report<errors::ConnectorError>,
> {
match &item.request.payment_method_data {
PaymentMethodData::Card(card) => Ok((
Some(get_card_data(item, card)?),
NexinetsProduct::Creditcard,
)),
PaymentMethodData::Wallet(wallet) => Ok(get_wallet_details(wallet)?),
PaymentMethodData::BankRedirect(bank_redirect) => match bank_redirect {
BankRedirectData::Eps { .. } => Ok((None, NexinetsProduct::Eps)),
BankRedirectData::Giropay { .. } => Ok((None, NexinetsProduct::Giropay)),
BankRedirectData::Ideal { bank_name, .. } => Ok((
Some(NexinetsPaymentDetails::BankRedirects(Box::new(
NexinetsBankRedirects {
bic: bank_name
.map(|bank_name| NexinetsBIC::try_from(&bank_name))
.transpose()?,
},
))),
NexinetsProduct::Ideal,
)),
BankRedirectData::Sofort { .. } => Ok((None, NexinetsProduct::Sofort)),
BankRedirectData::BancontactCard { .. }
| BankRedirectData::Blik { .. }
| BankRedirectData::Bizum { .. }
| BankRedirectData::Eft { .. }
| BankRedirectData::Interac { .. }
| BankRedirectData::OnlineBankingCzechRepublic { .. }
| BankRedirectData::OnlineBankingFinland { .. }
| BankRedirectData::OnlineBankingPoland { .. }
| BankRedirectData::OnlineBankingSlovakia { .. }
| BankRedirectData::OpenBankingUk { .. }
| BankRedirectData::Przelewy24 { .. }
| BankRedirectData::Trustly { .. }
| BankRedirectData::OnlineBankingFpx { .. }
| BankRedirectData::OnlineBankingThailand { .. }
| BankRedirectData::LocalBankRedirect {}
| BankRedirectData::OpenBanking { .. } => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("nexinets"),
))?,
},
PaymentMethodData::CardRedirect(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("nexinets"),
))?
}
}
}
fn get_card_data(
item: &PaymentsAuthorizeRouterData,
card: &Card,
) -> Result<NexinetsPaymentDetails, errors::ConnectorError> {
let (card_data, cof_contract) = match item.request.is_mandate_payment() {
true => {
let card_data = match item.request.off_session {
Some(true) => CardDataDetails::PaymentInstrument(Box::new(PaymentInstrument {
payment_instrument_id: item.request.connector_mandate_id().map(Secret::new),
})),
_ => CardDataDetails::CardDetails(Box::new(get_card_details(card)?)),
};
let cof_contract = Some(CofContract {
recurring_type: RecurringType::Unscheduled,
});
(card_data, cof_contract)
}
false => (
CardDataDetails::CardDetails(Box::new(get_card_details(card)?)),
None,
),
};
Ok(NexinetsPaymentDetails::Card(Box::new(NexiCardDetails {
card_data,
cof_contract,
})))
}
fn get_applepay_details(
wallet_data: &WalletData,
applepay_data: &ApplePayWalletData,
) -> CustomResult<ApplePayDetails, errors::ConnectorError> {
let payment_data = WalletData::get_wallet_token_as_json(wallet_data, "Apple Pay".to_string())?;
Ok(ApplePayDetails {
payment_data,
payment_method: ApplepayPaymentMethod {
display_name: applepay_data.payment_method.display_name.to_owned(),
network: applepay_data.payment_method.network.to_owned(),
token_type: applepay_data.payment_method.pm_type.to_owned(),
},
transaction_identifier: applepay_data.transaction_identifier.to_owned(),
})
}
fn get_card_details(req_card: &Card) -> Result<CardDetails, errors::ConnectorError> {
Ok(CardDetails {
card_number: req_card.card_number.clone(),
expiry_month: req_card.card_exp_month.clone(),
expiry_year: req_card.get_card_expiry_year_2_digit()?,
verification: req_card.card_cvc.clone(),
})
}
fn get_wallet_details(
wallet: &WalletData,
) -> Result<
(Option<NexinetsPaymentDetails>, NexinetsProduct),
error_stack::Report<errors::ConnectorError>,
> {
match wallet {
WalletData::PaypalRedirect(_) => Ok((None, NexinetsProduct::Paypal)),
WalletData::ApplePay(applepay_data) => Ok((
Some(NexinetsPaymentDetails::Wallet(Box::new(
NexinetsWalletDetails::ApplePayToken(Box::new(get_applepay_details(
wallet,
applepay_data,
)?)),
))),
NexinetsProduct::Applepay,
)),
WalletData::AliPayQr(_)
| WalletData::AliPayRedirect(_)
| WalletData::AliPayHkRedirect(_)
| WalletData::AmazonPay(_)
| WalletData::AmazonPayRedirect(_)
| WalletData::Paysera(_)
| WalletData::Skrill(_)
| WalletData::BluecodeRedirect {}
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
| WalletData::GcashRedirect(_)
| WalletData::ApplePayRedirect(_)
| WalletData::ApplePayThirdPartySdk(_)
| WalletData::DanaRedirect { .. }
| WalletData::GooglePay(_)
| WalletData::GooglePayRedirect(_)
| WalletData::GooglePayThirdPartySdk(_)
| WalletData::MbWayRedirect(_)
| WalletData::MobilePayRedirect(_)
| WalletData::PaypalSdk(_)
| WalletData::Paze(_)
| WalletData::SamsungPay(_)
| WalletData::TwintRedirect { .. }
| WalletData::VippsRedirect { .. }
| WalletData::TouchNGoRedirect(_)
| WalletData::WeChatPayRedirect(_)
| WalletData::WeChatPayQr(_)
| WalletData::CashappQr(_)
| WalletData::SwishQr(_)
| WalletData::Mifinity(_)
| WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("nexinets"),
))?,
}
}
pub fn get_order_id(
meta: &NexinetsPaymentsMetadata,
) -> Result<String, error_stack::Report<errors::ConnectorError>> {
let order_id = meta.order_id.clone().ok_or(
errors::ConnectorError::MissingConnectorRelatedTransactionID {
id: "order_id".to_string(),
},
)?;
Ok(order_id)
}
pub fn get_transaction_id(
meta: &NexinetsPaymentsMetadata,
) -> Result<String, error_stack::Report<errors::ConnectorError>> {
let transaction_id = meta.transaction_id.clone().ok_or(
errors::ConnectorError::MissingConnectorRelatedTransactionID {
id: "transaction_id".to_string(),
},
)?;
Ok(transaction_id)
}
| 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/finix/transformers.rs | crates/hyperswitch_connectors/src/connectors/finix/transformers.rs | pub mod request;
pub mod response;
use api_models::{
payments::{MandateReferenceId, PaymentIdType},
webhooks::{IncomingWebhookEvent, RefundIdType},
};
use base64::Engine;
use common_enums::{
enums, AttemptStatus, CaptureMethod, CountryAlpha2, CountryAlpha3, DisputeStage,
};
use common_utils::{errors::CustomResult, types::MinorUnit};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{PaymentMethodData, WalletData},
router_data::{ConnectorAuthType, ErrorResponse, PaymentMethodToken, RouterData},
router_flow_types::{
self as flows,
refunds::{Execute, RSync},
Authorize, Capture,
},
router_request_types::{
ConnectorCustomerData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
PaymentsCaptureData, RefundsData, ResponseId, SetupMandateRequestData,
},
router_response_types::{
ConnectorCustomerResponseData, MandateReference, PaymentsResponseData, RefundsResponseData,
},
types::RefundsRouterData,
};
use hyperswitch_interfaces::{consts, disputes::DisputePayload, errors::ConnectorError};
use masking::{ExposeInterface, Secret};
pub use request::*;
pub use response::*;
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
unimplemented_payment_method,
utils::{
self, get_unimplemented_payment_method_error_message, AddressDetailsData, CardData,
RouterData as _,
},
};
pub struct FinixRouterData<'a, Flow, Req, Res> {
pub amount: MinorUnit,
pub router_data: &'a RouterData<Flow, Req, Res>,
pub merchant_id: Secret<String>,
pub merchant_identity_id: Secret<String>,
}
impl<'a, Flow, Req, Res> TryFrom<(MinorUnit, &'a RouterData<Flow, Req, Res>)>
for FinixRouterData<'a, Flow, Req, Res>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(value: (MinorUnit, &'a RouterData<Flow, Req, Res>)) -> Result<Self, Self::Error> {
let (amount, router_data) = value;
let auth = FinixAuthType::try_from(&router_data.connector_auth_type)?;
Ok(Self {
amount,
router_data,
merchant_id: auth.merchant_id,
merchant_identity_id: auth.merchant_identity_id,
})
}
}
impl
TryFrom<
&FinixRouterData<
'_,
flows::CreateConnectorCustomer,
ConnectorCustomerData,
PaymentsResponseData,
>,
> for FinixCreateIdentityRequest
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: &FinixRouterData<
'_,
flows::CreateConnectorCustomer,
ConnectorCustomerData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let customer_data: &ConnectorCustomerData = &item.router_data.request;
let personal_address = item.router_data.get_optional_billing().and_then(|address| {
let billing = address.address.as_ref();
billing.map(|billing_address| FinixAddress {
line1: billing_address.get_optional_line1(),
line2: billing_address.get_optional_line2(),
city: billing_address.get_optional_city(),
region: billing_address.get_optional_state(),
postal_code: billing_address.get_optional_zip(),
country: billing_address
.get_optional_country()
.map(CountryAlpha2::from_alpha2_to_alpha3),
})
});
let entity = FinixIdentityEntity {
phone: customer_data.phone.clone(),
first_name: item.router_data.get_optional_billing_first_name(),
last_name: item.router_data.get_optional_billing_last_name(),
email: item.router_data.get_optional_billing_email(),
personal_address,
};
Ok(Self {
entity,
tags: None,
identity_type: FinixIdentityType::PERSONAL,
})
}
}
impl<F, T> TryFrom<ResponseRouterData<F, FinixIdentityResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<F, FinixIdentityResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(PaymentsResponseData::ConnectorCustomerResponse(
ConnectorCustomerResponseData::new_with_customer_id(item.response.id),
)),
..item.data
})
}
}
impl TryFrom<&FinixRouterData<'_, Authorize, PaymentsAuthorizeData, PaymentsResponseData>>
for FinixPaymentsRequest
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: &FinixRouterData<'_, Authorize, PaymentsAuthorizeData, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
if matches!(
item.router_data.request.payment_method_data,
PaymentMethodData::Card(_)
) && matches!(
item.router_data.auth_type,
enums::AuthenticationType::ThreeDs
) {
return Err(ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("finix"),
)
.into());
}
let source =
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(_)
| PaymentMethodData::Wallet(WalletData::GooglePay(_))
| PaymentMethodData::Wallet(WalletData::ApplePay(_)) => {
let source = item.router_data.get_payment_method_token()?;
match source {
PaymentMethodToken::Token(token) => token,
PaymentMethodToken::ApplePayDecrypt(_) => Err(
unimplemented_payment_method!("Apple Pay", "Simplified", "finix"),
)?,
PaymentMethodToken::PazeDecrypt(_) => {
Err(unimplemented_payment_method!("Paze", "finix"))?
}
PaymentMethodToken::GooglePayDecrypt(_) => {
Err(unimplemented_payment_method!("Google Pay", "finix"))?
}
}
}
PaymentMethodData::MandatePayment => Secret::new(
item.router_data
.request
.mandate_id
.as_ref()
.and_then(|mandate_ids| {
mandate_ids
.mandate_reference_id
.as_ref()
.and_then(|mandate_ref_id| match mandate_ref_id {
MandateReferenceId::ConnectorMandateId(id) => {
id.get_connector_mandate_id()
}
_ => None,
})
})
.ok_or(ConnectorError::MissingConnectorMandateID)?,
),
_ => Err(ConnectorError::NotImplemented(
"Payment method not supported".to_string(),
))?,
};
let statement_descriptor = item
.router_data
.request
.billing_descriptor
.clone()
.and_then(|billing_descriptor| billing_descriptor.statement_descriptor);
Ok(Self {
amount: item.amount,
currency: item.router_data.request.currency,
source,
merchant: item.merchant_id.clone(),
idempotency_id: Some(item.router_data.connector_request_reference_id.clone()),
tags: None,
three_d_secure: None,
statement_descriptor,
})
}
}
impl TryFrom<&FinixRouterData<'_, Capture, PaymentsCaptureData, PaymentsResponseData>>
for FinixCaptureRequest
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: &FinixRouterData<'_, Capture, PaymentsCaptureData, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
capture_amount: item.router_data.request.minor_amount_to_capture,
})
}
}
fn get_token_request(
payment_method_data: PaymentMethodData,
merchant_identity_id: Secret<String>,
identity: String,
customer_name: Option<Secret<String>>,
) -> Result<FinixCreatePaymentInstrumentRequest, error_stack::Report<ConnectorError>> {
match &payment_method_data {
PaymentMethodData::Card(card_data) => {
Ok(FinixCreatePaymentInstrumentRequest {
instrument_type: FinixPaymentInstrumentType::PaymentCard,
name: card_data.card_holder_name.clone(),
number: Some(Secret::new(card_data.card_number.clone().get_card_no())),
security_code: Some(card_data.card_cvc.clone()),
expiration_month: Some(card_data.get_expiry_month_as_i8()?),
expiration_year: Some(card_data.get_expiry_year_as_4_digit_i32()?),
identity: identity.clone(), // This would come from a previously created identity
tags: None,
address: None,
card_brand: None, // Finix determines this from the card number
card_type: None, // Finix determines this from the card number
additional_data: None,
merchant_identity: None,
third_party_token: None,
})
}
PaymentMethodData::Wallet(wallet) => match wallet {
WalletData::GooglePay(google_pay_wallet_data) => {
let third_party_token = google_pay_wallet_data
.tokenization_data
.get_encrypted_google_pay_token()
.change_context(ConnectorError::MissingRequiredField {
field_name: "google_pay_token",
})?;
Ok(FinixCreatePaymentInstrumentRequest {
instrument_type: FinixPaymentInstrumentType::GOOGLEPAY,
name: customer_name.clone(),
identity: identity.clone(),
number: None,
security_code: None,
expiration_month: None,
expiration_year: None,
tags: None,
address: None,
card_brand: None,
card_type: None,
additional_data: None,
merchant_identity: Some(merchant_identity_id.clone()),
third_party_token: Some(Secret::new(third_party_token)),
})
}
WalletData::ApplePay(apple_pay_wallet_data) => {
let applepay_encrypt_data = apple_pay_wallet_data
.payment_data
.get_encrypted_apple_pay_payment_data_mandatory()
.change_context(ConnectorError::MissingRequiredField {
field_name: "Apple pay encrypted data",
})?;
let decoded_data = base64::prelude::BASE64_STANDARD
.decode(applepay_encrypt_data)
.change_context(ConnectorError::InvalidDataFormat {
field_name: "apple_pay_encrypted_data",
})?;
let apple_pay_token: FinixApplePayEncryptedData = serde_json::from_slice(
&decoded_data,
)
.change_context(ConnectorError::InvalidDataFormat {
field_name: "apple_pay_token_json",
})?;
let finix_token = FinixApplePayPaymentToken {
token: FinixApplePayToken {
payment_data: FinixApplePayEncryptedData {
data: apple_pay_token.data.clone(),
signature: apple_pay_token.signature.clone(),
header: FinixApplePayHeader {
public_key_hash: apple_pay_token.header.public_key_hash.clone(),
ephemeral_public_key: apple_pay_token
.header
.ephemeral_public_key
.clone(),
transaction_id: apple_pay_token.header.transaction_id.clone(),
},
version: apple_pay_token.version.clone(),
},
payment_method: FinixApplePayPaymentMethod {
display_name: Secret::new(
apple_pay_wallet_data.payment_method.display_name.clone(),
),
network: Secret::new(
apple_pay_wallet_data.payment_method.network.clone(),
),
method_type: Secret::new(
apple_pay_wallet_data.payment_method.pm_type.clone(),
),
},
transaction_identifier: apple_pay_wallet_data
.transaction_identifier
.clone(),
},
};
let third_party_token = serde_json::to_string(&finix_token).change_context(
ConnectorError::InvalidDataFormat {
field_name: "apple pay token",
},
)?;
Ok(FinixCreatePaymentInstrumentRequest {
instrument_type: FinixPaymentInstrumentType::ApplePay,
name: customer_name.clone(),
number: None,
security_code: None,
expiration_month: None,
expiration_year: None,
identity: identity.clone(),
tags: None,
address: None,
card_brand: None,
card_type: None,
additional_data: None,
merchant_identity: Some(merchant_identity_id.clone()),
third_party_token: Some(Secret::new(third_party_token)),
})
}
_ => Err(ConnectorError::NotImplemented(
"Payment method not supported for tokenization".to_string(),
)
.into()),
},
_ => Err(ConnectorError::NotImplemented(
"Payment method not supported for tokenization".to_string(),
)
.into()),
}
}
impl
TryFrom<
&FinixRouterData<
'_,
flows::PaymentMethodToken,
PaymentMethodTokenizationData,
PaymentsResponseData,
>,
> for FinixCreatePaymentInstrumentRequest
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: &FinixRouterData<
'_,
flows::PaymentMethodToken,
PaymentMethodTokenizationData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let tokenization_data: &PaymentMethodTokenizationData = &item.router_data.request;
get_token_request(
tokenization_data.payment_method_data.clone(),
item.merchant_identity_id.clone(),
item.router_data.get_connector_customer_id()?,
item.router_data.get_optional_billing_full_name(),
)
}
}
// Implement response handling for tokenization
impl<F, T> TryFrom<ResponseRouterData<F, FinixInstrumentResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<F, FinixInstrumentResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(PaymentsResponseData::TokenizationResponse {
token: item.response.id,
}),
..item.data
})
}
}
pub(crate) fn get_setup_mandate_router_data<Request>(
item: ResponseRouterData<
flows::SetupMandate,
FinixInstrumentResponse,
Request,
PaymentsResponseData,
>,
) -> Result<
RouterData<flows::SetupMandate, Request, PaymentsResponseData>,
error_stack::Report<ConnectorError>,
> {
Ok(RouterData {
status: AttemptStatus::Charged,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(Some(MandateReference {
connector_mandate_id: Some(item.response.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
})
}
//setup mandate
impl
TryFrom<
&FinixRouterData<'_, flows::SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
> for FinixCreatePaymentInstrumentRequest
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: &FinixRouterData<
'_,
flows::SetupMandate,
SetupMandateRequestData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let tokenization_data = &item.router_data.request;
get_token_request(
tokenization_data.payment_method_data.clone(),
item.merchant_identity_id.clone(),
item.router_data.get_connector_customer_id()?,
item.router_data.get_optional_billing_full_name(),
)
}
}
// Auth Struct
impl TryFrom<&ConnectorAuthType> for FinixAuthType {
type Error = error_stack::Report<ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::MultiAuthKey {
api_key,
key1,
api_secret,
key2,
} => Ok(Self {
finix_user_name: api_key.clone(),
finix_password: api_secret.clone(),
merchant_id: key1.clone(),
merchant_identity_id: key2.clone(),
}),
_ => Err(ConnectorError::FailedToObtainAuthType.into()),
}
}
}
fn get_attempt_status(state: FinixState, flow: FinixFlow, is_void: Option<bool>) -> AttemptStatus {
if is_void == Some(true) {
return match state {
FinixState::FAILED | FinixState::CANCELED | FinixState::UNKNOWN => {
AttemptStatus::VoidFailed
}
FinixState::PENDING => AttemptStatus::Voided,
FinixState::SUCCEEDED => AttemptStatus::Voided,
};
}
match (flow, state) {
(FinixFlow::Auth, FinixState::PENDING) => AttemptStatus::AuthenticationPending,
(FinixFlow::Auth, FinixState::SUCCEEDED) => AttemptStatus::Authorized,
(FinixFlow::Auth, FinixState::FAILED) => AttemptStatus::AuthorizationFailed,
(FinixFlow::Auth, FinixState::CANCELED) | (FinixFlow::Auth, FinixState::UNKNOWN) => {
AttemptStatus::AuthorizationFailed
}
(FinixFlow::Transfer, FinixState::PENDING) => AttemptStatus::Pending,
(FinixFlow::Transfer, FinixState::SUCCEEDED) => AttemptStatus::Charged,
(FinixFlow::Transfer, FinixState::FAILED)
| (FinixFlow::Transfer, FinixState::CANCELED)
| (FinixFlow::Transfer, FinixState::UNKNOWN) => AttemptStatus::Failure,
(FinixFlow::Capture, FinixState::PENDING) => AttemptStatus::Pending,
(FinixFlow::Capture, FinixState::SUCCEEDED) => AttemptStatus::Pending, // Psync with Transfer id can determine actuall success
(FinixFlow::Capture, FinixState::FAILED)
| (FinixFlow::Capture, FinixState::CANCELED)
| (FinixFlow::Capture, FinixState::UNKNOWN) => AttemptStatus::Failure,
}
}
pub(crate) fn get_finix_response<F, T>(
router_data: ResponseRouterData<F, FinixPaymentsResponse, T, PaymentsResponseData>,
finix_flow: FinixFlow,
) -> Result<RouterData<F, T, PaymentsResponseData>, error_stack::Report<ConnectorError>> {
let status = get_attempt_status(
router_data.response.state.clone(),
finix_flow,
router_data.response.is_void,
);
Ok(RouterData {
status,
response: if router_data.response.state.is_failure() {
Err(ErrorResponse {
code: router_data
.response
.failure_code
.unwrap_or(consts::NO_ERROR_CODE.to_string()),
message: router_data
.response
.messages
.map_or(consts::NO_ERROR_MESSAGE.to_string(), |msg| msg.join(",")),
reason: router_data.response.failure_message,
status_code: router_data.http_code,
attempt_status: Some(status),
connector_transaction_id: Some(router_data.response.id.clone()),
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
router_data
.response
.transfer
.unwrap_or(router_data.response.id),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(Some(MandateReference {
connector_mandate_id: router_data.response.source.map(|id| id.expose()),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
})),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
})
},
..router_data.data
})
}
impl<F> TryFrom<&FinixRouterData<'_, F, RefundsData, RefundsResponseData>>
for FinixCreateRefundRequest
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: &FinixRouterData<'_, F, RefundsData, RefundsResponseData>,
) -> Result<Self, Self::Error> {
let refund_amount = item.router_data.request.minor_refund_amount;
Ok(Self::new(refund_amount))
}
}
impl From<FinixState> for enums::RefundStatus {
fn from(item: FinixState) -> Self {
match item {
FinixState::PENDING => Self::Pending,
FinixState::SUCCEEDED => Self::Success,
FinixState::FAILED | FinixState::CANCELED | FinixState::UNKNOWN => Self::Failure,
}
}
}
impl TryFrom<RefundsResponseRouterData<Execute, FinixPaymentsResponse>>
for RefundsRouterData<Execute>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, FinixPaymentsResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.state),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, FinixPaymentsResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, FinixPaymentsResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.state),
}),
..item.data
})
}
}
impl FinixErrorResponse {
pub fn get_message(&self) -> String {
self.embedded
.as_ref()
.and_then(|embedded| embedded.errors.as_ref())
.and_then(|errors| errors.first())
.and_then(|error| error.message.clone())
.unwrap_or(consts::NO_ERROR_MESSAGE.to_string())
}
pub fn get_code(&self) -> String {
self.embedded
.as_ref()
.and_then(|embedded| embedded.errors.as_ref())
.and_then(|errors| errors.first())
.and_then(|error| error.code.clone())
.unwrap_or(consts::NO_ERROR_MESSAGE.to_string())
}
}
impl FinixWebhookBody {
pub fn get_webhook_object_reference_id(
&self,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, ConnectorError> {
match &self.webhook_embedded {
FinixEmbedded::Authorizations { authorizations } => {
let authorization = authorizations.get_first_event()?;
Ok(api_models::webhooks::ObjectReferenceId::PaymentId(
PaymentIdType::ConnectorTransactionId(authorization.id.to_string()),
))
}
FinixEmbedded::Transfers { transfers } => {
let transfer = transfers.get_first_event()?;
match transfer.payment_type {
Some(FinixPaymentType::REVERSAL) => {
Ok(api_models::webhooks::ObjectReferenceId::RefundId(
RefundIdType::ConnectorRefundId(transfer.id.to_string()),
))
}
// finix platform fee ignored
Some(FinixPaymentType::FEE) => {
Err(ConnectorError::WebhookEventTypeNotFound.into())
}
_ => Ok(api_models::webhooks::ObjectReferenceId::PaymentId(
PaymentIdType::ConnectorTransactionId(transfer.id.to_string()),
)),
}
}
FinixEmbedded::Disputes { disputes } => {
let dispute = disputes.get_first_event()?;
Ok(api_models::webhooks::ObjectReferenceId::PaymentId(
PaymentIdType::ConnectorTransactionId(dispute.transfer.to_string()),
))
}
}
}
pub fn get_webhook_event_type(&self) -> CustomResult<IncomingWebhookEvent, ConnectorError> {
match &self.webhook_embedded {
FinixEmbedded::Authorizations { authorizations } => {
let authorizations = authorizations.get_first_event()?;
if authorizations.is_void == Some(true) {
match authorizations.state {
FinixState::FAILED | FinixState::CANCELED | FinixState::UNKNOWN => {
Ok(IncomingWebhookEvent::PaymentIntentCancelFailure)
}
FinixState::PENDING => Ok(IncomingWebhookEvent::PaymentIntentProcessing),
FinixState::SUCCEEDED => Ok(IncomingWebhookEvent::PaymentIntentCancelled),
}
} else {
match authorizations.state {
FinixState::PENDING => Ok(IncomingWebhookEvent::PaymentIntentProcessing),
FinixState::SUCCEEDED => {
Ok(IncomingWebhookEvent::PaymentIntentAuthorizationSuccess)
}
FinixState::FAILED | FinixState::CANCELED | FinixState::UNKNOWN => {
Ok(IncomingWebhookEvent::PaymentIntentAuthorizationFailure)
}
}
}
}
FinixEmbedded::Transfers { transfers } => {
let transfers = transfers.get_first_event()?;
if transfers.payment_type == Some(FinixPaymentType::REVERSAL) {
match transfers.state {
FinixState::SUCCEEDED => Ok(IncomingWebhookEvent::RefundSuccess),
FinixState::PENDING => Ok(IncomingWebhookEvent::EventNotSupported),
FinixState::FAILED | FinixState::CANCELED | FinixState::UNKNOWN => {
Ok(IncomingWebhookEvent::RefundFailure)
}
}
} else {
match transfers.state {
FinixState::PENDING => Ok(IncomingWebhookEvent::PaymentIntentProcessing),
FinixState::SUCCEEDED => Ok(IncomingWebhookEvent::PaymentIntentSuccess),
FinixState::FAILED | FinixState::CANCELED | FinixState::UNKNOWN => {
Ok(IncomingWebhookEvent::PaymentIntentFailure)
}
}
}
}
FinixEmbedded::Disputes { disputes } => {
let dispute = disputes.get_first_event()?;
match dispute.state {
FinixDisputeState::PENDING => Ok(IncomingWebhookEvent::DisputeOpened),
FinixDisputeState::INQUIRY => Ok(IncomingWebhookEvent::DisputeChallenged),
FinixDisputeState::LOST => Ok(IncomingWebhookEvent::DisputeLost),
FinixDisputeState::WON => Ok(IncomingWebhookEvent::DisputeWon),
}
}
}
}
pub fn get_dispute_details(&self) -> CustomResult<DisputePayload, ConnectorError> {
match &self.webhook_embedded {
FinixEmbedded::Disputes { disputes } => {
let dispute = disputes.get_first_event()?;
let amount = utils::convert_amount(
super::Finix::new().amount_converter_webhooks,
dispute.amount,
dispute.currency,
)?;
Ok(DisputePayload {
amount,
currency: dispute.currency,
dispute_stage: DisputeStage::Dispute,
connector_status: dispute.state.to_string(),
connector_dispute_id: dispute.id,
connector_reason: dispute.reason,
connector_reason_code: None,
challenge_required_by: dispute.respond_by,
created_at: dispute.created_at,
updated_at: dispute.updated_at,
})
}
FinixEmbedded::Authorizations { .. } | FinixEmbedded::Transfers { .. } => {
Err(ConnectorError::ResponseDeserializationFailed)
.attach_printable("Expected Dispute webhooks, but found other webhooks")?
}
}
}
}
| 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/finix/transformers/response.rs | crates/hyperswitch_connectors/src/connectors/finix/transformers/response.rs | use std::collections::HashMap;
use common_enums::Currency;
use common_utils::types::MinorUnit;
use serde::{Deserialize, Serialize};
use strum::Display;
use time::PrimitiveDateTime;
use super::*;
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub struct FinixPaymentsResponse {
pub id: String,
pub created_at: Option<String>,
pub updated_at: Option<String>,
pub application: Option<Secret<String>>,
pub amount: MinorUnit,
pub captured_amount: Option<MinorUnit>,
pub currency: Currency,
pub is_void: Option<bool>,
pub source: Option<Secret<String>>,
pub state: FinixState,
pub failure_code: Option<String>,
pub messages: Option<Vec<String>>,
pub failure_message: Option<String>,
pub transfer: Option<String>,
pub tags: FinixTags,
#[serde(rename = "type")]
pub payment_type: Option<FinixPaymentType>,
// pub trace_id: String,
pub three_d_secure: Option<FinixThreeDSecure>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(untagged)]
pub enum FinixCombinedPaymentResponse {
SyncResponse(Box<FinixPaymentsResponse>),
WebhookResponse(Box<FinixEmbedded>),
}
impl FinixCombinedPaymentResponse {
pub fn get_payment_response(&self) -> Result<FinixPaymentsResponse, ConnectorError> {
match self {
Self::SyncResponse(txn_res) => Ok(*txn_res.clone()),
Self::WebhookResponse(webhook_res) => match webhook_res.as_ref() {
FinixEmbedded::Authorizations { authorizations } => {
authorizations.get_first_event()
}
FinixEmbedded::Transfers { transfers } => transfers.get_first_event(),
FinixEmbedded::Disputes { .. } => Err(ConnectorError::ResponseHandlingFailed),
},
}
}
}
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub struct FinixIdentityResponse {
pub id: String,
pub created_at: Option<String>,
pub updated_at: Option<String>,
pub application: Option<String>,
pub entity: Option<HashMap<String, serde_json::Value>>,
pub tags: Option<FinixTags>,
}
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub struct FinixInstrumentResponse {
pub id: String,
pub created_at: String,
pub updated_at: String,
pub application: String,
pub identity: Option<String>,
#[serde(rename = "type")]
pub instrument_type: FinixPaymentInstrumentType,
pub tags: Option<FinixTags>,
pub card_type: Option<FinixCardType>,
pub card_brand: Option<String>,
pub fingerprint: Option<String>,
pub address: Option<FinixAddress>,
pub name: Option<Secret<String>>,
pub currency: Option<Currency>,
pub enabled: bool,
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct FinixErrorResponse {
// pub status_code: u16,
pub total: Option<i64>,
#[serde(rename = "_embedded")]
pub embedded: Option<FinixErrorEmbedded>,
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct FinixErrorEmbedded {
pub errors: Option<Vec<FinixError>>,
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct FinixError {
// pub logref: Option<String>,
pub message: Option<String>,
pub code: Option<String>,
}
//------------------- WEBHOOKS
#[derive(Clone, Display, Debug, Serialize, Deserialize)]
pub enum FinixDisputeState {
INQUIRY,
PENDING,
LOST,
WON,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct FinixDisputes {
pub transfer: String,
pub reason: Option<String>,
pub amount: MinorUnit,
pub state: FinixDisputeState,
pub currency: Currency,
pub id: String,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub created_at: Option<PrimitiveDateTime>,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub updated_at: Option<PrimitiveDateTime>,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub respond_by: Option<PrimitiveDateTime>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct SingleEventType<T>(Vec<T>);
impl<T: Clone> SingleEventType<T> {
pub fn get_first_event(&self) -> Result<T, ConnectorError> {
self.0
.first()
.cloned()
.ok_or(ConnectorError::WebhookBodyDecodingFailed)
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum FinixEmbedded {
Authorizations {
authorizations: SingleEventType<FinixPaymentsResponse>,
},
Transfers {
transfers: SingleEventType<FinixPaymentsResponse>,
},
Disputes {
disputes: SingleEventType<FinixDisputes>,
},
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct FinixWebhookBody {
#[serde(rename = "type")]
pub webhook_type: String,
pub entity: String,
#[serde(rename = "_embedded")]
pub webhook_embedded: FinixEmbedded,
}
//--------------
#[derive(Debug, serde::Deserialize)]
pub struct FinixWebhookSignature {
pub timestamp: String,
pub sig: Vec<u8>,
}
| 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/finix/transformers/request.rs | crates/hyperswitch_connectors/src/connectors/finix/transformers/request.rs | use std::collections::HashMap;
use common_enums::Currency;
use common_utils::{pii::Email, types::MinorUnit};
use masking::Secret;
use serde::{Deserialize, Serialize};
use super::*;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FinixPaymentsRequest {
pub amount: MinorUnit,
pub currency: Currency,
pub source: Secret<String>,
pub merchant: Secret<String>,
pub tags: Option<FinixTags>,
pub three_d_secure: Option<FinixThreeDSecure>,
pub idempotency_id: Option<String>,
pub statement_descriptor: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FinixCaptureRequest {
pub capture_amount: MinorUnit,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FinixCancelRequest {
pub void_me: bool,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FinixCaptureAuthorizationRequest {
pub amount: Option<MinorUnit>,
pub tags: Option<FinixTags>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FinixCreateIdentityRequest {
pub entity: FinixIdentityEntity,
pub tags: Option<FinixTags>,
#[serde(rename = "type")]
pub identity_type: FinixIdentityType,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FinixIdentityEntity {
pub phone: Option<Secret<String>>,
pub first_name: Option<Secret<String>>,
pub last_name: Option<Secret<String>>,
pub email: Option<Email>,
pub personal_address: Option<FinixAddress>,
}
#[derive(Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct FinixApplePayPaymentToken {
pub token: FinixApplePayToken,
}
#[derive(Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FinixApplePayHeader {
pub public_key_hash: String,
pub ephemeral_public_key: String,
pub transaction_id: String,
}
#[derive(Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FinixApplePayEncryptedData {
pub data: Secret<String>,
pub signature: Secret<String>,
pub header: FinixApplePayHeader,
pub version: Secret<String>,
}
#[derive(Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FinixApplePayPaymentMethod {
pub display_name: Secret<String>,
pub network: Secret<String>,
#[serde(rename = "type")]
pub method_type: Secret<String>,
}
#[derive(Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FinixApplePayToken {
pub payment_data: FinixApplePayEncryptedData,
pub payment_method: FinixApplePayPaymentMethod,
pub transaction_identifier: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FinixCreatePaymentInstrumentRequest {
#[serde(rename = "type")]
pub instrument_type: FinixPaymentInstrumentType,
pub name: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub number: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub security_code: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub expiration_month: Option<Secret<i8>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub expiration_year: Option<Secret<i32>>,
pub identity: String,
pub tags: Option<FinixTags>,
pub address: Option<FinixAddress>,
pub card_brand: Option<String>,
pub card_type: Option<FinixCardType>,
pub additional_data: Option<HashMap<String, String>>,
pub merchant_identity: Option<Secret<String>>,
pub third_party_token: Option<Secret<String>>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FinixCreateRefundRequest {
pub refund_amount: MinorUnit,
}
impl FinixCreateRefundRequest {
pub fn new(refund_amount: MinorUnit) -> Self {
Self { refund_amount }
}
}
// ---------- COMMON ENUMS
#[derive(Debug, Clone)]
pub enum FinixId {
Auth(String),
Transfer(String),
}
impl From<String> for FinixId {
fn from(id: String) -> Self {
if id.starts_with("AU") {
Self::Auth(id)
} else if id.starts_with("TR") {
Self::Transfer(id)
} else {
// Default to Auth if the prefix doesn't match
Self::Auth(id)
}
}
}
impl std::fmt::Display for FinixId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Auth(id) => write!(f, "{}", id),
Self::Transfer(id) => write!(f, "{}", id),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum FinixState {
PENDING,
SUCCEEDED,
FAILED,
CANCELED,
#[serde(other)]
UNKNOWN,
// RETURNED
}
impl FinixState {
pub fn is_failure(&self) -> bool {
match self {
Self::PENDING | Self::SUCCEEDED => false,
Self::FAILED | Self::CANCELED | Self::UNKNOWN => true,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum FinixPaymentType {
DEBIT,
CREDIT,
REVERSAL,
FEE,
ADJUSTMENT,
DISPUTE,
RESERVE,
SETTLEMENT,
#[serde(other)]
UNKNOWN,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum FinixPaymentInstrumentType {
#[serde(rename = "PAYMENT_CARD")]
PaymentCard,
#[serde(rename = "GOOGLE_PAY")]
GOOGLEPAY,
#[serde(rename = "BANK_ACCOUNT")]
BankAccount,
#[serde(rename = "APPLE_PAY")]
ApplePay,
#[serde(other)]
Unknown,
}
/// Represents the type of a payment card.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum FinixCardType {
DEBIT,
CREDIT,
PREPAID,
#[serde(other)]
UNKNOWN,
}
/// 3D Secure authentication details.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FinixThreeDSecure {
pub authenticated: Option<bool>,
pub liability_shift: Option<Secret<String>>,
pub version: Option<String>,
pub eci: Option<Secret<String>>,
pub cavv: Option<Secret<String>>,
pub xid: Option<Secret<String>>,
}
/// Key-value pair tags.
pub type FinixTags = HashMap<String, String>;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FinixAddress {
pub line1: Option<Secret<String>>,
pub line2: Option<Secret<String>>,
pub city: Option<String>,
pub region: Option<Secret<String>>,
pub postal_code: Option<Secret<String>>,
pub country: Option<CountryAlpha3>,
}
/// The type of the business.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum FinixIdentityType {
PERSONAL,
}
pub enum FinixFlow {
Auth,
Transfer,
Capture,
}
impl FinixFlow {
pub fn get_flow_for_auth(capture_method: CaptureMethod) -> Self {
match capture_method {
CaptureMethod::SequentialAutomatic | CaptureMethod::Automatic => Self::Transfer,
CaptureMethod::Manual | CaptureMethod::ManualMultiple | CaptureMethod::Scheduled => {
Self::Auth
}
}
}
}
pub struct FinixAuthType {
pub finix_user_name: Secret<String>,
pub finix_password: Secret<String>,
pub merchant_id: Secret<String>,
pub merchant_identity_id: Secret<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/custombilling/transformers.rs | crates/hyperswitch_connectors/src/connectors/custombilling/transformers.rs | use common_enums::enums;
use common_utils::types::StringMinorUnit;
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::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 CustombillingRouterData<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 CustombillingRouterData<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 CustombillingPaymentsRequest {
amount: StringMinorUnit,
card: CustombillingCard,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct CustombillingCard {
number: cards::CardNumber,
expiry_month: Secret<String>,
expiry_year: Secret<String>,
cvc: Secret<String>,
complete: bool,
}
impl TryFrom<&CustombillingRouterData<&PaymentsAuthorizeRouterData>>
for CustombillingPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &CustombillingRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(req_card) => {
let card = CustombillingCard {
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()),
}
}
}
// PaymentsResponse
//TODO: Append the remaining status flags
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum CustombillingPaymentStatus {
Succeeded,
Failed,
#[default]
Processing,
}
impl From<CustombillingPaymentStatus> for common_enums::AttemptStatus {
fn from(item: CustombillingPaymentStatus) -> Self {
match item {
CustombillingPaymentStatus::Succeeded => Self::Charged,
CustombillingPaymentStatus::Failed => Self::Failure,
CustombillingPaymentStatus::Processing => Self::Authorizing,
}
}
}
//TODO: Fill the struct with respective fields
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct CustombillingPaymentsResponse {
status: CustombillingPaymentStatus,
id: String,
}
impl<F, T> TryFrom<ResponseRouterData<F, CustombillingPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, CustombillingPaymentsResponse, 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 CustombillingRefundRequest {
pub amount: StringMinorUnit,
}
impl<F> TryFrom<&CustombillingRouterData<&RefundsRouterData<F>>> for CustombillingRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &CustombillingRouterData<&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 CustombillingErrorResponse {
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/inespay/transformers.rs | crates/hyperswitch_connectors/src/connectors/inespay/transformers.rs | use common_enums::enums;
use common_utils::{
request::Method,
types::{MinorUnit, StringMinorUnit, StringMinorUnitForConnector},
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{BankDebitData, PaymentMethodData},
router_data::{ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
types::{PaymentsAuthorizeRouterData, RefundsRouterData},
};
use hyperswitch_interfaces::errors;
use masking::Secret;
use serde::{Deserialize, Serialize};
use url::Url;
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{self, PaymentsAuthorizeRequestData, RouterData as _},
};
pub struct InespayRouterData<T> {
pub amount: StringMinorUnit,
pub router_data: T,
}
impl<T> From<(StringMinorUnit, T)> for InespayRouterData<T> {
fn from((amount, item): (StringMinorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
#[derive(Default, Debug, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct InespayPaymentsRequest {
description: String,
amount: StringMinorUnit,
reference: String,
debtor_account: Option<Secret<String>>,
success_link_redirect: Option<String>,
notif_url: Option<String>,
}
impl TryFrom<&InespayRouterData<&PaymentsAuthorizeRouterData>> for InespayPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &InespayRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::BankDebit(BankDebitData::SepaBankDebit { iban, .. }) => {
let order_id = item.router_data.connector_request_reference_id.clone();
let webhook_url = item.router_data.request.get_webhook_url()?;
let return_url = item.router_data.request.get_router_return_url()?;
Ok(Self {
description: item.router_data.get_description()?,
amount: item.amount.clone(),
reference: order_id,
debtor_account: Some(iban),
success_link_redirect: Some(return_url),
notif_url: Some(webhook_url),
})
}
_ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()),
}
}
}
pub struct InespayAuthType {
pub(super) api_key: Secret<String>,
pub authorization: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for InespayAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
api_key: api_key.to_owned(),
authorization: key1.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct InespayPaymentsResponseData {
status: String,
status_desc: String,
single_payin_id: String,
single_payin_link: String,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum InespayPaymentsResponse {
InespayPaymentsData(InespayPaymentsResponseData),
InespayPaymentsError(InespayErrorResponse),
}
impl<F, T> TryFrom<ResponseRouterData<F, InespayPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, InespayPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let (status, response) = match item.response {
InespayPaymentsResponse::InespayPaymentsData(data) => {
let redirection_url = Url::parse(data.single_payin_link.as_str())
.change_context(errors::ConnectorError::ParsingFailed)?;
let redirection_data = RedirectForm::from((redirection_url, Method::Get));
(
common_enums::AttemptStatus::AuthenticationPending,
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
data.single_payin_id.clone(),
),
redirection_data: Box::new(Some(redirection_data)),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
)
}
InespayPaymentsResponse::InespayPaymentsError(data) => (
common_enums::AttemptStatus::Failure,
Err(ErrorResponse {
code: data.status.clone(),
message: data.status_desc.clone(),
reason: Some(data.status_desc.clone()),
attempt_status: None,
connector_transaction_id: None,
status_code: item.http_code,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
),
};
Ok(Self {
status,
response,
..item.data
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum InespayPSyncStatus {
Ok,
Created,
Opened,
BankSelected,
Initiated,
Pending,
Aborted,
Unfinished,
Rejected,
Cancelled,
PartiallyAccepted,
Failed,
Settled,
PartRefunded,
Refunded,
}
impl From<InespayPSyncStatus> for common_enums::AttemptStatus {
fn from(item: InespayPSyncStatus) -> Self {
match item {
InespayPSyncStatus::Ok | InespayPSyncStatus::Settled => Self::Charged,
InespayPSyncStatus::Created
| InespayPSyncStatus::Opened
| InespayPSyncStatus::BankSelected
| InespayPSyncStatus::Initiated
| InespayPSyncStatus::Pending
| InespayPSyncStatus::Unfinished
| InespayPSyncStatus::PartiallyAccepted => Self::AuthenticationPending,
InespayPSyncStatus::Aborted
| InespayPSyncStatus::Rejected
| InespayPSyncStatus::Cancelled
| InespayPSyncStatus::Failed => Self::Failure,
InespayPSyncStatus::PartRefunded | InespayPSyncStatus::Refunded => Self::AutoRefunded,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct InespayPSyncResponseData {
cod_status: InespayPSyncStatus,
status_desc: String,
single_payin_id: String,
single_payin_link: String,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum InespayPSyncResponse {
InespayPSyncData(InespayPSyncResponseData),
InespayPSyncWebhook(InespayPaymentWebhookData),
InespayPSyncError(InespayErrorResponse),
}
impl<F, T> TryFrom<ResponseRouterData<F, InespayPSyncResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, InespayPSyncResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
match item.response {
InespayPSyncResponse::InespayPSyncData(data) => {
let redirection_url = Url::parse(data.single_payin_link.as_str())
.change_context(errors::ConnectorError::ParsingFailed)?;
let redirection_data = RedirectForm::from((redirection_url, Method::Get));
Ok(Self {
status: common_enums::AttemptStatus::from(data.cod_status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
data.single_payin_id.clone(),
),
redirection_data: Box::new(Some(redirection_data)),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
InespayPSyncResponse::InespayPSyncWebhook(data) => {
let status = enums::AttemptStatus::from(data.cod_status);
Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
data.single_payin_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
InespayPSyncResponse::InespayPSyncError(data) => Ok(Self {
response: Err(ErrorResponse {
code: data.status.clone(),
message: data.status_desc.clone(),
reason: Some(data.status_desc.clone()),
attempt_status: None,
connector_transaction_id: None,
status_code: item.http_code,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
}),
}
}
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct InespayRefundRequest {
single_payin_id: String,
amount: Option<MinorUnit>,
}
impl<F> TryFrom<&InespayRouterData<&RefundsRouterData<F>>> for InespayRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &InespayRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
let amount = utils::convert_back_amount_to_minor_units(
&StringMinorUnitForConnector,
item.amount.to_owned(),
item.router_data.request.currency,
)?;
Ok(Self {
single_payin_id: item.router_data.request.connector_transaction_id.clone(),
amount: Some(amount),
})
}
}
#[derive(Debug, Serialize, Default, Deserialize, Clone, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum InespayRSyncStatus {
Confirmed,
#[default]
Pending,
Rejected,
Denied,
Reversed,
Mistake,
}
impl From<InespayRSyncStatus> for enums::RefundStatus {
fn from(item: InespayRSyncStatus) -> Self {
match item {
InespayRSyncStatus::Confirmed => Self::Success,
InespayRSyncStatus::Pending => Self::Pending,
InespayRSyncStatus::Rejected
| InespayRSyncStatus::Denied
| InespayRSyncStatus::Reversed
| InespayRSyncStatus::Mistake => Self::Failure,
}
}
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RefundsData {
status: String,
status_desc: String,
refund_id: String,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum InespayRefundsResponse {
InespayRefundsData(RefundsData),
InespayRefundsError(InespayErrorResponse),
}
impl TryFrom<RefundsResponseRouterData<Execute, InespayRefundsResponse>>
for RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, InespayRefundsResponse>,
) -> Result<Self, Self::Error> {
match item.response {
InespayRefundsResponse::InespayRefundsData(data) => Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: data.refund_id,
refund_status: enums::RefundStatus::Pending,
}),
..item.data
}),
InespayRefundsResponse::InespayRefundsError(data) => Ok(Self {
response: Err(ErrorResponse {
code: data.status.clone(),
message: data.status_desc.clone(),
reason: Some(data.status_desc.clone()),
attempt_status: None,
connector_transaction_id: None,
status_code: item.http_code,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..item.data
}),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct InespayRSyncResponseData {
cod_status: InespayRSyncStatus,
status_desc: String,
refund_id: String,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum InespayRSyncResponse {
InespayRSyncData(InespayRSyncResponseData),
InespayRSyncWebhook(InespayRefundWebhookData),
InespayRSyncError(InespayErrorResponse),
}
impl TryFrom<RefundsResponseRouterData<RSync, InespayRSyncResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, InespayRSyncResponse>,
) -> Result<Self, Self::Error> {
let response = match item.response {
InespayRSyncResponse::InespayRSyncData(data) => Ok(RefundsResponseData {
connector_refund_id: data.refund_id,
refund_status: enums::RefundStatus::from(data.cod_status),
}),
InespayRSyncResponse::InespayRSyncWebhook(data) => Ok(RefundsResponseData {
connector_refund_id: data.refund_id,
refund_status: enums::RefundStatus::from(data.cod_status),
}),
InespayRSyncResponse::InespayRSyncError(data) => Err(ErrorResponse {
code: data.status.clone(),
message: data.status_desc.clone(),
reason: Some(data.status_desc.clone()),
attempt_status: None,
connector_transaction_id: None,
status_code: item.http_code,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
};
Ok(Self {
response,
..item.data
})
}
}
#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
pub struct InespayPaymentWebhookData {
pub single_payin_id: String,
pub cod_status: InespayPSyncStatus,
pub description: String,
pub amount: MinorUnit,
pub reference: String,
pub creditor_account: Secret<String>,
pub debtor_name: Secret<String>,
pub debtor_account: Secret<String>,
pub custom_data: Option<String>,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
pub struct InespayRefundWebhookData {
pub refund_id: String,
pub simple_payin_id: String,
pub cod_status: InespayRSyncStatus,
pub description: String,
pub amount: MinorUnit,
pub reference: String,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(untagged)]
pub enum InespayWebhookEventData {
Payment(InespayPaymentWebhookData),
Refund(InespayRefundWebhookData),
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct InespayWebhookEvent {
pub data_return: String,
pub signature_data_return: String,
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct InespayErrorResponse {
pub status: String,
pub status_desc: String,
}
impl From<InespayWebhookEventData> for api_models::webhooks::IncomingWebhookEvent {
fn from(item: InespayWebhookEventData) -> Self {
match item {
InespayWebhookEventData::Payment(payment_data) => match payment_data.cod_status {
InespayPSyncStatus::Ok | InespayPSyncStatus::Settled => Self::PaymentIntentSuccess,
InespayPSyncStatus::Failed | InespayPSyncStatus::Rejected => {
Self::PaymentIntentFailure
}
InespayPSyncStatus::Created
| InespayPSyncStatus::Opened
| InespayPSyncStatus::BankSelected
| InespayPSyncStatus::Initiated
| InespayPSyncStatus::Pending
| InespayPSyncStatus::Unfinished
| InespayPSyncStatus::PartiallyAccepted => Self::PaymentIntentProcessing,
InespayPSyncStatus::Aborted
| InespayPSyncStatus::Cancelled
| InespayPSyncStatus::PartRefunded
| InespayPSyncStatus::Refunded => Self::EventNotSupported,
},
InespayWebhookEventData::Refund(refund_data) => match refund_data.cod_status {
InespayRSyncStatus::Confirmed => Self::RefundSuccess,
InespayRSyncStatus::Rejected
| InespayRSyncStatus::Denied
| InespayRSyncStatus::Reversed
| InespayRSyncStatus::Mistake => Self::RefundFailure,
InespayRSyncStatus::Pending => Self::EventNotSupported,
},
}
}
}
| 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/helcim/transformers.rs | crates/hyperswitch_connectors/src/connectors/helcim/transformers.rs | use common_enums::enums;
use common_utils::{
pii::{Email, IpAddress},
types::FloatMajorUnit,
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{Card, PaymentMethodData},
router_data::{ConnectorAuthType, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::{ResponseId, SetupMandateRequestData},
router_response_types::{PaymentsResponseData, RefundsResponseData},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsSyncRouterData, RefundsRouterData, SetupMandateRouterData,
},
};
use hyperswitch_interfaces::errors;
use masking::Secret;
use serde::{Deserialize, Serialize};
use crate::{
types::{
PaymentsCancelResponseRouterData, PaymentsCaptureResponseRouterData,
PaymentsResponseRouterData, PaymentsSyncResponseRouterData, RefundsResponseRouterData,
ResponseRouterData,
},
utils::{
self, AddressDetailsData, BrowserInformationData, CardData, PaymentsAuthorizeRequestData,
PaymentsCancelRequestData, PaymentsCaptureRequestData, PaymentsSetupMandateRequestData,
RefundsRequestData, RouterData as RouterDataUtils,
},
};
#[derive(Debug, Serialize)]
pub struct HelcimRouterData<T> {
pub amount: FloatMajorUnit,
pub router_data: T,
}
impl<T> TryFrom<(FloatMajorUnit, T)> for HelcimRouterData<T> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from((amount, item): (FloatMajorUnit, T)) -> Result<Self, Self::Error> {
Ok(Self {
amount,
router_data: item,
})
}
}
pub fn check_currency(
currency: enums::Currency,
) -> Result<enums::Currency, errors::ConnectorError> {
if currency == enums::Currency::USD {
Ok(currency)
} else {
Err(errors::ConnectorError::NotSupported {
message: format!("currency {currency} is not supported for this merchant account"),
connector: "Helcim",
})?
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct HelcimVerifyRequest {
currency: enums::Currency,
ip_address: Secret<String, IpAddress>,
card_data: HelcimCard,
billing_address: HelcimBillingAddress,
#[serde(skip_serializing_if = "Option::is_none")]
ecommerce: Option<bool>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct HelcimPaymentsRequest {
amount: FloatMajorUnit,
currency: enums::Currency,
ip_address: Secret<String, IpAddress>,
card_data: HelcimCard,
invoice: HelcimInvoice,
billing_address: HelcimBillingAddress,
//The ecommerce field is an optional field in Connector Helcim.
//Setting the ecommerce field to true activates the Helcim Fraud Defender.
#[serde(skip_serializing_if = "Option::is_none")]
ecommerce: Option<bool>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct HelcimBillingAddress {
name: Secret<String>,
street1: Secret<String>,
postal_code: Secret<String>,
#[serde(skip_serializing_if = "Option::is_none")]
street2: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
city: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
email: Option<Email>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct HelcimInvoice {
invoice_number: String,
line_items: Vec<HelcimLineItems>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct HelcimLineItems {
description: String,
quantity: u8,
price: FloatMajorUnit,
total: FloatMajorUnit,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct HelcimCard {
card_number: cards::CardNumber,
card_expiry: Secret<String>,
card_c_v_v: Secret<String>,
}
impl TryFrom<(&SetupMandateRouterData, &Card)> for HelcimVerifyRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(value: (&SetupMandateRouterData, &Card)) -> Result<Self, Self::Error> {
let (item, req_card) = value;
let card_data = HelcimCard {
card_expiry: req_card
.get_card_expiry_month_year_2_digit_with_delimiter("".to_string())?,
card_number: req_card.card_number.clone(),
card_c_v_v: req_card.card_cvc.clone(),
};
let req_address = item.get_billing_address()?.to_owned();
let billing_address = HelcimBillingAddress {
name: req_address.get_full_name()?,
street1: req_address.get_line1()?.to_owned(),
postal_code: req_address.get_zip()?.to_owned(),
street2: req_address.line2,
city: req_address.city,
email: item.request.email.clone(),
};
let ip_address = item.request.get_browser_info()?.get_ip_address()?;
let currency = check_currency(item.request.currency)?;
Ok(Self {
currency,
ip_address,
card_data,
billing_address,
ecommerce: None,
})
}
}
impl TryFrom<&SetupMandateRouterData> for HelcimVerifyRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &SetupMandateRouterData) -> Result<Self, Self::Error> {
match item.request.payment_method_data.clone() {
PaymentMethodData::Card(req_card) => Self::try_from((item, &req_card)),
PaymentMethodData::BankTransfer(_) => {
Err(errors::ConnectorError::NotImplemented("Payment Method".to_string()).into())
}
PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Wallet(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Helcim"),
))?
}
}
}
}
impl TryFrom<(&HelcimRouterData<&PaymentsAuthorizeRouterData>, &Card)> for HelcimPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
value: (&HelcimRouterData<&PaymentsAuthorizeRouterData>, &Card),
) -> Result<Self, Self::Error> {
let (item, req_card) = value;
if item.router_data.is_three_ds() {
Err(errors::ConnectorError::NotSupported {
message: "Cards 3DS".to_string(),
connector: "Helcim",
})?
}
let card_data = HelcimCard {
card_expiry: req_card
.get_card_expiry_month_year_2_digit_with_delimiter("".to_string())?,
card_number: req_card.card_number.clone(),
card_c_v_v: req_card.card_cvc.clone(),
};
let req_address = item
.router_data
.get_billing()?
.to_owned()
.address
.ok_or_else(utils::missing_field_err("billing.address"))?;
let billing_address = HelcimBillingAddress {
name: req_address.get_full_name()?,
street1: req_address.get_line1()?.to_owned(),
postal_code: req_address.get_zip()?.to_owned(),
street2: req_address.line2,
city: req_address.city,
email: item.router_data.request.email.clone(),
};
let ip_address = item
.router_data
.request
.get_browser_info()?
.get_ip_address()?;
let line_items = vec![
(HelcimLineItems {
description: item
.router_data
.description
.clone()
.unwrap_or("No Description".to_string()),
// By default quantity is set to 1 and price and total is set to amount because these three fields are required to generate an invoice.
quantity: 1,
price: item.amount,
total: item.amount,
}),
];
let invoice = HelcimInvoice {
invoice_number: item.router_data.connector_request_reference_id.clone(),
line_items,
};
let currency = check_currency(item.router_data.request.currency)?;
Ok(Self {
amount: item.amount,
currency,
ip_address,
card_data,
invoice,
billing_address,
ecommerce: None,
})
}
}
impl TryFrom<&HelcimRouterData<&PaymentsAuthorizeRouterData>> for HelcimPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &HelcimRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(req_card) => Self::try_from((item, &req_card)),
PaymentMethodData::BankTransfer(_) => {
Err(errors::ConnectorError::NotImplemented("Payment Method".to_string()).into())
}
PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Wallet(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Helcim"),
))?
}
}
}
}
// Auth Struct
pub struct HelcimAuthType {
pub(super) api_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for HelcimAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
api_key: api_key.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
// PaymentsResponse
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum HelcimPaymentStatus {
Approved,
Declined,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum HelcimTransactionType {
Purchase,
PreAuth,
Capture,
Verify,
Reverse,
}
impl From<HelcimPaymentsResponse> for enums::AttemptStatus {
fn from(item: HelcimPaymentsResponse) -> Self {
match item.transaction_type {
HelcimTransactionType::Purchase | HelcimTransactionType::Verify => match item.status {
HelcimPaymentStatus::Approved => Self::Charged,
HelcimPaymentStatus::Declined => Self::Failure,
},
HelcimTransactionType::PreAuth => match item.status {
HelcimPaymentStatus::Approved => Self::Authorized,
HelcimPaymentStatus::Declined => Self::AuthorizationFailed,
},
HelcimTransactionType::Capture => match item.status {
HelcimPaymentStatus::Approved => Self::Charged,
HelcimPaymentStatus::Declined => Self::CaptureFailed,
},
HelcimTransactionType::Reverse => match item.status {
HelcimPaymentStatus::Approved => Self::Voided,
HelcimPaymentStatus::Declined => Self::VoidFailed,
},
}
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct HelcimPaymentsResponse {
status: HelcimPaymentStatus,
transaction_id: u64,
invoice_number: Option<String>,
#[serde(rename = "type")]
transaction_type: HelcimTransactionType,
}
impl<F>
TryFrom<
ResponseRouterData<
F,
HelcimPaymentsResponse,
SetupMandateRequestData,
PaymentsResponseData,
>,
> for RouterData<F, SetupMandateRequestData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
HelcimPaymentsResponse,
SetupMandateRequestData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.transaction_id.to_string(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: item.response.invoice_number.clone(),
incremental_authorization_allowed: None,
charges: None,
}),
status: enums::AttemptStatus::from(item.response),
..item.data
})
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct HelcimMetaData {
pub preauth_transaction_id: u64,
}
impl TryFrom<PaymentsResponseRouterData<HelcimPaymentsResponse>> for PaymentsAuthorizeRouterData {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsResponseRouterData<HelcimPaymentsResponse>,
) -> Result<Self, Self::Error> {
//PreAuth Transaction ID is stored in connector metadata
//Initially resource_id is stored as NoResponseID for manual capture
//After Capture Transaction is completed it is updated to store the Capture ID
let resource_id = if item.data.request.is_auto_capture()? {
ResponseId::ConnectorTransactionId(item.response.transaction_id.to_string())
} else {
ResponseId::NoResponseId
};
let connector_metadata = if !item.data.request.is_auto_capture()? {
Some(serde_json::json!(HelcimMetaData {
preauth_transaction_id: item.response.transaction_id,
}))
} else {
None
};
Ok(Self {
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id,
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata,
network_txn_id: None,
connector_response_reference_id: item.response.invoice_number.clone(),
incremental_authorization_allowed: None,
charges: None,
}),
status: enums::AttemptStatus::from(item.response),
..item.data
})
}
}
// impl utils::MultipleCaptureSyncResponse for HelcimPaymentsResponse {
// fn get_connector_capture_id(&self) -> String {
// self.transaction_id.to_string()
// }
// fn get_capture_attempt_status(&self) -> diesel_models::enums::AttemptStatus {
// enums::AttemptStatus::from(self.to_owned())
// }
// fn is_capture_response(&self) -> bool {
// true
// }
// fn get_amount_captured(&self) -> Option<i64> {
// Some(self.amount)
// }
// fn get_connector_reference_id(&self) -> Option<String> {
// None
// }
// }
impl TryFrom<PaymentsSyncResponseRouterData<HelcimPaymentsResponse>> for PaymentsSyncRouterData {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsSyncResponseRouterData<HelcimPaymentsResponse>,
) -> Result<Self, Self::Error> {
match item.data.request.sync_type {
hyperswitch_domain_models::router_request_types::SyncRequestType::SinglePaymentSync => Ok(Self {
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.transaction_id.to_string(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: item.response.invoice_number.clone(),
incremental_authorization_allowed: None,
charges: None,
}),
status: enums::AttemptStatus::from(item.response),
..item.data
}),
hyperswitch_domain_models::router_request_types::SyncRequestType::MultipleCaptureSync(_) => {
Err(errors::ConnectorError::NotImplemented(
"manual multiple capture sync".to_string(),
)
.into())
// let capture_sync_response_list =
// utils::construct_captures_response_hashmap(vec![item.response]);
// Ok(Self {
// response: Ok(PaymentsResponseData::MultipleCaptureResponse {
// capture_sync_response_list,
// }),
// ..item.data
// })
}
}
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct HelcimCaptureRequest {
pre_auth_transaction_id: u64,
amount: FloatMajorUnit,
ip_address: Secret<String, IpAddress>,
#[serde(skip_serializing_if = "Option::is_none")]
ecommerce: Option<bool>,
}
impl TryFrom<&HelcimRouterData<&PaymentsCaptureRouterData>> for HelcimCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &HelcimRouterData<&PaymentsCaptureRouterData>) -> Result<Self, Self::Error> {
let ip_address = item
.router_data
.request
.get_browser_info()?
.get_ip_address()?;
Ok(Self {
pre_auth_transaction_id: item
.router_data
.request
.connector_transaction_id
.parse::<u64>()
.change_context(errors::ConnectorError::RequestEncodingFailed)?,
amount: item.amount,
ip_address,
ecommerce: None,
})
}
}
impl TryFrom<PaymentsCaptureResponseRouterData<HelcimPaymentsResponse>>
for PaymentsCaptureRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsCaptureResponseRouterData<HelcimPaymentsResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.transaction_id.to_string(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: item.response.invoice_number.clone(),
incremental_authorization_allowed: None,
charges: None,
}),
status: enums::AttemptStatus::from(item.response),
..item.data
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct HelcimVoidRequest {
card_transaction_id: u64,
ip_address: Secret<String, IpAddress>,
#[serde(skip_serializing_if = "Option::is_none")]
ecommerce: Option<bool>,
}
impl TryFrom<&PaymentsCancelRouterData> for HelcimVoidRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> {
let ip_address = item.request.get_browser_info()?.get_ip_address()?;
Ok(Self {
card_transaction_id: item
.request
.connector_transaction_id
.parse::<u64>()
.change_context(errors::ConnectorError::RequestEncodingFailed)?,
ip_address,
ecommerce: None,
})
}
}
impl TryFrom<PaymentsCancelResponseRouterData<HelcimPaymentsResponse>>
for PaymentsCancelRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsCancelResponseRouterData<HelcimPaymentsResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.transaction_id.to_string(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: item.response.invoice_number.clone(),
incremental_authorization_allowed: None,
charges: None,
}),
status: enums::AttemptStatus::from(item.response),
..item.data
})
}
}
// REFUND :
// Type definition for RefundRequest
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct HelcimRefundRequest {
amount: FloatMajorUnit,
original_transaction_id: u64,
ip_address: Secret<String, IpAddress>,
#[serde(skip_serializing_if = "Option::is_none")]
ecommerce: Option<bool>,
}
impl<F> TryFrom<&HelcimRouterData<&RefundsRouterData<F>>> for HelcimRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &HelcimRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
let original_transaction_id = item
.router_data
.request
.connector_transaction_id
.parse::<u64>()
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
let ip_address = item
.router_data
.request
.get_browser_info()?
.get_ip_address()?;
Ok(Self {
amount: item.amount,
original_transaction_id,
ip_address,
ecommerce: None,
})
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum HelcimRefundTransactionType {
Refund,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RefundResponse {
status: HelcimPaymentStatus,
transaction_id: u64,
#[serde(rename = "type")]
transaction_type: HelcimRefundTransactionType,
}
impl From<RefundResponse> for enums::RefundStatus {
fn from(item: RefundResponse) -> Self {
match item.transaction_type {
HelcimRefundTransactionType::Refund => match item.status {
HelcimPaymentStatus::Approved => Self::Success,
HelcimPaymentStatus::Declined => Self::Failure,
},
}
}
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.transaction_id.to_string(),
refund_status: enums::RefundStatus::from(item.response),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.transaction_id.to_string(),
refund_status: enums::RefundStatus::from(item.response),
}),
..item.data
})
}
}
#[derive(Debug, strum::Display, Deserialize, Serialize)]
#[serde(untagged)]
pub enum HelcimErrorTypes {
StringType(String),
JsonType(serde_json::Value),
}
#[derive(Debug, Deserialize, Serialize)]
pub struct HelcimPaymentsErrorResponse {
pub errors: HelcimErrorTypes,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum HelcimErrorResponse {
Payment(HelcimPaymentsErrorResponse),
General(String),
}
| 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/billwerk/transformers.rs | crates/hyperswitch_connectors/src/connectors/billwerk/transformers.rs | use common_enums::enums;
use common_utils::{
id_type,
pii::{Email, SecretSerdeValue},
types::MinorUnit,
};
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{ConnectorAuthType, ErrorResponse, PaymentMethodToken, RouterData},
router_flow_types::{
payments,
refunds::{Execute, RSync},
},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RefundsResponseData},
types,
};
use hyperswitch_interfaces::{
consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE},
errors,
};
use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{self, CardData as _, PaymentsAuthorizeRequestData, RouterData as _},
};
pub struct BillwerkRouterData<T> {
pub amount: MinorUnit,
pub router_data: T,
}
impl<T> TryFrom<(MinorUnit, T)> for BillwerkRouterData<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 struct BillwerkAuthType {
pub(super) api_key: Secret<String>,
pub(super) public_api_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for BillwerkAuthType {
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(),
public_api_key: key1.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum BillwerkTokenRequestIntent {
ChargeAndStore,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum BillwerkStrongAuthRule {
UseScaIfAvailableAuth,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BillwerkTokenRequest {
number: cards::CardNumber,
month: Secret<String>,
year: Secret<String>,
cvv: Secret<String>,
pkey: Secret<String>,
recurring: Option<bool>,
intent: Option<BillwerkTokenRequestIntent>,
strong_authentication_rule: Option<BillwerkStrongAuthRule>,
}
impl TryFrom<&types::TokenizationRouterData> for BillwerkTokenRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::TokenizationRouterData) -> Result<Self, Self::Error> {
match item.request.payment_method_data.clone() {
PaymentMethodData::Card(ccard) => {
let connector_auth = &item.connector_auth_type;
let auth_type = BillwerkAuthType::try_from(connector_auth)?;
Ok(Self {
number: ccard.card_number.clone(),
month: ccard.card_exp_month.clone(),
year: ccard.get_card_expiry_year_2_digit()?,
cvv: ccard.card_cvc,
pkey: auth_type.public_api_key,
recurring: None,
intent: None,
strong_authentication_rule: None,
})
}
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::NotImplemented(
utils::get_unimplemented_payment_method_error_message("billwerk"),
)
.into())
}
}
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct BillwerkTokenResponse {
id: Secret<String>,
recurring: Option<bool>,
}
impl<T>
TryFrom<
ResponseRouterData<
payments::PaymentMethodToken,
BillwerkTokenResponse,
T,
PaymentsResponseData,
>,
> for RouterData<payments::PaymentMethodToken, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
payments::PaymentMethodToken,
BillwerkTokenResponse,
T,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(PaymentsResponseData::TokenizationResponse {
token: item.response.id.expose(),
}),
..item.data
})
}
}
#[derive(Debug, Serialize)]
pub struct BillwerkCustomerObject {
handle: Option<id_type::CustomerId>,
email: Option<Email>,
address: Option<Secret<String>>,
address2: Option<Secret<String>>,
city: Option<String>,
country: Option<common_enums::CountryAlpha2>,
first_name: Option<Secret<String>>,
last_name: Option<Secret<String>>,
}
#[derive(Debug, Serialize)]
pub struct BillwerkPaymentsRequest {
handle: String,
amount: MinorUnit,
source: Secret<String>,
currency: common_enums::Currency,
customer: BillwerkCustomerObject,
metadata: Option<SecretSerdeValue>,
settle: bool,
}
impl TryFrom<&BillwerkRouterData<&types::PaymentsAuthorizeRouterData>> for BillwerkPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &BillwerkRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
if item.router_data.is_three_ds() {
return Err(errors::ConnectorError::NotImplemented(
"Three_ds payments through Billwerk".to_string(),
)
.into());
};
let source = match item.router_data.get_payment_method_token()? {
PaymentMethodToken::Token(pm_token) => Ok(pm_token),
_ => Err(errors::ConnectorError::MissingRequiredField {
field_name: "payment_method_token",
}),
}?;
Ok(Self {
handle: item.router_data.connector_request_reference_id.clone(),
amount: item.amount,
source,
currency: item.router_data.request.currency,
customer: BillwerkCustomerObject {
handle: item.router_data.customer_id.clone(),
email: item.router_data.request.email.clone(),
address: item.router_data.get_optional_billing_line1(),
address2: item.router_data.get_optional_billing_line2(),
city: item.router_data.get_optional_billing_city(),
country: item.router_data.get_optional_billing_country(),
first_name: item.router_data.get_optional_billing_first_name(),
last_name: item.router_data.get_optional_billing_last_name(),
},
metadata: item.router_data.request.metadata.clone().map(Into::into),
settle: item.router_data.request.is_auto_capture()?,
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum BillwerkPaymentState {
Created,
Authorized,
Pending,
Settled,
Failed,
Cancelled,
}
impl From<BillwerkPaymentState> for enums::AttemptStatus {
fn from(item: BillwerkPaymentState) -> Self {
match item {
BillwerkPaymentState::Created | BillwerkPaymentState::Pending => Self::Pending,
BillwerkPaymentState::Authorized => Self::Authorized,
BillwerkPaymentState::Settled => Self::Charged,
BillwerkPaymentState::Failed => Self::Failure,
BillwerkPaymentState::Cancelled => Self::Voided,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct BillwerkPaymentsResponse {
state: BillwerkPaymentState,
handle: String,
error: Option<String>,
error_state: Option<String>,
}
impl<F, T> TryFrom<ResponseRouterData<F, BillwerkPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, BillwerkPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let error_response = if item.response.error.is_some() || item.response.error_state.is_some()
{
Some(ErrorResponse {
code: item
.response
.error_state
.clone()
.unwrap_or(NO_ERROR_CODE.to_string()),
message: item
.response
.error_state
.unwrap_or(NO_ERROR_MESSAGE.to_string()),
reason: item.response.error,
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(item.response.handle.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
None
};
let payments_response = PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.handle.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.handle),
incremental_authorization_allowed: None,
charges: None,
};
Ok(Self {
status: enums::AttemptStatus::from(item.response.state),
response: error_response.map_or_else(|| Ok(payments_response), Err),
..item.data
})
}
}
#[derive(Debug, Serialize)]
pub struct BillwerkCaptureRequest {
amount: MinorUnit,
}
impl TryFrom<&BillwerkRouterData<&types::PaymentsCaptureRouterData>> for BillwerkCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &BillwerkRouterData<&types::PaymentsCaptureRouterData>,
) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.amount,
})
}
}
// Type definition for RefundRequest
#[derive(Debug, Serialize)]
pub struct BillwerkRefundRequest {
pub invoice: String,
pub amount: MinorUnit,
pub text: Option<String>,
}
impl<F> TryFrom<&BillwerkRouterData<&types::RefundsRouterData<F>>> for BillwerkRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &BillwerkRouterData<&types::RefundsRouterData<F>>,
) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.amount,
invoice: item.router_data.request.connector_transaction_id.clone(),
text: item.router_data.request.reason.clone(),
})
}
}
// Type definition for Refund Response
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum RefundState {
Refunded,
Failed,
Processing,
}
impl From<RefundState> for enums::RefundStatus {
fn from(item: RefundState) -> Self {
match item {
RefundState::Refunded => Self::Success,
RefundState::Failed => Self::Failure,
RefundState::Processing => Self::Pending,
}
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct RefundResponse {
id: String,
state: RefundState,
}
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.state),
}),
..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.state),
}),
..item.data
})
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct BillwerkErrorResponse {
pub code: Option<i32>,
pub error: String,
pub 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/payeezy/transformers.rs | crates/hyperswitch_connectors/src/connectors/payeezy/transformers.rs | use cards::CardNumber;
use common_enums::{enums, AttemptStatus, CaptureMethod, Currency, PaymentMethod};
use common_utils::{errors::ParsingError, ext_traits::Encode};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{ConnectorAuthType, RouterData},
router_flow_types::Execute,
router_request_types::ResponseId,
router_response_types::{MandateReference, PaymentsResponseData, RefundsResponseData},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
RefundsRouterData,
},
};
use hyperswitch_interfaces::{api::CurrencyUnit, errors::ConnectorError};
use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{
get_amount_as_string, get_unimplemented_payment_method_error_message, to_connector_meta,
CardData, CardIssuer, RouterData as _,
},
};
#[derive(Debug, Serialize)]
pub struct PayeezyRouterData<T> {
pub amount: String,
pub router_data: T,
}
impl<T> TryFrom<(&CurrencyUnit, Currency, i64, T)> for PayeezyRouterData<T> {
type Error = error_stack::Report<ConnectorError>;
fn try_from(
(currency_unit, currency, amount, router_data): (&CurrencyUnit, Currency, i64, T),
) -> Result<Self, Self::Error> {
let amount = get_amount_as_string(currency_unit, amount, currency)?;
Ok(Self {
amount,
router_data,
})
}
}
#[derive(Serialize, Debug)]
pub struct PayeezyCard {
#[serde(rename = "type")]
pub card_type: PayeezyCardType,
pub cardholder_name: Secret<String>,
pub card_number: CardNumber,
pub exp_date: Secret<String>,
pub cvv: Secret<String>,
}
#[derive(Serialize, Debug)]
pub enum PayeezyCardType {
#[serde(rename = "American Express")]
AmericanExpress,
Visa,
Mastercard,
Discover,
}
impl TryFrom<CardIssuer> for PayeezyCardType {
type Error = error_stack::Report<ConnectorError>;
fn try_from(issuer: CardIssuer) -> Result<Self, Self::Error> {
match issuer {
CardIssuer::AmericanExpress => Ok(Self::AmericanExpress),
CardIssuer::Master => Ok(Self::Mastercard),
CardIssuer::Discover => Ok(Self::Discover),
CardIssuer::Visa => Ok(Self::Visa),
CardIssuer::Maestro
| CardIssuer::DinersClub
| CardIssuer::JCB
| CardIssuer::CarteBlanche
| CardIssuer::UnionPay
| CardIssuer::CartesBancaires => Err(ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("Payeezy"),
))?,
}
}
}
#[derive(Serialize, Debug)]
#[serde(untagged)]
pub enum PayeezyPaymentMethod {
PayeezyCard(PayeezyCard),
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PayeezyPaymentMethodType {
CreditCard,
}
#[derive(Serialize, Debug)]
pub struct PayeezyPaymentsRequest {
pub merchant_ref: String,
pub transaction_type: PayeezyTransactionType,
pub method: PayeezyPaymentMethodType,
pub amount: String,
pub currency_code: String,
pub credit_card: PayeezyPaymentMethod,
pub stored_credentials: Option<StoredCredentials>,
pub reference: String,
}
#[derive(Serialize, Debug)]
pub struct StoredCredentials {
pub sequence: Sequence,
pub initiator: Initiator,
pub is_scheduled: bool,
pub cardbrand_original_transaction_id: Option<Secret<String>>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum Sequence {
First,
Subsequent,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum Initiator {
Merchant,
CardHolder,
}
impl TryFrom<&PayeezyRouterData<&PaymentsAuthorizeRouterData>> for PayeezyPaymentsRequest {
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: &PayeezyRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.payment_method {
PaymentMethod::Card => get_card_specific_payment_data(item),
PaymentMethod::CardRedirect
| PaymentMethod::PayLater
| PaymentMethod::Wallet
| PaymentMethod::BankRedirect
| PaymentMethod::BankTransfer
| PaymentMethod::Crypto
| PaymentMethod::BankDebit
| PaymentMethod::Reward
| PaymentMethod::RealTimePayment
| PaymentMethod::MobilePayment
| PaymentMethod::Upi
| PaymentMethod::Voucher
| PaymentMethod::OpenBanking
| PaymentMethod::GiftCard
| PaymentMethod::NetworkToken => {
Err(ConnectorError::NotImplemented("Payment methods".to_string()).into())
}
}
}
}
fn get_card_specific_payment_data(
item: &PayeezyRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<PayeezyPaymentsRequest, error_stack::Report<ConnectorError>> {
let merchant_ref = item.router_data.attempt_id.to_string();
let method = PayeezyPaymentMethodType::CreditCard;
let amount = item.amount.clone();
let currency_code = item.router_data.request.currency.to_string();
let credit_card = get_payment_method_data(item)?;
let (transaction_type, stored_credentials) =
get_transaction_type_and_stored_creds(item.router_data)?;
Ok(PayeezyPaymentsRequest {
merchant_ref,
transaction_type,
method,
amount,
currency_code,
credit_card,
stored_credentials,
reference: item.router_data.connector_request_reference_id.clone(),
})
}
fn get_transaction_type_and_stored_creds(
item: &PaymentsAuthorizeRouterData,
) -> Result<(PayeezyTransactionType, Option<StoredCredentials>), error_stack::Report<ConnectorError>>
{
let connector_mandate_id = item.request.mandate_id.as_ref().and_then(|mandate_ids| {
match mandate_ids.mandate_reference_id.clone() {
Some(api_models::payments::MandateReferenceId::ConnectorMandateId(
connector_mandate_ids,
)) => connector_mandate_ids.get_connector_mandate_id(),
_ => None,
}
});
let (transaction_type, stored_credentials) =
if is_mandate_payment(item, connector_mandate_id.as_ref()) {
// Mandate payment
(
PayeezyTransactionType::Recurring,
Some(StoredCredentials {
// connector_mandate_id is not present then it is a First payment, else it is a Subsequent mandate payment
sequence: match connector_mandate_id.is_some() {
true => Sequence::Subsequent,
false => Sequence::First,
},
// off_session true denotes the customer not present during the checkout process. In other cases customer present at the checkout.
initiator: match item.request.off_session {
Some(true) => Initiator::Merchant,
_ => Initiator::CardHolder,
},
is_scheduled: true,
// In case of first mandate payment connector_mandate_id would be None, otherwise holds some value
cardbrand_original_transaction_id: connector_mandate_id.map(Secret::new),
}),
)
} else {
match item.request.capture_method {
Some(CaptureMethod::Manual) => Ok((PayeezyTransactionType::Authorize, None)),
Some(CaptureMethod::SequentialAutomatic) | Some(CaptureMethod::Automatic) => {
Ok((PayeezyTransactionType::Purchase, None))
}
Some(CaptureMethod::ManualMultiple) | Some(CaptureMethod::Scheduled) | None => {
Err(ConnectorError::FlowNotSupported {
flow: item.request.capture_method.unwrap_or_default().to_string(),
connector: "Payeezy".to_string(),
})
}
}?
};
Ok((transaction_type, stored_credentials))
}
fn is_mandate_payment(
item: &PaymentsAuthorizeRouterData,
connector_mandate_id: Option<&String>,
) -> bool {
item.request.setup_mandate_details.is_some() || connector_mandate_id.is_some()
}
fn get_payment_method_data(
item: &PayeezyRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<PayeezyPaymentMethod, error_stack::Report<ConnectorError>> {
match item.router_data.request.payment_method_data {
PaymentMethodData::Card(ref card) => {
let card_type = PayeezyCardType::try_from(card.get_card_issuer()?)?;
let payeezy_card = PayeezyCard {
card_type,
cardholder_name: item
.router_data
.get_optional_billing_full_name()
.unwrap_or(Secret::new("".to_string())),
card_number: card.card_number.clone(),
exp_date: card.get_card_expiry_month_year_2_digit_with_delimiter("".to_string())?,
cvv: card.card_cvc.clone(),
};
Ok(PayeezyPaymentMethod::PayeezyCard(payeezy_card))
}
PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Wallet(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => {
Err(ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("Payeezy"),
))?
}
}
}
// Auth Struct
pub struct PayeezyAuthType {
pub(super) api_key: Secret<String>,
pub(super) api_secret: Secret<String>,
pub(super) merchant_token: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for PayeezyAuthType {
type Error = error_stack::Report<ConnectorError>;
fn try_from(item: &ConnectorAuthType) -> Result<Self, Self::Error> {
if let ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} = item
{
Ok(Self {
api_key: api_key.to_owned(),
api_secret: api_secret.to_owned(),
merchant_token: key1.to_owned(),
})
} else {
Err(ConnectorError::FailedToObtainAuthType.into())
}
}
}
// PaymentsResponse
#[derive(Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum PayeezyPaymentStatus {
Approved,
Declined,
#[default]
#[serde(rename = "Not Processed")]
NotProcessed,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct PayeezyPaymentsResponse {
pub correlation_id: String,
pub transaction_status: PayeezyPaymentStatus,
pub validation_status: String,
pub transaction_type: PayeezyTransactionType,
pub transaction_id: String,
pub transaction_tag: Option<String>,
pub method: Option<String>,
pub amount: String,
pub currency: String,
pub bank_resp_code: String,
pub bank_message: String,
pub gateway_resp_code: String,
pub gateway_message: String,
pub stored_credentials: Option<PaymentsStoredCredentials>,
pub reference: Option<String>,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct PaymentsStoredCredentials {
cardbrand_original_transaction_id: Secret<String>,
}
#[derive(Debug, Serialize)]
pub struct PayeezyCaptureOrVoidRequest {
transaction_tag: String,
transaction_type: PayeezyTransactionType,
amount: String,
currency_code: String,
}
impl TryFrom<&PayeezyRouterData<&PaymentsCaptureRouterData>> for PayeezyCaptureOrVoidRequest {
type Error = error_stack::Report<ConnectorError>;
fn try_from(item: &PayeezyRouterData<&PaymentsCaptureRouterData>) -> Result<Self, Self::Error> {
let metadata: PayeezyPaymentsMetadata =
to_connector_meta(item.router_data.request.connector_meta.clone())
.change_context(ConnectorError::RequestEncodingFailed)?;
Ok(Self {
transaction_type: PayeezyTransactionType::Capture,
amount: item.amount.clone(),
currency_code: item.router_data.request.currency.to_string(),
transaction_tag: metadata.transaction_tag,
})
}
}
impl TryFrom<&PaymentsCancelRouterData> for PayeezyCaptureOrVoidRequest {
type Error = error_stack::Report<ConnectorError>;
fn try_from(item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> {
let metadata: PayeezyPaymentsMetadata =
to_connector_meta(item.request.connector_meta.clone())
.change_context(ConnectorError::RequestEncodingFailed)?;
Ok(Self {
transaction_type: PayeezyTransactionType::Void,
amount: item
.request
.amount
.ok_or(ConnectorError::RequestEncodingFailed)?
.to_string(),
currency_code: item.request.currency.unwrap_or_default().to_string(),
transaction_tag: metadata.transaction_tag,
})
}
}
#[derive(Debug, Deserialize, Serialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum PayeezyTransactionType {
Authorize,
Capture,
Purchase,
Recurring,
Void,
Refund,
#[default]
Pending,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct PayeezyPaymentsMetadata {
transaction_tag: String,
}
impl<F, T> TryFrom<ResponseRouterData<F, PayeezyPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<F, PayeezyPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let metadata = item
.response
.transaction_tag
.map(|txn_tag| construct_payeezy_payments_metadata(txn_tag).encode_to_value())
.transpose()
.change_context(ConnectorError::ResponseHandlingFailed)?;
let mandate_reference = item
.response
.stored_credentials
.map(|credentials| credentials.cardbrand_original_transaction_id)
.map(|id| MandateReference {
connector_mandate_id: Some(id.expose()),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
});
let status = get_status(
item.response.transaction_status,
item.response.transaction_type,
);
Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.transaction_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(mandate_reference),
connector_metadata: metadata,
network_txn_id: None,
connector_response_reference_id: Some(
item.response
.reference
.unwrap_or(item.response.transaction_id),
),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
fn get_status(status: PayeezyPaymentStatus, method: PayeezyTransactionType) -> AttemptStatus {
match status {
PayeezyPaymentStatus::Approved => match method {
PayeezyTransactionType::Authorize => AttemptStatus::Authorized,
PayeezyTransactionType::Capture
| PayeezyTransactionType::Purchase
| PayeezyTransactionType::Recurring => AttemptStatus::Charged,
PayeezyTransactionType::Void => AttemptStatus::Voided,
PayeezyTransactionType::Refund | PayeezyTransactionType::Pending => {
AttemptStatus::Pending
}
},
PayeezyPaymentStatus::Declined | PayeezyPaymentStatus::NotProcessed => match method {
PayeezyTransactionType::Capture => AttemptStatus::CaptureFailed,
PayeezyTransactionType::Authorize
| PayeezyTransactionType::Purchase
| PayeezyTransactionType::Recurring => AttemptStatus::AuthorizationFailed,
PayeezyTransactionType::Void => AttemptStatus::VoidFailed,
PayeezyTransactionType::Refund | PayeezyTransactionType::Pending => {
AttemptStatus::Pending
}
},
}
}
// REFUND :
// Type definition for RefundRequest
#[derive(Debug, Serialize)]
pub struct PayeezyRefundRequest {
transaction_tag: String,
transaction_type: PayeezyTransactionType,
amount: String,
currency_code: String,
}
impl<F> TryFrom<&PayeezyRouterData<&RefundsRouterData<F>>> for PayeezyRefundRequest {
type Error = error_stack::Report<ConnectorError>;
fn try_from(item: &PayeezyRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
let metadata: PayeezyPaymentsMetadata =
to_connector_meta(item.router_data.request.connector_metadata.clone())
.change_context(ConnectorError::RequestEncodingFailed)?;
Ok(Self {
transaction_type: PayeezyTransactionType::Refund,
amount: item.amount.clone(),
currency_code: item.router_data.request.currency.to_string(),
transaction_tag: metadata.transaction_tag,
})
}
}
// Type definition for Refund Response
#[derive(Debug, Deserialize, Default, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum RefundStatus {
Approved,
Declined,
#[default]
#[serde(rename = "Not Processed")]
NotProcessed,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Approved => Self::Success,
RefundStatus::Declined => Self::Failure,
RefundStatus::NotProcessed => Self::Pending,
}
}
}
#[derive(Deserialize, Debug, Serialize)]
pub struct RefundResponse {
pub correlation_id: String,
pub transaction_status: RefundStatus,
pub validation_status: String,
pub transaction_type: String,
pub transaction_id: String,
pub transaction_tag: Option<String>,
pub method: Option<String>,
pub amount: String,
pub currency: String,
pub bank_resp_code: String,
pub bank_message: String,
pub gateway_resp_code: String,
pub gateway_message: String,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<ParsingError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.transaction_id,
refund_status: enums::RefundStatus::from(item.response.transaction_status),
}),
..item.data
})
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct Message {
pub code: String,
pub description: String,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct PayeezyError {
pub messages: Vec<Message>,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct PayeezyErrorResponse {
pub transaction_status: String,
#[serde(rename = "Error")]
pub error: PayeezyError,
}
fn construct_payeezy_payments_metadata(transaction_tag: String) -> PayeezyPaymentsMetadata {
PayeezyPaymentsMetadata { transaction_tag }
}
| 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/facilitapay/responses.rs | crates/hyperswitch_connectors/src/connectors/facilitapay/responses.rs | use common_utils::{pii, types::StringMajorUnit};
use masking::Secret;
use serde::{Deserialize, Serialize};
use super::requests::DocumentType;
// Response body for POST /sign_in
#[derive(Debug, Deserialize, Serialize)]
pub struct FacilitapayAuthResponse {
username: Secret<String>,
name: Secret<String>,
pub jwt: Secret<String>,
}
#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum SubjectKycStatus {
// Customer is able to send/receive money through the platform. No action is needed on your side.
Approved,
// Customer is required to upload documents or uploaded documents have been rejected by KYC.
Reproved,
// Customer has uploaded KYC documents but awaiting analysis from the backoffice. No action is needed on your side.
WaitingApproval,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub struct FacilitapaySubject {
pub social_name: Secret<String>,
pub document_type: DocumentType,
pub document_number: Secret<String>,
// In documentation, both CountryAlpha2 and String are used. We cannot rely on CountryAlpha2.
pub fiscal_country: String,
pub updated_at: Option<String>,
pub status: SubjectKycStatus,
#[serde(rename = "id")]
pub customer_id: Secret<String>,
pub birth_date: Option<time::Date>,
pub email: Option<pii::Email>,
pub phone_country_code: Option<Secret<String>>,
pub phone_area_code: Option<Secret<String>>,
pub phone_number: Option<Secret<String>>,
pub address_street: Option<Secret<String>>,
pub address_number: Option<Secret<String>>,
pub address_complement: Option<Secret<String>>,
pub address_city: Option<String>,
pub address_state: Option<String>,
pub address_postal_code: Option<Secret<String>>,
pub address_country: Option<String>,
pub address_neighborhood: Option<Secret<String>>,
pub net_monthly_average_income: Option<StringMajorUnit>,
pub clearance_level: Option<i32>,
pub required_clearance_level: Option<i32>,
pub inserted_at: Option<String>,
pub references: Option<Vec<serde_json::Value>>,
pub rfc_pf: Option<Secret<String>>, // 13-digit RFC, specific to Mexico users
pub documents: Option<Vec<serde_json::Value>>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub struct FacilitapayCustomerResponse {
pub data: FacilitapaySubject,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct PixInfo {
#[serde(rename = "type")]
pub key_type: String,
pub key: Secret<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct CreditCardResponseInfo {
pub id: String,
pub status: Option<String>,
pub document_type: String,
pub document_number: Secret<String>,
pub birthdate: Option<String>,
pub phone_country_code: Option<String>,
pub phone_area_code: Option<String>,
pub phone_number: Option<Secret<String>>,
pub inserted_at: Option<String>,
}
// PaymentsResponse
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
#[derive(strum::Display)]
pub enum FacilitapayPaymentStatus {
/// Transaction has been created but it is waiting for an incoming TED/Wire.
/// This is the first recorded status in production mode.
#[default]
Pending,
/// Incoming TED/Wire has been identified into Facilita´s bank account.
/// When it is a deposit into an internal bank account and there is no
/// conversion involved (BRL to BRL for instance), that is the final state.
Identified,
/// The conversion rate has been closed and therefore the exchanged value
/// is defined - when it is a deposit into an internal bank account, that is the final state.
Exchanged,
/// The exchanged value has been wired to its destination (a real bank account) - that is also a final state.
Wired,
/// When for any reason the transaction cannot be concluded or need to be reversed, it is canceled.
#[serde(rename = "canceled")]
Cancelled,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct FacilitapayPaymentsResponse {
pub data: TransactionData,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct OwnerCompany {
pub social_name: Option<Secret<String>>,
#[serde(rename = "id")]
pub company_id: Option<String>,
pub document_type: DocumentType,
pub document_number: Secret<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct BankInfo {
pub swift: Option<Secret<String>>,
pub name: Option<String>,
#[serde(rename = "id")]
pub bank_id: Secret<String>,
pub code: Option<Secret<String>>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct BankAccountDetail {
pub routing_number: Option<Secret<String>>,
pub pix_info: Option<PixInfo>,
pub owner_name: Option<Secret<String>>,
pub owner_document_type: Option<String>,
pub owner_document_number: Option<Secret<String>>,
pub owner_company: Option<OwnerCompany>,
pub internal: Option<bool>,
pub intermediary_bank_account: Option<Secret<String>>,
pub intermediary_bank_account_id: Option<Secret<String>>,
#[serde(rename = "id")]
pub bank_account_id: Secret<String>,
pub iban: Option<Secret<String>>,
pub flow_type: Option<String>,
pub currency: api_models::enums::Currency,
pub branch_number: Option<Secret<String>>,
pub branch_country: Option<String>,
pub bank: Option<BankInfo>,
pub account_type: Option<String>,
pub account_number: Option<Secret<String>>,
pub aba: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct TransactionData {
#[serde(rename = "id")]
pub transaction_id: String,
pub value: StringMajorUnit,
pub status: FacilitapayPaymentStatus,
pub currency: api_models::enums::Currency,
pub exchange_currency: api_models::enums::Currency,
// Details about the destination account (Required)
pub to_bank_account: BankAccountDetail,
// Details about the source - mutually exclusive
pub from_credit_card: Option<CreditCardResponseInfo>,
pub from_bank_account: Option<BankAccountDetail>, // Populated for PIX
// Subject information (customer)
pub subject_id: String,
pub subject: Option<FacilitapaySubject>,
pub subject_is_receiver: Option<bool>,
// Source identification (potentially redundant with subject or card/bank info)
pub source_name: Option<Secret<String>>,
pub source_document_type: DocumentType,
pub source_document_number: Secret<String>,
// Timestamps and flags
pub inserted_at: Option<String>,
pub for_exchange: Option<bool>,
pub exchange_under_request: Option<bool>,
pub estimated_value_until_exchange: Option<bool>,
pub cleared: Option<bool>,
// PIX specific field
pub dynamic_pix_code: Option<String>, // QR code string for PIX
// Exchange details
pub exchanged_value: Option<StringMajorUnit>,
// Cancelation details
#[serde(rename = "canceled_reason")]
pub cancelled_reason: Option<String>,
#[serde(rename = "canceled_at")]
pub cancelled_at: Option<String>,
// Other fields
pub bank_transaction: Option<Secret<serde_json::Value>>,
pub meta: Option<serde_json::Value>,
}
// Void response structures (for /refund endpoint)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VoidBankTransaction {
#[serde(rename = "id")]
pub transaction_id: String,
pub value: StringMajorUnit,
pub currency: api_models::enums::Currency,
pub iof_value: Option<StringMajorUnit>,
pub fx_value: Option<StringMajorUnit>,
pub exchange_rate: Option<StringMajorUnit>,
pub exchange_currency: api_models::enums::Currency,
pub exchanged_value: StringMajorUnit,
pub exchange_approved: bool,
pub wire_id: Option<String>,
pub exchange_id: Option<String>,
pub movement_date: String,
pub source_name: Secret<String>,
pub source_document_number: Secret<String>,
pub source_document_type: String,
pub source_id: String,
pub source_type: String,
pub source_description: String,
pub source_bank: Option<String>,
pub source_branch: Option<String>,
pub source_account: Option<String>,
pub source_bank_ispb: Option<String>,
pub company_id: String,
pub company_name: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VoidData {
#[serde(rename = "id")]
pub void_id: String,
pub reason: Option<String>,
pub inserted_at: String,
pub status: FacilitapayPaymentStatus,
pub transaction_kind: String,
pub bank_transaction: VoidBankTransaction,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FacilitapayVoidResponse {
pub data: VoidData,
}
// Refund response uses the same TransactionData structure as payments
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FacilitapayRefundResponse {
pub data: TransactionData,
}
// Webhook structures
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FacilitapayWebhookNotification {
pub notification: FacilitapayWebhookBody,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct FacilitapayWebhookBody {
#[serde(rename = "type")]
pub event_type: FacilitapayWebhookEventType,
pub secret: Secret<String>,
#[serde(flatten)]
pub data: FacilitapayWebhookData,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum FacilitapayWebhookEventType {
ExchangeCreated,
Identified,
PaymentApproved,
PaymentExpired,
PaymentFailed,
PaymentRefunded,
WireCreated,
WireWaitingCorrection,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "UPPERCASE")]
pub enum FacilitapayWebhookErrorCode {
/// Creditor account number invalid or missing (branch_number or account_number incorrect)
Ac03,
/// Creditor account type missing or invalid (account_type incorrect)
Ac14,
/// Value in Creditor Identifier is incorrect (owner_document_number incorrect)
Ch11,
/// Transaction type not supported/authorized on this account (account rejected the payment)
Ag03,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum FacilitapayWebhookData {
CardPayment {
transaction_id: String,
checkout_id: Option<String>,
},
Exchange {
exchange_id: String,
transaction_ids: Vec<String>,
},
Transaction {
transaction_id: String,
},
Wire {
wire_id: String,
transaction_ids: Vec<String>,
},
WireError {
error_code: FacilitapayWebhookErrorCode,
error_description: String,
bank_account_owner_id: String,
bank_account_id: String,
transaction_ids: Vec<String>,
wire_id: String,
},
}
| 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/facilitapay/transformers.rs | crates/hyperswitch_connectors/src/connectors/facilitapay/transformers.rs | use api_models::payments::QrCodeInformation;
use common_enums::{enums, PaymentMethod};
use common_utils::{
errors::CustomResult,
ext_traits::{BytesExt, Encode},
new_type::MaskedBankAccount,
pii,
types::StringMajorUnit,
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{BankTransferData, PaymentMethodData},
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{
ConnectorCustomerResponseData, PaymentsResponseData, RefundsResponseData,
},
types,
};
use hyperswitch_interfaces::{
consts, errors, events::connector_api_logs::ConnectorEvent, types::Response,
};
use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
use url::Url;
use super::{
requests::{
DocumentType, FacilitapayAuthRequest, FacilitapayCredentials, FacilitapayCustomerRequest,
FacilitapayPaymentsRequest, FacilitapayPerson, FacilitapayRouterData,
FacilitapayTransactionRequest, PixTransactionRequest,
},
responses::{
FacilitapayAuthResponse, FacilitapayCustomerResponse, FacilitapayPaymentStatus,
FacilitapayPaymentsResponse, FacilitapayRefundResponse, FacilitapayVoidResponse,
},
};
use crate::{
types::{
PaymentsCancelResponseRouterData, RefreshTokenRouterData, RefundsResponseRouterData,
ResponseRouterData,
},
utils::{self, is_payment_failure, missing_field_err, QrImage, RouterData as OtherRouterData},
};
type Error = error_stack::Report<errors::ConnectorError>;
impl<T> From<(StringMajorUnit, T)> for FacilitapayRouterData<T> {
fn from((amount, item): (StringMajorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
// Auth Struct
#[derive(Debug, Clone)]
pub struct FacilitapayAuthType {
pub(super) username: Secret<String>,
pub(super) password: Secret<String>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct FacilitapayConnectorMetadataObject {
// pub destination_account_number: Secret<String>,
pub destination_account_number: MaskedBankAccount,
}
// Helper to build the request from Hyperswitch Auth Type
impl FacilitapayAuthRequest {
fn from_auth_type(auth: &FacilitapayAuthType) -> Self {
Self {
user: FacilitapayCredentials {
username: auth.username.clone(),
password: auth.password.clone(),
},
}
}
}
impl TryFrom<&ConnectorAuthType> for FacilitapayAuthType {
type Error = Error;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
username: key1.to_owned(),
password: api_key.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
impl TryFrom<&RefreshTokenRouterData> for FacilitapayAuthRequest {
type Error = Error;
fn try_from(item: &RefreshTokenRouterData) -> Result<Self, Self::Error> {
let auth_type = FacilitapayAuthType::try_from(&item.connector_auth_type)?;
Ok(Self::from_auth_type(&auth_type))
}
}
impl TryFrom<&Option<pii::SecretSerdeValue>> for FacilitapayConnectorMetadataObject {
type Error = Error;
fn try_from(meta_data: &Option<pii::SecretSerdeValue>) -> Result<Self, Self::Error> {
let metadata: Self = utils::to_connector_meta_from_secret(meta_data.clone())
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "merchant_connector_account.metadata",
})?;
Ok(metadata)
}
}
impl TryFrom<&FacilitapayRouterData<&types::PaymentsAuthorizeRouterData>>
for FacilitapayPaymentsRequest
{
type Error = Error;
fn try_from(
item: &FacilitapayRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let metadata =
FacilitapayConnectorMetadataObject::try_from(&item.router_data.connector_meta_data)?;
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::BankTransfer(bank_transfer_data) => match *bank_transfer_data {
BankTransferData::Pix {
source_bank_account_id,
..
} => {
// Set expiry time to 15 minutes from now
let dynamic_pix_expires_at = {
let now = time::OffsetDateTime::now_utc();
let expires_at = now + time::Duration::minutes(15);
PrimitiveDateTime::new(expires_at.date(), expires_at.time())
};
let transaction_data =
FacilitapayTransactionRequest::Pix(PixTransactionRequest {
// subject id must be generated by pre-process step and link with customer id
// might require discussions to be done
subject_id: item.router_data.get_connector_customer_id()?.into(),
from_bank_account_id: source_bank_account_id.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "source bank account id",
},
)?,
to_bank_account_id: metadata.destination_account_number,
currency: item.router_data.request.currency,
exchange_currency: item.router_data.request.currency,
value: item.amount.clone(),
use_dynamic_pix: true,
// Format: YYYY-MM-DDThh:mm:ssZ
dynamic_pix_expires_at,
});
Ok(Self {
transaction: transaction_data,
})
}
BankTransferData::AchBankTransfer {}
| BankTransferData::SepaBankTransfer {}
| BankTransferData::BacsBankTransfer {}
| BankTransferData::MultibancoBankTransfer {}
| BankTransferData::PermataBankTransfer {}
| BankTransferData::BcaBankTransfer {}
| BankTransferData::BniVaBankTransfer {}
| BankTransferData::BriVaBankTransfer {}
| BankTransferData::CimbVaBankTransfer {}
| BankTransferData::DanamonVaBankTransfer {}
| BankTransferData::MandiriVaBankTransfer {}
| BankTransferData::Pse {}
| BankTransferData::InstantBankTransfer {}
| BankTransferData::InstantBankTransferFinland {}
| BankTransferData::InstantBankTransferPoland {}
| BankTransferData::IndonesianBankTransfer { .. }
| BankTransferData::LocalBankTransfer { .. } => {
Err(errors::ConnectorError::NotImplemented(
"Selected payment method through Facilitapay".to_string(),
)
.into())
}
},
PaymentMethodData::Card(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Wallet(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
"Selected payment method through Facilitapay".to_string(),
)
.into())
}
}
}
}
fn convert_to_document_type(document_type: &str) -> Result<DocumentType, errors::ConnectorError> {
match document_type.to_lowercase().as_str() {
"cc" => Ok(DocumentType::CedulaDeCiudadania),
"cnpj" => Ok(DocumentType::CadastroNacionaldaPessoaJurídica),
"cpf" => Ok(DocumentType::CadastrodePessoasFísicas),
"curp" => Ok(DocumentType::ClaveÚnicadeRegistrodePoblación),
"nit" => Ok(DocumentType::NúmerodeIdentificaciónTributaria),
"passport" => Ok(DocumentType::Passport),
"rfc" => Ok(DocumentType::RegistroFederaldeContribuyentes),
"rut" => Ok(DocumentType::RolUnicoTributario),
"tax_id" | "taxid" => Ok(DocumentType::TaxId),
_ => Err(errors::ConnectorError::NotSupported {
message: format!("Document type '{document_type}'"),
connector: "Facilitapay",
}),
}
}
pub fn parse_facilitapay_error_response(
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let status_code = res.status_code;
let response_body_bytes = res.response.clone();
let (message, raw_error) =
match response_body_bytes.parse_struct::<serde_json::Value>("FacilitapayErrorResponse") {
Ok(json_value) => {
event_builder.map(|i| i.set_response_body(&json_value));
let message = extract_message_from_json(&json_value);
(
message,
serde_json::to_string(&json_value).unwrap_or_default(),
)
}
Err(_) => match String::from_utf8(response_body_bytes.to_vec()) {
Ok(text) => {
event_builder.map(|i| i.set_response_body(&text));
(text.clone(), text)
}
Err(_) => (
"Invalid response format received".to_string(),
format!(
"Unable to parse response as JSON or UTF-8 string. Status code: {status_code}",
),
),
},
};
Ok(ErrorResponse {
status_code,
code: consts::NO_ERROR_CODE.to_string(),
message,
reason: Some(raw_error),
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
// Helper function to extract a readable message from JSON error
fn extract_message_from_json(json: &serde_json::Value) -> String {
if let Some(obj) = json.as_object() {
if let Some(error) = obj.get("error").and_then(|e| e.as_str()) {
return error.to_string();
}
if obj.contains_key("errors") {
return "Validation error occurred".to_string();
}
if !obj.is_empty() {
return obj
.iter()
.next()
.map(|(k, v)| format!("{k}: {v}"))
.unwrap_or_else(|| "Unknown error".to_string());
}
} else if let Some(s) = json.as_str() {
return s.to_string();
}
"Unknown error format".to_string()
}
impl TryFrom<&types::ConnectorCustomerRouterData> for FacilitapayCustomerRequest {
type Error = Error;
fn try_from(item: &types::ConnectorCustomerRouterData) -> Result<Self, Self::Error> {
let email = item.request.email.clone();
let social_name = item.get_billing_full_name()?;
let (document_type, document_number) = match item.request.payment_method_data.clone() {
Some(PaymentMethodData::BankTransfer(bank_transfer_data)) => {
match *bank_transfer_data {
BankTransferData::Pix { cpf, .. } => {
// Extract only digits from the CPF string
let document_number =
cpf.ok_or_else(missing_field_err("cpf"))?.map(|cpf_number| {
cpf_number
.chars()
.filter(|chars| chars.is_ascii_digit())
.collect::<String>()
});
let document_type = convert_to_document_type("cpf")?;
(document_type, document_number)
}
_ => {
return Err(errors::ConnectorError::NotImplemented(
"Selected payment method through Facilitapay".to_string(),
)
.into())
}
}
}
_ => {
return Err(errors::ConnectorError::NotImplemented(
"Selected payment method through Facilitapay".to_string(),
)
.into())
}
};
let fiscal_country = item.get_billing_country()?;
let person = FacilitapayPerson {
document_number,
document_type,
social_name,
fiscal_country,
email,
birth_date: None,
phone_country_code: None,
phone_area_code: None,
phone_number: None,
address_city: None,
address_state: None,
address_complement: None,
address_country: None,
address_number: None,
address_postal_code: None,
address_street: None,
net_monthly_average_income: None,
};
Ok(Self { person })
}
}
impl<F, T> TryFrom<ResponseRouterData<F, FacilitapayCustomerResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = Error;
fn try_from(
item: ResponseRouterData<F, FacilitapayCustomerResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(PaymentsResponseData::ConnectorCustomerResponse(
ConnectorCustomerResponseData::new_with_customer_id(
item.response.data.customer_id.expose(),
),
)),
..item.data
})
}
}
impl From<FacilitapayPaymentStatus> for common_enums::AttemptStatus {
fn from(item: FacilitapayPaymentStatus) -> Self {
match item {
FacilitapayPaymentStatus::Pending => Self::Pending,
FacilitapayPaymentStatus::Identified
| FacilitapayPaymentStatus::Exchanged
| FacilitapayPaymentStatus::Wired => Self::Charged,
FacilitapayPaymentStatus::Cancelled => Self::Failure,
}
}
}
impl<F, T> TryFrom<ResponseRouterData<F, FacilitapayAuthResponse, T, AccessToken>>
for RouterData<F, T, AccessToken>
{
type Error = Error;
fn try_from(
item: ResponseRouterData<F, FacilitapayAuthResponse, T, AccessToken>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(AccessToken {
token: item.response.jwt,
expires: 86400, // Facilitapay docs say 24 hours validity. 24 * 60 * 60 = 86400 seconds.
}),
..item.data
})
}
}
impl<F, T> TryFrom<ResponseRouterData<F, FacilitapayPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = Error;
fn try_from(
item: ResponseRouterData<F, FacilitapayPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let status = if item.data.payment_method == PaymentMethod::BankTransfer
&& item.response.data.status == FacilitapayPaymentStatus::Identified
{
if item.response.data.currency != item.response.data.exchange_currency {
// Cross-currency: Identified is not terminal
common_enums::AttemptStatus::Pending
} else {
// Local currency: Identified is terminal
common_enums::AttemptStatus::Charged
}
} else {
common_enums::AttemptStatus::from(item.response.data.status.clone())
};
Ok(Self {
status,
response: if is_payment_failure(status) {
Err(ErrorResponse {
code: item.response.data.status.clone().to_string(),
message: item.response.data.status.clone().to_string(),
reason: item.response.data.cancelled_reason,
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(item.response.data.transaction_id),
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.data.transaction_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: get_qr_code_data(&item.response)?,
network_txn_id: None,
connector_response_reference_id: Some(item.response.data.transaction_id),
incremental_authorization_allowed: None,
charges: None,
})
},
..item.data
})
}
}
fn get_qr_code_data(
response: &FacilitapayPaymentsResponse,
) -> CustomResult<Option<serde_json::Value>, errors::ConnectorError> {
let expiration_time: i64 = if let Some(meta) = &response.data.meta {
if let Some(due_date_str) = meta
.get("dynamic_pix_due_date")
.and_then(|due_date_value| due_date_value.as_str())
{
let datetime = time::OffsetDateTime::parse(
due_date_str,
&time::format_description::well_known::Rfc3339,
)
.map_err(|_| errors::ConnectorError::ResponseHandlingFailed)?;
datetime.unix_timestamp() * 1000
} else {
// If dynamic_pix_due_date isn't present, use current time + 15 minutes
let now = time::OffsetDateTime::now_utc();
let expires_at = now + time::Duration::minutes(15);
expires_at.unix_timestamp() * 1000
}
} else {
// If meta is null, use current time + 15 minutes
let now = time::OffsetDateTime::now_utc();
let expires_at = now + time::Duration::minutes(15);
expires_at.unix_timestamp() * 1000
};
let dynamic_pix_code = response.data.dynamic_pix_code.as_ref().ok_or_else(|| {
errors::ConnectorError::MissingRequiredField {
field_name: "dynamic_pix_code",
}
})?;
let image_data = QrImage::new_from_data(dynamic_pix_code.clone())
.change_context(errors::ConnectorError::ResponseHandlingFailed)?;
let image_data_url = Url::parse(image_data.data.clone().as_str())
.change_context(errors::ConnectorError::ResponseHandlingFailed)?;
let qr_code_info = QrCodeInformation::QrDataUrl {
image_data_url,
display_to_timestamp: Some(expiration_time),
};
Some(qr_code_info.encode_to_value())
.transpose()
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
impl From<FacilitapayPaymentStatus> for enums::RefundStatus {
fn from(item: FacilitapayPaymentStatus) -> Self {
match item {
FacilitapayPaymentStatus::Identified
| FacilitapayPaymentStatus::Exchanged
| FacilitapayPaymentStatus::Wired => Self::Success,
FacilitapayPaymentStatus::Cancelled => Self::Failure,
FacilitapayPaymentStatus::Pending => Self::Pending,
}
}
}
// Void (cancel unprocessed payment) transformer
impl TryFrom<PaymentsCancelResponseRouterData<FacilitapayVoidResponse>>
for types::PaymentsCancelRouterData
{
type Error = Error;
fn try_from(
item: PaymentsCancelResponseRouterData<FacilitapayVoidResponse>,
) -> Result<Self, Self::Error> {
let status = common_enums::AttemptStatus::from(item.response.data.status.clone());
Ok(Self {
status,
response: if is_payment_failure(status) {
Err(ErrorResponse {
code: item.response.data.status.clone().to_string(),
message: item.response.data.status.clone().to_string(),
reason: item.response.data.reason,
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(item.response.data.void_id.clone()),
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.data.void_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.data.void_id),
incremental_authorization_allowed: None,
charges: None,
})
},
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<Execute, FacilitapayRefundResponse>>
for types::RefundsRouterData<Execute>
{
type Error = Error;
fn try_from(
item: RefundsResponseRouterData<Execute, FacilitapayRefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.data.transaction_id.clone(),
refund_status: enums::RefundStatus::from(item.response.data.status),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, FacilitapayRefundResponse>>
for types::RefundsRouterData<RSync>
{
type Error = Error;
fn try_from(
item: RefundsResponseRouterData<RSync, FacilitapayRefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.data.transaction_id.clone(),
refund_status: enums::RefundStatus::from(item.response.data.status),
}),
..item.data
})
}
}
| 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/facilitapay/requests.rs | crates/hyperswitch_connectors/src/connectors/facilitapay/requests.rs | use common_enums::CountryAlpha2;
use common_utils::{new_type::MaskedBankAccount, pii, types::StringMajorUnit};
use masking::Secret;
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
pub struct FacilitapayRouterData<T> {
pub amount: StringMajorUnit,
pub router_data: T,
}
#[derive(Debug, Serialize)]
pub struct FacilitapayAuthRequest {
pub user: FacilitapayCredentials,
}
#[derive(Debug, Serialize)]
pub struct FacilitapayCredentials {
pub username: Secret<String>, // email_id
pub password: Secret<String>,
}
#[derive(Debug, Serialize, PartialEq)]
pub struct FacilitapayCardDetails {
#[serde(rename = "card_number")]
pub number: cards::CardNumber,
#[serde(rename = "card_expiration_date")]
pub expiry_date: Secret<String>, // Format: "MM/YYYY"
#[serde(rename = "card_security_code")]
pub cvc: Secret<String>,
#[serde(rename = "card_brand")]
pub brand: String,
pub fullname: Secret<String>,
}
#[derive(Debug, Serialize, PartialEq)]
pub struct CardTransactionRequest {
pub currency: api_models::enums::Currency,
pub exchange_currency: api_models::enums::Currency,
pub value: StringMajorUnit,
pub from_credit_card: FacilitapayCardDetails,
pub to_bank_account_id: Secret<String>, // UUID
pub subject_id: String, // UUID
}
#[derive(Debug, Serialize, PartialEq)]
pub struct PixTransactionRequest {
pub subject_id: Secret<String>, // Customer ID (UUID)
pub from_bank_account_id: MaskedBankAccount, // UUID
pub to_bank_account_id: MaskedBankAccount, // UUID
pub currency: api_models::enums::Currency,
pub exchange_currency: api_models::enums::Currency,
pub value: StringMajorUnit,
pub use_dynamic_pix: bool,
#[serde(default, with = "common_utils::custom_serde::iso8601")]
pub dynamic_pix_expires_at: PrimitiveDateTime,
}
#[derive(Debug, Serialize, PartialEq)]
#[serde(untagged)]
pub enum FacilitapayTransactionRequest {
#[allow(dead_code)]
Card(CardTransactionRequest),
Pix(PixTransactionRequest),
}
#[derive(Debug, Serialize, PartialEq)]
pub struct FacilitapayPaymentsRequest {
pub transaction: FacilitapayTransactionRequest,
}
#[derive(Debug, Serialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub struct FacilitapayCustomerRequest {
pub person: FacilitapayPerson,
}
#[derive(Debug, Serialize, Clone, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum DocumentType {
/// CC is the Cedula de Ciudadania, is a 10-digit number, which is the national identity card for Colombian citizens.
/// It is used for citizen identification purposes.
#[serde(rename = "cc")]
CedulaDeCiudadania,
/// CNPJ stands for Cadastro Nacional da Pessoa Jurídica, is a 14-digit number,
/// which is the national registry of legal entities in Brazil used as a unique identifier for Brazilian companies.
#[serde(rename = "cnpj")]
CadastroNacionaldaPessoaJurídica,
/// CPF stands for Cadastro de Pessoas Físicas, is a 11-digit number,
/// which is the national registry of natural persons in Brazil used as a unique identifier for Brazilian citizens.
#[serde(rename = "cpf")]
CadastrodePessoasFísicas,
/// CURP stands for Clave Única de Registro de Población,is a 18-digit number used as a unique identifier for Mexican citizens.
/// It is used to track tax information and other identification purposes by the government.
#[serde(rename = "curp")]
ClaveÚnicadeRegistrodePoblación,
/// NIT is the Número de Identificación Tributaria, is a 10-digit number, which is the tax identification number in Colombia. Used for companies.
#[serde(rename = "nit")]
NúmerodeIdentificaciónTributaria,
/// Passport is the travel document usually issued by a country's government
Passport,
/// RFC stands for Registro Federal de Contribuyentes, is a 13-digit number used as a unique identifier for Mexican companies.
#[serde(rename = "rfc")]
RegistroFederaldeContribuyentes,
/// RUT stands for Rol Unico Tributario, is a 9-digit number used as a unique identifier for Chilean citizens and companies.
#[serde(rename = "rut")]
RolUnicoTributario,
/// A Taxpayer Identification Number is an identifying number used for tax purposes
TaxId,
}
#[derive(Debug, Serialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub struct FacilitapayPerson {
pub document_number: Secret<String>,
pub document_type: DocumentType,
pub social_name: Secret<String>,
pub fiscal_country: CountryAlpha2,
#[serde(skip_serializing_if = "Option::is_none")]
pub email: Option<pii::Email>,
#[serde(skip_serializing_if = "Option::is_none")]
pub birth_date: Option<time::Date>,
#[serde(skip_serializing_if = "Option::is_none")]
pub phone_country_code: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub phone_area_code: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub phone_number: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub address_city: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub address_state: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub address_complement: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub address_country: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub address_number: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub address_postal_code: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub address_street: Option<Secret<String>>,
pub net_monthly_average_income: Option<StringMajorUnit>,
}
| 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/tesouro/transformers.rs | crates/hyperswitch_connectors/src/connectors/tesouro/transformers.rs | pub mod tesouro_queries;
use api_models::payments::AdditionalPaymentData;
use common_enums::enums;
use common_types::payments::{ApplePayPredecryptData, GPayPredecryptData};
use common_utils::types::FloatMajorUnit;
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{
ApplePayWalletData, Card, GooglePayWalletData, PaymentMethodData, WalletData,
},
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, PaymentMethodToken, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::{PaymentsSyncData, ResponseId, SetupMandateRequestData},
router_response_types::{MandateReference, PaymentsResponseData, RefundsResponseData},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsSyncRouterData, RefreshTokenRouterData, RefundSyncRouterData, RefundsRouterData,
SetupMandateRouterData,
},
};
use hyperswitch_interfaces::{
consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE},
errors,
};
use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
types::{
PaymentsCancelResponseRouterData, PaymentsCaptureResponseRouterData,
PaymentsResponseRouterData, RefundsResponseRouterData, ResponseRouterData,
},
utils::{
self as connector_utils, AdditionalCardInfo, CardData, PaymentsAuthorizeRequestData,
PaymentsSyncRequestData, RefundsRequestData, RouterData as _,
},
};
pub mod tesouro_constants {
pub const MAX_PAYMENT_REFERENCE_ID_LENGTH: usize = 28;
}
#[derive(Debug, Clone, Serialize)]
pub struct GenericTesouroRequest<T> {
query: String,
variables: T,
}
pub type TesouroAuthorizeRequest = GenericTesouroRequest<TesouroPaymentRequest>;
pub type TesouroSetupMandateRequest = GenericTesouroRequest<TesouroVerifyAccountRequest>;
pub type TesouroCaptureRequest = GenericTesouroRequest<TesouroCaptureInput>;
pub type TesouroVoidRequest = GenericTesouroRequest<TesouroVoidInput>;
pub type TesouroRefundRequest = GenericTesouroRequest<TesouroRefundInput>;
pub type TesouroSyncRequest = GenericTesouroRequest<TesouroSyncInput>;
pub type TesouroAuthorizeResponse = TesouroApiResponse<TesouroAuthorizeResponseData>;
pub type TesouroSetupMandateResponse = TesouroApiResponse<TesouroVerifyAccountResponseData>;
pub type TesouroCaptureResponse = TesouroApiResponse<TesouroCaptureResponseData>;
pub type TesouroVoidResponse = TesouroApiResponse<TesouroVoidResponseData>;
pub type TesouroRefundResponse = TesouroApiResponse<RefundTransactionResponseData>;
pub type TesouroSyncResponse = TesouroApiResponse<TesouroSyncResponseData>;
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(untagged)]
pub enum TesouroApiResponse<T> {
TesouroApiSuccessResponse(TesouroApiResponseData<T>),
TesouroErrorResponse(TesouroApiErrorResponse),
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct TesouroApiResponseData<T> {
data: T,
}
pub struct TesouroRouterData<T> {
pub amount: FloatMajorUnit,
pub router_data: T,
}
impl<T> From<(FloatMajorUnit, T)> for TesouroRouterData<T> {
fn from((amount, item): (FloatMajorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TransactionResponseData<T> {
#[serde(rename = "__typename")]
pub type_name: Option<T>,
pub payment_id: Option<String>,
pub transaction_id: String,
pub decline_type: Option<String>,
pub message: Option<String>,
pub token_details: Option<TesouroTokenDetails>,
pub activity_date: Option<String>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TesouroAuthorizeResponseData {
#[serde(
alias = "authorizeRecurring",
alias = "authorizeCustomerInitiatedTransaction"
)]
authorize_customer_initiated_transaction: AuthorizeCustomerInitiatedTransactionResponseData,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TesouroVerifyAccountResponseData {
verify_account: TeseroVerifyAccountResponse,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub enum AuthorizeTransactionResponseType {
AuthorizationApproval,
AuthorizationDecline,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthorizeCustomerInitiatedTransactionResponseData {
authorization_response: Option<TransactionResponseData<AuthorizeTransactionResponseType>>,
errors: Option<Vec<TesouroTransactionErrorResponseData>>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TeseroVerifyAccountResponse {
verify_account_response: Option<VerifyAccountResponseType>,
errors: Option<Vec<TesouroTransactionErrorResponseData>>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct VerifyAccountResponseType {
pub payment_id: String,
pub transaction_id: String,
pub token_details: TesouroTokenDetails,
pub activity_date: String,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TesouroCaptureResponseData {
capture_authorization: CaptureCustomerInitiatedTransactionResponseData,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CaptureCustomerInitiatedTransactionResponseData {
capture_authorization_response: Option<TransactionResponseData<CaptureTransactionResponseType>>,
errors: Option<Vec<TesouroTransactionErrorResponseData>>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub enum CaptureTransactionResponseType {
CaptureAuthorizationApproval,
CaptureAuthorizationDecline,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TesouroVoidResponseData {
reverse_transaction: ReverseTransactionResponseData,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ReverseTransactionResponseData {
reverse_transaction_response: Option<TransactionResponseData<ReverseTransactionResponseType>>,
errors: Option<Vec<TesouroTransactionErrorResponseData>>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub enum ReverseTransactionResponseType {
ReverseTransactionApproval,
ReverseTransactionDecline,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RefundTransactionResponseData {
refund_previous_payment: TesouroRefundPreviousPaymentResponseData,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TesouroRefundPreviousPaymentResponseData {
refund_previous_payment_response:
Option<TransactionResponseData<RefundTransactionResponseType>>,
errors: Option<Vec<TesouroTransactionErrorResponseData>>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub enum RefundTransactionResponseType {
RefundPreviousPaymentApproval,
RefundPreviousPaymentDecline,
}
pub struct TesouroAuthType {
pub(super) client_id: Secret<String>,
pub(super) client_secret: Secret<String>,
pub(super) acceptor_id: Secret<String>,
}
impl TesouroAuthType {
fn get_acceptor_id(&self) -> Secret<String> {
self.acceptor_id.clone()
}
}
impl TryFrom<&ConnectorAuthType> for TesouroAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::SignatureKey {
api_key,
api_secret,
key1,
} => Ok(Self {
client_id: api_key.to_owned(),
client_secret: api_secret.to_owned(),
acceptor_id: key1.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct TesouroApiErrorResponse {
errors: Vec<TesouroApiErrorData>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct TesouroApiErrorData {
message: String,
}
#[derive(Debug, Serialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub struct TesouroAccessTokenRequest {
grant_type: TesouroGrantType,
client_id: Secret<String>,
client_secret: Secret<String>,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum TesouroGrantType {
ClientCredentials,
}
impl TryFrom<&RefreshTokenRouterData> for TesouroAccessTokenRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &RefreshTokenRouterData) -> Result<Self, Self::Error> {
let auth = TesouroAuthType::try_from(&item.connector_auth_type)?;
Ok(Self {
grant_type: TesouroGrantType::ClientCredentials,
client_id: auth.client_id,
client_secret: auth.client_secret,
})
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct TesouroAccessTokenResponse {
access_token: Secret<String>,
token_type: String,
expires_in: i64,
}
impl<F, T> TryFrom<ResponseRouterData<F, TesouroAccessTokenResponse, T, AccessToken>>
for RouterData<F, T, AccessToken>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, TesouroAccessTokenResponse, T, AccessToken>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(AccessToken {
token: item.response.access_token,
expires: item.response.expires_in,
}),
..item.data
})
}
}
#[derive(Debug, Serialize)]
#[serde(untagged, rename_all = "camelCase")]
pub enum TesouroPaymentRequest {
#[serde(rename_all = "camelCase")]
Authorize {
authorize_customer_initiated_transaction_input: AuthorizeCustomerInitiatedTransactionInput,
},
#[serde(rename_all = "camelCase")]
Recurring {
authorize_recurring_input: AuthorizeRecurringTransactionInput,
},
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TesouroVerifyAccountRequest {
verify_account_input: TesouroVerifyAccountInput,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TesouroCaptureInput {
pub capture_authorization_input: CaptureAuthorizationInput,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TesouroVoidInput {
pub reverse_transaction_input: ReverseTransactionInput,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TesouroRefundInput {
pub refund_previous_payment_input: RefundPreviousPaymentInput,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TesouroSyncInput {
pub payment_transaction_id: String,
}
#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum TesouroAuthorizationIntent {
FinalAuthorization,
PreAuthorization,
}
#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum TesouroChannel {
Ecommerce,
MailOrderTelephoneOrder,
Retail,
}
#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum TesouroAutomaticCapture {
Never,
OnApproval,
}
#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum TesouroWalletType {
ApplePay,
GooglePay,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TesouroAuthorizeRecurringAcquirerTokenDetails {
pub expiration_month: Option<Secret<String>>,
pub expiration_year: Option<Secret<String>>,
pub token: Secret<String>,
pub security_code: TesouroSecurityCode,
pub wallet_type: Option<TesouroWalletType>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum TesouroPaymentMethodDetails {
CardWithPanDetails(TesouroCardWithPanDetails),
NetworkTokenPassThroughDetails(TesouroNetworkTokenPassThroughDetails),
AcquirerTokenDetails(TesouroAuthorizeRecurringAcquirerTokenDetails),
}
impl TesouroPaymentMethodDetails {
fn get_recurring_acqquirer_token_details(
connector_mandate_id: String,
additional_payment_data: AdditionalPaymentData,
) -> Result<Self, error_stack::Report<errors::ConnectorError>> {
let (expiration_month, expiration_year, wallet_type) = match additional_payment_data {
AdditionalPaymentData::Card(additional_card_info) => Ok((
additional_card_info.card_exp_month.clone(),
Some(additional_card_info.get_card_expiry_year_4_digit()?),
None,
)),
AdditionalPaymentData::Wallet {
apple_pay,
google_pay,
samsung_pay: _,
} => {
if let Some(google_pay_token) = google_pay {
Ok((
google_pay_token.card_exp_month.clone(),
Some(google_pay_token.get_card_expiry_year_4_digit()?),
Some(TesouroWalletType::GooglePay),
))
} else if let Some(apple_pay_token) = apple_pay {
Ok((
apple_pay_token.card_exp_month.clone(),
Some(apple_pay_token.get_card_expiry_year_4_digit()?),
Some(TesouroWalletType::ApplePay),
))
} else {
Err(errors::ConnectorError::MissingRequiredField {
field_name: "expiration date and expiration year",
})
}
}
_ => Err(errors::ConnectorError::MissingRequiredField {
field_name: "expiration date and expiration year",
}),
}?;
Ok(Self::AcquirerTokenDetails(
TesouroAuthorizeRecurringAcquirerTokenDetails {
expiration_month,
expiration_year,
token: Secret::new(connector_mandate_id),
security_code: TesouroSecurityCode::OmissionReason {
omission_reason: TesouroOmissionReason::VerificationNotRequested,
},
wallet_type,
},
))
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TesouroCardWithPanDetails {
pub expiration_month: Secret<String>,
pub expiration_year: Secret<String>,
pub account_number: cards::CardNumber,
pub payment_entry_mode: TesouroPaymentEntryMode,
pub security_code: TesouroSecurityCode,
#[serde(skip_serializing_if = "Option::is_none")]
pub storage_intent: Option<TesouroStorageIntent>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TesouroNetworkTokenPassThroughDetails {
pub cryptogram: Option<Secret<String>>,
pub expiration_month: Secret<String>,
pub expiration_year: Secret<String>,
pub token_value: cards::CardNumber,
pub wallet_type: TesouroWalletType,
pub ecommerce_indicator: Option<String>,
}
#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum TesouroPaymentEntryMode {
PaymentMethodNotOnFile,
PaymentMethodOnFile,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum TesouroOmissionReason {
ILLEGIBLE,
NotImprinted,
VerificationNotRequested,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum TesouroSecurityCode {
Value {
value: Secret<String>,
},
#[serde(rename_all = "camelCase")]
OmissionReason {
omission_reason: TesouroOmissionReason,
},
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TransactionAmountDetails {
pub total_amount: FloatMajorUnit,
pub currency: enums::Currency,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BillToAddress {
pub address1: Option<Secret<String>>,
pub address2: Option<Secret<String>>,
pub address3: Option<Secret<String>>,
pub city: Option<String>,
pub country_code: Option<common_enums::CountryAlpha3>,
pub first_name: Option<Secret<String>>,
pub last_name: Option<Secret<String>>,
pub postal_code: Option<Secret<String>>,
pub state: Option<Secret<String>>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CitReference {
pub cit_payment_id: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthorizeCustomerInitiatedTransactionInput {
pub acceptor_id: Secret<String>,
pub transaction_reference: String,
pub payment_method_details: TesouroPaymentMethodDetails,
pub transaction_amount_details: TransactionAmountDetails,
pub automatic_capture: TesouroAutomaticCapture,
pub authorization_intent: TesouroAuthorizationIntent,
pub bill_to_address: BillToAddress,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum TesouroStorageIntent {
StoreOnFile,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthorizeRecurringTransactionInput {
pub acceptor_id: Secret<String>,
pub transaction_reference: String,
pub payment_method_details: TesouroPaymentMethodDetails,
pub transaction_amount_details: TransactionAmountDetails,
pub automatic_capture: TesouroAutomaticCapture,
pub bill_to_address: BillToAddress,
#[serde(skip_serializing_if = "Option::is_none")]
pub cit_reference: Option<CitReference>,
#[serde(skip_serializing_if = "Option::is_none")]
pub original_purchase_date: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TesouroVerifyAccountInput {
pub acceptor_id: Secret<String>,
pub transaction_reference: String,
pub bill_to_address: BillToAddress,
pub payment_method_details: TesouroPaymentMethodDetails,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CaptureAuthorizationInput {
pub acceptor_id: Secret<String>,
pub payment_id: String,
pub transaction_reference: String,
pub transaction_amount_details: TransactionAmountDetails,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ReverseTransactionInput {
pub acceptor_id: Secret<String>,
pub transaction_id: String,
pub transaction_reference: String,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RefundPreviousPaymentInput {
pub acceptor_id: Secret<String>,
pub payment_id: String,
pub transaction_reference: String,
pub transaction_amount_details: TransactionAmountDetails,
}
fn get_card_payment_method(
card: &Card,
is_mandate_payment: bool,
) -> Result<TesouroPaymentMethodDetails, error_stack::Report<errors::ConnectorError>> {
let card_data = TesouroCardWithPanDetails {
expiration_month: card.get_card_expiry_month_2_digit()?,
expiration_year: card.get_expiry_year_4_digit(),
account_number: card.card_number.clone(),
payment_entry_mode: if is_mandate_payment {
TesouroPaymentEntryMode::PaymentMethodOnFile
} else {
TesouroPaymentEntryMode::PaymentMethodNotOnFile
},
security_code: TesouroSecurityCode::Value {
value: card.card_cvc.clone(),
},
storage_intent: if is_mandate_payment {
Some(TesouroStorageIntent::StoreOnFile)
} else {
None
},
};
Ok(TesouroPaymentMethodDetails::CardWithPanDetails(card_data))
}
fn get_apple_pay_data(
apple_pay_wallet_data: &ApplePayWalletData,
payment_method_token: Option<&PaymentMethodToken>,
) -> Result<ApplePayPredecryptData, error_stack::Report<errors::ConnectorError>> {
if let Some(PaymentMethodToken::ApplePayDecrypt(decrypted_data)) = payment_method_token {
return Ok(*decrypted_data.clone());
}
match &apple_pay_wallet_data.payment_data {
common_types::payments::ApplePayPaymentData::Decrypted(decrypted_data) => {
Ok(decrypted_data.clone())
}
common_types::payments::ApplePayPaymentData::Encrypted(_) => {
Err(errors::ConnectorError::MissingRequiredField {
field_name: "decrypted apple pay data",
})?
}
}
}
fn get_google_pay_data(
google_pay_wallet_data: &GooglePayWalletData,
payment_method_token: Option<&PaymentMethodToken>,
) -> Result<GPayPredecryptData, error_stack::Report<errors::ConnectorError>> {
if let Some(PaymentMethodToken::GooglePayDecrypt(decrypted_data)) = payment_method_token {
return Ok(*decrypted_data.clone());
}
match &google_pay_wallet_data.tokenization_data {
common_types::payments::GpayTokenizationData::Decrypted(decrypted_data) => {
Ok(decrypted_data.clone())
}
common_types::payments::GpayTokenizationData::Encrypted(_) => {
Err(errors::ConnectorError::MissingRequiredField {
field_name: "decrypted google pay data",
})?
}
}
}
impl TryFrom<(&ApplePayWalletData, Option<&PaymentMethodToken>)> for TesouroPaymentMethodDetails {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(wallet_data, payment_method_token): (&ApplePayWalletData, Option<&PaymentMethodToken>),
) -> Result<Self, Self::Error> {
let apple_pay_data = get_apple_pay_data(wallet_data, payment_method_token)?;
let network_token_details = TesouroNetworkTokenPassThroughDetails {
expiration_year: apple_pay_data.get_four_digit_expiry_year(),
cryptogram: Some(apple_pay_data.payment_data.online_payment_cryptogram),
token_value: apple_pay_data.application_primary_account_number,
expiration_month: apple_pay_data.application_expiration_month,
ecommerce_indicator: apple_pay_data.payment_data.eci_indicator,
wallet_type: TesouroWalletType::ApplePay,
};
Ok(Self::NetworkTokenPassThroughDetails(network_token_details))
}
}
impl TryFrom<(&GooglePayWalletData, Option<&PaymentMethodToken>)> for TesouroPaymentMethodDetails {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(wallet_data, payment_method_token): (&GooglePayWalletData, Option<&PaymentMethodToken>),
) -> Result<Self, Self::Error> {
let google_pay_data = get_google_pay_data(wallet_data, payment_method_token)?;
let network_token_details = TesouroNetworkTokenPassThroughDetails {
expiration_year: google_pay_data
.get_four_digit_expiry_year()
.change_context(errors::ConnectorError::InvalidWalletToken {
wallet_name: "Google Pay".to_string(),
})?,
cryptogram: google_pay_data.cryptogram,
token_value: google_pay_data.application_primary_account_number,
expiration_month: google_pay_data.card_exp_month,
ecommerce_indicator: google_pay_data.eci_indicator,
wallet_type: TesouroWalletType::GooglePay,
};
Ok(Self::NetworkTokenPassThroughDetails(network_token_details))
}
}
pub struct TesouroCaptureData {
automatic_capture: TesouroAutomaticCapture,
authorization_intent: TesouroAuthorizationIntent,
}
impl From<bool> for TesouroCaptureData {
fn from(is_auto_capture: bool) -> Self {
if is_auto_capture {
Self {
automatic_capture: TesouroAutomaticCapture::OnApproval,
authorization_intent: TesouroAuthorizationIntent::FinalAuthorization,
}
} else {
Self {
automatic_capture: TesouroAutomaticCapture::Never,
authorization_intent: TesouroAuthorizationIntent::PreAuthorization,
}
}
}
}
impl<Flow, Request, Response> From<&RouterData<Flow, Request, Response>> for BillToAddress {
fn from(router_data: &RouterData<Flow, Request, Response>) -> Self {
Self {
address1: router_data.get_optional_billing_line1(),
address2: router_data.get_optional_billing_line2(),
address3: router_data.get_optional_billing_line3(),
city: router_data.get_optional_billing_city(),
country_code: router_data
.get_optional_billing_country()
.map(|billing_country| {
common_enums::CountryAlpha2::from_alpha2_to_alpha3(billing_country)
}),
first_name: router_data.get_optional_billing_first_name(),
last_name: router_data.get_optional_billing_last_name(),
postal_code: router_data.get_optional_billing_zip(),
state: router_data.get_optional_billing_state(),
}
}
}
pub fn get_tesouro_setupmandate_request(
router_data: &SetupMandateRouterData,
) -> Result<TesouroSetupMandateRequest, error_stack::Report<errors::ConnectorError>> {
let auth = TesouroAuthType::try_from(&router_data.connector_auth_type)?;
let acceptor_id = auth.get_acceptor_id();
let transaction_reference =
get_valid_transaction_id(router_data.connector_request_reference_id.clone())?;
let bill_to_address = BillToAddress::from(router_data);
let payment_method_details = match &router_data.request.payment_method_data {
PaymentMethodData::Card(card) => get_card_payment_method(card, true),
_ => Err(errors::ConnectorError::NotImplemented(
connector_utils::get_unimplemented_payment_method_error_message("tesouro"),
)
.into()),
}?;
let verify_account_input = TesouroVerifyAccountInput {
acceptor_id,
transaction_reference,
bill_to_address,
payment_method_details,
};
Ok(TesouroSetupMandateRequest {
query: tesouro_queries::SETUP_MANDATE.to_string(),
variables: TesouroVerifyAccountRequest {
verify_account_input,
},
})
}
impl TryFrom<&TesouroRouterData<&PaymentsAuthorizeRouterData>> for TesouroAuthorizeRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &TesouroRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let auth = TesouroAuthType::try_from(&item.router_data.connector_auth_type)?;
let acceptor_id = auth.get_acceptor_id();
let transaction_reference =
get_valid_transaction_id(item.router_data.connector_request_reference_id.clone())?;
let capture_data = TesouroCaptureData::from(item.router_data.request.is_auto_capture()?);
let mut cit_reference = None;
let mut original_purchase_date = None;
let payment_method_details = match &item.router_data.request.payment_method_data {
PaymentMethodData::Card(card) => {
if item.router_data.is_three_ds() {
Err(errors::ConnectorError::NotSupported {
message: "Cards 3DS".to_string(),
connector: "Tesouro",
})?
}
get_card_payment_method(card, item.router_data.request.is_mandate_payment())
}
PaymentMethodData::MandatePayment => {
let connector_mandate_id = item.router_data.request.connector_mandate_id().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "connector_mandate_id",
},
)?;
cit_reference = {
let mandate_reference_id = item
.router_data
.request
.get_connector_mandate_request_reference_id()
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "connector_mandate_id",
})?;
Some(CitReference {
cit_payment_id: mandate_reference_id.clone().into(),
})
};
let additional_payment_data = item
.router_data
.request
.additional_payment_method_data
.clone()
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "additional_payment_method_data",
})?;
original_purchase_date = {
if let Some(metadata) = item
.router_data
.get_recurring_mandate_payment_data()?
.mandate_metadata
{
let tesouro_metadata: TesouroMandateMetadata =
serde_json::from_value(metadata.expose()).map_err(|_| {
errors::ConnectorError::MissingConnectorMandateMetadata
})?;
Some(tesouro_metadata.activity_date)
} else {
let now = chrono::Utc::now();
Some(now.format("%Y-%m-%d").to_string())
}
};
TesouroPaymentMethodDetails::get_recurring_acqquirer_token_details(
connector_mandate_id,
additional_payment_data,
)
}
PaymentMethodData::Wallet(wallet_data) => match wallet_data {
WalletData::ApplePay(apple_pay_wallet_data) => {
let payment_method_token = item.router_data.payment_method_token.as_ref();
TesouroPaymentMethodDetails::try_from((
apple_pay_wallet_data,
payment_method_token,
))
}
WalletData::GooglePay(google_pay_wallet_data) => {
let payment_method_token = item.router_data.payment_method_token.as_ref();
TesouroPaymentMethodDetails::try_from((
google_pay_wallet_data,
payment_method_token,
))
}
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::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(
connector_utils::get_unimplemented_payment_method_error_message("Tesouro"),
))?,
},
PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| 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/tesouro/transformers/tesouro_queries.rs | crates/hyperswitch_connectors/src/connectors/tesouro/transformers/tesouro_queries.rs | pub const AUTHORIZE_TRANSACTION: &str = "mutation AuthorizeCustomerInitiatedTransaction(
$authorizeCustomerInitiatedTransactionInput: AuthorizeCustomerInitiatedTransactionInput!
) {
authorizeCustomerInitiatedTransaction(
authorizeCustomerInitiatedTransactionInput: $authorizeCustomerInitiatedTransactionInput
) {
authorizationResponse {
paymentId
transactionId
tokenDetails {
token
}
activityDate
__typename
... on AuthorizationApproval {
__typename
paymentId
transactionId
tokenDetails {
token
}
activityDate
}
... on AuthorizationDecline {
__typename
transactionId
paymentId
message
tokenDetails {
token
}
}
}
errors {
... on InternalServiceError {
message
transactionId
processorResponseCode
}
... on AcceptorNotFoundError {
message
transactionId
processorResponseCode
}
... on RuleInViolationError {
message
transactionId
processorResponseCode
}
... on SyntaxOnNetworkResponseError {
message
transactionId
processorResponseCode
}
... on TimeoutOnNetworkResponseError {
message
transactionId
processorResponseCode
}
... on ValidationFailureError {
message
processorResponseCode
transactionId
}
... on UnknownCardError {
message
processorResponseCode
transactionId
}
... on TokenNotFoundError {
message
processorResponseCode
transactionId
}
... on InvalidTokenError {
message
processorResponseCode
transactionId
}
... on RouteNotFoundError {
message
processorResponseCode
transactionId
}
}
}
}";
pub const AUTHORIZE_RECURRING: &str = "mutation AuthorizeRecurring(
$authorizeRecurringInput: AuthorizeRecurringInput!
) {
authorizeRecurring(
authorizeRecurringInput: $authorizeRecurringInput
) {
authorizationResponse {
paymentId
transactionId
tokenDetails {
token
}
activityDate
__typename
... on AuthorizationApproval {
__typename
paymentId
transactionId
tokenDetails {
token
}
activityDate
}
... on AuthorizationDecline {
__typename
transactionId
paymentId
message
}
}
errors {
... on InternalServiceError {
message
transactionId
processorResponseCode
}
... on AcceptorNotFoundError {
message
transactionId
processorResponseCode
}
... on RuleInViolationError {
message
transactionId
processorResponseCode
}
... on SyntaxOnNetworkResponseError {
message
transactionId
processorResponseCode
}
... on TimeoutOnNetworkResponseError {
message
transactionId
processorResponseCode
}
... on ValidationFailureError {
message
processorResponseCode
transactionId
}
... on UnknownCardError {
message
processorResponseCode
transactionId
}
... on TokenNotFoundError {
message
processorResponseCode
transactionId
}
... on InvalidTokenError {
message
processorResponseCode
transactionId
}
... on RouteNotFoundError {
message
processorResponseCode
transactionId
}
... on PriorPaymentNotFoundError {
message
processorResponseCode
transactionId
}
}
}
}";
pub const SETUP_MANDATE: &str = "mutation VerifyAccount(
$verifyAccountInput: VerifyAccountInput!
) {
verifyAccount(
verifyAccountInput: $verifyAccountInput
) {
verifyAccountResponse {
paymentId
transactionId
tokenDetails {
token
}
activityDate
}
errors {
... on InternalServiceError {
message
transactionId
processorResponseCode
}
... on AcceptorNotFoundError {
message
transactionId
processorResponseCode
}
... on RuleInViolationError {
message
transactionId
processorResponseCode
}
... on SyntaxOnNetworkResponseError {
message
transactionId
processorResponseCode
}
... on TimeoutOnNetworkResponseError {
message
transactionId
processorResponseCode
}
... on ValidationFailureError {
message
processorResponseCode
transactionId
}
... on UnknownCardError {
message
processorResponseCode
transactionId
}
... on TokenNotFoundError {
message
processorResponseCode
transactionId
}
... on InvalidTokenError {
message
processorResponseCode
transactionId
}
... on RouteNotFoundError {
message
processorResponseCode
transactionId
}
}
}
}";
pub const CAPTURE_TRANSACTION: &str =
"mutation CaptureAuthorization($captureAuthorizationInput: CaptureAuthorizationInput!) {
captureAuthorization(captureAuthorizationInput: $captureAuthorizationInput) {
captureAuthorizationResponse {
__typename
... on CaptureAuthorizationApproval {
__typename
paymentId
transactionId
tokenDetails {
token
}
activityDate
}
... on CaptureAuthorizationDecline {
__typename
paymentId
transactionId
message
}
}
errors {
... on InternalServiceError {
message
processorResponseCode
transactionId
}
... on RuleInViolationError {
message
processorResponseCode
transactionId
}
... on SyntaxOnNetworkResponseError {
message
processorResponseCode
transactionId
}
... on TimeoutOnNetworkResponseError {
message
processorResponseCode
transactionId
}
... on ValidationFailureError {
message
processorResponseCode
transactionId
}
... on PriorPaymentNotFoundError {
message
processorResponseCode
transactionId
}
}
}
}";
pub const VOID_TRANSACTION: &str =
"mutation ReverseTransaction($reverseTransactionInput: ReverseTransactionInput!) {
reverseTransaction(reverseTransactionInput: $reverseTransactionInput) {
errors {
... on InternalServiceError {
message
processorResponseCode
transactionId
}
... on RuleInViolationError {
message
processorResponseCode
transactionId
}
... on SyntaxOnNetworkResponseError {
message
processorResponseCode
transactionId
}
... on TimeoutOnNetworkResponseError {
message
processorResponseCode
transactionId
}
... on ValidationFailureError {
message
processorResponseCode
transactionId
}
... on PriorTransactionNotFoundError {
message
processorResponseCode
transactionId
}
}
reverseTransactionResponse {
paymentId
transactionId
... on ReverseTransactionApproval {
paymentId
transactionId
}
... on ReverseTransactionDecline {
message
paymentId
transactionId
declineType
}
}
}
}";
pub const REFUND_TRANSACTION: &str =
"mutation RefundPreviousPayment($refundPreviousPaymentInput: RefundPreviousPaymentInput!) {
refundPreviousPayment(refundPreviousPaymentInput: $refundPreviousPaymentInput) {
errors {
... on InternalServiceError {
message
processorResponseCode
transactionId
}
... on RuleInViolationError {
processorResponseCode
message
transactionId
}
... on SyntaxOnNetworkResponseError {
message
processorResponseCode
transactionId
}
... on TimeoutOnNetworkResponseError {
processorResponseCode
message
transactionId
}
... on ValidationFailureError {
message
processorResponseCode
transactionId
}
... on PriorPaymentNotFoundError {
message
processorResponseCode
transactionId
}
}
refundPreviousPaymentResponse {
__typename
... on RefundPreviousPaymentApproval {
__typename
paymentId
transactionId
}
... on RefundPreviousPaymentDecline {
__typename
declineType
message
transactionId
paymentId
}
}
}
}";
pub const SYNC_TRANSACTION: &str = "query PaymentTransaction($paymentTransactionId: UUID!) {
paymentTransaction(id: $paymentTransactionId) {
__typename
responseType
reference
id
paymentId
... on AcceptedSale {
__typename
id
processorResponseCode
processorResponseMessage
}
... on ApprovedAuthorization {
__typename
id
processorResponseCode
processorResponseMessage
}
... on ApprovedCapture {
__typename
id
processorResponseCode
processorResponseMessage
}
... on ApprovedReversal {
__typename
id
processorResponseCode
processorResponseMessage
}
... on DeclinedAuthorization {
__typename
id
processorResponseCode
processorResponseMessage
}
... on DeclinedCapture {
__typename
id
processorResponseCode
processorResponseMessage
}
... on DeclinedReversal {
__typename
id
processorResponseCode
processorResponseMessage
}
... on GenericPaymentTransaction {
__typename
id
processorResponseCode
processorResponseMessage
}
... on Authorization {
__typename
id
processorResponseCode
processorResponseMessage
}
... on Capture {
__typename
id
processorResponseCode
processorResponseMessage
}
... on Reversal {
__typename
id
processorResponseCode
processorResponseMessage
}
... on Sale {
__typename
id
processorResponseCode
processorResponseMessage
}
}
}";
| 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/ebanx/transformers.rs | crates/hyperswitch_connectors/src/connectors/ebanx/transformers.rs | #[cfg(feature = "payouts")]
use api_models::enums::Currency;
#[cfg(feature = "payouts")]
use api_models::payouts::{Bank, PayoutMethodData};
#[cfg(feature = "payouts")]
use common_enums::{PayoutStatus, PayoutType};
#[cfg(feature = "payouts")]
use common_utils::pii::Email;
use common_utils::types::FloatMajorUnit;
use hyperswitch_domain_models::router_data::ConnectorAuthType;
#[cfg(feature = "payouts")]
use hyperswitch_domain_models::router_flow_types::PoCreate;
#[cfg(feature = "payouts")]
use hyperswitch_domain_models::types::{PayoutsResponseData, PayoutsRouterData};
use hyperswitch_interfaces::errors::ConnectorError;
#[cfg(feature = "payouts")]
use masking::ExposeInterface;
use masking::Secret;
use serde::{Deserialize, Serialize};
#[cfg(feature = "payouts")]
use crate::types::PayoutsResponseRouterData;
#[cfg(feature = "payouts")]
use crate::utils::{
AddressDetailsData as _, CustomerDetails as _, PayoutsData as _, RouterData as _,
};
pub struct EbanxRouterData<T> {
pub amount: FloatMajorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc.
pub router_data: T,
}
impl<T> From<(FloatMajorUnit, T)> for EbanxRouterData<T> {
fn from((amount, item): (FloatMajorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
#[cfg(feature = "payouts")]
#[derive(Debug, Serialize, Clone)]
pub struct EbanxPayoutCreateRequest {
integration_key: Secret<String>,
external_reference: String,
country: String,
amount: FloatMajorUnit,
currency: Currency,
target: EbanxPayoutType,
target_account: Secret<String>,
payee: EbanxPayoutDetails,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Serialize, Clone)]
pub enum EbanxPayoutType {
BankAccount,
Mercadopago,
EwalletNequi,
PixKey,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Serialize, Clone)]
pub struct EbanxPayoutDetails {
name: Secret<String>,
email: Option<Email>,
document: Option<Secret<String>>,
document_type: Option<EbanxDocumentType>,
bank_info: EbanxBankDetails,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Serialize, Clone)]
pub enum EbanxDocumentType {
#[serde(rename = "CPF")]
NaturalPersonsRegister,
#[serde(rename = "CNPJ")]
NationalRegistryOfLegalEntities,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Serialize, Clone)]
pub struct EbanxBankDetails {
bank_name: Option<String>,
bank_branch: Option<String>,
bank_account: Option<Secret<String>>,
account_type: Option<EbanxBankAccountType>,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Serialize, Clone)]
pub enum EbanxBankAccountType {
#[serde(rename = "C")]
CheckingAccount,
}
#[cfg(feature = "payouts")]
impl TryFrom<&EbanxRouterData<&PayoutsRouterData<PoCreate>>> for EbanxPayoutCreateRequest {
type Error = error_stack::Report<ConnectorError>;
fn try_from(item: &EbanxRouterData<&PayoutsRouterData<PoCreate>>) -> Result<Self, Self::Error> {
let ebanx_auth_type = EbanxAuthType::try_from(&item.router_data.connector_auth_type)?;
match item.router_data.get_payout_method_data()? {
PayoutMethodData::Bank(Bank::Pix(pix_data)) => {
let bank_info = EbanxBankDetails {
bank_account: Some(pix_data.bank_account_number),
bank_branch: pix_data.bank_branch,
bank_name: pix_data.bank_name,
account_type: Some(EbanxBankAccountType::CheckingAccount),
};
let billing_address = item.router_data.get_billing_address()?;
let customer_details = item.router_data.request.get_customer_details()?;
let document_type = pix_data.tax_id.clone().map(|tax_id| {
if tax_id.clone().expose().len() == 11 {
EbanxDocumentType::NaturalPersonsRegister
} else {
EbanxDocumentType::NationalRegistryOfLegalEntities
}
});
let payee = EbanxPayoutDetails {
name: billing_address.get_full_name()?,
email: customer_details.email.clone(),
bank_info,
document_type,
document: pix_data.tax_id.to_owned(),
};
Ok(Self {
amount: item.amount,
integration_key: ebanx_auth_type.integration_key,
country: customer_details.get_customer_phone_country_code()?,
currency: item.router_data.request.source_currency,
external_reference: item.router_data.connector_request_reference_id.to_owned(),
target: EbanxPayoutType::PixKey,
target_account: pix_data.pix_key,
payee,
})
}
PayoutMethodData::Card(_)
| PayoutMethodData::Bank(_)
| PayoutMethodData::Wallet(_)
| PayoutMethodData::BankRedirect(_)
| PayoutMethodData::Passthrough(_) => Err(ConnectorError::NotSupported {
message: "Payment Method Not Supported".to_string(),
connector: "Ebanx",
})?,
}
}
}
pub struct EbanxAuthType {
pub integration_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for EbanxAuthType {
type Error = error_stack::Report<ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
integration_key: api_key.to_owned(),
}),
_ => Err(ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[cfg(feature = "payouts")]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum EbanxPayoutStatus {
#[serde(rename = "PA")]
Succeeded,
#[serde(rename = "CA")]
Cancelled,
#[serde(rename = "PE")]
Processing,
#[serde(rename = "OP")]
RequiresFulfillment,
}
#[cfg(feature = "payouts")]
impl From<EbanxPayoutStatus> for PayoutStatus {
fn from(item: EbanxPayoutStatus) -> Self {
match item {
EbanxPayoutStatus::Succeeded => Self::Success,
EbanxPayoutStatus::Cancelled => Self::Cancelled,
EbanxPayoutStatus::Processing => Self::Pending,
EbanxPayoutStatus::RequiresFulfillment => Self::RequiresFulfillment,
}
}
}
#[cfg(feature = "payouts")]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EbanxPayoutResponse {
payout: EbanxPayoutResponseDetails,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EbanxPayoutResponseDetails {
uid: String,
status: EbanxPayoutStatus,
}
#[cfg(feature = "payouts")]
impl<F> TryFrom<PayoutsResponseRouterData<F, EbanxPayoutResponse>> for PayoutsRouterData<F> {
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: PayoutsResponseRouterData<F, EbanxPayoutResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(PayoutsResponseData {
status: Some(PayoutStatus::from(item.response.payout.status)),
connector_payout_id: Some(item.response.payout.uid),
payout_eligible: None,
should_add_next_step_to_process_tracker: false,
error_code: None,
error_message: None,
payout_connector_metadata: None,
}),
..item.data
})
}
}
#[cfg(feature = "payouts")]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EbanxPayoutFulfillRequest {
integration_key: Secret<String>,
uid: String,
}
#[cfg(feature = "payouts")]
impl<F> TryFrom<&EbanxRouterData<&PayoutsRouterData<F>>> for EbanxPayoutFulfillRequest {
type Error = error_stack::Report<ConnectorError>;
fn try_from(item: &EbanxRouterData<&PayoutsRouterData<F>>) -> Result<Self, Self::Error> {
let request = item.router_data.request.to_owned();
let ebanx_auth_type = EbanxAuthType::try_from(&item.router_data.connector_auth_type)?;
let payout_type = request.get_payout_type()?;
match payout_type {
PayoutType::Bank => Ok(Self {
integration_key: ebanx_auth_type.integration_key,
uid: request
.connector_payout_id
.to_owned()
.ok_or(ConnectorError::MissingRequiredField { field_name: "uid" })?,
}),
PayoutType::Card | PayoutType::Wallet | PayoutType::BankRedirect => {
Err(ConnectorError::NotSupported {
message: "Payout Method Not Supported".to_string(),
connector: "Ebanx",
})?
}
}
}
}
#[cfg(feature = "payouts")]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EbanxFulfillResponse {
#[serde(rename = "type")]
status: EbanxFulfillStatus,
message: String,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum EbanxFulfillStatus {
Success,
ApiError,
AuthenticationError,
InvalidRequestError,
RequestError,
}
#[cfg(feature = "payouts")]
impl From<EbanxFulfillStatus> for PayoutStatus {
fn from(item: EbanxFulfillStatus) -> Self {
match item {
EbanxFulfillStatus::Success => Self::Success,
EbanxFulfillStatus::ApiError
| EbanxFulfillStatus::AuthenticationError
| EbanxFulfillStatus::InvalidRequestError
| EbanxFulfillStatus::RequestError => Self::Failed,
}
}
}
#[cfg(feature = "payouts")]
impl<F> TryFrom<PayoutsResponseRouterData<F, EbanxFulfillResponse>> for PayoutsRouterData<F> {
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: PayoutsResponseRouterData<F, EbanxFulfillResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(PayoutsResponseData {
status: Some(PayoutStatus::from(item.response.status)),
connector_payout_id: Some(item.data.request.get_transfer_id()?),
payout_eligible: None,
should_add_next_step_to_process_tracker: false,
error_code: None,
error_message: None,
payout_connector_metadata: None,
}),
..item.data
})
}
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct EbanxErrorResponse {
pub code: String,
pub status_code: String,
pub message: Option<String>,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EbanxPayoutCancelRequest {
integration_key: Secret<String>,
uid: String,
}
#[cfg(feature = "payouts")]
impl<F> TryFrom<&PayoutsRouterData<F>> for EbanxPayoutCancelRequest {
type Error = error_stack::Report<ConnectorError>;
fn try_from(item: &PayoutsRouterData<F>) -> Result<Self, Self::Error> {
let request = item.request.to_owned();
let ebanx_auth_type = EbanxAuthType::try_from(&item.connector_auth_type)?;
let payout_type = request.get_payout_type()?;
match payout_type {
PayoutType::Bank => Ok(Self {
integration_key: ebanx_auth_type.integration_key,
uid: request
.connector_payout_id
.to_owned()
.ok_or(ConnectorError::MissingRequiredField { field_name: "uid" })?,
}),
PayoutType::Card | PayoutType::Wallet | PayoutType::BankRedirect => {
Err(ConnectorError::NotSupported {
message: "Payout Method Not Supported".to_string(),
connector: "Ebanx",
})?
}
}
}
}
#[cfg(feature = "payouts")]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EbanxCancelResponse {
#[serde(rename = "type")]
status: EbanxCancelStatus,
message: String,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum EbanxCancelStatus {
Success,
ApiError,
AuthenticationError,
InvalidRequestError,
RequestError,
}
#[cfg(feature = "payouts")]
impl From<EbanxCancelStatus> for PayoutStatus {
fn from(item: EbanxCancelStatus) -> Self {
match item {
EbanxCancelStatus::Success => Self::Cancelled,
EbanxCancelStatus::ApiError
| EbanxCancelStatus::AuthenticationError
| EbanxCancelStatus::InvalidRequestError
| EbanxCancelStatus::RequestError => Self::Failed,
}
}
}
#[cfg(feature = "payouts")]
impl<F> TryFrom<PayoutsResponseRouterData<F, EbanxCancelResponse>> for PayoutsRouterData<F> {
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: PayoutsResponseRouterData<F, EbanxCancelResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(PayoutsResponseData {
status: Some(PayoutStatus::from(item.response.status)),
connector_payout_id: item.data.request.connector_payout_id.clone(),
payout_eligible: None,
should_add_next_step_to_process_tracker: false,
error_code: None,
error_message: None,
payout_connector_metadata: None,
}),
..item.data
})
}
}
| 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/recurly/transformers.rs | crates/hyperswitch_connectors/src/connectors/recurly/transformers.rs | #[cfg(all(feature = "v2", feature = "revenue_recovery"))]
use std::str::FromStr;
use common_enums::enums;
#[cfg(all(feature = "v2", feature = "revenue_recovery"))]
use common_utils::types::{ConnectorTransactionId, FloatMajorUnitForConnector};
use common_utils::{
errors::CustomResult,
ext_traits::ByteSliceExt,
id_type,
types::{FloatMajorUnit, StringMinorUnit},
};
use error_stack::ResultExt;
use hyperswitch_domain_models::router_data::ConnectorAuthType;
#[cfg(all(feature = "v2", feature = "revenue_recovery"))]
use hyperswitch_domain_models::{
router_data_v2::flow_common_types as recovery_flow_common_types,
router_flow_types::revenue_recovery as recovery_router_flows,
router_request_types::revenue_recovery as recovery_request_types,
router_response_types::revenue_recovery as recovery_response_types,
types as recovery_router_data_types,
};
use hyperswitch_interfaces::errors;
use masking::Secret;
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
#[cfg(all(feature = "v2", feature = "revenue_recovery"))]
use crate::{types::ResponseRouterDataV2, utils};
pub struct RecurlyRouterData<T> {
pub amount: StringMinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc.
pub router_data: T,
}
impl<T> From<(StringMinorUnit, T)> for RecurlyRouterData<T> {
fn from((amount, item): (StringMinorUnit, T)) -> Self {
//Todo : use utils to convert the amount to the type of amount that a connector accepts
Self {
amount,
router_data: item,
}
}
}
// Auth Struct
pub struct RecurlyAuthType {
pub(super) api_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for RecurlyAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
api_key: api_key.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
//TODO: Fill the struct with respective fields
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct RecurlyErrorResponse {
pub status_code: u16,
pub code: String,
pub message: String,
pub reason: Option<String>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct RecurlyWebhookBody {
// Transaction uuid
pub uuid: String,
pub event_type: RecurlyPaymentEventType,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy)]
pub enum RecurlyPaymentEventType {
#[serde(rename = "succeeded")]
PaymentSucceeded,
#[serde(rename = "failed")]
PaymentFailed,
}
impl RecurlyWebhookBody {
pub fn get_webhook_object_from_body(body: &[u8]) -> CustomResult<Self, errors::ConnectorError> {
let webhook_body = body
.parse_struct::<Self>("RecurlyWebhookBody")
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
Ok(webhook_body)
}
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy)]
pub enum RecurlyChargeStatus {
#[serde(rename = "success")]
Succeeded,
#[serde(rename = "declined")]
Failed,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy)]
#[serde(rename_all = "snake_case")]
pub enum RecurlyFundingTypes {
Credit,
Debit,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy)]
#[serde(rename_all = "snake_case")]
pub enum RecurlyPaymentObject {
CreditCard,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct RecurlyRecoveryDetailsData {
pub amount: FloatMajorUnit,
pub currency: common_enums::Currency,
pub id: String,
pub status_code: Option<String>,
pub status_message: Option<String>,
pub account: Account,
pub invoice: Invoice,
pub payment_method: PaymentMethod,
pub payment_gateway: PaymentGateway,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
pub status: RecurlyChargeStatus,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct PaymentMethod {
pub gateway_token: String,
pub funding_source: RecurlyFundingTypes,
pub object: RecurlyPaymentObject,
pub card_type: common_enums::CardNetwork,
pub first_six: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Invoice {
pub id: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Account {
pub id: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct PaymentGateway {
pub id: String,
}
#[cfg(all(feature = "v2", feature = "revenue_recovery"))]
impl
TryFrom<
ResponseRouterDataV2<
recovery_router_flows::BillingConnectorPaymentsSync,
RecurlyRecoveryDetailsData,
recovery_flow_common_types::BillingConnectorPaymentsSyncFlowData,
recovery_request_types::BillingConnectorPaymentsSyncRequest,
recovery_response_types::BillingConnectorPaymentsSyncResponse,
>,
> for recovery_router_data_types::BillingConnectorPaymentsSyncRouterDataV2
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterDataV2<
recovery_router_flows::BillingConnectorPaymentsSync,
RecurlyRecoveryDetailsData,
recovery_flow_common_types::BillingConnectorPaymentsSyncFlowData,
recovery_request_types::BillingConnectorPaymentsSyncRequest,
recovery_response_types::BillingConnectorPaymentsSyncResponse,
>,
) -> Result<Self, Self::Error> {
let merchant_reference_id =
id_type::PaymentReferenceId::from_str(&item.response.invoice.id)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
let connector_transaction_id = Some(ConnectorTransactionId::from(item.response.id));
Ok(Self {
response: Ok(
recovery_response_types::BillingConnectorPaymentsSyncResponse {
status: item.response.status.into(),
amount: utils::convert_back_amount_to_minor_units(
&FloatMajorUnitForConnector,
item.response.amount,
item.response.currency,
)?,
currency: item.response.currency,
merchant_reference_id,
connector_account_reference_id: item.response.payment_gateway.id,
connector_transaction_id,
error_code: item.response.status_code,
error_message: item.response.status_message,
processor_payment_method_token: item.response.payment_method.gateway_token,
connector_customer_id: item.response.account.id,
transaction_created_at: Some(item.response.created_at),
payment_method_sub_type: common_enums::PaymentMethodType::from(
item.response.payment_method.funding_source,
),
payment_method_type: common_enums::PaymentMethod::from(
item.response.payment_method.object,
),
// This none because this field is specific to stripebilling.
charge_id: None,
// Need to populate these card info field
card_info: api_models::payments::AdditionalCardInfo {
card_network: Some(item.response.payment_method.card_type),
card_isin: Some(item.response.payment_method.first_six),
card_issuer: None,
card_type: None,
card_issuing_country: None,
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<RecurlyChargeStatus> for enums::AttemptStatus {
fn from(status: RecurlyChargeStatus) -> Self {
match status {
RecurlyChargeStatus::Succeeded => Self::Charged,
RecurlyChargeStatus::Failed => Self::Failure,
}
}
}
#[cfg(all(feature = "v2", feature = "revenue_recovery"))]
impl From<RecurlyFundingTypes> for common_enums::PaymentMethodType {
fn from(funding: RecurlyFundingTypes) -> Self {
match funding {
RecurlyFundingTypes::Credit => Self::Credit,
RecurlyFundingTypes::Debit => Self::Debit,
}
}
}
#[cfg(all(feature = "v2", feature = "revenue_recovery"))]
impl From<RecurlyPaymentObject> for common_enums::PaymentMethod {
fn from(funding: RecurlyPaymentObject) -> Self {
match funding {
RecurlyPaymentObject::CreditCard => Self::Card,
}
}
}
#[derive(Debug, Serialize, Clone, Copy)]
#[serde(rename_all = "snake_case")]
pub enum RecurlyRecordStatus {
Success,
Failure,
}
#[cfg(all(feature = "v2", feature = "revenue_recovery"))]
impl TryFrom<enums::AttemptStatus> for RecurlyRecordStatus {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(status: enums::AttemptStatus) -> Result<Self, Self::Error> {
match status {
enums::AttemptStatus::Charged
| enums::AttemptStatus::PartialCharged
| enums::AttemptStatus::PartialChargedAndChargeable => Ok(Self::Success),
enums::AttemptStatus::Failure
| enums::AttemptStatus::CaptureFailed
| enums::AttemptStatus::RouterDeclined => Ok(Self::Failure),
enums::AttemptStatus::AuthenticationFailed
| enums::AttemptStatus::Started
| enums::AttemptStatus::AuthenticationPending
| enums::AttemptStatus::AuthenticationSuccessful
| enums::AttemptStatus::Authorized
| enums::AttemptStatus::PartiallyAuthorized
| enums::AttemptStatus::AuthorizationFailed
| enums::AttemptStatus::Authorizing
| enums::AttemptStatus::CodInitiated
| enums::AttemptStatus::Voided
| enums::AttemptStatus::VoidedPostCharge
| enums::AttemptStatus::VoidInitiated
| enums::AttemptStatus::CaptureInitiated
| enums::AttemptStatus::VoidFailed
| enums::AttemptStatus::AutoRefunded
| enums::AttemptStatus::Unresolved
| enums::AttemptStatus::Pending
| enums::AttemptStatus::PaymentMethodAwaited
| enums::AttemptStatus::ConfirmationAwaited
| enums::AttemptStatus::DeviceDataCollectionPending
| enums::AttemptStatus::IntegrityFailure
| enums::AttemptStatus::Expired => Err(errors::ConnectorError::NotSupported {
message: "Record back flow is only supported for terminal status".to_string(),
connector: "recurly",
}
.into()),
}
}
}
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct RecurlyRecordBackResponse {
// Invoice id
pub id: id_type::PaymentReferenceId,
}
#[cfg(all(feature = "v2", feature = "revenue_recovery"))]
impl
TryFrom<
ResponseRouterDataV2<
recovery_router_flows::InvoiceRecordBack,
RecurlyRecordBackResponse,
recovery_flow_common_types::InvoiceRecordBackData,
recovery_request_types::InvoiceRecordBackRequest,
recovery_response_types::InvoiceRecordBackResponse,
>,
> for recovery_router_data_types::InvoiceRecordBackRouterDataV2
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterDataV2<
recovery_router_flows::InvoiceRecordBack,
RecurlyRecordBackResponse,
recovery_flow_common_types::InvoiceRecordBackData,
recovery_request_types::InvoiceRecordBackRequest,
recovery_response_types::InvoiceRecordBackResponse,
>,
) -> Result<Self, Self::Error> {
let merchant_reference_id = item.response.id;
Ok(Self {
response: Ok(recovery_response_types::InvoiceRecordBackResponse {
merchant_reference_id,
}),
..item.data
})
}
}
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct RecurlyInvoiceSyncResponse {
pub id: String,
pub total: FloatMajorUnit,
pub currency: common_enums::Currency,
pub address: Option<RecurlyInvoiceBillingAddress>,
pub line_items: Vec<RecurlyLineItems>,
pub transactions: Vec<RecurlyInvoiceTransactionsStatus>,
}
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct RecurlyInvoiceBillingAddress {
pub street1: Option<Secret<String>>,
pub street2: Option<Secret<String>>,
pub region: Option<Secret<String>>,
pub country: Option<enums::CountryAlpha2>,
pub postal_code: Option<Secret<String>>,
pub city: Option<String>,
}
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct RecurlyLineItems {
#[serde(rename = "type")]
pub invoice_type: RecurlyInvoiceLineItemType,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub start_date: PrimitiveDateTime,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub end_date: PrimitiveDateTime,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy)]
#[serde(rename_all = "snake_case")]
pub enum RecurlyInvoiceLineItemType {
Credit,
Charge,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "snake_case")]
pub struct RecurlyInvoiceTransactionsStatus {
pub status: String,
}
#[cfg(all(feature = "v2", feature = "revenue_recovery"))]
impl
TryFrom<
ResponseRouterDataV2<
recovery_router_flows::BillingConnectorInvoiceSync,
RecurlyInvoiceSyncResponse,
recovery_flow_common_types::BillingConnectorInvoiceSyncFlowData,
recovery_request_types::BillingConnectorInvoiceSyncRequest,
recovery_response_types::BillingConnectorInvoiceSyncResponse,
>,
> for recovery_router_data_types::BillingConnectorInvoiceSyncRouterDataV2
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterDataV2<
recovery_router_flows::BillingConnectorInvoiceSync,
RecurlyInvoiceSyncResponse,
recovery_flow_common_types::BillingConnectorInvoiceSyncFlowData,
recovery_request_types::BillingConnectorInvoiceSyncRequest,
recovery_response_types::BillingConnectorInvoiceSyncResponse,
>,
) -> Result<Self, Self::Error> {
#[allow(clippy::as_conversions)]
// No of retries never exceeds u16 in recurly. So its better to suppress the clippy warning
let retry_count = item.response.transactions.len() as u16;
let merchant_reference_id = id_type::PaymentReferenceId::from_str(&item.response.id)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
Ok(Self {
response: Ok(
recovery_response_types::BillingConnectorInvoiceSyncResponse {
amount: utils::convert_back_amount_to_minor_units(
&FloatMajorUnitForConnector,
item.response.total,
item.response.currency,
)?,
currency: item.response.currency,
merchant_reference_id,
retry_count: Some(retry_count),
billing_address: Some(api_models::payments::Address {
address: Some(api_models::payments::AddressDetails {
city: item
.response
.address
.clone()
.and_then(|address| address.city),
state: item
.response
.address
.clone()
.and_then(|address| address.region),
country: item
.response
.address
.clone()
.and_then(|address| address.country),
line1: item
.response
.address
.clone()
.and_then(|address| address.street1),
line2: item
.response
.address
.clone()
.and_then(|address| address.street2),
line3: None,
zip: item
.response
.address
.clone()
.and_then(|address| address.postal_code),
first_name: None,
last_name: None,
origin_zip: None,
}),
phone: None,
email: None,
}),
created_at: item.response.line_items.first().map(|line| line.start_date),
ends_at: item.response.line_items.first().map(|line| line.end_date),
},
),
..item.data
})
}
}
| 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/flexiti/transformers.rs | crates/hyperswitch_connectors/src/connectors/flexiti/transformers.rs | use common_enums::enums;
use common_utils::{pii::Email, request::Method, types::FloatMajorUnit};
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{AccessToken, ConnectorAuthType, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
types::{PaymentsAuthorizeRouterData, RefundsRouterData},
};
use hyperswitch_interfaces::errors;
use masking::Secret;
use serde::{Deserialize, Serialize};
use crate::{
types::{self, RefundsResponseRouterData, ResponseRouterData},
utils::{
self, AddressDetailsData, BrowserInformationData, PaymentsAuthorizeRequestData,
RouterData as _,
},
};
pub struct FlexitiRouterData<T> {
pub amount: FloatMajorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc.
pub router_data: T,
}
impl<T> From<(FloatMajorUnit, T)> for FlexitiRouterData<T> {
fn from((amount, item): (FloatMajorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
#[derive(Debug, Serialize)]
pub struct FlexitiPaymentsRequest {
merchant_order_id: Option<String>,
lang: String,
flow: FlexitiFlow,
amount_requested: FloatMajorUnit,
email: Option<Email>,
fname: Secret<String>,
billing_information: BillingInformation,
shipping_information: ShippingInformation,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum FlexitiFlow {
#[serde(rename = "apply/buy")]
ApplyAndBuy,
Apply,
Buy,
}
#[derive(Debug, Serialize)]
pub struct BillingInformation {
first_name: Secret<String>,
last_name: Secret<String>,
address_1: Secret<String>,
address_2: Secret<String>,
city: Secret<String>,
postal_code: Secret<String>,
province: Secret<String>,
}
#[derive(Debug, Serialize)]
pub struct ShippingInformation {
first_name: Secret<String>,
last_name: Secret<String>,
address_1: Secret<String>,
address_2: Secret<String>,
city: Secret<String>,
postal_code: Secret<String>,
province: Secret<String>,
}
impl TryFrom<&FlexitiRouterData<&PaymentsAuthorizeRouterData>> for FlexitiPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &FlexitiRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::PayLater(pay_later_data) => match pay_later_data {
hyperswitch_domain_models::payment_method_data::PayLaterData::FlexitiRedirect { } => {
let shipping_address = item.router_data.get_shipping_address()?;
let shipping_information = ShippingInformation {
first_name: shipping_address.get_first_name()?.to_owned(),
last_name: shipping_address.get_last_name()?.to_owned(),
address_1: shipping_address.get_line1()?.to_owned(),
address_2: shipping_address.get_line2()?.to_owned(),
city: shipping_address.get_city()?.to_owned().into(),
postal_code: shipping_address.get_zip()?.to_owned(),
province: shipping_address.to_state_code()?,
};
let billing_information = BillingInformation {
first_name: item.router_data.get_billing_first_name()?,
last_name: item.router_data.get_billing_last_name()?,
address_1: item.router_data.get_billing_line1()?,
address_2: item.router_data.get_billing_line2()?,
city: item.router_data.get_billing_city()?.into(),
postal_code: item.router_data.get_billing_zip()?,
province: item.router_data.get_billing_state_code()?,
};
Ok(Self {
merchant_order_id: item.router_data.request.merchant_order_reference_id.to_owned(),
lang: item.router_data.request.get_browser_info()?.get_language()?,
flow: FlexitiFlow::ApplyAndBuy,
amount_requested: item.amount.to_owned(),
email: item.router_data.get_optional_billing_email(),
fname: item.router_data.get_billing_first_name()?,
billing_information,
shipping_information,
})
},
hyperswitch_domain_models::payment_method_data::PayLaterData::KlarnaRedirect { } |
hyperswitch_domain_models::payment_method_data::PayLaterData::KlarnaSdk { .. } |
hyperswitch_domain_models::payment_method_data::PayLaterData::AffirmRedirect { } |
hyperswitch_domain_models::payment_method_data::PayLaterData::BreadpayRedirect { } |
hyperswitch_domain_models::payment_method_data::PayLaterData::AfterpayClearpayRedirect { } |
hyperswitch_domain_models::payment_method_data::PayLaterData::PayBrightRedirect { } |
hyperswitch_domain_models::payment_method_data::PayLaterData::WalleyRedirect { } |
hyperswitch_domain_models::payment_method_data::PayLaterData::AlmaRedirect { } |
hyperswitch_domain_models::payment_method_data::PayLaterData::AtomeRedirect { } |
hyperswitch_domain_models::payment_method_data::PayLaterData::PayjustnowRedirect { } => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("flexiti"),
))
}?,
}
_ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()),
}
}
}
#[derive(Debug, Serialize)]
pub struct FlexitiAccessTokenRequest {
client_id: Secret<String>,
client_secret: Secret<String>,
grant_type: FlexitiGranttype,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum FlexitiGranttype {
Password,
RefreshToken,
ClientCredentials,
}
impl TryFrom<&types::RefreshTokenRouterData> for FlexitiAccessTokenRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::RefreshTokenRouterData) -> Result<Self, Self::Error> {
let auth_details = FlexitiAuthType::try_from(&item.connector_auth_type)?;
Ok(Self {
client_id: auth_details.client_id,
client_secret: auth_details.client_secret,
grant_type: FlexitiGranttype::ClientCredentials,
})
}
}
impl<F, T> TryFrom<ResponseRouterData<F, FlexitiAccessTokenResponse, T, AccessToken>>
for RouterData<F, T, AccessToken>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, FlexitiAccessTokenResponse, T, AccessToken>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(AccessToken {
token: item.response.access_token,
expires: item.response.expires_in,
}),
..item.data
})
}
}
// Auth Struct
pub struct FlexitiAuthType {
pub(super) client_id: Secret<String>,
pub(super) client_secret: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for FlexitiAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
client_id: api_key.to_owned(),
client_secret: key1.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct FlexitiAccessTokenResponse {
access_token: Secret<String>,
expires_in: i64,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FlexitiPaymentsResponse {
redirection_url: url::Url,
online_order_id: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FlexitiSyncResponse {
transaction_id: String,
purchase: FlexitiPurchase,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FlexitiPurchase {
status: FlexitiPurchaseStatus,
}
// Since this is an alpha integration, we don't have access to all the status mapping. This needs to be updated.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum FlexitiPurchaseStatus {
Success,
Failed,
}
// Since this is an alpha integration, we don't have access to all the status mapping. This needs to be updated.
impl From<FlexitiPurchaseStatus> for common_enums::AttemptStatus {
fn from(item: FlexitiPurchaseStatus) -> Self {
match item {
FlexitiPurchaseStatus::Success => Self::Authorized,
FlexitiPurchaseStatus::Failed => Self::Failure,
}
}
}
impl<F, T> TryFrom<ResponseRouterData<F, FlexitiSyncResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, FlexitiSyncResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: common_enums::AttemptStatus::from(item.response.purchase.status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.transaction_id.to_owned(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
impl<F, T> TryFrom<ResponseRouterData<F, FlexitiPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, FlexitiPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: common_enums::AttemptStatus::AuthenticationPending,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.online_order_id.to_owned(),
),
redirection_data: Box::new(Some(RedirectForm::from((
item.response.redirection_url,
Method::Get,
)))),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
//TODO: Fill the struct with respective fields
// REFUND :
// Type definition for RefundRequest
#[derive(Default, Debug, Serialize)]
pub struct FlexitiRefundRequest {
pub amount: FloatMajorUnit,
}
impl<F> TryFrom<&FlexitiRouterData<&RefundsRouterData<F>>> for FlexitiRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &FlexitiRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.amount.to_owned(),
})
}
}
// Type definition for Refund Response
#[allow(dead_code)]
#[derive(Debug, Copy, Serialize, Default, Deserialize, Clone)]
pub enum RefundStatus {
Succeeded,
Failed,
#[default]
Processing,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Succeeded => Self::Success,
RefundStatus::Failed => Self::Failure,
RefundStatus::Processing => Self::Pending,
//TODO: Review mapping
}
}
}
//TODO: Fill the struct with respective fields
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct RefundResponse {
id: String,
status: RefundStatus,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct FlexitiErrorResponse {
pub message: String,
pub error: String,
}
| 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/tsys/transformers.rs | crates/hyperswitch_connectors/src/connectors/tsys/transformers.rs | use common_enums::enums;
use common_utils::types::StringMinorUnit;
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{self, ConnectorAuthType, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RefundsResponseData},
types::{
self, PaymentsCancelRouterData, PaymentsSyncRouterData, RefundSyncRouterData,
RefundsRouterData,
},
};
use hyperswitch_interfaces::errors;
use masking::Secret;
use serde::{Deserialize, Serialize};
pub struct TsysRouterData<T> {
pub amount: StringMinorUnit,
pub router_data: T,
}
impl<T> From<(StringMinorUnit, T)> for TsysRouterData<T> {
fn from((amount, router_data): (StringMinorUnit, T)) -> Self {
Self {
amount,
router_data,
}
}
}
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{self, CardData as _, PaymentsAuthorizeRequestData, RefundsRequestData as _},
};
#[derive(Debug, Serialize)]
pub enum TsysPaymentsRequest {
Auth(TsysPaymentAuthSaleRequest),
Sale(TsysPaymentAuthSaleRequest),
}
#[derive(Default, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TsysPaymentAuthSaleRequest {
#[serde(rename = "deviceID")]
device_id: Secret<String>,
transaction_key: Secret<String>,
card_data_source: String,
transaction_amount: StringMinorUnit,
currency_code: enums::Currency,
card_number: cards::CardNumber,
expiration_date: Secret<String>,
cvv2: Secret<String>,
order_number: String,
terminal_capability: String,
terminal_operating_environment: String,
cardholder_authentication_method: String,
#[serde(rename = "developerID")]
developer_id: Secret<String>,
}
impl TryFrom<&TsysRouterData<&types::PaymentsAuthorizeRouterData>> for TsysPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item_data: &TsysRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let item = item_data.router_data.clone();
match item.request.payment_method_data.clone() {
PaymentMethodData::Card(ccard) => {
let connector_auth: TsysAuthType =
TsysAuthType::try_from(&item.connector_auth_type)?;
let auth_data: TsysPaymentAuthSaleRequest = TsysPaymentAuthSaleRequest {
device_id: connector_auth.device_id,
transaction_key: connector_auth.transaction_key,
card_data_source: "INTERNET".to_string(),
transaction_amount: item_data.amount.clone(),
currency_code: item.request.currency,
card_number: ccard.card_number.clone(),
expiration_date: ccard
.get_card_expiry_month_year_2_digit_with_delimiter("/".to_owned())?,
cvv2: ccard.card_cvc,
order_number: item.connector_request_reference_id.clone(),
terminal_capability: "ICC_CHIP_READ_ONLY".to_string(),
terminal_operating_environment: "ON_MERCHANT_PREMISES_ATTENDED".to_string(),
cardholder_authentication_method: "NOT_AUTHENTICATED".to_string(),
developer_id: connector_auth.developer_id,
};
if item.request.is_auto_capture()? {
Ok(Self::Sale(auth_data))
} else {
Ok(Self::Auth(auth_data))
}
}
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("tsys"),
))?
}
}
}
}
// Auth Struct
pub struct TsysAuthType {
pub(super) device_id: Secret<String>,
pub(super) transaction_key: Secret<String>,
pub(super) developer_id: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for TsysAuthType {
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 {
device_id: api_key.to_owned(),
transaction_key: key1.to_owned(),
developer_id: api_secret.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
// PaymentsResponse
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum TsysPaymentStatus {
Pass,
Fail,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum TsysTransactionStatus {
Approved,
Declined,
Void,
}
impl From<TsysTransactionDetails> for enums::AttemptStatus {
fn from(item: TsysTransactionDetails) -> Self {
match item.transaction_status {
TsysTransactionStatus::Approved => {
if item.transaction_type.contains("Auth-Only") {
Self::Authorized
} else {
Self::Charged
}
}
TsysTransactionStatus::Void => Self::Voided,
TsysTransactionStatus::Declined => Self::Failure,
}
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TsysErrorResponse {
pub status: TsysPaymentStatus,
pub response_code: String,
pub response_message: String,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TsysTransactionDetails {
#[serde(rename = "transactionID")]
transaction_id: String,
transaction_type: String,
transaction_status: TsysTransactionStatus,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TsysPaymentsSyncResponse {
pub status: TsysPaymentStatus,
pub response_code: String,
pub response_message: String,
pub transaction_details: TsysTransactionDetails,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TsysResponse {
pub status: TsysPaymentStatus,
pub response_code: String,
pub response_message: String,
#[serde(rename = "transactionID")]
pub transaction_id: String,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(untagged)]
pub enum TsysResponseTypes {
SuccessResponse(TsysResponse),
ErrorResponse(TsysErrorResponse),
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[allow(clippy::enum_variant_names)]
pub enum TsysPaymentsResponse {
AuthResponse(TsysResponseTypes),
SaleResponse(TsysResponseTypes),
CaptureResponse(TsysResponseTypes),
VoidResponse(TsysResponseTypes),
}
fn get_error_response(
connector_response: TsysErrorResponse,
status_code: u16,
) -> router_data::ErrorResponse {
router_data::ErrorResponse {
code: connector_response.response_code,
message: connector_response.response_message.clone(),
reason: Some(connector_response.response_message),
status_code,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}
}
fn get_payments_response(connector_response: TsysResponse) -> PaymentsResponseData {
PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(connector_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(connector_response.transaction_id),
incremental_authorization_allowed: None,
charges: None,
}
}
fn get_payments_sync_response(
connector_response: &TsysPaymentsSyncResponse,
) -> PaymentsResponseData {
PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
connector_response
.transaction_details
.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(
connector_response
.transaction_details
.transaction_id
.clone(),
),
incremental_authorization_allowed: None,
charges: None,
}
}
impl<F, T> TryFrom<ResponseRouterData<F, TsysPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, TsysPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let (response, status) = match item.response {
TsysPaymentsResponse::AuthResponse(resp) => match resp {
TsysResponseTypes::SuccessResponse(auth_response) => (
Ok(get_payments_response(auth_response)),
enums::AttemptStatus::Authorized,
),
TsysResponseTypes::ErrorResponse(connector_response) => (
Err(get_error_response(connector_response, item.http_code)),
enums::AttemptStatus::AuthorizationFailed,
),
},
TsysPaymentsResponse::SaleResponse(resp) => match resp {
TsysResponseTypes::SuccessResponse(sale_response) => (
Ok(get_payments_response(sale_response)),
enums::AttemptStatus::Charged,
),
TsysResponseTypes::ErrorResponse(connector_response) => (
Err(get_error_response(connector_response, item.http_code)),
enums::AttemptStatus::Failure,
),
},
TsysPaymentsResponse::CaptureResponse(resp) => match resp {
TsysResponseTypes::SuccessResponse(capture_response) => (
Ok(get_payments_response(capture_response)),
enums::AttemptStatus::Charged,
),
TsysResponseTypes::ErrorResponse(connector_response) => (
Err(get_error_response(connector_response, item.http_code)),
enums::AttemptStatus::CaptureFailed,
),
},
TsysPaymentsResponse::VoidResponse(resp) => match resp {
TsysResponseTypes::SuccessResponse(void_response) => (
Ok(get_payments_response(void_response)),
enums::AttemptStatus::Voided,
),
TsysResponseTypes::ErrorResponse(connector_response) => (
Err(get_error_response(connector_response, item.http_code)),
enums::AttemptStatus::VoidFailed,
),
},
};
Ok(Self {
status,
response,
..item.data
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TsysSearchTransactionRequest {
#[serde(rename = "deviceID")]
device_id: Secret<String>,
transaction_key: Secret<String>,
#[serde(rename = "transactionID")]
transaction_id: String,
#[serde(rename = "developerID")]
developer_id: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "PascalCase")]
pub struct TsysSyncRequest {
search_transaction: TsysSearchTransactionRequest,
}
impl TryFrom<&PaymentsSyncRouterData> for TsysSyncRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsSyncRouterData) -> Result<Self, Self::Error> {
let connector_auth: TsysAuthType = TsysAuthType::try_from(&item.connector_auth_type)?;
let search_transaction = TsysSearchTransactionRequest {
device_id: connector_auth.device_id,
transaction_key: connector_auth.transaction_key,
transaction_id: item
.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?,
developer_id: connector_auth.developer_id,
};
Ok(Self { search_transaction })
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum SearchResponseTypes {
SuccessResponse(TsysPaymentsSyncResponse),
ErrorResponse(TsysErrorResponse),
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "PascalCase")]
pub struct TsysSyncResponse {
search_transaction_response: SearchResponseTypes,
}
impl<F, T> TryFrom<ResponseRouterData<F, TsysSyncResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, TsysSyncResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let tsys_search_response = item.response.search_transaction_response;
let (response, status) = match tsys_search_response {
SearchResponseTypes::SuccessResponse(search_response) => (
Ok(get_payments_sync_response(&search_response)),
enums::AttemptStatus::from(search_response.transaction_details),
),
SearchResponseTypes::ErrorResponse(connector_response) => (
Err(get_error_response(connector_response, item.http_code)),
item.data.status,
),
};
Ok(Self {
status,
response,
..item.data
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TsysCancelRequest {
#[serde(rename = "deviceID")]
device_id: Secret<String>,
transaction_key: Secret<String>,
#[serde(rename = "transactionID")]
transaction_id: String,
#[serde(rename = "developerID")]
developer_id: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "PascalCase")]
pub struct TsysPaymentsCancelRequest {
void: TsysCancelRequest,
}
impl TryFrom<&PaymentsCancelRouterData> for TsysPaymentsCancelRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> {
let connector_auth: TsysAuthType = TsysAuthType::try_from(&item.connector_auth_type)?;
let void = TsysCancelRequest {
device_id: connector_auth.device_id,
transaction_key: connector_auth.transaction_key,
transaction_id: item.request.connector_transaction_id.clone(),
developer_id: connector_auth.developer_id,
};
Ok(Self { void })
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TsysCaptureRequest {
#[serde(rename = "deviceID")]
device_id: Secret<String>,
transaction_key: Secret<String>,
transaction_amount: StringMinorUnit,
#[serde(rename = "transactionID")]
transaction_id: String,
#[serde(rename = "developerID")]
developer_id: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "PascalCase")]
pub struct TsysPaymentsCaptureRequest {
capture: TsysCaptureRequest,
}
impl TryFrom<&TsysRouterData<&types::PaymentsCaptureRouterData>> for TsysPaymentsCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item_data: &TsysRouterData<&types::PaymentsCaptureRouterData>,
) -> Result<Self, Self::Error> {
let item = item_data.router_data.clone();
let connector_auth: TsysAuthType = TsysAuthType::try_from(&item.connector_auth_type)?;
let capture = TsysCaptureRequest {
device_id: connector_auth.device_id,
transaction_key: connector_auth.transaction_key,
transaction_id: item.request.connector_transaction_id.clone(),
developer_id: connector_auth.developer_id,
transaction_amount: item_data.amount.clone(),
};
Ok(Self { capture })
}
}
// REFUND :
// Type definition for RefundRequest
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TsysReturnRequest {
#[serde(rename = "deviceID")]
device_id: Secret<String>,
transaction_key: Secret<String>,
transaction_amount: StringMinorUnit,
#[serde(rename = "transactionID")]
transaction_id: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "PascalCase")]
pub struct TsysRefundRequest {
#[serde(rename = "Return")]
return_request: TsysReturnRequest,
}
impl<F> TryFrom<&TsysRouterData<&RefundsRouterData<F>>> for TsysRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item_data: &TsysRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
let item = item_data.router_data;
let connector_auth: TsysAuthType = TsysAuthType::try_from(&item.connector_auth_type)?;
let return_request = TsysReturnRequest {
device_id: connector_auth.device_id,
transaction_key: connector_auth.transaction_key,
transaction_amount: item_data.amount.clone(),
transaction_id: item.request.connector_transaction_id.clone(),
};
Ok(Self { return_request })
}
}
impl From<TsysPaymentStatus> for enums::RefundStatus {
fn from(item: TsysPaymentStatus) -> Self {
match item {
TsysPaymentStatus::Pass => Self::Success,
TsysPaymentStatus::Fail => Self::Failure,
}
}
}
impl From<TsysTransactionDetails> for enums::RefundStatus {
fn from(item: TsysTransactionDetails) -> Self {
match item.transaction_status {
TsysTransactionStatus::Approved => Self::Pending,
//Connector calls refunds as Void
TsysTransactionStatus::Void => Self::Success,
TsysTransactionStatus::Declined => Self::Failure,
}
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "PascalCase")]
pub struct RefundResponse {
return_response: TsysResponseTypes,
}
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 tsys_return_response = item.response.return_response;
let response = match tsys_return_response {
TsysResponseTypes::SuccessResponse(return_response) => Ok(RefundsResponseData {
connector_refund_id: return_response.transaction_id,
refund_status: enums::RefundStatus::from(return_response.status),
}),
TsysResponseTypes::ErrorResponse(connector_response) => {
Err(get_error_response(connector_response, item.http_code))
}
};
Ok(Self {
response,
..item.data
})
}
}
impl TryFrom<&RefundSyncRouterData> for TsysSyncRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &RefundSyncRouterData) -> Result<Self, Self::Error> {
let connector_auth: TsysAuthType = TsysAuthType::try_from(&item.connector_auth_type)?;
let search_transaction = TsysSearchTransactionRequest {
device_id: connector_auth.device_id,
transaction_key: connector_auth.transaction_key,
transaction_id: item.request.get_connector_refund_id()?,
developer_id: connector_auth.developer_id,
};
Ok(Self { search_transaction })
}
}
impl TryFrom<RefundsResponseRouterData<RSync, TsysSyncResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, TsysSyncResponse>,
) -> Result<Self, Self::Error> {
let tsys_search_response = item.response.search_transaction_response;
let response = match tsys_search_response {
SearchResponseTypes::SuccessResponse(search_response) => Ok(RefundsResponseData {
connector_refund_id: search_response.transaction_details.transaction_id.clone(),
refund_status: enums::RefundStatus::from(search_response.transaction_details),
}),
SearchResponseTypes::ErrorResponse(connector_response) => {
Err(get_error_response(connector_response, item.http_code))
}
};
Ok(Self {
response,
..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/boku/transformers.rs | crates/hyperswitch_connectors/src/connectors/boku/transformers.rs | use std::fmt;
use common_enums::enums;
use common_utils::{request::Method, types::MinorUnit};
use hyperswitch_domain_models::{
payment_method_data::{PaymentMethodData, WalletData},
router_data::{ConnectorAuthType, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
types::{self, RefundsRouterData},
};
use hyperswitch_interfaces::errors;
use masking::Secret;
use serde::{Deserialize, Serialize};
use url::Url;
use uuid::Uuid;
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{self, AddressDetailsData, RouterData as _},
};
#[derive(Debug, Serialize)]
pub struct BokuRouterData<T> {
pub amount: MinorUnit,
pub router_data: T,
}
impl<T> From<(MinorUnit, T)> for BokuRouterData<T> {
fn from((amount, router_data): (MinorUnit, T)) -> Self {
Self {
amount,
router_data,
}
}
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum BokuPaymentsRequest {
BeginSingleCharge(SingleChargeData),
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct SingleChargeData {
total_amount: MinorUnit,
currency: String,
country: String,
merchant_id: Secret<String>,
merchant_transaction_id: Secret<String>,
merchant_request_id: String,
merchant_item_description: String,
notification_url: Option<String>,
payment_method: String,
charge_type: String,
hosted: Option<BokuHostedData>,
}
#[derive(Debug, Clone, Serialize)]
pub enum BokuPaymentType {
Dana,
Momo,
Gcash,
GoPay,
Kakaopay,
}
impl fmt::Display for BokuPaymentType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Dana => write!(f, "Dana"),
Self::Momo => write!(f, "Momo"),
Self::Gcash => write!(f, "Gcash"),
Self::GoPay => write!(f, "GoPay"),
Self::Kakaopay => write!(f, "Kakaopay"),
}
}
}
#[derive(Debug, Clone, Serialize)]
pub enum BokuChargeType {
Hosted,
}
impl fmt::Display for BokuChargeType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Hosted => write!(f, "hosted"),
}
}
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "kebab-case")]
struct BokuHostedData {
forward_url: String,
}
impl TryFrom<&BokuRouterData<&types::PaymentsAuthorizeRouterData>> for BokuPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &BokuRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Wallet(wallet_data) => Self::try_from((item, &wallet_data)),
PaymentMethodData::Card(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("boku"),
))?
}
}
}
}
impl
TryFrom<(
&BokuRouterData<&types::PaymentsAuthorizeRouterData>,
&WalletData,
)> for BokuPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
value: (
&BokuRouterData<&types::PaymentsAuthorizeRouterData>,
&WalletData,
),
) -> Result<Self, Self::Error> {
let (item_router_data, wallet_data) = value;
let item = item_router_data.router_data;
let address = item.get_billing_address()?;
let country = address.get_country()?.to_string();
let payment_method = get_wallet_type(wallet_data)?;
let hosted = get_hosted_data(item);
let auth_type = BokuAuthType::try_from(&item.connector_auth_type)?;
let merchant_item_description = item.get_description()?;
let payment_data = SingleChargeData {
total_amount: item_router_data.amount,
currency: item.request.currency.to_string(),
country,
merchant_id: auth_type.merchant_id,
merchant_transaction_id: Secret::new(item.payment_id.to_string()),
merchant_request_id: Uuid::new_v4().to_string(),
merchant_item_description,
notification_url: item.request.webhook_url.clone(),
payment_method,
charge_type: BokuChargeType::Hosted.to_string(),
hosted,
};
Ok(Self::BeginSingleCharge(payment_data))
}
}
fn get_wallet_type(wallet_data: &WalletData) -> Result<String, errors::ConnectorError> {
match wallet_data {
WalletData::DanaRedirect { .. } => Ok(BokuPaymentType::Dana.to_string()),
WalletData::MomoRedirect { .. } => Ok(BokuPaymentType::Momo.to_string()),
WalletData::GcashRedirect { .. } => Ok(BokuPaymentType::Gcash.to_string()),
WalletData::GoPayRedirect { .. } => Ok(BokuPaymentType::GoPay.to_string()),
WalletData::KakaoPayRedirect { .. } => Ok(BokuPaymentType::Kakaopay.to_string()),
WalletData::AliPayQr(_)
| WalletData::AliPayRedirect(_)
| WalletData::AliPayHkRedirect(_)
| WalletData::AmazonPay(_)
| WalletData::AmazonPayRedirect(_)
| WalletData::Paysera(_)
| WalletData::Skrill(_)
| WalletData::BluecodeRedirect {}
| WalletData::ApplePay(_)
| WalletData::ApplePayRedirect(_)
| WalletData::ApplePayThirdPartySdk(_)
| WalletData::GooglePay(_)
| WalletData::GooglePayRedirect(_)
| WalletData::GooglePayThirdPartySdk(_)
| WalletData::MbWayRedirect(_)
| WalletData::MobilePayRedirect(_)
| WalletData::PaypalRedirect(_)
| WalletData::PaypalSdk(_)
| WalletData::Paze(_)
| WalletData::SamsungPay(_)
| WalletData::TwintRedirect {}
| WalletData::VippsRedirect {}
| WalletData::TouchNGoRedirect(_)
| WalletData::WeChatPayRedirect(_)
| WalletData::WeChatPayQr(_)
| WalletData::CashappQr(_)
| WalletData::SwishQr(_)
| WalletData::Mifinity(_)
| WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("boku"),
)),
}
}
pub struct BokuAuthType {
pub(super) merchant_id: Secret<String>,
pub(super) key_id: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for BokuAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
merchant_id: key1.to_owned(),
key_id: api_key.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename = "query-charge-request")]
#[serde(rename_all = "kebab-case")]
pub struct BokuPsyncRequest {
country: String,
merchant_id: Secret<String>,
merchant_transaction_id: Secret<String>,
}
impl TryFrom<&types::PaymentsSyncRouterData> for BokuPsyncRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::PaymentsSyncRouterData) -> Result<Self, Self::Error> {
let address = item.get_billing_address()?;
let country = address.get_country()?.to_string();
let auth_type = BokuAuthType::try_from(&item.connector_auth_type)?;
Ok(Self {
country,
merchant_id: auth_type.merchant_id,
merchant_transaction_id: Secret::new(item.payment_id.to_string()),
})
}
}
// Connector Meta Data
#[derive(Debug, Clone, Deserialize)]
pub struct BokuMetaData {
pub(super) country: String,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum BokuResponse {
BeginSingleChargeResponse(BokuPaymentsResponse),
QueryChargeResponse(BokuPsyncResponse),
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct BokuPaymentsResponse {
charge_status: String, // xml parse only string to fields
charge_id: String,
hosted: Option<HostedUrlResponse>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct HostedUrlResponse {
redirect_url: Option<Url>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename = "query-charge-response")]
#[serde(rename_all = "kebab-case")]
pub struct BokuPsyncResponse {
charges: ChargeResponseData,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct ChargeResponseData {
charge: SingleChargeResponseData,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct SingleChargeResponseData {
charge_status: String,
charge_id: String,
}
impl<F, T> TryFrom<ResponseRouterData<F, BokuResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, BokuResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let (status, transaction_id, redirection_data) = match item.response {
BokuResponse::BeginSingleChargeResponse(response) => get_authorize_response(response),
BokuResponse::QueryChargeResponse(response) => get_psync_response(response),
}?;
Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(transaction_id),
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
fn get_response_status(status: String) -> enums::AttemptStatus {
match status.as_str() {
"Success" => enums::AttemptStatus::Charged,
"Failure" => enums::AttemptStatus::Failure,
_ => enums::AttemptStatus::Pending,
}
}
fn get_authorize_response(
response: BokuPaymentsResponse,
) -> Result<(enums::AttemptStatus, String, Option<RedirectForm>), errors::ConnectorError> {
let status = get_response_status(response.charge_status);
let redirection_data = match response.hosted {
Some(hosted_value) => Ok(hosted_value
.redirect_url
.map(|url| RedirectForm::from((url, Method::Get)))),
None => Err(errors::ConnectorError::MissingConnectorRedirectionPayload {
field_name: "redirect_url",
}),
}?;
Ok((status, response.charge_id, redirection_data))
}
fn get_psync_response(
response: BokuPsyncResponse,
) -> Result<(enums::AttemptStatus, String, Option<RedirectForm>), errors::ConnectorError> {
let status = get_response_status(response.charges.charge.charge_status);
Ok((status, response.charges.charge.charge_id, None))
}
// REFUND :
#[derive(Debug, Clone, Serialize)]
#[serde(rename = "refund-charge-request")]
pub struct BokuRefundRequest {
refund_amount: MinorUnit,
merchant_id: Secret<String>,
merchant_request_id: String,
merchant_refund_id: Secret<String>,
charge_id: String,
reason_code: String,
}
#[derive(Debug, Clone, Serialize)]
pub enum BokuRefundReasonCode {
NonFulfillment,
}
impl fmt::Display for BokuRefundReasonCode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::NonFulfillment => write!(f, "8"),
}
}
}
impl<F> TryFrom<&BokuRouterData<&RefundsRouterData<F>>> for BokuRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &BokuRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
let auth_type = BokuAuthType::try_from(&item.router_data.connector_auth_type)?;
let payment_data = Self {
refund_amount: item.amount,
merchant_id: auth_type.merchant_id,
merchant_refund_id: Secret::new(item.router_data.request.refund_id.to_string()),
merchant_request_id: Uuid::new_v4().to_string(),
charge_id: item
.router_data
.request
.connector_transaction_id
.to_string(),
reason_code: BokuRefundReasonCode::NonFulfillment.to_string(),
};
Ok(payment_data)
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename = "refund-charge-response")]
pub struct RefundResponse {
charge_id: String,
refund_status: String,
}
fn get_refund_status(status: String) -> enums::RefundStatus {
match status.as_str() {
"Success" => enums::RefundStatus::Success,
"Failure" => enums::RefundStatus::Failure,
_ => enums::RefundStatus::Pending,
}
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.charge_id,
refund_status: get_refund_status(item.response.refund_status),
}),
..item.data
})
}
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename = "query-refund-request")]
#[serde(rename_all = "kebab-case")]
pub struct BokuRsyncRequest {
country: String,
merchant_id: Secret<String>,
merchant_transaction_id: Secret<String>,
}
impl TryFrom<&types::RefundSyncRouterData> for BokuRsyncRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::RefundSyncRouterData) -> Result<Self, Self::Error> {
let address = item.get_billing_address()?;
let country = address.get_country()?.to_string();
let auth_type = BokuAuthType::try_from(&item.connector_auth_type)?;
Ok(Self {
country,
merchant_id: auth_type.merchant_id,
merchant_transaction_id: Secret::new(item.payment_id.to_string()),
})
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename = "query-refund-response")]
#[serde(rename_all = "kebab-case")]
pub struct BokuRsyncResponse {
refunds: RefundResponseData,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct RefundResponseData {
refund: SingleRefundResponseData,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct SingleRefundResponseData {
refund_status: String, // quick-xml only parse string as a field
refund_id: String,
}
impl TryFrom<RefundsResponseRouterData<RSync, BokuRsyncResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, BokuRsyncResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.refunds.refund.refund_id,
refund_status: get_refund_status(item.response.refunds.refund.refund_status),
}),
..item.data
})
}
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct BokuErrorResponse {
pub status_code: u16,
pub code: String,
pub message: String,
pub reason: Option<String>,
}
fn get_hosted_data(item: &types::PaymentsAuthorizeRouterData) -> Option<BokuHostedData> {
item.request
.router_return_url
.clone()
.map(|url| BokuHostedData { forward_url: url })
}
| 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/gigadat/transformers.rs | crates/hyperswitch_connectors/src/connectors/gigadat/transformers.rs | use api_models::webhooks::IncomingWebhookEvent;
#[cfg(feature = "payouts")]
use api_models::{
self,
payouts::{BankRedirect, PayoutMethodData},
};
use common_enums::{enums, Currency};
use common_utils::{
id_type,
pii::{self, Email, IpAddress},
request::Method,
types::FloatMajorUnit,
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{BankRedirectData, PaymentMethodData},
router_data::{
AdditionalPaymentMethodConnectorResponse, ConnectorAuthType, ConnectorResponseData,
InteracCustomerInfo, RouterData,
},
router_flow_types::refunds::Execute,
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
types::{PaymentsAuthorizeRouterData, RefundsRouterData},
};
#[cfg(feature = "payouts")]
use hyperswitch_domain_models::{
router_flow_types::PoQuote, router_response_types::PayoutsResponseData,
types::PayoutsRouterData,
};
use hyperswitch_interfaces::errors;
use masking::{PeekInterface, Secret};
use serde::{Deserialize, Serialize};
#[cfg(feature = "payouts")]
use crate::{types::PayoutsResponseRouterData, utils::PayoutsData as _};
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{self, BrowserInformationData, PaymentsAuthorizeRequestData, RouterData as _},
};
pub struct GigadatRouterData<T> {
pub amount: FloatMajorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc.
pub router_data: T,
}
impl<T> From<(FloatMajorUnit, T)> for GigadatRouterData<T> {
fn from((amount, item): (FloatMajorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
const CONNECTOR_BASE_URL: &str = "https://interac.express-connect.com/";
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct GigadatConnectorMetadataObject {
pub site: String,
}
impl TryFrom<&Option<pii::SecretSerdeValue>> for GigadatConnectorMetadataObject {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(meta_data: &Option<pii::SecretSerdeValue>) -> Result<Self, Self::Error> {
let metadata: Self = utils::to_connector_meta_from_secret::<Self>(meta_data.clone())
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "merchant_connector_account.metadata",
})?;
Ok(metadata)
}
}
// CPI (Combined Pay-in) Request Structure for Gigadat
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GigadatCpiRequest {
pub user_id: id_type::CustomerId,
pub site: String,
pub user_ip: Secret<String, IpAddress>,
pub currency: Currency,
pub amount: FloatMajorUnit,
pub transaction_id: String,
#[serde(rename = "type")]
pub transaction_type: GidadatTransactionType,
pub sandbox: bool,
pub name: Secret<String>,
pub email: Email,
pub mobile: Secret<String>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum GidadatTransactionType {
Cpi,
Eto,
}
impl TryFrom<&GigadatRouterData<&PaymentsAuthorizeRouterData>> for GigadatCpiRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &GigadatRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let metadata: GigadatConnectorMetadataObject =
utils::to_connector_meta_from_secret(item.router_data.connector_meta_data.clone())
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "merchant_connector_account.metadata",
})?;
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::BankRedirect(BankRedirectData::Interac { .. }) => {
let router_data = item.router_data;
let name = router_data.get_billing_full_name()?;
let email = router_data.get_billing_email()?;
let mobile = router_data.get_billing_phone_number()?;
let currency = item.router_data.request.currency;
let sandbox = match item.router_data.test_mode {
Some(true) => true,
Some(false) | None => false,
};
let user_ip = router_data.request.get_browser_info()?.get_ip_address()?;
Ok(Self {
user_id: router_data.get_customer_id()?,
site: metadata.site,
user_ip,
currency,
amount: item.amount,
transaction_id: router_data.connector_request_reference_id.clone(),
transaction_type: GidadatTransactionType::Cpi,
name,
sandbox,
email,
mobile,
})
}
PaymentMethodData::BankRedirect(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Gigadat"),
))?,
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Gigadat"),
)
.into()),
}
}
}
#[derive(Debug, Clone)]
pub struct GigadatAuthType {
pub campaign_id: Secret<String>,
pub access_token: Secret<String>,
pub security_token: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for GigadatAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} => Ok(Self {
security_token: api_secret.to_owned(),
access_token: api_key.to_owned(),
campaign_id: key1.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GigadatPaymentResponse {
pub token: Secret<String>,
pub data: GigadatPaymentData,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GigadatPaymentData {
pub transaction_id: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum GigadatTransactionStatus {
StatusInited,
StatusSuccess,
StatusRejected,
StatusRejected1,
StatusExpired,
StatusAborted1,
StatusPending,
StatusFailed,
}
impl From<GigadatTransactionStatus> for enums::AttemptStatus {
fn from(item: GigadatTransactionStatus) -> Self {
match item {
GigadatTransactionStatus::StatusSuccess => Self::Charged,
GigadatTransactionStatus::StatusInited | GigadatTransactionStatus::StatusPending => {
Self::Pending
}
GigadatTransactionStatus::StatusRejected
| GigadatTransactionStatus::StatusExpired
| GigadatTransactionStatus::StatusRejected1
| GigadatTransactionStatus::StatusAborted1
| GigadatTransactionStatus::StatusFailed => Self::Failure,
}
}
}
pub enum GigadatFlow {
Payment,
#[cfg(feature = "payouts")]
Payout,
}
impl GigadatFlow {
pub fn get_flow(webhook_type: &str) -> Result<Self, errors::ConnectorError> {
match webhook_type {
#[cfg(feature = "payouts")]
"ETO" | "RTO" | "RTX" | "ANR" | "ANX" => Ok(Self::Payout),
"ETI" | "RFM" | "CPI" | "ACK" => Ok(Self::Payment),
_ => Err(errors::ConnectorError::NotImplemented(
"Invalid transaction type ".to_string(),
)),
}
}
}
pub fn get_gigadat_webhook_event_type(
status: GigadatTransactionStatus,
flow: GigadatFlow,
) -> IncomingWebhookEvent {
match flow {
GigadatFlow::Payment => match status {
GigadatTransactionStatus::StatusSuccess => IncomingWebhookEvent::PaymentIntentSuccess,
GigadatTransactionStatus::StatusFailed
| GigadatTransactionStatus::StatusRejected
| GigadatTransactionStatus::StatusRejected1
| GigadatTransactionStatus::StatusExpired
| GigadatTransactionStatus::StatusAborted1 => {
IncomingWebhookEvent::PaymentIntentFailure
}
GigadatTransactionStatus::StatusInited | GigadatTransactionStatus::StatusPending => {
IncomingWebhookEvent::PaymentIntentProcessing
}
},
#[cfg(feature = "payouts")]
GigadatFlow::Payout => match status {
GigadatTransactionStatus::StatusSuccess => IncomingWebhookEvent::PayoutSuccess,
GigadatTransactionStatus::StatusFailed
| GigadatTransactionStatus::StatusRejected
| GigadatTransactionStatus::StatusRejected1
| GigadatTransactionStatus::StatusExpired
| GigadatTransactionStatus::StatusAborted1 => IncomingWebhookEvent::PayoutFailure,
GigadatTransactionStatus::StatusInited | GigadatTransactionStatus::StatusPending => {
IncomingWebhookEvent::PayoutProcessing
}
},
}
}
impl TryFrom<String> for GigadatTransactionStatus {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(value: String) -> Result<Self, Self::Error> {
match value.as_str() {
"STATUS_INITED" => Ok(Self::StatusInited),
"STATUS_SUCCESS" => Ok(Self::StatusSuccess),
"STATUS_REJECTED" => Ok(Self::StatusRejected),
"STATUS_REJECTED1" => Ok(Self::StatusRejected1),
"STATUS_EXPIRED" => Ok(Self::StatusExpired),
"STATUS_ABORTED1" => Ok(Self::StatusAborted1),
"STATUS_PENDING" => Ok(Self::StatusPending),
"STATUS_FAILED" => Ok(Self::StatusFailed),
_ => Err(errors::ConnectorError::WebhookBodyDecodingFailed.into()),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GigadatTransactionStatusResponse {
pub status: GigadatTransactionStatus,
pub interac_bank_name: Option<Secret<String>>,
pub data: Option<GigadatSyncData>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GigadatSyncData {
pub name: Option<Secret<String>>,
pub email: Option<Email>,
pub mobile: Option<Secret<String>>,
}
impl<F, T> TryFrom<ResponseRouterData<F, GigadatPaymentResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, GigadatPaymentResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
// Will be raising a sepearte PR to populate a field connect_base_url in routerData and use it here
let base_url = CONNECTOR_BASE_URL;
let redirect_url = format!(
"{}webflow?transaction={}&token={}",
base_url,
item.data.connector_request_reference_id,
item.response.token.peek()
);
let redirection_data = Some(RedirectForm::Form {
endpoint: redirect_url,
method: Method::Get,
form_fields: Default::default(),
});
Ok(Self {
status: enums::AttemptStatus::AuthenticationPending,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.data.transaction_id),
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
impl<F, T> TryFrom<ResponseRouterData<F, GigadatTransactionStatusResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, GigadatTransactionStatusResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let connector_response = item.response.data.as_ref().map(|sync_data| {
ConnectorResponseData::with_additional_payment_method_data(
AdditionalPaymentMethodConnectorResponse::BankRedirect {
interac: Some(InteracCustomerInfo {
customer_info: Some(build_interac_customer_info_details(
sync_data,
item.response.interac_bank_name.clone(),
)),
}),
},
)
});
Ok(Self {
status: enums::AttemptStatus::from(item.response.status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
connector_response,
..item.data
})
}
}
fn build_interac_customer_info_details(
sync_data: &GigadatSyncData,
bank_name: Option<Secret<String>>,
) -> common_types::payments::InteracCustomerInfoDetails {
common_types::payments::InteracCustomerInfoDetails {
customer_name: sync_data.name.clone(),
customer_email: sync_data.email.clone(),
customer_phone_number: sync_data.mobile.clone(),
customer_bank_id: None,
customer_bank_name: bank_name,
}
}
// REFUND :
// Type definition for RefundRequest
#[derive(Default, Debug, Serialize)]
pub struct GigadatRefundRequest {
pub amount: FloatMajorUnit,
pub transaction_id: String,
pub campaign_id: Secret<String>,
}
impl<F> TryFrom<&GigadatRouterData<&RefundsRouterData<F>>> for GigadatRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &GigadatRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
let auth_type = GigadatAuthType::try_from(&item.router_data.connector_auth_type)?;
Ok(Self {
amount: item.amount.to_owned(),
transaction_id: item.router_data.request.connector_transaction_id.clone(),
campaign_id: auth_type.campaign_id,
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RefundResponse {
success: bool,
data: GigadatPaymentData,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
let refund_status = match item.http_code {
200 => enums::RefundStatus::Success,
400 | 401 | 422 => enums::RefundStatus::Failure,
_ => enums::RefundStatus::Pending,
};
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.data.transaction_id.to_string(),
refund_status,
}),
..item.data
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GigadatPayoutQuoteRequest {
pub amount: FloatMajorUnit,
pub campaign: Secret<String>,
pub currency: Currency,
pub email: Email,
pub mobile: Secret<String>,
pub name: Secret<String>,
pub site: String,
pub transaction_id: String,
#[serde(rename = "type")]
pub transaction_type: GidadatTransactionType,
pub user_id: id_type::CustomerId,
pub user_ip: Secret<String, IpAddress>,
pub sandbox: bool,
}
// Payouts fulfill request transform
#[cfg(feature = "payouts")]
impl TryFrom<&GigadatRouterData<&PayoutsRouterData<PoQuote>>> for GigadatPayoutQuoteRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &GigadatRouterData<&PayoutsRouterData<PoQuote>>,
) -> Result<Self, Self::Error> {
match item.router_data.get_payout_method_data()? {
PayoutMethodData::BankRedirect(BankRedirect::Interac(interac_data)) => {
let metadata: GigadatConnectorMetadataObject =
utils::to_connector_meta_from_secret(
item.router_data.connector_meta_data.clone(),
)
.change_context(
errors::ConnectorError::InvalidConnectorConfig {
config: "merchant_connector_account.metadata",
},
)?;
let router_data = item.router_data;
let name = router_data.get_billing_full_name()?;
let email = interac_data.email;
let mobile = router_data.get_billing_phone_number()?;
let currency = item.router_data.request.destination_currency;
let user_ip = router_data.request.get_browser_info()?.get_ip_address()?;
let auth_type = GigadatAuthType::try_from(&item.router_data.connector_auth_type)?;
let sandbox = match item.router_data.test_mode {
Some(true) => true,
Some(false) | None => false,
};
Ok(Self {
user_id: router_data.get_customer_id()?,
site: metadata.site,
user_ip,
currency,
amount: item.amount,
transaction_id: router_data.connector_request_reference_id.clone(),
transaction_type: GidadatTransactionType::Eto,
name,
email,
mobile,
campaign: auth_type.campaign_id,
sandbox,
})
}
PayoutMethodData::Card(_)
| PayoutMethodData::Bank(_)
| PayoutMethodData::Wallet(_)
| PayoutMethodData::Passthrough(_) => Err(errors::ConnectorError::NotSupported {
message: "Payment Method Not Supported".to_string(),
connector: "Gigadat",
})?,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GigadatPayoutQuoteResponse {
pub token: Secret<String>,
pub data: GigadatPayoutData,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GigadatPayoutData {
pub transaction_id: String,
#[serde(rename = "type")]
pub transaction_type: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct GigadatPayoutMeta {
pub token: Secret<String>,
}
#[cfg(feature = "payouts")]
impl<F> TryFrom<PayoutsResponseRouterData<F, GigadatPayoutQuoteResponse>> for PayoutsRouterData<F> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PayoutsResponseRouterData<F, GigadatPayoutQuoteResponse>,
) -> Result<Self, Self::Error> {
let connector_meta = serde_json::json!(GigadatPayoutMeta {
token: item.response.token,
});
Ok(Self {
response: Ok(PayoutsResponseData {
status: None,
connector_payout_id: Some(item.response.data.transaction_id),
payout_eligible: None,
should_add_next_step_to_process_tracker: false,
error_code: None,
error_message: None,
payout_connector_metadata: Some(Secret::new(connector_meta)),
}),
..item.data
})
}
}
#[cfg(feature = "payouts")]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GigadatPayoutResponse {
pub id: String,
pub status: GigadatPayoutStatus,
pub data: GigadatPayoutData,
}
#[cfg(feature = "payouts")]
impl<F> TryFrom<PayoutsResponseRouterData<F, GigadatPayoutResponse>> for PayoutsRouterData<F> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PayoutsResponseRouterData<F, GigadatPayoutResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(PayoutsResponseData {
status: Some(enums::PayoutStatus::from(item.response.status)),
connector_payout_id: Some(item.response.data.transaction_id),
payout_eligible: None,
should_add_next_step_to_process_tracker: false,
error_code: None,
error_message: None,
payout_connector_metadata: None,
}),
..item.data
})
}
}
#[cfg(feature = "payouts")]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GigadatPayoutSyncResponse {
pub status: GigadatPayoutStatus,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum GigadatPayoutStatus {
StatusInited,
StatusSuccess,
StatusRejected,
StatusRejected1,
StatusExpired,
StatusAborted1,
StatusPending,
StatusFailed,
}
#[cfg(feature = "payouts")]
impl From<GigadatPayoutStatus> for enums::PayoutStatus {
fn from(item: GigadatPayoutStatus) -> Self {
match item {
GigadatPayoutStatus::StatusSuccess => Self::Success,
GigadatPayoutStatus::StatusPending => Self::RequiresFulfillment,
GigadatPayoutStatus::StatusInited => Self::Pending,
GigadatPayoutStatus::StatusRejected
| GigadatPayoutStatus::StatusExpired
| GigadatPayoutStatus::StatusRejected1
| GigadatPayoutStatus::StatusAborted1
| GigadatPayoutStatus::StatusFailed => Self::Failed,
}
}
}
#[cfg(feature = "payouts")]
impl<F> TryFrom<PayoutsResponseRouterData<F, GigadatPayoutSyncResponse>> for PayoutsRouterData<F> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PayoutsResponseRouterData<F, GigadatPayoutSyncResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(PayoutsResponseData {
status: Some(enums::PayoutStatus::from(item.response.status)),
connector_payout_id: None,
payout_eligible: None,
should_add_next_step_to_process_tracker: false,
error_code: None,
error_message: None,
payout_connector_metadata: None,
}),
..item.data
})
}
}
#[derive(Default, Debug, Serialize, Deserialize)]
pub struct GigadatErrorResponse {
pub err: String,
}
#[derive(Default, Debug, Serialize, Deserialize)]
pub struct GigadatRefundErrorResponse {
pub error: Vec<Error>,
pub message: String,
}
#[derive(Default, Debug, Serialize, Deserialize)]
pub struct Error {
pub code: Option<String>,
pub detail: String,
}
#[derive(Debug, Deserialize)]
pub struct GigadatWebhookQueryParameters {
pub transaction: String,
pub status: GigadatTransactionStatus,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GigadatWebhookKeyValueBody {
#[serde(rename = "type")]
pub webhook_type: String,
pub final_type: Option<String>,
pub cpi_type: Option<String>,
// donot remove the below fields
pub name: Option<Secret<String>>,
pub mobile: Option<Secret<String>>,
pub user_id: Option<Secret<String>>,
pub email: Option<Email>,
pub financial_institution: Option<Secret<String>>,
}
impl GigadatWebhookKeyValueBody {
pub fn decode_from_url(body_str: &str) -> Result<Self, errors::ConnectorError> {
serde_urlencoded::from_str(body_str)
.map_err(|_| errors::ConnectorError::WebhookBodyDecodingFailed)
}
}
| 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/paypal/transformers.rs | crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs | #[cfg(feature = "payouts")]
use api_models::payouts::{PayoutMethodData, Wallet as WalletPayout};
use api_models::{enums, webhooks::IncomingWebhookEvent};
use base64::Engine;
use common_enums::enums as storage_enums;
#[cfg(feature = "payouts")]
use common_utils::pii::Email;
use common_utils::{consts, errors::CustomResult, request::Method, types::StringMajorUnit};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{
BankDebitData, BankRedirectData, BankTransferData, CardRedirectData, GiftCardData,
PayLaterData, PaymentMethodData, VoucherData, WalletData,
},
router_data::{
AccessToken, ConnectorAuthType, ConnectorResponseData, ErrorResponse,
ExtendedAuthorizationResponseData, RouterData,
},
router_flow_types::{
payments::{Authorize, PostSessionTokens},
refunds::{Execute, RSync},
VerifyWebhookSource,
},
router_request_types::{
CompleteAuthorizeData, PaymentsAuthorizeData, PaymentsIncrementalAuthorizationData,
PaymentsPostSessionTokensData, PaymentsSyncData, ResponseId,
VerifyWebhookSourceRequestData,
},
router_response_types::{
MandateReference, PaymentsResponseData, RedirectForm, RefundsResponseData,
VerifyWebhookSourceResponseData, VerifyWebhookStatus,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCaptureRouterData,
PaymentsExtendAuthorizationRouterData, PaymentsIncrementalAuthorizationRouterData,
PaymentsPostSessionTokensRouterData, PaymentsSyncRouterData, RefreshTokenRouterData,
RefundsRouterData, SdkSessionUpdateRouterData, SetupMandateRouterData,
VerifyWebhookSourceRouterData,
},
};
#[cfg(feature = "payouts")]
use hyperswitch_domain_models::{
router_flow_types::PoFulfill, router_response_types::PayoutsResponseData,
types::PayoutsRouterData,
};
use hyperswitch_interfaces::{
consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE},
errors,
};
use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
use url::Url;
use utils::ForeignTryFrom;
#[cfg(feature = "payouts")]
use crate::{constants, types::PayoutsResponseRouterData};
use crate::{
types::{
PaymentsCaptureResponseRouterData, PaymentsExtendAuthorizationResponseRouterData,
PaymentsResponseRouterData, PaymentsSyncResponseRouterData, RefundsResponseRouterData,
ResponseRouterData,
},
utils::{
self, is_payment_failure, missing_field_err, to_connector_meta, AccessTokenRequestInfo,
AddressDetailsData, CardData, PaymentsAuthorizeRequestData,
PaymentsPostSessionTokensRequestData, RouterData as OtherRouterData,
},
};
trait GetRequestIncrementalAuthorization {
fn get_request_incremental_authorization(&self) -> Option<bool>;
}
impl GetRequestIncrementalAuthorization for PaymentsAuthorizeData {
fn get_request_incremental_authorization(&self) -> Option<bool> {
Some(self.request_incremental_authorization)
}
}
impl GetRequestIncrementalAuthorization for CompleteAuthorizeData {
fn get_request_incremental_authorization(&self) -> Option<bool> {
None
}
}
impl GetRequestIncrementalAuthorization for PaymentsSyncData {
fn get_request_incremental_authorization(&self) -> Option<bool> {
None
}
}
#[derive(Debug, Serialize)]
pub struct PaypalRouterData<T> {
pub amount: StringMajorUnit,
pub shipping_cost: Option<StringMajorUnit>,
pub order_tax_amount: Option<StringMajorUnit>,
pub order_amount: Option<StringMajorUnit>,
pub router_data: T,
}
impl<T>
TryFrom<(
StringMajorUnit,
Option<StringMajorUnit>,
Option<StringMajorUnit>,
Option<StringMajorUnit>,
T,
)> for PaypalRouterData<T>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(amount, shipping_cost, order_tax_amount, order_amount, item): (
StringMajorUnit,
Option<StringMajorUnit>,
Option<StringMajorUnit>,
Option<StringMajorUnit>,
T,
),
) -> Result<Self, Self::Error> {
Ok(Self {
amount,
shipping_cost,
order_tax_amount,
order_amount,
router_data: item,
})
}
}
mod webhook_headers {
pub const PAYPAL_TRANSMISSION_ID: &str = "paypal-transmission-id";
pub const PAYPAL_TRANSMISSION_TIME: &str = "paypal-transmission-time";
pub const PAYPAL_TRANSMISSION_SIG: &str = "paypal-transmission-sig";
pub const PAYPAL_CERT_URL: &str = "paypal-cert-url";
pub const PAYPAL_AUTH_ALGO: &str = "paypal-auth-algo";
}
pub mod auth_headers {
pub const PAYPAL_PARTNER_ATTRIBUTION_ID: &str = "PayPal-Partner-Attribution-Id";
pub const PREFER: &str = "Prefer";
pub const PAYPAL_REQUEST_ID: &str = "PayPal-Request-Id";
pub const PAYPAL_AUTH_ASSERTION: &str = "PayPal-Auth-Assertion";
}
const ORDER_QUANTITY: u16 = 1;
#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq)]
#[serde(rename_all = "UPPERCASE")]
pub enum PaypalPaymentIntent {
Capture,
Authorize,
Authenticate,
}
#[derive(Default, Debug, Clone, Serialize, Eq, PartialEq, Deserialize)]
pub struct OrderAmount {
pub currency_code: storage_enums::Currency,
pub value: StringMajorUnit,
}
#[derive(Default, Debug, Serialize, Deserialize, Eq, PartialEq)]
pub struct OrderRequestAmount {
pub currency_code: storage_enums::Currency,
pub value: StringMajorUnit,
pub breakdown: AmountBreakdown,
}
impl From<&PaypalRouterData<&PaymentsAuthorizeRouterData>> for OrderRequestAmount {
fn from(item: &PaypalRouterData<&PaymentsAuthorizeRouterData>) -> Self {
Self {
currency_code: item.router_data.request.currency,
value: item.amount.clone(),
breakdown: AmountBreakdown {
item_total: OrderAmount {
currency_code: item.router_data.request.currency,
value: item.amount.clone(),
},
tax_total: None,
shipping: Some(OrderAmount {
currency_code: item.router_data.request.currency,
value: item
.shipping_cost
.clone()
.unwrap_or(StringMajorUnit::zero()),
}),
},
}
}
}
impl TryFrom<&PaypalRouterData<&PaymentsPostSessionTokensRouterData>> for OrderRequestAmount {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &PaypalRouterData<&PaymentsPostSessionTokensRouterData>,
) -> Result<Self, Self::Error> {
Ok(Self {
currency_code: item.router_data.request.currency,
value: item.amount.clone(),
breakdown: AmountBreakdown {
item_total: OrderAmount {
currency_code: item.router_data.request.currency,
value: item.order_amount.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "order_amount",
},
)?,
},
tax_total: None,
shipping: Some(OrderAmount {
currency_code: item.router_data.request.currency,
value: item
.shipping_cost
.clone()
.unwrap_or(StringMajorUnit::zero()),
}),
},
})
}
}
impl TryFrom<&PaypalRouterData<&SdkSessionUpdateRouterData>> for OrderRequestAmount {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaypalRouterData<&SdkSessionUpdateRouterData>) -> Result<Self, Self::Error> {
Ok(Self {
currency_code: item.router_data.request.currency,
value: item.amount.clone(),
breakdown: AmountBreakdown {
item_total: OrderAmount {
currency_code: item.router_data.request.currency,
value: item.order_amount.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "order_amount",
},
)?,
},
tax_total: Some(OrderAmount {
currency_code: item.router_data.request.currency,
value: item.order_tax_amount.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "order_tax_amount",
},
)?,
}),
shipping: Some(OrderAmount {
currency_code: item.router_data.request.currency,
value: item
.shipping_cost
.clone()
.unwrap_or(StringMajorUnit::zero()),
}),
},
})
}
}
#[derive(Default, Debug, Serialize, Deserialize, Eq, PartialEq)]
pub struct AmountBreakdown {
item_total: OrderAmount,
tax_total: Option<OrderAmount>,
shipping: Option<OrderAmount>,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct PurchaseUnitRequest {
reference_id: Option<String>, //reference for an item in purchase_units
invoice_id: Option<String>, //The API caller-provided external invoice number for this order. Appears in both the payer's transaction history and the emails that the payer receives.
custom_id: Option<String>, //Used to reconcile client transactions with PayPal transactions.
amount: OrderRequestAmount,
#[serde(skip_serializing_if = "Option::is_none")]
payee: Option<Payee>,
shipping: Option<ShippingAddress>,
items: Vec<ItemDetails>,
}
#[derive(Default, Debug, Deserialize, Serialize, Eq, PartialEq)]
pub struct Payee {
merchant_id: Secret<String>,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct ItemDetails {
name: String,
quantity: u16,
unit_amount: OrderAmount,
tax: Option<OrderAmount>,
}
impl From<&PaypalRouterData<&PaymentsAuthorizeRouterData>> for ItemDetails {
fn from(item: &PaypalRouterData<&PaymentsAuthorizeRouterData>) -> Self {
Self {
name: format!(
"Payment for invoice {}",
item.router_data.connector_request_reference_id
),
quantity: ORDER_QUANTITY,
unit_amount: OrderAmount {
currency_code: item.router_data.request.currency,
value: item.amount.clone(),
},
tax: None,
}
}
}
impl TryFrom<&PaypalRouterData<&PaymentsPostSessionTokensRouterData>> for ItemDetails {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &PaypalRouterData<&PaymentsPostSessionTokensRouterData>,
) -> Result<Self, Self::Error> {
Ok(Self {
name: format!(
"Payment for invoice {}",
item.router_data.connector_request_reference_id
),
quantity: ORDER_QUANTITY,
unit_amount: OrderAmount {
currency_code: item.router_data.request.currency,
value: item.order_amount.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "order_amount",
},
)?,
},
tax: None,
})
}
}
impl TryFrom<&PaypalRouterData<&SdkSessionUpdateRouterData>> for ItemDetails {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaypalRouterData<&SdkSessionUpdateRouterData>) -> Result<Self, Self::Error> {
Ok(Self {
name: format!(
"Payment for invoice {}",
item.router_data.connector_request_reference_id
),
quantity: ORDER_QUANTITY,
unit_amount: OrderAmount {
currency_code: item.router_data.request.currency,
value: item.order_amount.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "order_amount",
},
)?,
},
tax: Some(OrderAmount {
currency_code: item.router_data.request.currency,
value: item.order_tax_amount.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "order_tax_amount",
},
)?,
}),
})
}
}
#[derive(Default, Debug, Serialize, Eq, PartialEq, Deserialize)]
pub struct Address {
address_line_1: Option<Secret<String>>,
postal_code: Option<Secret<String>>,
country_code: enums::CountryAlpha2,
admin_area_2: Option<String>,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct ShippingAddress {
address: Option<Address>,
name: Option<ShippingName>,
}
impl From<&PaypalRouterData<&PaymentsAuthorizeRouterData>> for ShippingAddress {
fn from(item: &PaypalRouterData<&PaymentsAuthorizeRouterData>) -> Self {
Self {
address: get_address_info(item.router_data.get_optional_shipping()),
name: Some(ShippingName {
full_name: item
.router_data
.get_optional_shipping()
.and_then(|inner_data| inner_data.address.as_ref())
.and_then(|inner_data| inner_data.first_name.clone()),
}),
}
}
}
impl From<&PaypalRouterData<&PaymentsPostSessionTokensRouterData>> for ShippingAddress {
fn from(item: &PaypalRouterData<&PaymentsPostSessionTokensRouterData>) -> Self {
Self {
address: get_address_info(item.router_data.get_optional_shipping()),
name: Some(ShippingName {
full_name: item
.router_data
.get_optional_shipping()
.and_then(|inner_data| inner_data.address.as_ref())
.and_then(|inner_data| inner_data.first_name.clone()),
}),
}
}
}
#[derive(Debug, Serialize, PartialEq, Eq)]
pub struct PaypalUpdateOrderRequest(Vec<Operation>);
impl PaypalUpdateOrderRequest {
pub fn get_inner_value(self) -> Vec<Operation> {
self.0
}
}
#[derive(Debug, Serialize, PartialEq, Eq)]
pub struct Operation {
pub op: PaypalOperationType,
pub path: String,
pub value: Value,
}
#[derive(Debug, Serialize, PartialEq, Eq, Clone)]
#[serde(rename_all = "lowercase")]
pub enum PaypalOperationType {
Add,
Remove,
Replace,
Move,
Copy,
Test,
}
#[derive(Debug, Serialize, PartialEq, Eq)]
#[serde(untagged)]
pub enum Value {
Amount(OrderRequestAmount),
Items(Vec<ItemDetails>),
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct ShippingName {
full_name: Option<Secret<String>>,
}
#[derive(Debug, Serialize)]
pub struct CardRequestStruct {
billing_address: Option<Address>,
expiry: Option<Secret<String>>,
name: Option<Secret<String>>,
number: Option<cards::CardNumber>,
security_code: Option<Secret<String>>,
attributes: Option<CardRequestAttributes>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct VaultStruct {
vault_id: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum CardRequest {
CardRequestStruct(CardRequestStruct),
CardVaultStruct(VaultStruct),
}
#[derive(Debug, Serialize)]
pub struct CardRequestAttributes {
vault: Option<PaypalVault>,
verification: Option<ThreeDsMethod>,
}
#[derive(Debug, Serialize)]
pub struct ThreeDsMethod {
method: ThreeDsType,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum ThreeDsType {
ScaAlways,
}
#[derive(Debug, Serialize)]
pub struct RedirectRequest {
name: Secret<String>,
country_code: enums::CountryAlpha2,
experience_context: ContextStruct,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct ContextStruct {
return_url: Option<String>,
cancel_url: Option<String>,
user_action: Option<UserAction>,
shipping_preference: ShippingPreference,
}
#[derive(Debug, Serialize, Deserialize)]
pub enum UserAction {
#[serde(rename = "PAY_NOW")]
PayNow,
}
#[derive(Debug, Serialize, Deserialize)]
pub enum ShippingPreference {
#[serde(rename = "SET_PROVIDED_ADDRESS")]
SetProvidedAddress,
#[serde(rename = "GET_FROM_FILE")]
GetFromFile,
}
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum PaypalRedirectionRequest {
PaypalRedirectionStruct(PaypalRedirectionStruct),
PaypalVaultStruct(VaultStruct),
}
#[derive(Debug, Serialize)]
pub struct PaypalRedirectionStruct {
experience_context: ContextStruct,
attributes: Option<Attributes>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Attributes {
vault: PaypalVault,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct PaypalRedirectionResponse {
attributes: Option<AttributeResponse>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct EpsRedirectionResponse {
name: Option<Secret<String>>,
country_code: Option<enums::CountryAlpha2>,
bic: Option<Secret<String>>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct IdealRedirectionResponse {
name: Option<Secret<String>>,
country_code: Option<enums::CountryAlpha2>,
bic: Option<Secret<String>>,
iban_last_chars: Option<Secret<String>>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct AttributeResponse {
vault: PaypalVaultResponse,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct PaypalVault {
store_in_vault: StoreInVault,
usage_type: UsageType,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct PaypalVaultResponse {
id: String,
status: String,
customer: CustomerId,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct CustomerId {
id: String,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum StoreInVault {
OnSuccess,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum UsageType {
Merchant,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum PaymentSourceItem {
Card(CardRequest),
Paypal(PaypalRedirectionRequest),
IDeal(RedirectRequest),
Eps(RedirectRequest),
Giropay(RedirectRequest),
Sofort(RedirectRequest),
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct CardVaultResponse {
attributes: Option<AttributeResponse>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "lowercase")]
pub enum PaymentSourceItemResponse {
Card(CardVaultResponse),
Paypal(PaypalRedirectionResponse),
Eps(EpsRedirectionResponse),
Ideal(IdealRedirectionResponse),
}
#[derive(Debug, Serialize)]
pub struct PaypalPaymentsRequest {
intent: PaypalPaymentIntent,
purchase_units: Vec<PurchaseUnitRequest>,
payment_source: Option<PaymentSourceItem>,
}
#[derive(Debug, Serialize)]
pub struct PaypalZeroMandateRequest {
payment_source: ZeroMandateSourceItem,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum ZeroMandateSourceItem {
Card(CardMandateRequest),
Paypal(PaypalMandateStruct),
}
#[derive(Debug, Serialize, Deserialize)]
pub struct PaypalMandateStruct {
experience_context: Option<ContextStruct>,
usage_type: UsageType,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct CardMandateRequest {
billing_address: Option<Address>,
expiry: Option<Secret<String>>,
name: Option<Secret<String>>,
number: Option<cards::CardNumber>,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct PaypalSetupMandatesResponse {
id: String,
customer: Customer,
payment_source: ZeroMandateSourceItem,
links: Vec<PaypalLinks>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Customer {
id: String,
}
impl<F, T> TryFrom<ResponseRouterData<F, PaypalSetupMandatesResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, PaypalSetupMandatesResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let info_response = item.response;
let mandate_reference = Some(MandateReference {
connector_mandate_id: Some(info_response.id.clone()),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
});
// https://developer.paypal.com/docs/api/payment-tokens/v3/#payment-tokens_create
// If 201 status code, then order is captured, other status codes are handled by the error handler
let status = if item.http_code == 201 {
enums::AttemptStatus::Charged
} else {
enums::AttemptStatus::Failure
};
Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(info_response.id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(mandate_reference),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(info_response.id.clone()),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
impl TryFrom<&SetupMandateRouterData> for PaypalZeroMandateRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &SetupMandateRouterData) -> Result<Self, Self::Error> {
let payment_source = match item.request.payment_method_data.clone() {
PaymentMethodData::Card(ccard) => ZeroMandateSourceItem::Card(CardMandateRequest {
billing_address: get_address_info(item.get_optional_billing()),
expiry: Some(ccard.get_expiry_date_as_yyyymm("-")),
name: item.get_optional_billing_full_name(),
number: Some(ccard.card_number),
}),
PaymentMethodData::Wallet(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::MobilePayment(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Paypal"),
))?,
};
Ok(Self { payment_source })
}
}
fn get_address_info(
payment_address: Option<&hyperswitch_domain_models::address::Address>,
) -> Option<Address> {
let address = payment_address.and_then(|payment_address| payment_address.address.as_ref());
match address {
Some(address) => address.get_optional_country().map(|country| Address {
country_code: country.to_owned(),
address_line_1: address.line1.clone(),
postal_code: address.zip.clone(),
admin_area_2: address.city.clone(),
}),
None => None,
}
}
fn get_payment_source(
item: &PaymentsAuthorizeRouterData,
bank_redirection_data: &BankRedirectData,
) -> Result<PaymentSourceItem, error_stack::Report<errors::ConnectorError>> {
match bank_redirection_data {
BankRedirectData::Eps { bank_name: _, .. } => Ok(PaymentSourceItem::Eps(RedirectRequest {
name: item.get_billing_full_name()?,
country_code: item.get_billing_country()?,
experience_context: ContextStruct {
return_url: item.request.complete_authorize_url.clone(),
cancel_url: item.request.complete_authorize_url.clone(),
shipping_preference: if item.get_optional_shipping_country().is_some() {
ShippingPreference::SetProvidedAddress
} else {
ShippingPreference::GetFromFile
},
user_action: Some(UserAction::PayNow),
},
})),
BankRedirectData::Giropay { .. } => Ok(PaymentSourceItem::Giropay(RedirectRequest {
name: item.get_billing_full_name()?,
country_code: item.get_billing_country()?,
experience_context: ContextStruct {
return_url: item.request.complete_authorize_url.clone(),
cancel_url: item.request.complete_authorize_url.clone(),
shipping_preference: if item.get_optional_shipping_country().is_some() {
ShippingPreference::SetProvidedAddress
} else {
ShippingPreference::GetFromFile
},
user_action: Some(UserAction::PayNow),
},
})),
BankRedirectData::Ideal { bank_name: _, .. } => {
Ok(PaymentSourceItem::IDeal(RedirectRequest {
name: item.get_billing_full_name()?,
country_code: item.get_billing_country()?,
experience_context: ContextStruct {
return_url: item.request.complete_authorize_url.clone(),
cancel_url: item.request.complete_authorize_url.clone(),
shipping_preference: if item.get_optional_shipping_country().is_some() {
ShippingPreference::SetProvidedAddress
} else {
ShippingPreference::GetFromFile
},
user_action: Some(UserAction::PayNow),
},
}))
}
BankRedirectData::Sofort {
preferred_language: _,
..
} => Ok(PaymentSourceItem::Sofort(RedirectRequest {
name: item.get_billing_full_name()?,
country_code: item.get_billing_country()?,
experience_context: ContextStruct {
return_url: item.request.complete_authorize_url.clone(),
cancel_url: item.request.complete_authorize_url.clone(),
shipping_preference: if item.get_optional_shipping_country().is_some() {
ShippingPreference::SetProvidedAddress
} else {
ShippingPreference::GetFromFile
},
user_action: Some(UserAction::PayNow),
},
})),
BankRedirectData::BancontactCard { .. }
| BankRedirectData::Blik { .. }
| BankRedirectData::Przelewy24 { .. } => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Paypal"),
)
.into()),
BankRedirectData::Bizum {}
| BankRedirectData::Eft { .. }
| BankRedirectData::Interac { .. }
| BankRedirectData::OnlineBankingCzechRepublic { .. }
| BankRedirectData::OnlineBankingFinland { .. }
| BankRedirectData::OnlineBankingPoland { .. }
| BankRedirectData::OnlineBankingSlovakia { .. }
| BankRedirectData::OpenBankingUk { .. }
| BankRedirectData::Trustly { .. }
| BankRedirectData::OnlineBankingFpx { .. }
| BankRedirectData::OnlineBankingThailand { .. }
| BankRedirectData::LocalBankRedirect {}
| BankRedirectData::OpenBanking { .. } => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Paypal"),
))?,
}
}
fn get_payee(auth_type: &PaypalAuthType) -> Option<Payee> {
auth_type
.get_credentials()
.ok()
.and_then(|credentials| credentials.get_payer_id())
.map(|payer_id| Payee {
merchant_id: payer_id,
})
}
impl TryFrom<&PaypalRouterData<&PaymentsPostSessionTokensRouterData>> for PaypalPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &PaypalRouterData<&PaymentsPostSessionTokensRouterData>,
) -> Result<Self, Self::Error> {
let intent = if item.router_data.request.is_auto_capture()? {
PaypalPaymentIntent::Capture
} else {
PaypalPaymentIntent::Authorize
};
let paypal_auth: PaypalAuthType =
PaypalAuthType::try_from(&item.router_data.connector_auth_type)?;
let payee = get_payee(&paypal_auth);
let amount = OrderRequestAmount::try_from(item)?;
let connector_request_reference_id =
item.router_data.connector_request_reference_id.clone();
let shipping_address = ShippingAddress::from(item);
let item_details = vec![ItemDetails::try_from(item)?];
let purchase_units = vec![PurchaseUnitRequest {
reference_id: Some(connector_request_reference_id.clone()),
custom_id: item.router_data.request.merchant_order_reference_id.clone(),
invoice_id: Some(connector_request_reference_id),
amount,
payee,
shipping: Some(shipping_address),
items: item_details,
}];
let payment_source = Some(PaymentSourceItem::Paypal(
PaypalRedirectionRequest::PaypalRedirectionStruct(PaypalRedirectionStruct {
experience_context: ContextStruct {
return_url: item.router_data.request.router_return_url.clone(),
cancel_url: item.router_data.request.router_return_url.clone(),
shipping_preference: ShippingPreference::GetFromFile,
user_action: Some(UserAction::PayNow),
},
attributes: match item.router_data.request.setup_future_usage {
Some(setup_future_usage) => match setup_future_usage {
enums::FutureUsage::OffSession => Some(Attributes {
vault: PaypalVault {
store_in_vault: StoreInVault::OnSuccess,
usage_type: UsageType::Merchant,
},
}),
enums::FutureUsage::OnSession => None,
},
None => None,
},
}),
));
Ok(Self {
intent,
purchase_units,
payment_source,
})
}
}
impl TryFrom<&PaypalRouterData<&SdkSessionUpdateRouterData>> for PaypalUpdateOrderRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaypalRouterData<&SdkSessionUpdateRouterData>) -> Result<Self, Self::Error> {
let op = PaypalOperationType::Replace;
// Create separate paths for amount and items
let reference_id = &item.router_data.connector_request_reference_id;
let amount_path = format!("/purchase_units/@reference_id=='{reference_id}'/amount");
let items_path = format!("/purchase_units/@reference_id=='{reference_id}'/items");
let amount_value = Value::Amount(OrderRequestAmount::try_from(item)?);
let items_value = Value::Items(vec![ItemDetails::try_from(item)?]);
Ok(Self(vec![
Operation {
op: op.clone(),
path: amount_path,
value: amount_value,
},
Operation {
op,
path: items_path,
value: items_value,
},
]))
}
}
#[derive(Debug, Serialize)]
pub struct PaypalExtendAuthorizationRequest {
amount: OrderAmount,
}
impl TryFrom<&PaypalRouterData<&PaymentsExtendAuthorizationRouterData>>
| 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/worldpayxml/transformers.rs | crates/hyperswitch_connectors/src/connectors/worldpayxml/transformers.rs | #[cfg(feature = "payouts")]
use api_models::payouts::{ApplePayDecrypt, CardPayout};
use base64::Engine;
use common_enums::enums;
#[cfg(feature = "payouts")]
use common_utils::pii;
use common_utils::types::StringMinorUnit;
use error_stack::ResultExt;
use http::HeaderMap;
#[cfg(feature = "payouts")]
use hyperswitch_domain_models::{
address::Address,
router_flow_types::payouts::{PoCancel, PoFulfill, PoSync},
router_response_types::PayoutsResponseData,
types::PayoutsRouterData,
};
use hyperswitch_domain_models::{
payment_method_data::{
ApplePayWalletData, Card, GooglePayWalletData, PaymentMethodData, WalletData,
},
router_data::{ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::{
CompleteAuthorizeData, PaymentsAuthorizeData, PaymentsSyncData, ResponseId,
},
router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsCompleteAuthorizeRouterData, PaymentsSyncRouterData, RefundSyncRouterData,
RefundsRouterData,
},
};
use hyperswitch_interfaces::{consts, errors};
use josekit;
use masking::Secret;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
#[cfg(feature = "payouts")]
use crate::types::PayoutsResponseRouterData;
use crate::{
types::{
PaymentsCancelResponseRouterData, PaymentsCaptureResponseRouterData,
RefundsResponseRouterData, ResponseRouterData,
},
utils::{
self as connector_utils, AddressDetailsData, CardData, ForeignTryFrom,
PaymentsAuthorizeRequestData, PaymentsCompleteAuthorizeRequestData,
PaymentsSyncRequestData, RouterData as _,
},
};
pub struct WorldpayxmlRouterData<T> {
pub amount: StringMinorUnit,
pub router_data: T,
}
impl<T> From<(StringMinorUnit, T)> for WorldpayxmlRouterData<T> {
fn from((amount, item): (StringMinorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
pub mod worldpayxml_constants {
pub const WORLDPAYXML_VERSION: &str = "1.4";
pub const XML_VERSION: &str = "1.0";
pub const XML_ENCODING: &str = "UTF-8";
pub const WORLDPAYXML_DOC_TYPE: &str = r#"paymentService PUBLIC "-//Worldpay//DTD Worldpay PaymentService v1//EN" "http://dtd.worldpay.com/paymentService_v1.dtd""#;
pub const MAX_PAYMENT_REFERENCE_ID_LENGTH: usize = 64;
pub const COOKIE: &str = "cookie";
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename = "paymentService")]
pub struct PaymentService {
#[serde(rename = "@version")]
version: String,
#[serde(rename = "@merchantCode")]
merchant_code: Secret<String>,
#[serde(skip_serializing_if = "Option::is_none")]
submit: Option<Submit>,
#[serde(skip_serializing_if = "Option::is_none")]
pub reply: Option<Reply>,
#[serde(skip_serializing_if = "Option::is_none")]
inquiry: Option<Inquiry>,
#[serde(skip_serializing_if = "Option::is_none")]
modify: Option<Modify>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct Modify {
order_modification: OrderModification,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct OrderModification {
#[serde(rename = "@orderCode")]
order_code: String,
#[serde(skip_serializing_if = "Option::is_none")]
capture: Option<CaptureRequest>,
#[serde(skip_serializing_if = "Option::is_none")]
cancel: Option<CancelRequest>,
#[serde(skip_serializing_if = "Option::is_none")]
cancel_refund: Option<CancelRequest>,
#[serde(skip_serializing_if = "Option::is_none")]
refund: Option<RefundRequest>,
}
#[derive(Debug, Serialize, Deserialize)]
struct RefundRequest {
amount: WorldpayXmlAmount,
}
#[derive(Debug, Serialize, Deserialize)]
struct CancelRequest {}
#[derive(Debug, Serialize, Deserialize)]
struct CaptureRequest {
amount: WorldpayXmlAmount,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct Inquiry {
order_inquiry: OrderInquiry,
}
#[derive(Debug, Serialize, Deserialize)]
struct OrderInquiry {
#[serde(rename = "@orderCode")]
order_code: String,
}
#[derive(Debug, Serialize, Deserialize)]
struct Submit {
order: Order,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Reply {
order_status: Option<OrderStatus>,
pub error: Option<WorldpayXmlErrorResponse>,
ok: Option<OkResponse>,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PayoutResponse {
reply: PayoutReply,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
struct PayoutReply {
ok: Option<OkPayoutResponse>,
order_status: Option<OrderStatus>,
error: Option<WorldpayXmlErrorResponse>,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
struct OkPayoutResponse {
refund_received: Option<ModifyRequestReceived>,
cancel_received: Option<ModifyRequestReceived>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
struct OkResponse {
capture_received: Option<ModifyRequestReceived>,
cancel_received: Option<ModifyRequestReceived>,
refund_received: Option<ModifyRequestReceived>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
struct ModifyRequestReceived {
#[serde(rename = "@orderCode")]
order_code: String,
amount: Option<WorldpayXmlAmount>,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct WorldpayXmlErrorResponse {
#[serde(rename = "@code")]
pub code: String,
#[serde(rename = "$value")]
pub message: String,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
struct OrderStatus {
#[serde(rename = "@orderCode")]
order_code: String,
challenge_required: Option<ChallengeRequired>,
payment: Option<Payment>,
error: Option<WorldpayXmlErrorResponse>,
}
#[derive(Debug, Deserialize, Serialize)]
struct ChallengeRequired {
#[serde(rename = "threeDSChallengeDetails")]
three_ds_challenge_details: Option<ThreeDSChallengeDetails>,
}
#[derive(Debug, Deserialize, Serialize)]
struct ThreeDSChallengeDetails {
#[serde(rename = "threeDSVersion")]
three_ds_version: Option<String>,
#[serde(rename = "acsURL")]
acs_url: Option<String>,
#[serde(rename = "transactionId3DS")]
transaction_id_3ds: Option<String>,
payload: Option<String>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Payment {
payment_method: String,
amount: WorldpayXmlAmount,
pub last_event: LastEvent,
#[serde(rename = "AuthorisationId")]
authorisation_id: Option<AuthorisationId>,
scheme_response: Option<SchemeResponse>,
payment_method_detail: Option<PaymentMethodDetail>,
#[serde(rename = "CVCResultCode")]
cvc_result_code: Option<ResultCode>,
#[serde(rename = "AVSResultCode")]
avs_result_code: Option<ResultCode>,
#[serde(rename = "AAVAddressResultCode")]
aav_address_result_code: Option<ResultCode>,
#[serde(rename = "AAVPostcodeResultCode")]
aav_postcode_result_code: Option<ResultCode>,
#[serde(rename = "AAVCardholderNameResultCode")]
aav_cardholder_name_result_code: Option<ResultCode>,
#[serde(rename = "AAVTelephoneResultCode")]
aav_telephone_result_code: Option<ResultCode>,
#[serde(rename = "AAVEmailResultCode")]
aav_email_result_code: Option<ResultCode>,
#[serde(rename = "ThreeDSecureResult")]
three_d_secure_result: Option<ResultCode>,
issuer_country_code: Option<String>,
issuer_name: Option<String>,
balance: Option<Vec<Balance>>,
card_holder_name: Option<String>,
fast_funds: Option<bool>,
#[serde(rename = "ISO8583ReturnCode")]
return_code: Option<ReturnCode>,
}
#[derive(Debug, Deserialize, Serialize)]
struct ReturnCode {
#[serde(rename = "@description")]
description: String,
#[serde(rename = "@code")]
code: String,
}
#[derive(Debug, Deserialize, Serialize)]
struct ResultCode {
#[serde(rename = "@description")]
description: String,
}
#[derive(Debug, Deserialize, Serialize)]
struct Balance {
#[serde(rename = "@accountType")]
account_type: String,
amount: WorldpayXmlAmount,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
struct PaymentMethodDetail {
card: CardResponse,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
struct CardResponse {
#[serde(rename = "@number")]
number: Option<Secret<String>>,
#[serde(rename = "@type")]
card_type: String,
expiry_date: Option<ExpiryDate>,
}
#[derive(Debug, Deserialize, Serialize)]
struct AuthorisationId {
#[serde(rename = "@id")]
id: Secret<String>,
}
#[derive(Debug, Clone, Copy, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum LastEvent {
Authorised,
Refused,
Cancelled,
Captured,
Settled,
SentForAuthorisation,
SentForRefund,
SentForFastRefund,
Refunded,
RefundRequested,
RefundFailed,
RefundedByMerchant,
Error,
QueryRequired,
CancelReceived,
RefundReceived,
PushApproved,
PushPending,
PushRequested,
PushRefused,
SettledByMerchant,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
struct SchemeResponse {
transaction_identifier: String,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct Order {
#[serde(rename = "@orderCode")]
order_code: String,
#[serde(skip_serializing_if = "Option::is_none", rename = "@captureDelay")]
capture_delay: Option<AutoCapture>,
#[serde(skip_serializing_if = "Option::is_none")]
description: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
amount: Option<WorldpayXmlAmount>,
#[serde(skip_serializing_if = "Option::is_none")]
payment_details: Option<PaymentDetails>,
#[serde(skip_serializing_if = "Option::is_none")]
shopper: Option<WorldpayxmlShopper>,
#[serde(skip_serializing_if = "Option::is_none")]
shipping_address: Option<WorldpayxmlPayinAddress>,
#[serde(skip_serializing_if = "Option::is_none")]
billing_address: Option<WorldpayxmlPayinAddress>,
#[serde(skip_serializing_if = "Option::is_none", rename = "additional3DSData")]
additional_threeds_data: Option<AdditionalThreeDSData>,
#[serde(skip_serializing_if = "Option::is_none", rename = "info3DSecure")]
info_threed_secure: Option<Info3DSecure>,
#[serde(skip_serializing_if = "Option::is_none")]
session: Option<CompleteAuthSession>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct Info3DSecure {
completed_authentication: CompletedAuthentication,
}
#[derive(Debug, Serialize, Deserialize)]
struct CompletedAuthentication {}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct CompleteAuthSession {
#[serde(rename = "@id")]
id: Secret<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct WorldpayxmlShopper {
#[serde(skip_serializing_if = "Option::is_none")]
pub shopper_email_address: Option<pii::Email>,
#[serde(skip_serializing_if = "Option::is_none")]
pub browser: Option<WPGBrowserData>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct WPGBrowserData {
#[serde(skip_serializing_if = "Option::is_none")]
pub accept_header: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub user_agent_header: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub http_accept_language: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub http_referer: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub time_zone: Option<i32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub browser_language: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub browser_java_enabled: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub browser_java_script_enabled: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub browser_colour_depth: Option<u8>,
#[serde(skip_serializing_if = "Option::is_none")]
pub browser_screen_height: Option<u32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub browser_screen_width: Option<u32>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct WorldpayxmlPayinAddress {
address: WorldpayxmlAddressData,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct WorldpayxmlAddressData {
#[serde(skip_serializing_if = "Option::is_none")]
first_name: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
last_name: Option<Secret<String>>,
address1: Secret<String>,
#[serde(skip_serializing_if = "Option::is_none")]
address2: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
address3: Option<Secret<String>>,
postal_code: Secret<String>,
city: String,
#[serde(skip_serializing_if = "Option::is_none")]
state: Option<Secret<String>>,
country_code: common_enums::CountryAlpha2,
}
#[derive(Debug, Serialize, Deserialize)]
struct AdditionalThreeDSData {
#[serde(rename = "@dfReferenceId")]
df_reference_id: Option<String>,
#[serde(rename = "@javaScriptEnabled")]
javascript_enabled: bool,
#[serde(rename = "@deviceChannel")]
device_channel: String,
#[serde(rename = "@challengePreference")]
challenge_preference: ChallengePreference,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
enum ChallengePreference {
NoChallengeRequested,
ChallengeRequested,
ChallengeMandated,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "UPPERCASE")]
enum AutoCapture {
Off,
#[serde(rename = "0")]
On,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct WorldpayXmlAmount {
#[serde(rename = "@value")]
value: StringMinorUnit,
#[serde(rename = "@currencyCode")]
currency_code: api_models::enums::Currency,
#[serde(rename = "@exponent")]
exponent: String,
}
#[derive(Debug, Serialize, Deserialize)]
struct PaymentDetails {
#[serde(skip_serializing_if = "Option::is_none", rename = "@action")]
action: Option<Action>,
#[serde(flatten)]
payment_method: PaymentMethod,
#[serde(skip_serializing_if = "Option::is_none")]
session: Option<Session>,
}
#[derive(Debug, Serialize, Deserialize)]
struct Session {
#[serde(rename = "@id")]
id: String,
#[serde(rename = "@shopperIPAddress")]
shopper_ip_address: Secret<String, pii::IpAddress>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
enum PaymentMethod {
#[serde(rename = "CARD-SSL")]
CardSSL(CardSSL),
#[serde(rename = "FF_DISBURSE-SSL")]
FastAccessSSL(FastAccessData),
#[serde(rename = "PAYWITHGOOGLE-SSL")]
PayWithGoogleSSL(GooglePayData),
#[serde(rename = "APPLEPAY-SSL")]
PayWithAppleSSL(ApplePayData),
}
#[cfg(feature = "payouts")]
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct FastAccessData {
recipient: Recipient,
#[serde(skip_serializing_if = "Option::is_none")]
purpose_of_payment: Option<String>,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct Recipient {
payment_instrument: PaymentInstrument,
address: Option<WorldpayxmlAddressData>,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct PaymentInstrument {
card_details: CardDetails,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Serialize, Deserialize)]
struct CardDetails {
#[serde(flatten)]
card_ssl: CardSSL,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
struct CardSSL {
card_number: cards::CardNumber,
expiry_date: ExpiryDate,
card_holder_name: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
cvc: Option<Secret<String>>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename = "expiryDate")]
struct ExpiryDate {
date: Date,
}
#[derive(Debug, Deserialize, Serialize)]
struct Date {
#[serde(rename = "@month")]
month: Secret<String>,
#[serde(rename = "@year")]
year: Secret<String>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct GooglePayData {
protocol_version: Secret<String>,
signature: Secret<String>,
signed_message: Secret<String>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct ApplePayData {
header: ApplePayHeader,
signature: Secret<String>,
version: Secret<String>,
data: Secret<String>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct ApplePayHeader {
ephemeral_public_key: Secret<String>,
public_key_hash: Secret<String>,
transaction_id: Secret<String>,
}
#[cfg(feature = "payouts")]
impl TryFrom<LastEvent> for enums::PayoutStatus {
type Error = errors::ConnectorError;
fn try_from(item: LastEvent) -> Result<Self, Self::Error> {
match item {
LastEvent::PushRequested => Ok(Self::Initiated),
LastEvent::PushPending => Ok(Self::Pending),
LastEvent::Error | LastEvent::PushRefused => Ok(Self::Failed),
LastEvent::PushApproved | LastEvent::SettledByMerchant => Ok(Self::Success),
LastEvent::CancelReceived => Ok(Self::Cancelled),
_ => Err(errors::ConnectorError::UnexpectedResponseError(
bytes::Bytes::from("Invalid LastEvent".to_string()),
)),
}
}
}
#[cfg(feature = "payouts")]
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct WorldpayxmlPayoutConnectorMetadataObject {
pub purpose_of_payment: Option<String>,
}
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct WorldpayxmlConnectorMetadataObject {
pub issuer_id: Option<String>,
pub organizational_unit_id: Option<String>,
pub jwt_mac_key: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
enum Action {
Authorise,
Sale,
Refund,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum WorldpayxmlSyncResponse {
Webhook(Box<WorldpayXmlWebhookBody>),
Payment(Box<PaymentService>),
}
impl TryFrom<(&Card, Option<enums::CaptureMethod>, Option<Session>)> for PaymentDetails {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(card_data, capture_method, session): (
&Card,
Option<enums::CaptureMethod>,
Option<Session>,
),
) -> Result<Self, Self::Error> {
Ok(Self {
action: if connector_utils::is_manual_capture(capture_method) {
Some(Action::Authorise)
} else {
Some(Action::Sale)
},
payment_method: PaymentMethod::CardSSL(CardSSL {
card_number: card_data.card_number.clone(),
expiry_date: ExpiryDate {
date: Date {
month: card_data.get_card_expiry_month_2_digit()?,
year: card_data.get_expiry_year_4_digit(),
},
},
card_holder_name: card_data.card_holder_name.to_owned(),
cvc: Some(card_data.card_cvc.to_owned()),
}),
session,
})
}
}
impl TryFrom<(&GooglePayWalletData, Option<enums::CaptureMethod>)> for PaymentDetails {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(gpay_data, capture_method): (&GooglePayWalletData, Option<enums::CaptureMethod>),
) -> Result<Self, Self::Error> {
let token_string = gpay_data
.tokenization_data
.get_encrypted_google_pay_token()
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "gpay wallet_token",
})?
.to_owned();
let parsed_token = serde_json::from_str::<GooglePayData>(&token_string)
.change_context(errors::ConnectorError::ParsingFailed)?;
Ok(Self {
action: if connector_utils::is_manual_capture(capture_method) {
Some(Action::Authorise)
} else {
Some(Action::Sale)
},
payment_method: PaymentMethod::PayWithGoogleSSL(GooglePayData {
protocol_version: parsed_token.protocol_version,
signature: parsed_token.signature,
signed_message: parsed_token.signed_message.clone(),
}),
session: None,
})
}
}
impl TryFrom<(&ApplePayWalletData, Option<enums::CaptureMethod>)> for PaymentDetails {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(apple_pay_wallet_data, capture_method): (
&ApplePayWalletData,
Option<enums::CaptureMethod>,
),
) -> Result<Self, Self::Error> {
let applepay_encrypt_data = apple_pay_wallet_data
.payment_data
.get_encrypted_apple_pay_payment_data_mandatory()
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "Apple pay encrypted data",
})?;
let decoded_data = base64::prelude::BASE64_STANDARD
.decode(applepay_encrypt_data)
.change_context(errors::ConnectorError::InvalidDataFormat {
field_name: "apple_pay_encrypted_data",
})?;
let apple_pay_token: ApplePayData = serde_json::from_slice(&decoded_data).change_context(
errors::ConnectorError::InvalidDataFormat {
field_name: "apple_pay_token_json",
},
)?;
Ok(Self {
action: if connector_utils::is_manual_capture(capture_method) {
Some(Action::Authorise)
} else {
Some(Action::Sale)
},
payment_method: PaymentMethod::PayWithAppleSSL(apple_pay_token),
session: None,
})
}
}
fn get_address_details(data: &Address) -> Option<WorldpayxmlPayinAddress> {
let address1_option = data
.address
.as_ref()
.and_then(|address| address.get_optional_line1());
let postal_code_option = data
.address
.as_ref()
.and_then(|address| address.get_optional_zip());
let country_code_option = data
.address
.as_ref()
.and_then(|address| address.get_optional_country());
let city_option = data
.address
.as_ref()
.and_then(|address| address.get_optional_city());
if let (Some(address1), Some(postal_code), Some(country_code), Some(city), Some(address_data)) = (
address1_option,
postal_code_option,
country_code_option,
city_option,
data.address.as_ref(),
) {
Some(WorldpayxmlPayinAddress {
address: WorldpayxmlAddressData {
first_name: address_data.get_optional_first_name(),
last_name: address_data.get_optional_last_name(),
address1,
address2: address_data.get_optional_line2(),
address3: address_data.get_optional_line2(),
postal_code,
city,
state: address_data.get_optional_state(),
country_code,
},
})
} else {
None
}
}
fn get_shopper_details(
item: &PaymentsAuthorizeRouterData,
accept_header: Option<String>,
user_agent_header: Option<String>,
) -> Result<Option<WorldpayxmlShopper>, errors::ConnectorError> {
let shopper_email = item.request.email.clone();
let browser_info = item
.request
.browser_info
.clone()
.as_ref()
.map(|browser_info| WPGBrowserData {
accept_header,
http_accept_language: browser_info.accept_language.clone(),
http_referer: browser_info.referer.clone(),
browser_language: browser_info.language.clone(),
browser_java_enabled: browser_info.java_enabled,
browser_java_script_enabled: browser_info.java_script_enabled,
browser_colour_depth: browser_info.color_depth,
browser_screen_height: browser_info.screen_height,
browser_screen_width: browser_info.screen_width,
user_agent_header,
time_zone: browser_info.time_zone,
});
if shopper_email.is_some() || browser_info.is_some() {
Ok(Some(WorldpayxmlShopper {
shopper_email_address: shopper_email,
browser: browser_info,
}))
} else {
Ok(None)
}
}
impl TryFrom<&WorldpayxmlRouterData<&PaymentsAuthorizeRouterData>> for PaymentService {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &WorldpayxmlRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let auth = WorldpayxmlAuthType::try_from(&item.router_data.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let order_code = if item.router_data.connector_request_reference_id.len()
<= worldpayxml_constants::MAX_PAYMENT_REFERENCE_ID_LENGTH
{
Ok(item.router_data.connector_request_reference_id.clone())
} else {
Err(errors::ConnectorError::MaxFieldLengthViolated {
connector: "Worldpayxml".to_string(),
field_name: "order_code".to_string(),
max_length: worldpayxml_constants::MAX_PAYMENT_REFERENCE_ID_LENGTH,
received_length: item.router_data.connector_request_reference_id.len(),
})
}?;
let capture_delay = if item.router_data.request.is_auto_capture()? {
Some(AutoCapture::On)
} else {
Some(AutoCapture::Off)
};
let description = item.router_data.description.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "description",
},
)?;
let is_three_ds = item.router_data.is_three_ds();
let (additional_threeds_data, session, accept_header, user_agent_header) =
if is_three_ds {
let additional_threeds_data = Some(AdditionalThreeDSData {
df_reference_id: None,
javascript_enabled: false,
device_channel: "Browser".to_string(),
challenge_preference: ChallengePreference::ChallengeRequested,
});
let browser_info = item.router_data.request.get_browser_info()?;
let accept_header = browser_info.accept_header.ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "browser_info.accept_header",
},
)?;
let user_agent_header = browser_info.user_agent.ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "browser_info.user_agent",
},
)?;
let session = Some(Session {
id: item.router_data.connector_request_reference_id.clone(),
shopper_ip_address: item.router_data.request.get_ip_address()?,
});
(
additional_threeds_data,
session,
Some(accept_header),
Some(user_agent_header),
)
} else {
let accept_header = item
.router_data
.request
.browser_info
.as_ref()
.and_then(|info| info.accept_header.clone());
let user_agent_header = item
.router_data
.request
.browser_info
.as_ref()
.and_then(|info| info.user_agent.clone());
(None, None, accept_header, user_agent_header)
};
let exponent = item
.router_data
.request
.currency
.number_of_digits_after_decimal_point()
.to_string();
let amount = WorldpayXmlAmount {
currency_code: item.router_data.request.currency.to_owned(),
exponent,
value: item.amount.to_owned(),
};
let shopper = get_shopper_details(item.router_data, accept_header, user_agent_header)?;
let billing_address = item
.router_data
.get_optional_billing()
.and_then(get_address_details);
let shipping_address = item
.router_data
.get_optional_shipping()
.and_then(get_address_details);
let payment_details = match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(req_card) => PaymentDetails::try_from((
&req_card,
item.router_data.request.capture_method,
session,
))?,
PaymentMethodData::Wallet(wallet_data) => match wallet_data {
WalletData::GooglePay(google_pay_data) => PaymentDetails::try_from((
&google_pay_data,
item.router_data.request.capture_method,
))?,
WalletData::ApplePay(apple_pay_data) => PaymentDetails::try_from((
&apple_pay_data,
item.router_data.request.capture_method,
))?,
_ => Err(errors::ConnectorError::NotImplemented(
connector_utils::get_unimplemented_payment_method_error_message("Worldpayxml"),
))?,
},
_ => Err(errors::ConnectorError::NotImplemented(
connector_utils::get_unimplemented_payment_method_error_message("Worldpayxml"),
))?,
};
let submit = Some(Submit {
order: Order {
order_code,
capture_delay,
description: Some(description),
amount: Some(amount),
payment_details: Some(payment_details),
shopper,
shipping_address,
billing_address,
additional_threeds_data,
info_threed_secure: None,
session: None,
},
});
Ok(Self {
version: worldpayxml_constants::WORLDPAYXML_VERSION.to_string(),
merchant_code: auth.merchant_code.clone(),
submit,
reply: None,
inquiry: None,
modify: None,
})
}
}
impl TryFrom<&WorldpayxmlRouterData<&PaymentsCaptureRouterData>> for PaymentService {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &WorldpayxmlRouterData<&PaymentsCaptureRouterData>,
) -> Result<Self, Self::Error> {
let auth = WorldpayxmlAuthType::try_from(&item.router_data.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let modify = Some(Modify {
order_modification: OrderModification {
order_code: item.router_data.request.connector_transaction_id.clone(),
capture: Some(CaptureRequest {
amount: WorldpayXmlAmount {
currency_code: item.router_data.request.currency.to_owned(),
exponent: item
.router_data
.request
.currency
.number_of_digits_after_decimal_point()
.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/volt/transformers.rs | crates/hyperswitch_connectors/src/connectors/volt/transformers.rs | use common_enums::enums;
use common_utils::{id_type, pii::Email, request::Method, types::MinorUnit};
use hyperswitch_domain_models::{
payment_method_data::{BankRedirectData, PaymentMethodData},
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::refunds::Execute,
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
types,
};
use hyperswitch_interfaces::{consts, errors};
use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
types::{
PaymentsCancelResponseRouterData, RefreshTokenRouterData, RefundsResponseRouterData,
ResponseRouterData,
},
utils::{
self, is_payment_failure, AddressDetailsData, PaymentsAuthorizeRequestData, RouterData as _,
},
};
const PASSWORD: &str = "password";
pub struct VoltRouterData<T> {
pub amount: MinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc.
pub router_data: T,
}
impl<T> From<(MinorUnit, T)> for VoltRouterData<T> {
fn from((amount, item): (MinorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
pub mod webhook_headers {
pub const X_VOLT_SIGNED: &str = "X-Volt-Signed";
pub const X_VOLT_TIMED: &str = "X-Volt-Timed";
pub const USER_AGENT: &str = "User-Agent";
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct VoltPaymentsRequest {
amount: MinorUnit,
currency: enums::Currency,
#[serde(skip_serializing_if = "Option::is_none")]
open_banking_u_k: Option<OpenBankingUk>,
#[serde(skip_serializing_if = "Option::is_none")]
open_banking_e_u: Option<OpenBankingEu>,
internal_reference: String,
payer: PayerDetails,
payment_system: PaymentSystem,
communication: CommunicationDetails,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum TransactionType {
Bills,
Goods,
PersonToPerson,
Other,
Services,
}
#[derive(Debug, Serialize)]
pub struct OpenBankingUk {
#[serde(rename = "type")]
transaction_type: TransactionType,
}
#[derive(Debug, Serialize)]
pub struct OpenBankingEu {
#[serde(rename = "type")]
transaction_type: TransactionType,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PayerDetails {
reference: id_type::CustomerId,
email: Option<Email>,
first_name: Secret<String>,
last_name: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PaymentSystem {
OpenBankingEu,
OpenBankingUk,
NppPayToAu,
}
#[derive(Debug, Serialize)]
pub struct CommunicationDetails {
#[serde[rename = "return"]]
return_urls: ReturnUrls,
}
#[derive(Debug, Serialize)]
pub struct ReturnUrls {
success: Link,
failure: Link,
pending: Link,
cancel: Link,
}
#[derive(Debug, Serialize)]
pub struct Link {
link: Option<String>,
}
impl TryFrom<&VoltRouterData<&types::PaymentsAuthorizeRouterData>> for VoltPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &VoltRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::BankRedirect(ref bank_redirect) => {
let transaction_type = TransactionType::Services; //transaction_type is a form of enum, it is pre defined and value for this can not be taken from user so we are keeping it as Services as this transaction is type of service.
let currency = item.router_data.request.currency;
let (payment_system, open_banking_u_k, open_banking_e_u) = match bank_redirect {
BankRedirectData::OpenBankingUk { .. } => Ok((
PaymentSystem::OpenBankingUk,
Some(OpenBankingUk { transaction_type }),
None,
)),
BankRedirectData::OpenBanking {} => {
if matches!(currency, common_enums::Currency::GBP) {
Ok((
PaymentSystem::OpenBankingUk,
Some(OpenBankingUk { transaction_type }),
None,
))
} else {
Ok((
PaymentSystem::OpenBankingEu,
None,
Some(OpenBankingEu { transaction_type }),
))
}
}
BankRedirectData::BancontactCard { .. }
| BankRedirectData::Bizum {}
| BankRedirectData::Blik { .. }
| BankRedirectData::Eft { .. }
| BankRedirectData::Eps { .. }
| BankRedirectData::Giropay { .. }
| BankRedirectData::Ideal { .. }
| BankRedirectData::Interac { .. }
| BankRedirectData::OnlineBankingCzechRepublic { .. }
| BankRedirectData::OnlineBankingFinland { .. }
| BankRedirectData::OnlineBankingPoland { .. }
| BankRedirectData::OnlineBankingSlovakia { .. }
| BankRedirectData::Przelewy24 { .. }
| BankRedirectData::Sofort { .. }
| BankRedirectData::Trustly { .. }
| BankRedirectData::OnlineBankingFpx { .. }
| BankRedirectData::OnlineBankingThailand { .. }
| BankRedirectData::LocalBankRedirect {} => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Volt"),
))
}
}?;
let amount = item.amount;
let internal_reference = item.router_data.connector_request_reference_id.clone();
let communication = CommunicationDetails {
return_urls: ReturnUrls {
success: Link {
link: item.router_data.request.router_return_url.clone(),
},
failure: Link {
link: item.router_data.request.router_return_url.clone(),
},
pending: Link {
link: item.router_data.request.router_return_url.clone(),
},
cancel: Link {
link: item.router_data.request.router_return_url.clone(),
},
},
};
let address = item.router_data.get_billing_address()?;
let first_name = address.get_first_name()?;
let payer = PayerDetails {
email: item.router_data.request.get_optional_email(),
first_name: first_name.to_owned(),
last_name: address.get_last_name().unwrap_or(first_name).to_owned(),
reference: item.router_data.get_customer_id()?.to_owned(),
};
Ok(Self {
amount,
currency,
internal_reference,
communication,
payer,
payment_system,
open_banking_u_k,
open_banking_e_u,
})
}
PaymentMethodData::Card(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Wallet(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Volt"),
)
.into())
}
}
}
}
#[derive(Debug, Clone, Serialize, PartialEq)]
pub struct VoltAuthUpdateRequest {
grant_type: String,
client_id: Secret<String>,
client_secret: Secret<String>,
username: Secret<String>,
password: Secret<String>,
}
impl TryFrom<&RefreshTokenRouterData> for VoltAuthUpdateRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &RefreshTokenRouterData) -> Result<Self, Self::Error> {
let auth = VoltAuthType::try_from(&item.connector_auth_type)?;
Ok(Self {
grant_type: PASSWORD.to_string(),
username: auth.username,
password: auth.password,
client_id: auth.client_id,
client_secret: auth.client_secret,
})
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct VoltAuthUpdateResponse {
pub access_token: Secret<String>,
pub token_type: String,
pub expires_in: i64,
pub refresh_token: Secret<String>,
}
impl<F, T> TryFrom<ResponseRouterData<F, VoltAuthUpdateResponse, T, AccessToken>>
for RouterData<F, T, AccessToken>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, VoltAuthUpdateResponse, T, AccessToken>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(AccessToken {
token: item.response.access_token,
expires: item.response.expires_in,
}),
..item.data
})
}
}
pub struct VoltAuthType {
pub(super) username: Secret<String>,
pub(super) password: Secret<String>,
pub(super) client_id: Secret<String>,
pub(super) client_secret: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for VoltAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::MultiAuthKey {
api_key,
key1,
api_secret,
key2,
} => Ok(Self {
username: api_key.to_owned(),
password: api_secret.to_owned(),
client_id: key1.to_owned(),
client_secret: key2.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
fn get_attempt_status(
(item, current_status): (VoltPaymentStatus, enums::AttemptStatus),
) -> enums::AttemptStatus {
match item {
VoltPaymentStatus::Received | VoltPaymentStatus::Settled => enums::AttemptStatus::Charged,
VoltPaymentStatus::Completed
| VoltPaymentStatus::DelayedAtBank
| VoltPaymentStatus::AuthorisedByUser
| VoltPaymentStatus::ApprovedByRisk => enums::AttemptStatus::Pending,
VoltPaymentStatus::NewPayment
| VoltPaymentStatus::BankRedirect
| VoltPaymentStatus::AwaitingCheckoutAuthorisation
| VoltPaymentStatus::AdditionalAuthorizationRequired => {
enums::AttemptStatus::AuthenticationPending
}
VoltPaymentStatus::RefusedByBank
| VoltPaymentStatus::RefusedByRisk
| VoltPaymentStatus::NotReceived
| VoltPaymentStatus::ErrorAtBank
| VoltPaymentStatus::CancelledByUser
| VoltPaymentStatus::AbandonedByUser
| VoltPaymentStatus::Failed
| VoltPaymentStatus::ProviderCommunicationError => enums::AttemptStatus::Failure,
VoltPaymentStatus::Unknown => current_status,
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct VoltPaymentsResponse {
id: String,
amount: MinorUnit,
currency: enums::Currency,
status: VoltPaymentStatus,
payment_initiation_flow: VoltPaymentInitiationFlow,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct VoltPaymentInitiationFlow {
status: VoltPaymentInitiationFlowStatus,
details: VoltPaymentInitiationFlowDetails,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum VoltPaymentInitiationFlowStatus {
Processing,
Finished,
Aborted,
Exception,
WaitingForInput,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct VoltPaymentInitiationFlowDetails {
reason: String,
redirect: VoltRedirect,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct VoltRedirect {
url: Secret<url::Url>,
direct_url: Secret<url::Url>,
}
impl<F, T> TryFrom<ResponseRouterData<F, VoltPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, VoltPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let url = item
.response
.payment_initiation_flow
.details
.redirect
.url
.clone()
.expose();
let redirection_data = Some(RedirectForm::Form {
endpoint: url.to_string(),
method: Method::Get,
form_fields: Default::default(),
});
Ok(Self {
status: enums::AttemptStatus::AuthenticationPending,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.id),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Debug, Serialize, Clone, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
#[derive(strum::Display)]
pub enum VoltPaymentStatus {
NewPayment,
ApprovedByRisk,
AdditionalAuthorizationRequired,
AuthorisedByUser,
ProviderCommunicationError,
Completed,
Received,
NotReceived,
BankRedirect,
DelayedAtBank,
AwaitingCheckoutAuthorisation,
RefusedByBank,
RefusedByRisk,
ErrorAtBank,
CancelledByUser,
AbandonedByUser,
Failed,
Settled,
Unknown,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum VoltPaymentsResponseData {
PsyncResponse(VoltPsyncResponse),
WebhookResponse(VoltPaymentWebhookObjectResource),
}
#[derive(Debug, Serialize, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct VoltPsyncResponse {
status: VoltPaymentStatus,
id: String,
merchant_internal_reference: Option<String>,
amount: MinorUnit,
currency: enums::Currency,
}
impl<F, T> TryFrom<ResponseRouterData<F, VoltPaymentsResponseData, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, VoltPaymentsResponseData, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
match item.response {
VoltPaymentsResponseData::PsyncResponse(payment_response) => {
let status =
get_attempt_status((payment_response.status.clone(), item.data.status));
Ok(Self {
status,
response: if is_payment_failure(status) {
Err(ErrorResponse {
code: payment_response.status.clone().to_string(),
message: payment_response.status.clone().to_string(),
reason: Some(payment_response.status.to_string()),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(payment_response.id),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
payment_response.id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: payment_response
.merchant_internal_reference
.or(Some(payment_response.id)),
incremental_authorization_allowed: None,
charges: None,
})
},
..item.data
})
}
VoltPaymentsResponseData::WebhookResponse(webhook_response) => {
let detailed_status = webhook_response.detailed_status.clone();
let status = enums::AttemptStatus::from(webhook_response.status);
Ok(Self {
status,
response: if is_payment_failure(status) {
Err(ErrorResponse {
code: detailed_status
.clone()
.map(|volt_status| volt_status.to_string())
.unwrap_or_else(|| consts::NO_ERROR_CODE.to_owned()),
message: detailed_status
.clone()
.map(|volt_status| volt_status.to_string())
.unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_owned()),
reason: detailed_status
.clone()
.map(|volt_status| volt_status.to_string()),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(webhook_response.payment.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
webhook_response.payment.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: webhook_response
.merchant_internal_reference
.or(Some(webhook_response.payment)),
incremental_authorization_allowed: None,
charges: None,
})
},
..item.data
})
}
}
}
}
#[derive(Debug, Serialize, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct VoltCancelResponse {
payment_id: String,
status: VoltPaymentStatus,
}
impl TryFrom<PaymentsCancelResponseRouterData<VoltCancelResponse>>
for types::PaymentsCancelRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PaymentsCancelResponseRouterData<VoltCancelResponse>,
) -> Result<Self, Self::Error> {
let status = get_attempt_status((item.response.status.clone(), item.data.status));
Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.payment_id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.payment_id),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
impl From<VoltWebhookPaymentStatus> for enums::AttemptStatus {
fn from(status: VoltWebhookPaymentStatus) -> Self {
match status {
VoltWebhookPaymentStatus::Received => Self::Charged,
VoltWebhookPaymentStatus::Failed | VoltWebhookPaymentStatus::NotReceived => {
Self::Failure
}
VoltWebhookPaymentStatus::Completed | VoltWebhookPaymentStatus::Pending => {
Self::Pending
}
}
}
}
// REFUND :
// Type definition for RefundRequest
#[derive(Default, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct VoltRefundRequest {
pub amount: MinorUnit,
pub external_reference: String,
}
impl<F> TryFrom<&VoltRouterData<&types::RefundsRouterData<F>>> for VoltRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &VoltRouterData<&types::RefundsRouterData<F>>) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.amount,
external_reference: item.router_data.request.refund_id.clone(),
})
}
}
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
pub struct RefundResponse {
id: String,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>>
for types::RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::Pending, //We get Refund Status only by Webhooks
}),
..item.data
})
}
}
#[derive(Debug, Deserialize, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct VoltPaymentWebhookBodyReference {
pub payment: String,
pub merchant_internal_reference: Option<String>,
}
#[derive(Debug, Deserialize, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct VoltRefundWebhookBodyReference {
pub refund: String,
pub external_reference: Option<String>,
}
#[derive(Debug, Deserialize, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
#[serde(untagged)]
pub enum WebhookResponse {
// the enum order shouldn't be changed as this is being used during serialization and deserialization
Refund(VoltRefundWebhookBodyReference),
Payment(VoltPaymentWebhookBodyReference),
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum VoltWebhookBodyEventType {
Payment(VoltPaymentsWebhookBodyEventType),
Refund(VoltRefundsWebhookBodyEventType),
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct VoltPaymentsWebhookBodyEventType {
pub status: VoltWebhookPaymentStatus,
pub detailed_status: Option<VoltDetailedStatus>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct VoltRefundsWebhookBodyEventType {
pub status: VoltWebhookRefundsStatus,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum VoltWebhookObjectResource {
Payment(VoltPaymentWebhookObjectResource),
Refund(VoltRefundWebhookObjectResource),
}
#[derive(Debug, Deserialize, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct VoltPaymentWebhookObjectResource {
#[serde(alias = "id")]
pub payment: String,
pub merchant_internal_reference: Option<String>,
pub status: VoltWebhookPaymentStatus,
pub detailed_status: Option<VoltDetailedStatus>,
}
#[derive(Debug, Deserialize, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct VoltRefundWebhookObjectResource {
pub refund: String,
pub external_reference: Option<String>,
pub status: VoltWebhookRefundsStatus,
}
#[derive(Debug, Deserialize, Clone, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum VoltWebhookPaymentStatus {
Completed,
Failed,
Pending,
Received,
NotReceived,
}
#[derive(Debug, Deserialize, Clone, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum VoltWebhookRefundsStatus {
RefundConfirmed,
RefundFailed,
}
#[derive(Debug, Deserialize, Clone, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
#[derive(strum::Display)]
pub enum VoltDetailedStatus {
RefusedByRisk,
RefusedByBank,
ErrorAtBank,
CancelledByUser,
AbandonedByUser,
Failed,
Completed,
BankRedirect,
DelayedAtBank,
AwaitingCheckoutAuthorisation,
}
impl From<VoltWebhookBodyEventType> for api_models::webhooks::IncomingWebhookEvent {
fn from(status: VoltWebhookBodyEventType) -> Self {
match status {
VoltWebhookBodyEventType::Payment(payment_data) => match payment_data.status {
VoltWebhookPaymentStatus::Received => Self::PaymentIntentSuccess,
VoltWebhookPaymentStatus::Failed | VoltWebhookPaymentStatus::NotReceived => {
Self::PaymentIntentFailure
}
VoltWebhookPaymentStatus::Completed | VoltWebhookPaymentStatus::Pending => {
Self::PaymentIntentProcessing
}
},
VoltWebhookBodyEventType::Refund(refund_data) => match refund_data.status {
VoltWebhookRefundsStatus::RefundConfirmed => Self::RefundSuccess,
VoltWebhookRefundsStatus::RefundFailed => Self::RefundFailure,
},
}
}
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct VoltErrorResponse {
pub code: Option<String>,
pub message: String,
pub errors: Option<Vec<Errors>>,
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Errors {
#[serde(rename = "type")]
pub error_type: String,
pub property_path: String,
pub message: String,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct VoltAuthErrorResponse {
pub code: u64,
pub message: String,
}
| 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.