text
string | file_path
string | module
string | type
string | tokens
int64 | language
string | struct_name
string | type_name
string | trait_name
string | impl_type
string | function_name
string | source
string | section
string | keys
list | macro_type
string | url
string | title
string | chunk_index
int64 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
pub async fn make_card_network_tokenization_request(
state: &routes::SessionState,
card: &api_payment_methods::CardDetail,
customer_id: &id_type::GlobalCustomerId,
) -> CustomResult<(NetworkTokenDetails, String), errors::NetworkTokenizationError> {
let card_data = pm_types::CardData {
card_number: card.card_number.clone(),
exp_month: card.card_exp_month.clone(),
exp_year: card.card_exp_year.clone(),
card_security_code: None,
};
let payload = card_data
.encode_to_string_of_json()
.and_then(|x| x.encode_to_string_of_json())
.change_context(errors::NetworkTokenizationError::RequestEncodingFailed)?;
let payload_bytes = payload.as_bytes();
let network_tokenization_service = match &state.conf.network_tokenization_service {
Some(nt_service) => Ok(nt_service.get_inner()),
None => Err(report!(
errors::NetworkTokenizationError::NetworkTokenizationServiceNotConfigured
)),
}?;
let (resp, network_token_req_ref_id) = record_operation_time(
async {
generate_network_token(
state,
payload_bytes,
customer_id.clone(),
network_tokenization_service,
)
.await
.inspect_err(|e| logger::error!(error=?e, "Error while making tokenization request"))
},
&metrics::GENERATE_NETWORK_TOKEN_TIME,
router_env::metric_attributes!(("locker", "rust")),
)
.await?;
let network_token_details = NetworkTokenDetails {
network_token: resp.token,
network_token_exp_month: resp.token_expiry_month,
network_token_exp_year: resp.token_expiry_year,
card_issuer: card.card_issuer.clone(),
card_network: Some(resp.card_brand),
card_type: card.card_type.clone(),
card_issuing_country: card.card_issuing_country,
card_holder_name: card.card_holder_name.clone(),
nick_name: card.nick_name.clone(),
};
Ok((network_token_details, network_token_req_ref_id))
}
|
crates/router/src/core/payment_methods/network_tokenization.rs
|
router
|
function_signature
| 437
|
rust
| null | null | null | null |
make_card_network_tokenization_request
| null | null | null | null | null | null | null |
pub fn get_connector_transaction_id(
&self,
) -> errors::CustomResult<String, errors::ValidationError> {
match self {
Self::ConnectorTransactionId(txn_id) => Ok(txn_id.to_string()),
_ => Err(errors::ValidationError::IncorrectValueProvided {
field_name: "connector_transaction_id",
})
.attach_printable("Expected connector transaction ID not found"),
}
}
|
crates/hyperswitch_domain_models/src/router_request_types.rs
|
hyperswitch_domain_models
|
function_signature
| 88
|
rust
| null | null | null | null |
get_connector_transaction_id
| null | null | null | null | null | null | null |
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>>,
}
|
crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 186
|
rust
|
ShipToList
| null | null | null | null | null | null | null | null | null | null | null |
pub struct FiuuAuthType {
pub(super) merchant_id: Secret<String>,
pub(super) verify_key: Secret<String>,
pub(super) secret_key: Secret<String>,
}
|
crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 39
|
rust
|
FiuuAuthType
| null | null | null | null | null | null | null | null | null | null | null |
Self::Japan => CountryAlpha2::JP,
Self::Jersey => CountryAlpha2::JE,
Self::Jordan => CountryAlpha2::JO,
Self::Kazakhstan => CountryAlpha2::KZ,
Self::Kenya => CountryAlpha2::KE,
Self::Kiribati => CountryAlpha2::KI,
Self::KoreaDemocraticPeoplesRepublic => CountryAlpha2::KP,
Self::KoreaRepublic => CountryAlpha2::KR,
Self::Kuwait => CountryAlpha2::KW,
Self::Kyrgyzstan => CountryAlpha2::KG,
Self::LaoPeoplesDemocraticRepublic => CountryAlpha2::LA,
Self::Latvia => CountryAlpha2::LV,
Self::Lebanon => CountryAlpha2::LB,
Self::Lesotho => CountryAlpha2::LS,
Self::Liberia => CountryAlpha2::LR,
Self::Libya => CountryAlpha2::LY,
Self::Liechtenstein => CountryAlpha2::LI,
Self::Lithuania => CountryAlpha2::LT,
Self::Luxembourg => CountryAlpha2::LU,
Self::Macao => CountryAlpha2::MO,
Self::MacedoniaTheFormerYugoslavRepublic => CountryAlpha2::MK,
Self::Madagascar => CountryAlpha2::MG,
Self::Malawi => CountryAlpha2::MW,
Self::Malaysia => CountryAlpha2::MY,
Self::Maldives => CountryAlpha2::MV,
Self::Mali => CountryAlpha2::ML,
Self::Malta => CountryAlpha2::MT,
Self::MarshallIslands => CountryAlpha2::MH,
Self::Martinique => CountryAlpha2::MQ,
Self::Mauritania => CountryAlpha2::MR,
Self::Mauritius => CountryAlpha2::MU,
Self::Mayotte => CountryAlpha2::YT,
Self::Mexico => CountryAlpha2::MX,
Self::MicronesiaFederatedStates => CountryAlpha2::FM,
Self::MoldovaRepublic => CountryAlpha2::MD,
Self::Monaco => CountryAlpha2::MC,
Self::Mongolia => CountryAlpha2::MN,
Self::Montenegro => CountryAlpha2::ME,
Self::Montserrat => CountryAlpha2::MS,
Self::Morocco => CountryAlpha2::MA,
Self::Mozambique => CountryAlpha2::MZ,
Self::Myanmar => CountryAlpha2::MM,
Self::Namibia => CountryAlpha2::NA,
Self::Nauru => CountryAlpha2::NR,
Self::Nepal => CountryAlpha2::NP,
Self::Netherlands => CountryAlpha2::NL,
Self::NewCaledonia => CountryAlpha2::NC,
Self::NewZealand => CountryAlpha2::NZ,
Self::Nicaragua => CountryAlpha2::NI,
Self::Niger => CountryAlpha2::NE,
Self::Nigeria => CountryAlpha2::NG,
Self::Niue => CountryAlpha2::NU,
Self::NorfolkIsland => CountryAlpha2::NF,
Self::NorthernMarianaIslands => CountryAlpha2::MP,
Self::Norway => CountryAlpha2::NO,
Self::Oman => CountryAlpha2::OM,
Self::Pakistan => CountryAlpha2::PK,
Self::Palau => CountryAlpha2::PW,
Self::PalestineState => CountryAlpha2::PS,
Self::Panama => CountryAlpha2::PA,
Self::PapuaNewGuinea => CountryAlpha2::PG,
Self::Paraguay => CountryAlpha2::PY,
Self::Peru => CountryAlpha2::PE,
Self::Philippines => CountryAlpha2::PH,
Self::Pitcairn => CountryAlpha2::PN,
Self::Poland => CountryAlpha2::PL,
Self::Portugal => CountryAlpha2::PT,
Self::PuertoRico => CountryAlpha2::PR,
Self::Qatar => CountryAlpha2::QA,
Self::Reunion => CountryAlpha2::RE,
Self::Romania => CountryAlpha2::RO,
Self::RussianFederation => CountryAlpha2::RU,
Self::Rwanda => CountryAlpha2::RW,
Self::SaintBarthelemy => CountryAlpha2::BL,
Self::SaintHelenaAscensionAndTristandaCunha => CountryAlpha2::SH,
Self::SaintKittsAndNevis => CountryAlpha2::KN,
Self::SaintLucia => CountryAlpha2::LC,
Self::SaintMartinFrenchpart => CountryAlpha2::MF,
Self::SaintPierreAndMiquelon => CountryAlpha2::PM,
Self::SaintVincentAndTheGrenadines => CountryAlpha2::VC,
Self::Samoa => CountryAlpha2::WS,
Self::SanMarino => CountryAlpha2::SM,
Self::SaoTomeAndPrincipe => CountryAlpha2::ST,
Self::SaudiArabia => CountryAlpha2::SA,
Self::Senegal => CountryAlpha2::SN,
Self::Serbia => CountryAlpha2::RS,
Self::Seychelles => CountryAlpha2::SC,
Self::SierraLeone => CountryAlpha2::SL,
Self::Singapore => CountryAlpha2::SG,
Self::SintMaartenDutchpart => CountryAlpha2::SX,
Self::Slovakia => CountryAlpha2::SK,
Self::Slovenia => CountryAlpha2::SI,
Self::SolomonIslands => CountryAlpha2::SB,
Self::Somalia => CountryAlpha2::SO,
Self::SouthAfrica => CountryAlpha2::ZA,
Self::SouthGeorgiaAndTheSouthSandwichIslands => CountryAlpha2::GS,
Self::SouthSudan => CountryAlpha2::SS,
Self::Spain => CountryAlpha2::ES,
Self::SriLanka => CountryAlpha2::LK,
Self::Sudan => CountryAlpha2::SD,
Self::Suriname => CountryAlpha2::SR,
Self::SvalbardAndJanMayen => CountryAlpha2::SJ,
Self::Swaziland => CountryAlpha2::SZ,
Self::Sweden => CountryAlpha2::SE,
Self::Switzerland => CountryAlpha2::CH,
Self::SyrianArabRepublic => CountryAlpha2::SY,
Self::TaiwanProvinceOfChina => CountryAlpha2::TW,
Self::Tajikistan => CountryAlpha2::TJ,
Self::TanzaniaUnitedRepublic => CountryAlpha2::TZ,
Self::Thailand => CountryAlpha2::TH,
Self::TimorLeste => CountryAlpha2::TL,
Self::Togo => CountryAlpha2::TG,
Self::Tokelau => CountryAlpha2::TK,
Self::Tonga => CountryAlpha2::TO,
Self::TrinidadAndTobago => CountryAlpha2::TT,
Self::Tunisia => CountryAlpha2::TN,
Self::Turkey => CountryAlpha2::TR,
Self::Turkmenistan => CountryAlpha2::TM,
Self::TurksAndCaicosIslands => CountryAlpha2::TC,
Self::Tuvalu => CountryAlpha2::TV,
Self::Uganda => CountryAlpha2::UG,
Self::Ukraine => CountryAlpha2::UA,
Self::UnitedArabEmirates => CountryAlpha2::AE,
Self::UnitedKingdomOfGreatBritainAndNorthernIreland => CountryAlpha2::GB,
Self::UnitedStatesOfAmerica => CountryAlpha2::US,
Self::UnitedStatesMinorOutlyingIslands => CountryAlpha2::UM,
Self::Uruguay => CountryAlpha2::UY,
Self::Uzbekistan => CountryAlpha2::UZ,
Self::Vanuatu => CountryAlpha2::VU,
Self::VenezuelaBolivarianRepublic => CountryAlpha2::VE,
Self::Vietnam => CountryAlpha2::VN,
Self::VirginIslandsBritish => CountryAlpha2::VG,
Self::VirginIslandsUS => CountryAlpha2::VI,
Self::WallisAndFutuna => CountryAlpha2::WF,
Self::WesternSahara => CountryAlpha2::EH,
Self::Yemen => CountryAlpha2::YE,
Self::Zambia => CountryAlpha2::ZM,
Self::Zimbabwe => CountryAlpha2::ZW,
}
}
pub const fn from_alpha3(code: CountryAlpha3) -> Self {
match code {
CountryAlpha3::AFG => Self::Afghanistan,
CountryAlpha3::ALA => Self::AlandIslands,
CountryAlpha3::ALB => Self::Albania,
CountryAlpha3::DZA => Self::Algeria,
CountryAlpha3::ASM => Self::AmericanSamoa,
CountryAlpha3::AND => Self::Andorra,
CountryAlpha3::AGO => Self::Angola,
CountryAlpha3::AIA => Self::Anguilla,
CountryAlpha3::ATA => Self::Antarctica,
CountryAlpha3::ATG => Self::AntiguaAndBarbuda,
CountryAlpha3::ARG => Self::Argentina,
CountryAlpha3::ARM => Self::Armenia,
CountryAlpha3::ABW => Self::Aruba,
CountryAlpha3::AUS => Self::Australia,
CountryAlpha3::AUT => Self::Austria,
CountryAlpha3::AZE => Self::Azerbaijan,
CountryAlpha3::BHS => Self::Bahamas,
CountryAlpha3::BHR => Self::Bahrain,
CountryAlpha3::BGD => Self::Bangladesh,
CountryAlpha3::BRB => Self::Barbados,
CountryAlpha3::BLR => Self::Belarus,
CountryAlpha3::BEL => Self::Belgium,
CountryAlpha3::BLZ => Self::Belize,
CountryAlpha3::BEN => Self::Benin,
CountryAlpha3::BMU => Self::Bermuda,
CountryAlpha3::BTN => Self::Bhutan,
CountryAlpha3::BOL => Self::BoliviaPlurinationalState,
CountryAlpha3::BES => Self::BonaireSintEustatiusAndSaba,
CountryAlpha3::BIH => Self::BosniaAndHerzegovina,
CountryAlpha3::BWA => Self::Botswana,
CountryAlpha3::BVT => Self::BouvetIsland,
CountryAlpha3::BRA => Self::Brazil,
CountryAlpha3::IOT => Self::BritishIndianOceanTerritory,
CountryAlpha3::BRN => Self::BruneiDarussalam,
CountryAlpha3::BGR => Self::Bulgaria,
CountryAlpha3::BFA => Self::BurkinaFaso,
CountryAlpha3::BDI => Self::Burundi,
CountryAlpha3::CPV => Self::CaboVerde,
CountryAlpha3::KHM => Self::Cambodia,
CountryAlpha3::CMR => Self::Cameroon,
CountryAlpha3::CAN => Self::Canada,
CountryAlpha3::CYM => Self::CaymanIslands,
CountryAlpha3::CAF => Self::CentralAfricanRepublic,
CountryAlpha3::TCD => Self::Chad,
CountryAlpha3::CHL => Self::Chile,
CountryAlpha3::CHN => Self::China,
CountryAlpha3::CXR => Self::ChristmasIsland,
CountryAlpha3::CCK => Self::CocosKeelingIslands,
CountryAlpha3::COL => Self::Colombia,
CountryAlpha3::COM => Self::Comoros,
CountryAlpha3::COG => Self::Congo,
CountryAlpha3::COD => Self::CongoDemocraticRepublic,
CountryAlpha3::COK => Self::CookIslands,
CountryAlpha3::CRI => Self::CostaRica,
CountryAlpha3::CIV => Self::CotedIvoire,
CountryAlpha3::HRV => Self::Croatia,
CountryAlpha3::CUB => Self::Cuba,
CountryAlpha3::CUW => Self::Curacao,
CountryAlpha3::CYP => Self::Cyprus,
CountryAlpha3::CZE => Self::Czechia,
CountryAlpha3::DNK => Self::Denmark,
CountryAlpha3::DJI => Self::Djibouti,
CountryAlpha3::DMA => Self::Dominica,
CountryAlpha3::DOM => Self::DominicanRepublic,
CountryAlpha3::ECU => Self::Ecuador,
CountryAlpha3::EGY => Self::Egypt,
CountryAlpha3::SLV => Self::ElSalvador,
CountryAlpha3::GNQ => Self::EquatorialGuinea,
CountryAlpha3::ERI => Self::Eritrea,
CountryAlpha3::EST => Self::Estonia,
CountryAlpha3::ETH => Self::Ethiopia,
CountryAlpha3::FLK => Self::FalklandIslandsMalvinas,
CountryAlpha3::FRO => Self::FaroeIslands,
CountryAlpha3::FJI => Self::Fiji,
CountryAlpha3::FIN => Self::Finland,
CountryAlpha3::FRA => Self::France,
CountryAlpha3::GUF => Self::FrenchGuiana,
CountryAlpha3::PYF => Self::FrenchPolynesia,
CountryAlpha3::ATF => Self::FrenchSouthernTerritories,
CountryAlpha3::GAB => Self::Gabon,
CountryAlpha3::GMB => Self::Gambia,
CountryAlpha3::GEO => Self::Georgia,
CountryAlpha3::DEU => Self::Germany,
CountryAlpha3::GHA => Self::Ghana,
CountryAlpha3::GIB => Self::Gibraltar,
CountryAlpha3::GRC => Self::Greece,
CountryAlpha3::GRL => Self::Greenland,
CountryAlpha3::GRD => Self::Grenada,
CountryAlpha3::GLP => Self::Guadeloupe,
CountryAlpha3::GUM => Self::Guam,
CountryAlpha3::GTM => Self::Guatemala,
CountryAlpha3::GGY => Self::Guernsey,
CountryAlpha3::GIN => Self::Guinea,
CountryAlpha3::GNB => Self::GuineaBissau,
CountryAlpha3::GUY => Self::Guyana,
CountryAlpha3::HTI => Self::Haiti,
CountryAlpha3::HMD => Self::HeardIslandAndMcDonaldIslands,
CountryAlpha3::VAT => Self::HolySee,
CountryAlpha3::HND => Self::Honduras,
CountryAlpha3::HKG => Self::HongKong,
CountryAlpha3::HUN => Self::Hungary,
CountryAlpha3::ISL => Self::Iceland,
CountryAlpha3::IND => Self::India,
CountryAlpha3::IDN => Self::Indonesia,
CountryAlpha3::IRN => Self::IranIslamicRepublic,
CountryAlpha3::IRQ => Self::Iraq,
CountryAlpha3::IRL => Self::Ireland,
CountryAlpha3::IMN => Self::IsleOfMan,
CountryAlpha3::ISR => Self::Israel,
CountryAlpha3::ITA => Self::Italy,
CountryAlpha3::JAM => Self::Jamaica,
CountryAlpha3::JPN => Self::Japan,
CountryAlpha3::JEY => Self::Jersey,
CountryAlpha3::JOR => Self::Jordan,
CountryAlpha3::KAZ => Self::Kazakhstan,
CountryAlpha3::KEN => Self::Kenya,
CountryAlpha3::KIR => Self::Kiribati,
CountryAlpha3::PRK => Self::KoreaDemocraticPeoplesRepublic,
CountryAlpha3::KOR => Self::KoreaRepublic,
CountryAlpha3::KWT => Self::Kuwait,
CountryAlpha3::KGZ => Self::Kyrgyzstan,
CountryAlpha3::LAO => Self::LaoPeoplesDemocraticRepublic,
CountryAlpha3::LVA => Self::Latvia,
CountryAlpha3::LBN => Self::Lebanon,
CountryAlpha3::LSO => Self::Lesotho,
CountryAlpha3::LBR => Self::Liberia,
CountryAlpha3::LBY => Self::Libya,
CountryAlpha3::LIE => Self::Liechtenstein,
CountryAlpha3::LTU => Self::Lithuania,
CountryAlpha3::LUX => Self::Luxembourg,
CountryAlpha3::MAC => Self::Macao,
CountryAlpha3::MKD => Self::MacedoniaTheFormerYugoslavRepublic,
CountryAlpha3::MDG => Self::Madagascar,
CountryAlpha3::MWI => Self::Malawi,
CountryAlpha3::MYS => Self::Malaysia,
CountryAlpha3::MDV => Self::Maldives,
CountryAlpha3::MLI => Self::Mali,
CountryAlpha3::MLT => Self::Malta,
CountryAlpha3::MHL => Self::MarshallIslands,
CountryAlpha3::MTQ => Self::Martinique,
CountryAlpha3::MRT => Self::Mauritania,
CountryAlpha3::MUS => Self::Mauritius,
CountryAlpha3::MYT => Self::Mayotte,
CountryAlpha3::MEX => Self::Mexico,
CountryAlpha3::FSM => Self::MicronesiaFederatedStates,
CountryAlpha3::MDA => Self::MoldovaRepublic,
CountryAlpha3::MCO => Self::Monaco,
CountryAlpha3::MNG => Self::Mongolia,
CountryAlpha3::MNE => Self::Montenegro,
CountryAlpha3::MSR => Self::Montserrat,
CountryAlpha3::MAR => Self::Morocco,
CountryAlpha3::MOZ => Self::Mozambique,
CountryAlpha3::MMR => Self::Myanmar,
CountryAlpha3::NAM => Self::Namibia,
CountryAlpha3::NRU => Self::Nauru,
CountryAlpha3::NPL => Self::Nepal,
CountryAlpha3::NLD => Self::Netherlands,
CountryAlpha3::NCL => Self::NewCaledonia,
CountryAlpha3::NZL => Self::NewZealand,
CountryAlpha3::NIC => Self::Nicaragua,
CountryAlpha3::NER => Self::Niger,
CountryAlpha3::NGA => Self::Nigeria,
CountryAlpha3::NIU => Self::Niue,
CountryAlpha3::NFK => Self::NorfolkIsland,
CountryAlpha3::MNP => Self::NorthernMarianaIslands,
CountryAlpha3::NOR => Self::Norway,
CountryAlpha3::OMN => Self::Oman,
CountryAlpha3::PAK => Self::Pakistan,
CountryAlpha3::PLW => Self::Palau,
CountryAlpha3::PSE => Self::PalestineState,
CountryAlpha3::PAN => Self::Panama,
CountryAlpha3::PNG => Self::PapuaNewGuinea,
CountryAlpha3::PRY => Self::Paraguay,
CountryAlpha3::PER => Self::Peru,
CountryAlpha3::PHL => Self::Philippines,
CountryAlpha3::PCN => Self::Pitcairn,
CountryAlpha3::POL => Self::Poland,
CountryAlpha3::PRT => Self::Portugal,
CountryAlpha3::PRI => Self::PuertoRico,
CountryAlpha3::QAT => Self::Qatar,
CountryAlpha3::REU => Self::Reunion,
CountryAlpha3::ROU => Self::Romania,
CountryAlpha3::RUS => Self::RussianFederation,
CountryAlpha3::RWA => Self::Rwanda,
CountryAlpha3::BLM => Self::SaintBarthelemy,
CountryAlpha3::SHN => Self::SaintHelenaAscensionAndTristandaCunha,
CountryAlpha3::KNA => Self::SaintKittsAndNevis,
CountryAlpha3::LCA => Self::SaintLucia,
CountryAlpha3::MAF => Self::SaintMartinFrenchpart,
CountryAlpha3::SPM => Self::SaintPierreAndMiquelon,
CountryAlpha3::VCT => Self::SaintVincentAndTheGrenadines,
CountryAlpha3::WSM => Self::Samoa,
CountryAlpha3::SMR => Self::SanMarino,
CountryAlpha3::STP => Self::SaoTomeAndPrincipe,
CountryAlpha3::SAU => Self::SaudiArabia,
CountryAlpha3::SEN => Self::Senegal,
CountryAlpha3::SRB => Self::Serbia,
CountryAlpha3::SYC => Self::Seychelles,
CountryAlpha3::SLE => Self::SierraLeone,
CountryAlpha3::SGP => Self::Singapore,
CountryAlpha3::SXM => Self::SintMaartenDutchpart,
CountryAlpha3::SVK => Self::Slovakia,
CountryAlpha3::SVN => Self::Slovenia,
CountryAlpha3::SLB => Self::SolomonIslands,
CountryAlpha3::SOM => Self::Somalia,
CountryAlpha3::ZAF => Self::SouthAfrica,
CountryAlpha3::SGS => Self::SouthGeorgiaAndTheSouthSandwichIslands,
CountryAlpha3::SSD => Self::SouthSudan,
CountryAlpha3::ESP => Self::Spain,
CountryAlpha3::LKA => Self::SriLanka,
CountryAlpha3::SDN => Self::Sudan,
CountryAlpha3::SUR => Self::Suriname,
CountryAlpha3::SJM => Self::SvalbardAndJanMayen,
CountryAlpha3::SWZ => Self::Swaziland,
CountryAlpha3::SWE => Self::Sweden,
CountryAlpha3::CHE => Self::Switzerland,
CountryAlpha3::SYR => Self::SyrianArabRepublic,
CountryAlpha3::TWN => Self::TaiwanProvinceOfChina,
CountryAlpha3::TJK => Self::Tajikistan,
CountryAlpha3::TZA => Self::TanzaniaUnitedRepublic,
CountryAlpha3::THA => Self::Thailand,
CountryAlpha3::TLS => Self::TimorLeste,
CountryAlpha3::TGO => Self::Togo,
CountryAlpha3::TKL => Self::Tokelau,
CountryAlpha3::TON => Self::Tonga,
CountryAlpha3::TTO => Self::TrinidadAndTobago,
CountryAlpha3::TUN => Self::Tunisia,
CountryAlpha3::TUR => Self::Turkey,
CountryAlpha3::TKM => Self::Turkmenistan,
CountryAlpha3::TCA => Self::TurksAndCaicosIslands,
CountryAlpha3::TUV => Self::Tuvalu,
CountryAlpha3::UGA => Self::Uganda,
CountryAlpha3::UKR => Self::Ukraine,
CountryAlpha3::ARE => Self::UnitedArabEmirates,
CountryAlpha3::GBR => Self::UnitedKingdomOfGreatBritainAndNorthernIreland,
CountryAlpha3::USA => Self::UnitedStatesOfAmerica,
CountryAlpha3::UMI => Self::UnitedStatesMinorOutlyingIslands,
CountryAlpha3::URY => Self::Uruguay,
CountryAlpha3::UZB => Self::Uzbekistan,
CountryAlpha3::VUT => Self::Vanuatu,
CountryAlpha3::VEN => Self::VenezuelaBolivarianRepublic,
CountryAlpha3::VNM => Self::Vietnam,
CountryAlpha3::VGB => Self::VirginIslandsBritish,
CountryAlpha3::VIR => Self::VirginIslandsUS,
CountryAlpha3::WLF => Self::WallisAndFutuna,
CountryAlpha3::ESH => Self::WesternSahara,
CountryAlpha3::YEM => Self::Yemen,
CountryAlpha3::ZMB => Self::Zambia,
CountryAlpha3::ZWE => Self::Zimbabwe,
}
}
pub const fn to_alpha3(self) -> CountryAlpha3 {
match self {
Self::Afghanistan => CountryAlpha3::AFG,
Self::AlandIslands => CountryAlpha3::ALA,
Self::Albania => CountryAlpha3::ALB,
Self::Algeria => CountryAlpha3::DZA,
Self::AmericanSamoa => CountryAlpha3::ASM,
Self::Andorra => CountryAlpha3::AND,
Self::Angola => CountryAlpha3::AGO,
Self::Anguilla => CountryAlpha3::AIA,
Self::Antarctica => CountryAlpha3::ATA,
Self::AntiguaAndBarbuda => CountryAlpha3::ATG,
Self::Argentina => CountryAlpha3::ARG,
Self::Armenia => CountryAlpha3::ARM,
Self::Aruba => CountryAlpha3::ABW,
Self::Australia => CountryAlpha3::AUS,
Self::Austria => CountryAlpha3::AUT,
Self::Azerbaijan => CountryAlpha3::AZE,
Self::Bahamas => CountryAlpha3::BHS,
Self::Bahrain => CountryAlpha3::BHR,
Self::Bangladesh => CountryAlpha3::BGD,
Self::Barbados => CountryAlpha3::BRB,
Self::Belarus => CountryAlpha3::BLR,
Self::Belgium => CountryAlpha3::BEL,
Self::Belize => CountryAlpha3::BLZ,
Self::Benin => CountryAlpha3::BEN,
Self::Bermuda => CountryAlpha3::BMU,
Self::Bhutan => CountryAlpha3::BTN,
Self::BoliviaPlurinationalState => CountryAlpha3::BOL,
Self::BonaireSintEustatiusAndSaba => CountryAlpha3::BES,
Self::BosniaAndHerzegovina => CountryAlpha3::BIH,
Self::Botswana => CountryAlpha3::BWA,
Self::BouvetIsland => CountryAlpha3::BVT,
Self::Brazil => CountryAlpha3::BRA,
Self::BritishIndianOceanTerritory => CountryAlpha3::IOT,
Self::BruneiDarussalam => CountryAlpha3::BRN,
Self::Bulgaria => CountryAlpha3::BGR,
Self::BurkinaFaso => CountryAlpha3::BFA,
Self::Burundi => CountryAlpha3::BDI,
Self::CaboVerde => CountryAlpha3::CPV,
Self::Cambodia => CountryAlpha3::KHM,
Self::Cameroon => CountryAlpha3::CMR,
Self::Canada => CountryAlpha3::CAN,
Self::CaymanIslands => CountryAlpha3::CYM,
Self::CentralAfricanRepublic => CountryAlpha3::CAF,
Self::Chad => CountryAlpha3::TCD,
Self::Chile => CountryAlpha3::CHL,
Self::China => CountryAlpha3::CHN,
Self::ChristmasIsland => CountryAlpha3::CXR,
Self::CocosKeelingIslands => CountryAlpha3::CCK,
Self::Colombia => CountryAlpha3::COL,
Self::Comoros => CountryAlpha3::COM,
Self::Congo => CountryAlpha3::COG,
Self::CongoDemocraticRepublic => CountryAlpha3::COD,
Self::CookIslands => CountryAlpha3::COK,
Self::CostaRica => CountryAlpha3::CRI,
Self::CotedIvoire => CountryAlpha3::CIV,
Self::Croatia => CountryAlpha3::HRV,
Self::Cuba => CountryAlpha3::CUB,
Self::Curacao => CountryAlpha3::CUW,
Self::Cyprus => CountryAlpha3::CYP,
Self::Czechia => CountryAlpha3::CZE,
Self::Denmark => CountryAlpha3::DNK,
Self::Djibouti => CountryAlpha3::DJI,
Self::Dominica => CountryAlpha3::DMA,
Self::DominicanRepublic => CountryAlpha3::DOM,
Self::Ecuador => CountryAlpha3::ECU,
Self::Egypt => CountryAlpha3::EGY,
Self::ElSalvador => CountryAlpha3::SLV,
Self::EquatorialGuinea => CountryAlpha3::GNQ,
Self::Eritrea => CountryAlpha3::ERI,
Self::Estonia => CountryAlpha3::EST,
Self::Ethiopia => CountryAlpha3::ETH,
Self::FalklandIslandsMalvinas => CountryAlpha3::FLK,
Self::FaroeIslands => CountryAlpha3::FRO,
Self::Fiji => CountryAlpha3::FJI,
Self::Finland => CountryAlpha3::FIN,
Self::France => CountryAlpha3::FRA,
Self::FrenchGuiana => CountryAlpha3::GUF,
Self::FrenchPolynesia => CountryAlpha3::PYF,
Self::FrenchSouthernTerritories => CountryAlpha3::ATF,
Self::Gabon => CountryAlpha3::GAB,
Self::Gambia => CountryAlpha3::GMB,
Self::Georgia => CountryAlpha3::GEO,
Self::Germany => CountryAlpha3::DEU,
Self::Ghana => CountryAlpha3::GHA,
Self::Gibraltar => CountryAlpha3::GIB,
Self::Greece => CountryAlpha3::GRC,
Self::Greenland => CountryAlpha3::GRL,
Self::Grenada => CountryAlpha3::GRD,
Self::Guadeloupe => CountryAlpha3::GLP,
Self::Guam => CountryAlpha3::GUM,
Self::Guatemala => CountryAlpha3::GTM,
Self::Guernsey => CountryAlpha3::GGY,
Self::Guinea => CountryAlpha3::GIN,
Self::GuineaBissau => CountryAlpha3::GNB,
Self::Guyana => CountryAlpha3::GUY,
Self::Haiti => CountryAlpha3::HTI,
Self::HeardIslandAndMcDonaldIslands => CountryAlpha3::HMD,
Self::HolySee => CountryAlpha3::VAT,
Self::Honduras => CountryAlpha3::HND,
Self::HongKong => CountryAlpha3::HKG,
Self::Hungary => CountryAlpha3::HUN,
Self::Iceland => CountryAlpha3::ISL,
Self::India => CountryAlpha3::IND,
Self::Indonesia => CountryAlpha3::IDN,
Self::IranIslamicRepublic => CountryAlpha3::IRN,
Self::Iraq => CountryAlpha3::IRQ,
Self::Ireland => CountryAlpha3::IRL,
Self::IsleOfMan => CountryAlpha3::IMN,
Self::Israel => CountryAlpha3::ISR,
Self::Italy => CountryAlpha3::ITA,
Self::Jamaica => CountryAlpha3::JAM,
Self::Japan => CountryAlpha3::JPN,
Self::Jersey => CountryAlpha3::JEY,
Self::Jordan => CountryAlpha3::JOR,
Self::Kazakhstan => CountryAlpha3::KAZ,
Self::Kenya => CountryAlpha3::KEN,
Self::Kiribati => CountryAlpha3::KIR,
Self::KoreaDemocraticPeoplesRepublic => CountryAlpha3::PRK,
Self::KoreaRepublic => CountryAlpha3::KOR,
Self::Kuwait => CountryAlpha3::KWT,
Self::Kyrgyzstan => CountryAlpha3::KGZ,
Self::LaoPeoplesDemocraticRepublic => CountryAlpha3::LAO,
Self::Latvia => CountryAlpha3::LVA,
Self::Lebanon => CountryAlpha3::LBN,
Self::Lesotho => CountryAlpha3::LSO,
Self::Liberia => CountryAlpha3::LBR,
Self::Libya => CountryAlpha3::LBY,
Self::Liechtenstein => CountryAlpha3::LIE,
Self::Lithuania => CountryAlpha3::LTU,
Self::Luxembourg => CountryAlpha3::LUX,
Self::Macao => CountryAlpha3::MAC,
Self::MacedoniaTheFormerYugoslavRepublic => CountryAlpha3::MKD,
Self::Madagascar => CountryAlpha3::MDG,
Self::Malawi => CountryAlpha3::MWI,
Self::Malaysia => CountryAlpha3::MYS,
Self::Maldives => CountryAlpha3::MDV,
Self::Mali => CountryAlpha3::MLI,
Self::Malta => CountryAlpha3::MLT,
Self::MarshallIslands => CountryAlpha3::MHL,
Self::Martinique => CountryAlpha3::MTQ,
Self::Mauritania => CountryAlpha3::MRT,
Self::Mauritius => CountryAlpha3::MUS,
Self::Mayotte => CountryAlpha3::MYT,
Self::Mexico => CountryAlpha3::MEX,
Self::MicronesiaFederatedStates => CountryAlpha3::FSM,
Self::MoldovaRepublic => CountryAlpha3::MDA,
Self::Monaco => CountryAlpha3::MCO,
Self::Mongolia => CountryAlpha3::MNG,
Self::Montenegro => CountryAlpha3::MNE,
Self::Montserrat => CountryAlpha3::MSR,
Self::Morocco => CountryAlpha3::MAR,
Self::Mozambique => CountryAlpha3::MOZ,
Self::Myanmar => CountryAlpha3::MMR,
Self::Namibia => CountryAlpha3::NAM,
Self::Nauru => CountryAlpha3::NRU,
Self::Nepal => CountryAlpha3::NPL,
Self::Netherlands => CountryAlpha3::NLD,
Self::NewCaledonia => CountryAlpha3::NCL,
Self::NewZealand => CountryAlpha3::NZL,
Self::Nicaragua => CountryAlpha3::NIC,
Self::Niger => CountryAlpha3::NER,
Self::Nigeria => CountryAlpha3::NGA,
Self::Niue => CountryAlpha3::NIU,
Self::NorfolkIsland => CountryAlpha3::NFK,
Self::NorthernMarianaIslands => CountryAlpha3::MNP,
Self::Norway => CountryAlpha3::NOR,
Self::Oman => CountryAlpha3::OMN,
Self::Pakistan => CountryAlpha3::PAK,
Self::Palau => CountryAlpha3::PLW,
Self::PalestineState => CountryAlpha3::PSE,
Self::Panama => CountryAlpha3::PAN,
Self::PapuaNewGuinea => CountryAlpha3::PNG,
Self::Paraguay => CountryAlpha3::PRY,
Self::Peru => CountryAlpha3::PER,
Self::Philippines => CountryAlpha3::PHL,
Self::Pitcairn => CountryAlpha3::PCN,
Self::Poland => CountryAlpha3::POL,
Self::Portugal => CountryAlpha3::PRT,
Self::PuertoRico => CountryAlpha3::PRI,
Self::Qatar => CountryAlpha3::QAT,
Self::Reunion => CountryAlpha3::REU,
Self::Romania => CountryAlpha3::ROU,
Self::RussianFederation => CountryAlpha3::RUS,
Self::Rwanda => CountryAlpha3::RWA,
Self::SaintBarthelemy => CountryAlpha3::BLM,
Self::SaintHelenaAscensionAndTristandaCunha => CountryAlpha3::SHN,
Self::SaintKittsAndNevis => CountryAlpha3::KNA,
Self::SaintLucia => CountryAlpha3::LCA,
Self::SaintMartinFrenchpart => CountryAlpha3::MAF,
Self::SaintPierreAndMiquelon => CountryAlpha3::SPM,
Self::SaintVincentAndTheGrenadines => CountryAlpha3::VCT,
Self::Samoa => CountryAlpha3::WSM,
Self::SanMarino => CountryAlpha3::SMR,
Self::SaoTomeAndPrincipe => CountryAlpha3::STP,
Self::SaudiArabia => CountryAlpha3::SAU,
Self::Senegal => CountryAlpha3::SEN,
Self::Serbia => CountryAlpha3::SRB,
Self::Seychelles => CountryAlpha3::SYC,
Self::SierraLeone => CountryAlpha3::SLE,
Self::Singapore => CountryAlpha3::SGP,
Self::SintMaartenDutchpart => CountryAlpha3::SXM,
|
crates/common_enums/src/transformers.rs#chunk1
|
common_enums
|
chunk
| 8,189
| null | null | null | null | null | null | null | null | null | null | null | null | null |
pub async fn complete_authorize_preprocessing_steps<F: Clone>(
state: &SessionState,
router_data: &types::RouterData<F, types::CompleteAuthorizeData, types::PaymentsResponseData>,
confirm: bool,
connector: &api::ConnectorData,
) -> RouterResult<types::RouterData<F, types::CompleteAuthorizeData, types::PaymentsResponseData>> {
if confirm {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::PreProcessing,
types::PaymentsPreProcessingData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
let preprocessing_request_data =
types::PaymentsPreProcessingData::try_from(router_data.request.to_owned())?;
let preprocessing_response_data: Result<types::PaymentsResponseData, types::ErrorResponse> =
Err(types::ErrorResponse::default());
let preprocessing_router_data =
helpers::router_data_type_conversion::<_, api::PreProcessing, _, _, _, _>(
router_data.clone(),
preprocessing_request_data,
preprocessing_response_data,
);
let resp = services::execute_connector_processing_step(
state,
connector_integration,
&preprocessing_router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.to_payment_failed_response()?;
metrics::PREPROCESSING_STEPS_COUNT.add(
1,
router_env::metric_attributes!(
("connector", connector.connector_name.to_string()),
("payment_method", router_data.payment_method.to_string()),
),
);
let mut router_data_request = router_data.request.to_owned();
if let Ok(types::PaymentsResponseData::TransactionResponse {
connector_metadata, ..
}) = &resp.response
{
connector_metadata.clone_into(&mut router_data_request.connector_meta);
};
let authorize_router_data = helpers::router_data_type_conversion::<_, F, _, _, _, _>(
resp.clone(),
router_data_request,
resp.response,
);
Ok(authorize_router_data)
} else {
Ok(router_data.clone())
}
}
|
crates/router/src/core/payments/flows/complete_authorize_flow.rs
|
router
|
function_signature
| 434
|
rust
| null | null | null | null |
complete_authorize_preprocessing_steps
| null | null | null | null | null | null | null |
pub async fn build_cloned_connector_create_request(
source_mca: DomainMerchantConnectorAccount,
destination_profile_id: Option<id_type::ProfileId>,
destination_connector_label: Option<String>,
) -> UserResult<admin_api::MerchantConnectorCreate> {
let source_mca_name = source_mca
.connector_name
.parse::<connector_enums::Connector>()
.change_context(UserErrors::InternalServerError)
.attach_printable("Invalid connector name received")?;
let payment_methods_enabled = source_mca
.payment_methods_enabled
.clone()
.map(|data| {
let val = data.into_iter().map(|secret| secret.expose()).collect();
serde_json::Value::Array(val)
.parse_value("PaymentMethods")
.change_context(UserErrors::InternalServerError)
.attach_printable("Unable to deserialize PaymentMethods")
})
.transpose()?;
let frm_configs = source_mca
.frm_configs
.as_ref()
.map(|configs_vec| {
configs_vec
.iter()
.map(|config_secret| {
config_secret
.peek()
.clone()
.parse_value("FrmConfigs")
.change_context(UserErrors::InternalServerError)
.attach_printable("Unable to deserialize FrmConfigs")
})
.collect::<Result<Vec<_>, _>>()
})
.transpose()?;
let connector_webhook_details = source_mca
.connector_webhook_details
.map(|webhook_details| {
serde_json::Value::parse_value(
webhook_details.expose(),
"MerchantConnectorWebhookDetails",
)
.change_context(UserErrors::InternalServerError)
.attach_printable("Unable to deserialize connector_webhook_details")
})
.transpose()?;
let connector_wallets_details = source_mca
.connector_wallets_details
.map(|secret_value| {
secret_value
.into_inner()
.expose()
.parse_value::<admin_api::ConnectorWalletDetails>("ConnectorWalletDetails")
.change_context(UserErrors::InternalServerError)
.attach_printable("Unable to parse ConnectorWalletDetails from Value")
})
.transpose()?;
let additional_merchant_data = source_mca
.additional_merchant_data
.map(|secret_value| {
secret_value
.into_inner()
.expose()
.parse_value::<AdditionalMerchantData>("AdditionalMerchantData")
.change_context(UserErrors::InternalServerError)
.attach_printable("Unable to parse AdditionalMerchantData from Value")
})
.transpose()?
.map(admin_api::AdditionalMerchantData::foreign_from);
Ok(admin_api::MerchantConnectorCreate {
connector_type: source_mca.connector_type,
connector_name: source_mca_name,
connector_label: destination_connector_label.or(source_mca.connector_label.clone()),
merchant_connector_id: None,
connector_account_details: Some(source_mca.connector_account_details.clone().into_inner()),
test_mode: source_mca.test_mode,
disabled: source_mca.disabled,
payment_methods_enabled,
metadata: source_mca.metadata,
business_country: source_mca.business_country,
business_label: source_mca.business_label.clone(),
business_sub_label: source_mca.business_sub_label.clone(),
frm_configs,
connector_webhook_details,
profile_id: destination_profile_id,
pm_auth_config: source_mca.pm_auth_config.clone(),
connector_wallets_details,
status: Some(source_mca.status),
additional_merchant_data,
})
}
|
crates/router/src/utils/user.rs
|
router
|
function_signature
| 749
|
rust
| null | null | null | null |
build_cloned_connector_create_request
| null | null | null | null | null | null | null |
pub async fn create_domain_model(
payment_intent: &super::PaymentIntent,
cell_id: id_type::CellId,
storage_scheme: storage_enums::MerchantStorageScheme,
request: &api_models::payments::PaymentsConfirmIntentRequest,
encrypted_data: DecryptedPaymentAttempt,
) -> CustomResult<Self, errors::api_error_response::ApiErrorResponse> {
let id = id_type::GlobalAttemptId::generate(&cell_id);
let intent_amount_details = payment_intent.amount_details.clone();
let attempt_amount_details = intent_amount_details.create_attempt_amount_details(request);
let now = common_utils::date_time::now();
let payment_method_billing_address = encrypted_data
.payment_method_billing_address
.as_ref()
.map(|data| {
data.clone()
.deserialize_inner_value(|value| value.parse_value("Address"))
})
.transpose()
.change_context(errors::api_error_response::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to decode billing address")?;
let connector_token = Some(diesel_models::ConnectorTokenDetails {
connector_mandate_id: None,
connector_token_request_reference_id: Some(common_utils::generate_id_with_len(
consts::CONNECTOR_MANDATE_REQUEST_REFERENCE_ID_LENGTH,
)),
});
let authentication_type = payment_intent.authentication_type.unwrap_or_default();
Ok(Self {
payment_id: payment_intent.id.clone(),
merchant_id: payment_intent.merchant_id.clone(),
amount_details: attempt_amount_details,
status: common_enums::AttemptStatus::Started,
// This will be decided by the routing algorithm and updated in update trackers
// right before calling the connector
connector: None,
authentication_type,
created_at: now,
modified_at: now,
last_synced: None,
cancellation_reason: None,
browser_info: request.browser_info.clone(),
payment_token: request.payment_token.clone(),
connector_metadata: None,
payment_experience: None,
payment_method_data: None,
routing_result: None,
preprocessing_step_id: None,
multiple_capture_count: None,
connector_response_reference_id: None,
updated_by: storage_scheme.to_string(),
redirection_data: None,
encoded_data: None,
merchant_connector_id: None,
external_three_ds_authentication_attempted: None,
authentication_connector: None,
authentication_id: None,
fingerprint_id: None,
charges: None,
client_source: None,
client_version: None,
customer_acceptance: request.customer_acceptance.clone().map(Secret::new),
profile_id: payment_intent.profile_id.clone(),
organization_id: payment_intent.organization_id.clone(),
payment_method_type: request.payment_method_type,
payment_method_id: request.payment_method_id.clone(),
connector_payment_id: None,
payment_method_subtype: request.payment_method_subtype,
authentication_applied: None,
external_reference_id: None,
payment_method_billing_address,
error: None,
connector_token_details: connector_token,
id,
card_discovery: None,
feature_metadata: None,
processor_merchant_id: payment_intent.merchant_id.clone(),
created_by: None,
connector_request_reference_id: None,
network_transaction_id: None,
})
}
|
crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
|
hyperswitch_domain_models
|
function_signature
| 686
|
rust
| null | null | null | null |
create_domain_model
| null | null | null | null | null | null | null |
pub async fn get_org_auth_event_sankey(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<TimeRange>,
) -> impl Responder {
let flow = AnalyticsFlow::GetSankey;
let payload = json_payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: AuthenticationData, req, _| async move {
let org_id = auth.merchant_account.get_org_id();
let auth: AuthInfo = AuthInfo::OrgLevel {
org_id: org_id.clone(),
};
analytics::auth_events::get_sankey(&state.pool, &auth, req)
.await
.map(ApplicationResponse::Json)
},
auth::auth_type(
&auth::PlatformOrgAdminAuth {
is_admin_auth_allowed: false,
organization_id: None,
},
&auth::JWTAuth {
permission: Permission::OrganizationAnalyticsRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
|
crates/router/src/analytics.rs
|
router
|
function_signature
| 246
|
rust
| null | null | null | null |
get_org_auth_event_sankey
| null | null | null | null | null | null | null |
pub async fn get_merchant_dispute_filters(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<api_models::analytics::GetDisputeFilterRequest>,
) -> impl Responder {
let flow = AnalyticsFlow::GetDisputeFilters;
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: AuthenticationData, req, _| async move {
let org_id = auth.merchant_account.get_org_id();
let merchant_id = auth.merchant_account.get_id();
let auth: AuthInfo = AuthInfo::MerchantLevel {
org_id: org_id.clone(),
merchant_ids: vec![merchant_id.clone()],
};
analytics::disputes::get_filters(&state.pool, req, &auth)
.await
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
permission: Permission::MerchantAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
|
crates/router/src/analytics.rs
|
router
|
function_signature
| 234
|
rust
| null | null | null | null |
get_merchant_dispute_filters
| null | null | null | null | null | null | null |
pub struct PaymentMethodMetadata {
pub payment_method_tokenization: std::collections::HashMap<String, String>,
}
|
crates/router/src/core/payment_methods/transformers.rs
|
router
|
struct_definition
| 23
|
rust
|
PaymentMethodMetadata
| null | null | null | null | null | null | null | null | null | null | null |
pub async fn api_key_list() {}
|
crates/openapi/src/routes/api_keys.rs
|
openapi
|
function_signature
| 8
|
rust
| null | null | null | null |
api_key_list
| null | null | null | null | null | null | null |
impl api::ConnectorAccessToken for Paysafe {}
|
crates/hyperswitch_connectors/src/connectors/paysafe.rs
|
hyperswitch_connectors
|
impl_block
| 9
|
rust
| null |
Paysafe
|
api::ConnectorAccessToken for
|
impl api::ConnectorAccessToken for for Paysafe
| null | null | null | null | null | null | null | null |
pub struct PhonepePaymentsResponse {
status: PhonepePaymentStatus,
id: String,
}
|
crates/hyperswitch_connectors/src/connectors/phonepe/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 21
|
rust
|
PhonepePaymentsResponse
| null | null | null | null | null | null | null | null | null | null | null |
impl CardInfoBuilder<CardInfoResponse> {
pub fn build(self) -> cards_info_api_types::CardInfoMigrateResponseRecord {
match self.card_info {
Some(card_info) => cards_info_api_types::CardInfoMigrateResponseRecord {
card_iin: Some(card_info.card_iin),
card_issuer: card_info.card_issuer,
card_network: card_info.card_network.map(|cn| cn.to_string()),
card_type: card_info.card_type,
card_sub_type: card_info.card_subtype,
card_issuing_country: card_info.card_issuing_country,
},
None => cards_info_api_types::CardInfoMigrateResponseRecord {
card_iin: None,
card_issuer: None,
card_network: None,
card_type: None,
card_sub_type: None,
card_issuing_country: None,
},
}
}
}
|
crates/router/src/core/cards_info.rs
|
router
|
impl_block
| 191
|
rust
| null |
CardInfoBuilder
| null |
impl CardInfoBuilder
| null | null | null | null | null | null | null | null |
pub async fn save_payment_method<FData>(
_state: &SessionState,
_connector_name: String,
_save_payment_method_data: SavePaymentMethodData<FData>,
_customer_id: Option<id_type::CustomerId>,
_merchant_context: &domain::MerchantContext,
_payment_method_type: Option<storage_enums::PaymentMethodType>,
_billing_name: Option<Secret<String>>,
_payment_method_billing_address: Option<&api::Address>,
_business_profile: &domain::Profile,
_connector_mandate_request_reference_id: Option<String>,
) -> RouterResult<SavePaymentMethodDataResponse>
where
FData: mandate::MandateBehaviour + Clone,
{
todo!()
}
|
crates/router/src/core/payments/tokenization.rs
|
router
|
function_signature
| 155
|
rust
| null | null | null | null |
save_payment_method
| null | null | null | null | null | null | null |
File: crates/router/src/core/payments/flows/cancel_post_capture_flow.rs
use async_trait::async_trait;
use super::{ConstructFlowSpecificData, Feature};
use crate::{
core::{
errors::{ConnectorErrorExt, RouterResult},
payments::{self, access_token, helpers, transformers, PaymentData},
},
routes::{metrics, SessionState},
services,
types::{self, api, domain},
};
#[async_trait]
impl
ConstructFlowSpecificData<
api::PostCaptureVoid,
types::PaymentsCancelPostCaptureData,
types::PaymentsResponseData,
> for PaymentData<api::PostCaptureVoid>
{
#[cfg(feature = "v2")]
async fn construct_router_data<'a>(
&self,
_state: &SessionState,
_connector_id: &str,
_merchant_context: &domain::MerchantContext,
_customer: &Option<domain::Customer>,
_merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
_merchant_recipient_data: Option<types::MerchantRecipientData>,
_header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
) -> RouterResult<types::PaymentsCancelPostCaptureRouterData> {
todo!()
}
#[cfg(feature = "v1")]
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
merchant_context: &domain::MerchantContext,
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
) -> RouterResult<types::PaymentsCancelPostCaptureRouterData> {
Box::pin(transformers::construct_payment_router_data::<
api::PostCaptureVoid,
types::PaymentsCancelPostCaptureData,
>(
state,
self.clone(),
connector_id,
merchant_context,
customer,
merchant_connector_account,
merchant_recipient_data,
header_payload,
))
.await
}
}
#[async_trait]
impl Feature<api::PostCaptureVoid, types::PaymentsCancelPostCaptureData>
for types::RouterData<
api::PostCaptureVoid,
types::PaymentsCancelPostCaptureData,
types::PaymentsResponseData,
>
{
async fn decide_flows<'a>(
self,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
connector_request: Option<services::Request>,
_business_profile: &domain::Profile,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
_return_raw_connector_response: Option<bool>,
) -> RouterResult<Self> {
metrics::PAYMENT_CANCEL_COUNT.add(
1,
router_env::metric_attributes!(("connector", connector.connector_name.to_string())),
);
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::PostCaptureVoid,
types::PaymentsCancelPostCaptureData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
let resp = services::execute_connector_processing_step(
state,
connector_integration,
&self,
call_connector_action,
connector_request,
None,
)
.await
.to_payment_failed_response()?;
Ok(resp)
}
async fn add_access_token<'a>(
&self,
state: &SessionState,
connector: &api::ConnectorData,
merchant_context: &domain::MerchantContext,
creds_identifier: Option<&str>,
) -> RouterResult<types::AddAccessTokenResult> {
Box::pin(access_token::add_access_token(
state,
connector,
merchant_context,
self,
creds_identifier,
))
.await
}
async fn build_flow_specific_connector_request(
&mut self,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
) -> RouterResult<(Option<services::Request>, bool)> {
let request = match call_connector_action {
payments::CallConnectorAction::Trigger => {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::PostCaptureVoid,
types::PaymentsCancelPostCaptureData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
connector_integration
.build_request(self, &state.conf.connectors)
.to_payment_failed_response()?
}
_ => None,
};
Ok((request, true))
}
}
|
crates/router/src/core/payments/flows/cancel_post_capture_flow.rs
|
router
|
full_file
| 993
| null | null | null | null | null | null | null | null | null | null | null | null | null |
impl api::PaymentToken for Custombilling {}
|
crates/hyperswitch_connectors/src/connectors/custombilling.rs
|
hyperswitch_connectors
|
impl_block
| 9
|
rust
| null |
Custombilling
|
api::PaymentToken for
|
impl api::PaymentToken for for Custombilling
| null | null | null | null | null | null | null | null |
pub async fn find_optional_resource<D, R, M>(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
execute_query_fut: R,
) -> error_stack::Result<Option<D>, StorageError>
where
D: Debug + Sync + Conversion,
R: futures::Future<
Output = error_stack::Result<Option<M>, diesel_models::errors::DatabaseError>,
> + Send,
M: ReverseConversion<D>,
{
match execute_query_fut.await.map_err(|error| {
let new_err = diesel_error_to_data_error(*error.current_context());
error.change_context(new_err)
})? {
Some(resource) => Ok(Some(
resource
.convert(
state,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError)?,
)),
None => Ok(None),
}
}
|
crates/storage_impl/src/lib.rs
|
storage_impl
|
function_signature
| 210
|
rust
| null | null | null | null |
find_optional_resource
| null | null | null | null | null | null | null |
pub async fn authentication_create_core(
state: SessionState,
merchant_context: domain::MerchantContext,
req: AuthenticationCreateRequest,
) -> RouterResponse<AuthenticationResponse> {
let db = &*state.store;
let merchant_account = merchant_context.get_merchant_account();
let merchant_id = merchant_account.get_id();
let key_manager_state = (&state).into();
let profile_id = core_utils::get_profile_id_from_business_details(
&key_manager_state,
None,
None,
&merchant_context,
req.profile_id.as_ref(),
db,
true,
)
.await?;
let business_profile = db
.find_business_profile_by_profile_id(
&key_manager_state,
merchant_context.get_merchant_key_store(),
&profile_id,
)
.await
.to_not_found_response(ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
let organization_id = merchant_account.organization_id.clone();
let authentication_id = common_utils::id_type::AuthenticationId::generate_authentication_id(
consts::AUTHENTICATION_ID_PREFIX,
);
let force_3ds_challenge = Some(
req.force_3ds_challenge
.unwrap_or(business_profile.force_3ds_challenge),
);
// Priority logic: First check req.acquirer_details, then fallback to profile_acquirer_id lookup
let (acquirer_bin, acquirer_merchant_id, acquirer_country_code) =
if let Some(acquirer_details) = &req.acquirer_details {
// Priority 1: Use acquirer_details from request if present
(
acquirer_details.acquirer_bin.clone(),
acquirer_details.acquirer_merchant_id.clone(),
acquirer_details.merchant_country_code.clone(),
)
} else {
// Priority 2: Fallback to profile_acquirer_id lookup
let acquirer_details = req.profile_acquirer_id.clone().and_then(|acquirer_id| {
business_profile
.acquirer_config_map
.and_then(|acquirer_config_map| {
acquirer_config_map.0.get(&acquirer_id).cloned()
})
});
acquirer_details
.as_ref()
.map(|details| {
(
Some(details.acquirer_bin.clone()),
Some(details.acquirer_assigned_merchant_id.clone()),
business_profile
.merchant_country_code
.map(|code| code.get_country_code().to_owned()),
)
})
.unwrap_or((None, None, None))
};
let new_authentication = create_new_authentication(
&state,
merchant_id.clone(),
req.authentication_connector
.map(|connector| connector.to_string()),
profile_id.clone(),
None,
None,
&authentication_id,
None,
common_enums::AuthenticationStatus::Started,
None,
organization_id,
force_3ds_challenge,
req.psd2_sca_exemption_type,
acquirer_bin,
acquirer_merchant_id,
acquirer_country_code,
Some(req.amount),
Some(req.currency),
req.return_url,
req.profile_acquirer_id.clone(),
)
.await?;
let acquirer_details = Some(AcquirerDetails {
acquirer_bin: new_authentication.acquirer_bin.clone(),
acquirer_merchant_id: new_authentication.acquirer_merchant_id.clone(),
merchant_country_code: new_authentication.acquirer_country_code.clone(),
});
let amount = new_authentication
.amount
.ok_or(ApiErrorResponse::InternalServerError)
.attach_printable("amount failed to get amount from authentication table")?;
let currency = new_authentication
.currency
.ok_or(ApiErrorResponse::InternalServerError)
.attach_printable("currency failed to get currency from authentication table")?;
let response = AuthenticationResponse::foreign_try_from((
new_authentication.clone(),
amount,
currency,
profile_id,
acquirer_details,
new_authentication.profile_acquirer_id,
))?;
Ok(hyperswitch_domain_models::api::ApplicationResponse::Json(
response,
))
}
|
crates/router/src/core/unified_authentication_service.rs
|
router
|
function_signature
| 862
|
rust
| null | null | null | null |
authentication_create_core
| null | null | null | null | null | null | null |
impl api::RefundSync for Worldpayxml {}
|
crates/hyperswitch_connectors/src/connectors/worldpayxml.rs
|
hyperswitch_connectors
|
impl_block
| 11
|
rust
| null |
Worldpayxml
|
api::RefundSync for
|
impl api::RefundSync for for Worldpayxml
| null | null | null | null | null | null | null | null |
pub fn validate(&self) -> Result<(), ApplicationError> {
match self {
Self::Kafka { kafka } => kafka.validate(),
Self::Logs => Ok(()),
}
}
|
crates/router/src/events.rs
|
router
|
function_signature
| 41
|
rust
| null | null | null | null |
validate
| null | null | null | null | null | null | null |
impl api::PaymentAuthorize for Cashtocode {}
|
crates/hyperswitch_connectors/src/connectors/cashtocode.rs
|
hyperswitch_connectors
|
impl_block
| 10
|
rust
| null |
Cashtocode
|
api::PaymentAuthorize for
|
impl api::PaymentAuthorize for for Cashtocode
| null | null | null | null | null | null | null | null |
impl common_utils::events::ApiEventMetric for ConnectorAgnosticMitChoice {}
|
crates/api_models/src/admin.rs
|
api_models
|
impl_block
| 18
|
rust
| null |
ConnectorAgnosticMitChoice
|
common_utils::events::ApiEventMetric for
|
impl common_utils::events::ApiEventMetric for for ConnectorAgnosticMitChoice
| null | null | null | null | null | null | null | null |
pub struct AcquirerData {
/// The country of the acquirer.
#[schema(value_type = Country)]
pub country: Option<common_enums::Country>,
/// The fraud rate associated with the acquirer.
pub fraud_rate: Option<f64>,
}
|
crates/api_models/src/three_ds_decision_rule.rs
|
api_models
|
struct_definition
| 57
|
rust
|
AcquirerData
| null | null | null | null | null | null | null | null | null | null | null |
pub fn get_error_response(
operation_result: NexixpayPaymentStatus,
status_code: u16,
) -> ErrorResponse {
ErrorResponse {
status_code,
code: NO_ERROR_CODE.to_string(),
message: operation_result.to_string(),
reason: Some(operation_result.to_string()),
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}
}
|
crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs
|
hyperswitch_connectors
|
function_signature
| 106
|
rust
| null | null | null | null |
get_error_response
| null | null | null | null | null | null | null |
pub async fn switch_profile_for_user_in_org_and_merchant(
state: SessionState,
request: user_api::SwitchProfileRequest,
user_from_token: auth::UserFromToken,
) -> UserResponse<user_api::TokenResponse> {
if user_from_token.profile_id == request.profile_id {
return Err(UserErrors::InvalidRoleOperationWithMessage(
"User switching to same profile".to_string(),
)
.into());
}
let key_manager_state = &(&state).into();
let role_info = roles::RoleInfo::from_role_id_org_id_tenant_id(
&state,
&user_from_token.role_id,
&user_from_token.org_id,
user_from_token
.tenant_id
.as_ref()
.unwrap_or(&state.tenant.tenant_id),
)
.await
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to retrieve role information")?;
let (profile_id, role_id) = match role_info.get_entity_type() {
EntityType::Tenant | EntityType::Organization | EntityType::Merchant => {
let merchant_key_store = state
.store
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&user_from_token.merchant_id,
&state.store.get_master_key().to_vec().into(),
)
.await
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to retrieve merchant key store by merchant_id")?;
let profile_id = state
.store
.find_business_profile_by_merchant_id_profile_id(
key_manager_state,
&merchant_key_store,
&user_from_token.merchant_id,
&request.profile_id,
)
.await
.change_context(UserErrors::InvalidRoleOperationWithMessage(
"No such profile found for the merchant".to_string(),
))?
.get_id()
.to_owned();
(profile_id, user_from_token.role_id)
}
EntityType::Profile => {
let user_role = state
.global_store
.list_user_roles_by_user_id(ListUserRolesByUserIdPayload{
user_id:&user_from_token.user_id,
tenant_id: user_from_token
.tenant_id
.as_ref()
.unwrap_or(&state.tenant.tenant_id),
org_id: Some(&user_from_token.org_id),
merchant_id: Some(&user_from_token.merchant_id),
profile_id:Some(&request.profile_id),
entity_id: None,
version:None,
status: Some(UserStatus::Active),
limit: Some(1)
}
)
.await
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to list user roles for the given user_id, org_id, merchant_id and profile_id")?
.pop()
.ok_or(UserErrors::InvalidRoleOperationWithMessage(
"No user role associated with the profile".to_string(),
))?;
(request.profile_id, user_role.role_id)
}
};
let lineage_context = LineageContext {
user_id: user_from_token.user_id.clone(),
merchant_id: user_from_token.merchant_id.clone(),
role_id: role_id.clone(),
org_id: user_from_token.org_id.clone(),
profile_id: profile_id.clone(),
tenant_id: user_from_token
.tenant_id
.as_ref()
.unwrap_or(&state.tenant.tenant_id)
.clone(),
};
utils::user::spawn_async_lineage_context_update_to_db(
&state,
&user_from_token.user_id,
lineage_context,
);
let token = utils::user::generate_jwt_auth_token_with_attributes(
&state,
user_from_token.user_id,
user_from_token.merchant_id.clone(),
user_from_token.org_id.clone(),
role_id.clone(),
profile_id,
user_from_token.tenant_id.clone(),
)
.await?;
utils::user_role::set_role_info_in_cache_by_role_id_org_id(
&state,
&role_id,
&user_from_token.org_id,
user_from_token
.tenant_id
.as_ref()
.unwrap_or(&state.tenant.tenant_id),
)
.await;
let response = user_api::TokenResponse {
token: token.clone(),
token_type: common_enums::TokenPurpose::UserInfo,
};
auth::cookies::set_cookie_response(response, token)
}
|
crates/router/src/core/user.rs
|
router
|
function_signature
| 955
|
rust
| null | null | null | null |
switch_profile_for_user_in_org_and_merchant
| null | null | null | null | null | null | null |
impl api::RefundExecute for Cryptopay {}
|
crates/hyperswitch_connectors/src/connectors/cryptopay.rs
|
hyperswitch_connectors
|
impl_block
| 11
|
rust
| null |
Cryptopay
|
api::RefundExecute for
|
impl api::RefundExecute for for Cryptopay
| null | null | null | null | null | null | null | null |
OpenAPI Block Path: components.schemas.TokenizeCardRequest
{
"type": "object",
"required": [
"raw_card_number",
"card_expiry_month",
"card_expiry_year"
],
"properties": {
"raw_card_number": {
"type": "string",
"description": "Card Number",
"example": "4111111145551142"
},
"card_expiry_month": {
"type": "string",
"description": "Card Expiry Month",
"example": "10"
},
"card_expiry_year": {
"type": "string",
"description": "Card Expiry Year",
"example": "25"
},
"card_cvc": {
"type": "string",
"description": "The CVC number for the card",
"example": "242",
"nullable": true
},
"card_holder_name": {
"type": "string",
"description": "Card Holder Name",
"example": "John Doe",
"nullable": true
},
"nick_name": {
"type": "string",
"description": "Card Holder's Nick Name",
"example": "John Doe",
"nullable": true
},
"card_issuing_country": {
"type": "string",
"description": "Card Issuing Country",
"nullable": true
},
"card_network": {
"allOf": [
{
"$ref": "#/components/schemas/CardNetwork"
}
],
"nullable": true
},
"card_issuer": {
"type": "string",
"description": "Issuer Bank for Card",
"nullable": true
},
"card_type": {
"allOf": [
{
"$ref": "#/components/schemas/CardType"
}
],
"nullable": true
}
},
"additionalProperties": false
}
|
./hyperswitch/api-reference/v1/openapi_spec_v1.json
| null |
openapi_block
| 440
|
.json
| null | null | null | null | null |
openapi_spec
|
components
|
[
"schemas",
"TokenizeCardRequest"
] | null | null | null | null |
pub struct PlacetopayStatusResponse {
status: PlacetopayTransactionStatus,
}
|
crates/hyperswitch_connectors/src/connectors/placetopay/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 20
|
rust
|
PlacetopayStatusResponse
| null | null | null | null | null | null | null | null | null | null | null |
pub fn get_compatible_connector(&self) -> Option<api_models::enums::Connector> {
let metadata: Option<api_models::admin::MerchantAccountMetadata> =
self.metadata.as_ref().and_then(|meta| {
meta.clone()
.parse_value("MerchantAccountMetadata")
.map_err(|err| logger::error!("Failed to deserialize {:?}", err))
.ok()
});
metadata.and_then(|a| a.compatible_connector)
}
|
crates/hyperswitch_domain_models/src/merchant_account.rs
|
hyperswitch_domain_models
|
function_signature
| 98
|
rust
| null | null | null | null |
get_compatible_connector
| null | null | null | null | null | null | null |
pub fn check_if_pull_mechanism_for_external_3ds_enabled_from_connector_metadata(
metadata: Option<Value>,
) -> bool {
let external_three_ds_connector_metadata: Option<ExternalThreeDSConnectorMetadata> = metadata
.parse_value("ExternalThreeDSConnectorMetadata")
.map_err(|err| logger::warn!(parsing_error=?err,"Error while parsing ExternalThreeDSConnectorMetadata"))
.ok();
external_three_ds_connector_metadata
.and_then(|metadata| metadata.pull_mechanism_for_external_3ds_enabled)
.unwrap_or(true)
}
|
crates/router/src/utils.rs
|
router
|
function_signature
| 121
|
rust
| null | null | null | null |
check_if_pull_mechanism_for_external_3ds_enabled_from_connector_metadata
| null | null | null | null | null | null | null |
pub async fn get_token(&self, state: &SessionState) -> UserResult<Secret<String>> {
match self.next_flow {
UserFlow::SPTFlow(spt_flow) => spt_flow.generate_spt(state, self).await,
UserFlow::JWTFlow(jwt_flow) => {
#[cfg(feature = "email")]
{
self.user.get_verification_days_left(state)?;
}
let user_role = state
.global_store
.list_user_roles_by_user_id(ListUserRolesByUserIdPayload {
user_id: self.user.get_user_id(),
tenant_id: self.tenant_id.as_ref().unwrap_or(&state.tenant.tenant_id),
org_id: None,
merchant_id: None,
profile_id: None,
entity_id: None,
version: None,
status: Some(UserStatus::Active),
limit: Some(1),
})
.await
.change_context(UserErrors::InternalServerError)?
.pop()
.ok_or(UserErrors::InternalServerError)?;
utils::user_role::set_role_info_in_cache_by_user_role(state, &user_role).await;
jwt_flow.generate_jwt(state, self, &user_role).await
}
}
}
|
crates/router/src/types/domain/user/decision_manager.rs
|
router
|
function_signature
| 259
|
rust
| null | null | null | null |
get_token
| null | null | null | null | null | null | null |
pub fn check_permission_exists(&self, required_permission: Permission) -> bool {
required_permission.entity_type() <= self.entity_type
&& self.get_permission_groups().iter().any(|group| {
required_permission.scope() <= group.scope()
&& group.resources().contains(&required_permission.resource())
})
}
|
crates/router/src/services/authorization/roles.rs
|
router
|
function_signature
| 65
|
rust
| null | null | null | null |
check_permission_exists
| null | null | null | null | null | null | null |
pub fn mk_card_value1(
card_number: cards::CardNumber,
exp_year: String,
exp_month: String,
name_on_card: Option<String>,
nickname: Option<String>,
card_last_four: Option<String>,
card_token: Option<String>,
) -> CustomResult<String, errors::VaultError> {
let value1 = api::TokenizedCardValue1 {
card_number: card_number.peek().clone(),
exp_year,
exp_month,
name_on_card,
nickname,
card_last_four,
card_token,
};
let value1_req = value1
.encode_to_string_of_json()
.change_context(errors::VaultError::FetchCardFailed)?;
Ok(value1_req)
}
|
crates/router/src/core/payment_methods/transformers.rs
|
router
|
function_signature
| 156
|
rust
| null | null | null | null |
mk_card_value1
| null | null | null | null | null | null | null |
pub struct EbanxCancelResponse {
#[serde(rename = "type")]
status: EbanxCancelStatus,
message: String,
}
|
crates/hyperswitch_connectors/src/connectors/ebanx/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 31
|
rust
|
EbanxCancelResponse
| null | null | null | null | null | null | null | null | null | null | null |
pub fn server(config: routes::AppState) -> Scope {
web::scope("/payment_methods")
.app_data(web::Data::new(config))
.service(web::resource("/{id}/detach").route(web::post().to(mandates::revoke_mandate)))
}
|
crates/router/src/compatibility/stripe/app.rs
|
router
|
function_signature
| 60
|
rust
| null | null | null | null |
server
| null | null | null | null | null | null | null |
impl api::PaymentVoid for Facilitapay {}
|
crates/hyperswitch_connectors/src/connectors/facilitapay.rs
|
hyperswitch_connectors
|
impl_block
| 11
|
rust
| null |
Facilitapay
|
api::PaymentVoid for
|
impl api::PaymentVoid for for Facilitapay
| null | null | null | null | null | null | null | null |
pub fn generate_aes256_key() -> errors::CustomResult<[u8;
|
crates/router/src/services.rs
|
router
|
function_signature
| 18
|
rust
| null | null | null | null |
generate_aes256_key
| null | null | null | null | null | null | null |
pub struct MerchantCountryCode(String);
|
crates/common_types/src/payments.rs
|
common_types
|
struct_definition
| 7
|
rust
|
MerchantCountryCode
| null | null | null | null | null | null | null | null | null | null | null |
impl RequestExtendedAuthorizationBool {
/// returns the inner bool value
pub fn is_true(&self) -> bool {
self.0
}
}
|
crates/common_utils/src/types/primitive_wrappers.rs
|
common_utils
|
impl_block
| 34
|
rust
| null |
RequestExtendedAuthorizationBool
| null |
impl RequestExtendedAuthorizationBool
| null | null | null | null | null | null | null | null |
impl PartialEq for DisputeMetricsBucketIdentifier {
fn eq(&self, other: &Self) -> bool {
let mut left = DefaultHasher::new();
self.hash(&mut left);
let mut right = DefaultHasher::new();
other.hash(&mut right);
left.finish() == right.finish()
}
}
|
crates/api_models/src/analytics/disputes.rs
|
api_models
|
impl_block
| 70
|
rust
| null |
DisputeMetricsBucketIdentifier
|
PartialEq for
|
impl PartialEq for for DisputeMetricsBucketIdentifier
| null | null | null | null | null | null | null | null |
pub fn validate_schema(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let input = syn::parse_macro_input!(input as syn::DeriveInput);
macros::validate_schema_derive(input)
.unwrap_or_else(|error| error.into_compile_error())
.into()
}
|
crates/router_derive/src/lib.rs
|
router_derive
|
function_signature
| 64
|
rust
| null | null | null | null |
validate_schema
| null | null | null | null | null | null | null |
impl api::PaymentVoid for Payu {}
|
crates/hyperswitch_connectors/src/connectors/payu.rs
|
hyperswitch_connectors
|
impl_block
| 9
|
rust
| null |
Payu
|
api::PaymentVoid for
|
impl api::PaymentVoid for for Payu
| null | null | null | null | null | null | null | null |
pub struct CreateUserThemeRequest {
pub entity_type: EntityType,
pub theme_name: String,
pub theme_data: ThemeData,
pub email_config: Option<EmailThemeConfig>,
}
|
crates/api_models/src/user/theme.rs
|
api_models
|
struct_definition
| 39
|
rust
|
CreateUserThemeRequest
| null | null | null | null | null | null | null | null | null | null | null |
impl api::RefundExecute for Getnet {}
|
crates/hyperswitch_connectors/src/connectors/getnet.rs
|
hyperswitch_connectors
|
impl_block
| 10
|
rust
| null |
Getnet
|
api::RefundExecute for
|
impl api::RefundExecute for for Getnet
| null | null | null | null | null | null | null | null |
pub struct BraintreeAuthType {
pub(super) public_key: Secret<String>,
pub(super) private_key: Secret<String>,
}
|
crates/hyperswitch_connectors/src/connectors/braintree/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 28
|
rust
|
BraintreeAuthType
| null | null | null | null | null | null | null | null | null | null | null |
pub struct Score {
factor_codes: Option<Vec<String>>,
result: Option<RiskResult>,
model_used: Option<String>,
}
|
crates/hyperswitch_connectors/src/connectors/barclaycard/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 28
|
rust
|
Score
| null | null | null | null | null | null | null | null | null | null | null |
pub struct RedirectUrl {
pub return_url: Option<String>,
pub url: Option<String>,
}
|
crates/router/src/compatibility/stripe/setup_intents/types.rs
|
router
|
struct_definition
| 21
|
rust
|
RedirectUrl
| null | null | null | null | null | null | null | null | null | null | null |
File: crates/test_utils/tests/connectors/nuvei_ui.rs
use serial_test::serial;
use thirtyfour::{prelude::*, WebDriver};
use crate::{selenium::*, tester};
struct NuveiSeleniumTest;
impl SeleniumTest for NuveiSeleniumTest {
fn get_connector_name(&self) -> String {
"nuvei".to_string()
}
}
async fn should_make_nuvei_3ds_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = NuveiSeleniumTest {};
conn.make_redirection_payment(c, vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/card?cname=CL-BRW1&ccnum=4000027891380961&expmonth=10&expyear=25&cvv=123&amount=200&country=US¤cy=USD"))),
Event::Assert(Assert::IsPresent("Expiry Year")),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Query(By::ClassName("title"))),
Event::Assert(Assert::Eq(Selector::Title, "ThreeDS ACS Emulator - Challenge Page")),
Event::Trigger(Trigger::Click(By::Id("btn1"))),
Event::Trigger(Trigger::Click(By::Id("btn5"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::Contains(Selector::QueryParamStr, "status=succeeded")),
]).await?;
Ok(())
}
async fn should_make_nuvei_3ds_mandate_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = NuveiSeleniumTest {};
conn.make_redirection_payment(c, vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/card?cname=CL-BRW1&ccnum=4000027891380961&expmonth=10&expyear=25&cvv=123&amount=200&country=US¤cy=USD&setup_future_usage=off_session&mandate_data[customer_acceptance][acceptance_type]=offline&mandate_data[customer_acceptance][accepted_at]=1963-05-03T04:07:52.723Z&mandate_data[customer_acceptance][online][ip_address]=in%20sit&mandate_data[customer_acceptance][online][user_agent]=amet%20irure%20esse&mandate_data[mandate_type][multi_use][amount]=7000&mandate_data[mandate_type][multi_use][currency]=USD&mandate_data[mandate_type][multi_use][start_date]=2022-09-10T00:00:00Z&mandate_data[mandate_type][multi_use][end_date]=2023-09-10T00:00:00Z&mandate_data[mandate_type][multi_use][metadata][frequency]=13&return_url={CHECKOUT_BASE_URL}/payments"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Query(By::ClassName("title"))),
Event::Assert(Assert::Eq(Selector::Title, "ThreeDS ACS Emulator - Challenge Page")),
Event::Trigger(Trigger::Click(By::Id("btn1"))),
Event::Trigger(Trigger::Click(By::Id("btn5"))),
Event::Assert(Assert::IsPresent("succeeded")),
Event::Assert(Assert::IsPresent("man_")),//mandate id prefix is present
]).await?;
Ok(())
}
async fn should_make_nuvei_gpay_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = NuveiSeleniumTest {};
conn.make_gpay_payment(c,
&format!("{CHECKOUT_BASE_URL}/gpay?gatewayname=nuveidigital&gatewaymerchantid=googletest&amount=10.00&country=IN¤cy=USD"),
vec![
Event::Assert(Assert::IsPresent("succeeded")),
]).await?;
Ok(())
}
async fn should_make_nuvei_pypl_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = NuveiSeleniumTest {};
conn.make_paypal_payment(
c,
&format!("{CHECKOUT_BASE_URL}/saved/5"),
vec![
Event::Trigger(Trigger::Click(By::Id("payment-submit-btn"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::ContainsAny(
Selector::QueryParamStr,
vec!["status=succeeded"],
)),
],
)
.await?;
Ok(())
}
async fn should_make_nuvei_giropay_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = NuveiSeleniumTest {};
conn.make_redirection_payment(c, vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/bank-redirect?amount=1.00&country=DE¤cy=EUR&paymentmethod=giropay"))),
Event::Trigger(Trigger::Click(By::Id("bank-redirect-btn"))),
Event::Assert(Assert::IsPresent("You are about to make a payment using the Giropay service.")),
Event::Trigger(Trigger::Click(By::Id("ctl00_ctl00_mainContent_btnConfirm"))),
Event::RunIf(Assert::IsPresent("Bank suchen"), vec![
Event::Trigger(Trigger::SendKeys(By::Id("bankSearch"), "GIROPAY Testbank 1")),
Event::Trigger(Trigger::Click(By::Id("GIROPAY Testbank 1"))),
]),
Event::Assert(Assert::IsPresent("GIROPAY Testbank 1")),
Event::Trigger(Trigger::Click(By::Css("button[name='claimCheckoutButton']"))),
Event::Assert(Assert::IsPresent("sandbox.paydirekt")),
Event::Trigger(Trigger::Click(By::Id("submitButton"))),
Event::Trigger(Trigger::Sleep(5)),
Event::Trigger(Trigger::SwitchTab(Position::Next)),
Event::Assert(Assert::IsPresent("Sicher bezahlt!")),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::ContainsAny(Selector::QueryParamStr, vec!["status=succeeded", "status=processing"]))
]).await?;
Ok(())
}
async fn should_make_nuvei_ideal_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = NuveiSeleniumTest {};
conn.make_redirection_payment(c, vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/bank-redirect?amount=10.00&country=NL¤cy=EUR&paymentmethod=ideal&processingbank=ing"))),
Event::Trigger(Trigger::Click(By::Id("bank-redirect-btn"))),
Event::Assert(Assert::IsPresent("Your account will be debited:")),
Event::Trigger(Trigger::SelectOption(By::Id("ctl00_ctl00_mainContent_ServiceContent_ddlBanks"), "ING Simulator")),
Event::Trigger(Trigger::Click(By::Id("ctl00_ctl00_mainContent_btnConfirm"))),
Event::Assert(Assert::IsPresent("IDEALFORTIS")),
Event::Trigger(Trigger::Sleep(5)),
Event::Trigger(Trigger::Click(By::Id("ctl00_mainContent_btnGo"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::ContainsAny(Selector::QueryParamStr, vec!["status=succeeded", "status=processing"]))
]).await?;
Ok(())
}
async fn should_make_nuvei_sofort_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = NuveiSeleniumTest {};
conn.make_redirection_payment(c, vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/bank-redirect?amount=10.00&country=DE¤cy=EUR&paymentmethod=sofort"))),
Event::Trigger(Trigger::Click(By::Id("bank-redirect-btn"))),
Event::Assert(Assert::IsPresent("SOFORT")),
Event::Trigger(Trigger::ChangeQueryParam("sender_holder", "John Doe")),
Event::Trigger(Trigger::Click(By::Id("ctl00_mainContent_btnGo"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::ContainsAny(Selector::QueryParamStr, vec!["status=succeeded", "status=processing"]))
]).await?;
Ok(())
}
async fn should_make_nuvei_eps_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = NuveiSeleniumTest {};
conn.make_redirection_payment(c, vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/bank-redirect?amount=10.00&country=AT¤cy=EUR&paymentmethod=eps&processingbank=ing"))),
Event::Trigger(Trigger::Click(By::Id("bank-redirect-btn"))),
Event::Assert(Assert::IsPresent("You are about to make a payment using the EPS service.")),
Event::Trigger(Trigger::SendKeys(By::Id("ctl00_ctl00_mainContent_ServiceContent_txtCustomerName"), "John Doe")),
Event::Trigger(Trigger::Click(By::Id("ctl00_ctl00_mainContent_btnConfirm"))),
Event::Assert(Assert::IsPresent("Simulator")),
Event::Trigger(Trigger::SelectOption(By::Css("select[name='result']"), "Succeeded")),
Event::Trigger(Trigger::Click(By::Id("submitbutton"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::ContainsAny(Selector::QueryParamStr, vec!["status=succeeded", "status=processing"]))
]).await?;
Ok(())
}
#[test]
#[serial]
fn should_make_nuvei_3ds_payment_test() {
tester!(should_make_nuvei_3ds_payment);
}
#[test]
#[serial]
fn should_make_nuvei_3ds_mandate_payment_test() {
tester!(should_make_nuvei_3ds_mandate_payment);
}
#[test]
#[serial]
fn should_make_nuvei_gpay_payment_test() {
tester!(should_make_nuvei_gpay_payment);
}
#[test]
#[serial]
fn should_make_nuvei_pypl_payment_test() {
tester!(should_make_nuvei_pypl_payment);
}
#[test]
#[serial]
fn should_make_nuvei_giropay_payment_test() {
tester!(should_make_nuvei_giropay_payment);
}
#[test]
#[serial]
fn should_make_nuvei_ideal_payment_test() {
tester!(should_make_nuvei_ideal_payment);
}
#[test]
#[serial]
fn should_make_nuvei_sofort_payment_test() {
tester!(should_make_nuvei_sofort_payment);
}
#[test]
#[serial]
fn should_make_nuvei_eps_payment_test() {
tester!(should_make_nuvei_eps_payment);
}
|
crates/test_utils/tests/connectors/nuvei_ui.rs
|
test_utils
|
full_file
| 2,497
| null | null | null | null | null | null | null | null | null | null | null | null | null |
pub struct FrmData {
pub payment_intent: PaymentIntent,
pub payment_attempt: PaymentAttempt,
pub merchant_account: MerchantAccount,
pub fraud_check: FraudCheck,
pub address: PaymentAddress,
pub connector_details: ConnectorDetailsCore,
pub order_details: Option<Vec<OrderDetailsWithAmount>>,
pub refund: Option<RefundResponse>,
pub frm_metadata: Option<SecretSerdeValue>,
}
|
crates/router/src/core/fraud_check/types.rs
|
router
|
struct_definition
| 88
|
rust
|
FrmData
| null | null | null | null | null | null | null | null | null | null | null |
pub async fn retrieve_decision_manager_config(
state: web::Data<AppState>,
req: HttpRequest,
) -> impl Responder {
let flow = Flow::DecisionManagerRetrieveConfig;
Box::pin(oss_api::server_wrap(
flow,
state,
&req,
(),
|state, auth: auth::AuthenticationData, _, _| {
conditional_config::retrieve_conditional_config(state, auth.key_store, auth.profile)
},
#[cfg(not(feature = "release"))]
auth::auth_type(
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
&auth::JWTAuth {
permission: Permission::ProfileThreeDsDecisionManagerWrite,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuth {
permission: Permission::ProfileThreeDsDecisionManagerWrite,
},
api_locking::LockAction::NotApplicable,
))
.await
}
|
crates/router/src/routes/routing.rs
|
router
|
function_signature
| 211
|
rust
| null | null | null | null |
retrieve_decision_manager_config
| null | null | null | null | null | null | null |
File: crates/router/src/core/health_check.rs
#[cfg(feature = "olap")]
use analytics::health_check::HealthCheck;
#[cfg(feature = "dynamic_routing")]
use api_models::health_check::HealthCheckMap;
use api_models::health_check::HealthState;
use error_stack::ResultExt;
use router_env::logger;
use crate::{
consts,
core::errors::{self, CustomResult},
routes::app,
services::api as services,
};
#[async_trait::async_trait]
pub trait HealthCheckInterface {
async fn health_check_db(&self) -> CustomResult<HealthState, errors::HealthCheckDBError>;
async fn health_check_redis(&self) -> CustomResult<HealthState, errors::HealthCheckRedisError>;
async fn health_check_locker(
&self,
) -> CustomResult<HealthState, errors::HealthCheckLockerError>;
async fn health_check_outgoing(&self)
-> CustomResult<HealthState, errors::HealthCheckOutGoing>;
#[cfg(feature = "olap")]
async fn health_check_analytics(&self)
-> CustomResult<HealthState, errors::HealthCheckDBError>;
#[cfg(feature = "olap")]
async fn health_check_opensearch(
&self,
) -> CustomResult<HealthState, errors::HealthCheckDBError>;
#[cfg(feature = "dynamic_routing")]
async fn health_check_grpc(
&self,
) -> CustomResult<HealthCheckMap, errors::HealthCheckGRPCServiceError>;
#[cfg(feature = "dynamic_routing")]
async fn health_check_decision_engine(
&self,
) -> CustomResult<HealthState, errors::HealthCheckDecisionEngineError>;
async fn health_check_unified_connector_service(
&self,
) -> CustomResult<HealthState, errors::HealthCheckUnifiedConnectorServiceError>;
}
#[async_trait::async_trait]
impl HealthCheckInterface for app::SessionState {
async fn health_check_db(&self) -> CustomResult<HealthState, errors::HealthCheckDBError> {
let db = &*self.store;
db.health_check_db().await?;
Ok(HealthState::Running)
}
async fn health_check_redis(&self) -> CustomResult<HealthState, errors::HealthCheckRedisError> {
let db = &*self.store;
let redis_conn = db
.get_redis_conn()
.change_context(errors::HealthCheckRedisError::RedisConnectionError)?;
redis_conn
.serialize_and_set_key_with_expiry(&"test_key".into(), "test_value", 30)
.await
.change_context(errors::HealthCheckRedisError::SetFailed)?;
logger::debug!("Redis set_key was successful");
redis_conn
.get_key::<()>(&"test_key".into())
.await
.change_context(errors::HealthCheckRedisError::GetFailed)?;
logger::debug!("Redis get_key was successful");
redis_conn
.delete_key(&"test_key".into())
.await
.change_context(errors::HealthCheckRedisError::DeleteFailed)?;
logger::debug!("Redis delete_key was successful");
Ok(HealthState::Running)
}
async fn health_check_locker(
&self,
) -> CustomResult<HealthState, errors::HealthCheckLockerError> {
let locker = &self.conf.locker;
if !locker.mock_locker {
let mut url = locker.host_rs.to_owned();
url.push_str(consts::LOCKER_HEALTH_CALL_PATH);
let request = services::Request::new(services::Method::Get, &url);
services::call_connector_api(self, request, "health_check_for_locker")
.await
.change_context(errors::HealthCheckLockerError::FailedToCallLocker)?
.map_err(|_| {
error_stack::report!(errors::HealthCheckLockerError::FailedToCallLocker)
})?;
Ok(HealthState::Running)
} else {
Ok(HealthState::NotApplicable)
}
}
#[cfg(feature = "olap")]
async fn health_check_analytics(
&self,
) -> CustomResult<HealthState, errors::HealthCheckDBError> {
let analytics = &self.pool;
match analytics {
analytics::AnalyticsProvider::Sqlx(client) => client
.deep_health_check()
.await
.change_context(errors::HealthCheckDBError::SqlxAnalyticsError),
analytics::AnalyticsProvider::Clickhouse(client) => client
.deep_health_check()
.await
.change_context(errors::HealthCheckDBError::ClickhouseAnalyticsError),
analytics::AnalyticsProvider::CombinedCkh(sqlx_client, ckh_client) => {
sqlx_client
.deep_health_check()
.await
.change_context(errors::HealthCheckDBError::SqlxAnalyticsError)?;
ckh_client
.deep_health_check()
.await
.change_context(errors::HealthCheckDBError::ClickhouseAnalyticsError)
}
analytics::AnalyticsProvider::CombinedSqlx(sqlx_client, ckh_client) => {
sqlx_client
.deep_health_check()
.await
.change_context(errors::HealthCheckDBError::SqlxAnalyticsError)?;
ckh_client
.deep_health_check()
.await
.change_context(errors::HealthCheckDBError::ClickhouseAnalyticsError)
}
}?;
Ok(HealthState::Running)
}
#[cfg(feature = "olap")]
async fn health_check_opensearch(
&self,
) -> CustomResult<HealthState, errors::HealthCheckDBError> {
if let Some(client) = self.opensearch_client.as_ref() {
client
.deep_health_check()
.await
.change_context(errors::HealthCheckDBError::OpensearchError)?;
Ok(HealthState::Running)
} else {
Ok(HealthState::NotApplicable)
}
}
async fn health_check_outgoing(
&self,
) -> CustomResult<HealthState, errors::HealthCheckOutGoing> {
let request = services::Request::new(services::Method::Get, consts::OUTGOING_CALL_URL);
services::call_connector_api(self, request, "outgoing_health_check")
.await
.map_err(|err| errors::HealthCheckOutGoing::OutGoingFailed {
message: err.to_string(),
})?
.map_err(|err| errors::HealthCheckOutGoing::OutGoingFailed {
message: format!(
"Got a non 200 status while making outgoing request. Error {:?}",
err.response
),
})?;
logger::debug!("Outgoing request successful");
Ok(HealthState::Running)
}
#[cfg(feature = "dynamic_routing")]
async fn health_check_grpc(
&self,
) -> CustomResult<HealthCheckMap, errors::HealthCheckGRPCServiceError> {
let health_client = &self.grpc_client.health_client;
let grpc_config = &self.conf.grpc_client;
let health_check_map = health_client
.perform_health_check(grpc_config)
.await
.change_context(errors::HealthCheckGRPCServiceError::FailedToCallService)?;
logger::debug!("Health check successful");
Ok(health_check_map)
}
#[cfg(feature = "dynamic_routing")]
async fn health_check_decision_engine(
&self,
) -> CustomResult<HealthState, errors::HealthCheckDecisionEngineError> {
if self.conf.open_router.dynamic_routing_enabled {
let url = format!("{}/{}", &self.conf.open_router.url, "health");
let request = services::Request::new(services::Method::Get, &url);
let _ = services::call_connector_api(self, request, "health_check_for_decision_engine")
.await
.change_context(
errors::HealthCheckDecisionEngineError::FailedToCallDecisionEngineService,
)?;
logger::debug!("Decision engine health check successful");
Ok(HealthState::Running)
} else {
logger::debug!("Decision engine health check not applicable");
Ok(HealthState::NotApplicable)
}
}
async fn health_check_unified_connector_service(
&self,
) -> CustomResult<HealthState, errors::HealthCheckUnifiedConnectorServiceError> {
if let Some(_ucs_client) = &self.grpc_client.unified_connector_service_client {
// For now, we'll just check if the client exists and is configured
// In the future, this could be enhanced to make an actual health check call
// to the unified connector service if it supports health check endpoints
logger::debug!("Unified Connector Service client is configured and available");
Ok(HealthState::Running)
} else {
logger::debug!("Unified Connector Service client not configured");
Ok(HealthState::NotApplicable)
}
}
}
|
crates/router/src/core/health_check.rs
|
router
|
full_file
| 1,908
| null | null | null | null | null | null | null | null | null | null | null | null | null |
/// Get string representation of enclosed ID type
pub fn to_str(&self) -> &str {
match self {
Self::Payment(id) => id.get_string_repr(),
Self::Customer(id) => id.get_string_repr(),
Self::PaymentMethodSession(id) => id.get_string_repr(),
}
}
|
crates/common_utils/src/types/authentication.rs
|
common_utils
|
function_signature
| 67
|
rust
| null | null | null | null |
to_str
| null | null | null | null | null | null | null |
pub struct GlobepayRefundResponse {
pub result_code: Option<GlobepayRefundStatus>,
pub refund_id: Option<String>,
pub return_code: GlobepayReturnCode,
pub return_msg: Option<String>,
}
|
crates/hyperswitch_connectors/src/connectors/globepay/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 51
|
rust
|
GlobepayRefundResponse
| null | null | null | null | null | null | null | null | null | null | null |
pub struct DeutschebankThreeDSInitializeRequestMeansOfPayment {
credit_card: DeutschebankThreeDSInitializeRequestCreditCard,
}
|
crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 26
|
rust
|
DeutschebankThreeDSInitializeRequestMeansOfPayment
| null | null | null | null | null | null | null | null | null | null | null |
impl common_utils::events::ApiEventMetric for RelayRetrieveBody {}
|
crates/api_models/src/relay.rs
|
api_models
|
impl_block
| 14
|
rust
| null |
RelayRetrieveBody
|
common_utils::events::ApiEventMetric for
|
impl common_utils::events::ApiEventMetric for for RelayRetrieveBody
| null | null | null | null | null | null | null | null |
Web Documentation: For SaaS Businesses | Hyperswitch
# Type: Web Doc
Hyperswitch empowers SaaS businesses with a comprehensive, modular, and scalable payment solution tailored to enhance subscription management, reduce passive churn, and optimize payment operations globally.
Whether you're a startup or an established enterprise, Hyperswitch provides the tools needed to deliver seamless payment experiences for your users.
Seamless recurring payments
Passive churn reduction
Optimize payment costs
Global payment support with no code connector integrations
Simplified payment operations
Seamless recurring payments
Automate and streamline recurring payments with flexible subscription models, ensuring a hassle-free experience for both customers and teams.
Saving a payment method for future recurring payments
PG agnostic card forwarding for recurring payments
Passive churn reduction
Maximize revenue by reducing passive churn due to payment failures in recurring payment.
Reducing passive churn with smart retries for failed recurring payments
Optimize Payment Costs
Optimize payment costs by ensuring that every transaction flows through the most cost-effective processor, and get actionable insights to reduce costs with AI, along with deeper visibility into transaction fees and anomaly detection.
Smart routing
AI Ops cost observability with HyperSense
Global payment support with no code connector integrations
Reduce weeks or even months of development on payment connector integrations and support for various payment methods with Hyperswitch’s no-code solution.
List of 70+ supported connectors and 150+ payment methods
How to configure a connector in few clicks
Simplified payment operations
Enhance efficiency in your payment operations by accessing unified analytics, managing teams with custom roles and profiles, and more, all with just a few clicks from the powerful Hyperswitch Control Center.
Access unified analytics
Manage your team
Have Questions?
Join our
Slack Community
Prefer direct support? Use our
Contact Us
page to reach out.
For B2B SaaS Businesses
2 months ago
Was this helpful?
|
https://docs.hyperswitch.io/use-cases/for-saas-providers
| null |
web_doc_file
| 399
|
doc
| null | null | null | null | null |
web
| null | null | null |
https://docs.hyperswitch.io/use-cases/for-saas-providers
|
For SaaS Businesses | Hyperswitch
| null |
pub struct Entity {
pub entity_id: String,
pub entity_type: EntityType,
}
|
crates/router/src/services/email/types.rs
|
router
|
struct_definition
| 19
|
rust
|
Entity
| null | null | null | null | null | null | null | null | null | null | null |
File: crates/hyperswitch_connectors/src/connectors/flexiti.rs
Public functions: 1
Public structs: 1
pub mod transformers;
use std::sync::LazyLock;
use common_enums::enums;
use common_utils::{
errors::CustomResult,
ext_traits::BytesExt,
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector},
};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
refunds::{Execute, RSync},
},
router_request_types::{
AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
RefundsData, SetupMandateRequestData,
},
router_response_types::{
ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData,
RefundSyncRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
errors,
events::connector_api_logs::ConnectorEvent,
types::{self, Response},
webhooks,
};
use masking::PeekInterface;
use transformers as flexiti;
use uuid::Uuid;
use crate::{
capture_method_not_supported,
constants::headers,
types::{RefreshTokenRouterData, ResponseRouterData},
utils,
};
#[derive(Clone)]
pub struct Flexiti {
amount_converter: &'static (dyn AmountConvertor<Output = FloatMajorUnit> + Sync),
}
impl Flexiti {
pub fn new() -> &'static Self {
&Self {
amount_converter: &FloatMajorUnitForConnector,
}
}
}
impl api::Payment for Flexiti {}
impl api::PaymentSession for Flexiti {}
impl api::ConnectorAccessToken for Flexiti {}
impl api::MandateSetup for Flexiti {}
impl api::PaymentAuthorize for Flexiti {}
impl api::PaymentSync for Flexiti {}
impl api::PaymentCapture for Flexiti {}
impl api::PaymentVoid for Flexiti {}
impl api::Refund for Flexiti {}
impl api::RefundExecute for Flexiti {}
impl api::RefundSync for Flexiti {}
impl api::PaymentToken for Flexiti {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Flexiti
{
// Not Implemented (R)
}
impl Flexiti {
fn get_default_header() -> (String, masking::Maskable<String>) {
(
"x-reference-id".to_string(),
Uuid::new_v4().to_string().into(),
)
}
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Flexiti
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
req: &RouterData<Flow, Request, Response>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let access_token = req
.access_token
.clone()
.ok_or(errors::ConnectorError::FailedToObtainAuthType)?;
let mut header = vec![(
headers::AUTHORIZATION.to_string(),
format!("Bearer {}", access_token.token.peek()).into(),
)];
header.push(Self::get_default_header());
Ok(header)
}
}
impl ConnectorCommon for Flexiti {
fn id(&self) -> &'static str {
"flexiti"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Base
}
fn common_get_content_type(&self) -> &'static str {
"application/x-www-form-urlencoded"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.flexiti.base_url.as_ref()
}
fn get_auth_header(
&self,
_auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
Ok(vec![])
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: flexiti::FlexitiErrorResponse = res
.response
.parse_struct("FlexitiErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
code: response.error.to_owned(),
message: response.message.to_owned(),
reason: Some(response.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,
})
}
}
impl ConnectorValidation for Flexiti {
fn validate_mandate_payment(
&self,
_pm_type: Option<enums::PaymentMethodType>,
pm_data: PaymentMethodData,
) -> CustomResult<(), errors::ConnectorError> {
match pm_data {
PaymentMethodData::Card(_) => Err(errors::ConnectorError::NotImplemented(
"validate_mandate_payment does not support cards".to_string(),
)
.into()),
_ => Ok(()),
}
}
fn validate_connector_against_payment_request(
&self,
capture_method: Option<common_enums::CaptureMethod>,
_payment_method: common_enums::PaymentMethod,
pmt: Option<common_enums::PaymentMethodType>,
) -> CustomResult<(), errors::ConnectorError> {
let capture_method = capture_method.unwrap_or_default();
match capture_method {
enums::CaptureMethod::Manual => Ok(()),
enums::CaptureMethod::Automatic
| enums::CaptureMethod::SequentialAutomatic
| enums::CaptureMethod::ManualMultiple
| enums::CaptureMethod::Scheduled => {
let connector = self.id();
match pmt {
Some(payment_method_type) => {
capture_method_not_supported!(
connector,
capture_method,
payment_method_type
)
}
None => capture_method_not_supported!(connector, capture_method),
}
}
}
}
fn validate_psync_reference_id(
&self,
_data: &PaymentsSyncData,
_is_three_ds: bool,
_status: enums::AttemptStatus,
_connector_meta_data: Option<common_utils::pii::SecretSerdeValue>,
) -> CustomResult<(), errors::ConnectorError> {
Ok(())
}
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Flexiti {
fn get_url(
&self,
_req: &RefreshTokenRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}oauth/token", self.base_url(connectors)))
}
fn get_content_type(&self) -> &'static str {
"application/x-www-form-urlencoded"
}
fn get_headers(
&self,
_req: &RefreshTokenRouterData,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
Ok(vec![(Self::get_default_header())])
}
fn get_request_body(
&self,
req: &RefreshTokenRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = flexiti::FlexitiAccessTokenRequest::try_from(req)?;
Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RefreshTokenRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let req = Some(
RequestBuilder::new()
.method(Method::Post)
.attach_default_headers()
.headers(types::RefreshTokenType::get_headers(self, req, connectors)?)
.url(&types::RefreshTokenType::get_url(self, req, connectors)?)
.set_body(types::RefreshTokenType::get_request_body(
self, req, connectors,
)?)
.build(),
);
Ok(req)
}
fn handle_response(
&self,
data: &RefreshTokenRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefreshTokenRouterData, errors::ConnectorError> {
let response: flexiti::FlexitiAccessTokenResponse = res
.response
.parse_struct("FlexitiAccessTokenResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Flexiti {
//TODO: implement sessions flow
}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Flexiti {}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Flexiti {
fn get_headers(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let auth_details = flexiti::FlexitiAuthType::try_from(&req.connector_auth_type)?;
Ok(format!(
"{}online/v2/client-id/{:?}/systems/init",
self.base_url(connectors),
auth_details.client_id.peek()
))
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = utils::convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = flexiti::FlexitiRouterData::from((amount, req));
let connector_req = flexiti::FlexitiPaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsAuthorizeType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::PaymentsAuthorizeType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: flexiti::FlexitiPaymentsResponse = res
.response
.parse_struct("Flexiti PaymentsAuthorizeResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Flexiti {
fn get_headers(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let auth_details = flexiti::FlexitiAuthType::try_from(&req.connector_auth_type.to_owned())?;
let order_id = req
.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
Ok(format!(
"{}online/client-id/{}/notifications/order-id/{}",
self.base_url(connectors),
auth_details.client_id.peek(),
order_id
))
}
fn build_request(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: flexiti::FlexitiSyncResponse = res
.response
.parse_struct("flexiti FlexitiSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Flexiti {
fn get_headers(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
}
fn get_request_body(
&self,
_req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_request_body method".to_string()).into())
}
fn build_request(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsCaptureType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsCaptureType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
let response: flexiti::FlexitiPaymentsResponse = res
.response
.parse_struct("Flexiti PaymentsCaptureResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Flexiti {}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Flexiti {
fn get_headers(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
}
fn get_request_body(
&self,
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let refund_amount = utils::convert_amount(
self.amount_converter,
req.request.minor_refund_amount,
req.request.currency,
)?;
let connector_router_data = flexiti::FlexitiRouterData::from((refund_amount, req));
let connector_req = flexiti::FlexitiRefundRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&types::RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundExecuteType::get_headers(
self, req, connectors,
)?)
.set_body(types::RefundExecuteType::get_request_body(
self, req, connectors,
)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
let response: flexiti::RefundResponse = res
.response
.parse_struct("flexiti RefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Flexiti {
fn get_headers(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &RefundSyncRouterData,
_connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
}
fn build_request(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundSyncType::get_headers(self, req, connectors)?)
.set_body(types::RefundSyncType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
let response: flexiti::RefundResponse = res
.response
.parse_struct("flexiti RefundSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Flexiti {
fn get_webhook_object_reference_id(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_event_type(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_resource_object(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
}
static FLEXITI_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLock::new(|| {
let supported_capture_methods = vec![enums::CaptureMethod::Manual];
let mut flexiti_supported_payment_methods = SupportedPaymentMethods::new();
flexiti_supported_payment_methods.add(
enums::PaymentMethod::PayLater,
enums::PaymentMethodType::Klarna,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::NotSupported,
supported_capture_methods,
specific_features: None,
},
);
flexiti_supported_payment_methods
});
static FLEXITI_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Flexiti",
description: "Flexiti connector",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: enums::ConnectorIntegrationStatus::Alpha,
};
static FLEXITI_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = [];
impl ConnectorSpecifications for Flexiti {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&FLEXITI_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*FLEXITI_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&FLEXITI_SUPPORTED_WEBHOOK_FLOWS)
}
}
|
crates/hyperswitch_connectors/src/connectors/flexiti.rs
|
hyperswitch_connectors
|
full_file
| 5,659
| null | null | null | null | null | null | null | null | null | null | null | null | null |
pub struct NexinetsPreAuthOrDebitResponse {
order_id: String,
transaction_type: NexinetsTransactionType,
transactions: Vec<NexinetsTransaction>,
payment_instrument: PaymentInstrument,
redirect_url: Option<Url>,
}
|
crates/hyperswitch_connectors/src/connectors/nexinets/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 55
|
rust
|
NexinetsPreAuthOrDebitResponse
| null | null | null | null | null | null | null | null | null | null | null |
pub struct CreateRoleRequest {
pub role_name: String,
pub groups: Vec<PermissionGroup>,
pub role_scope: RoleScope,
pub entity_type: Option<EntityType>,
}
|
crates/api_models/src/user_role/role.rs
|
api_models
|
struct_definition
| 40
|
rust
|
CreateRoleRequest
| null | null | null | null | null | null | null | null | null | null | null |
File: crates/router/src/core/payment_methods/cards.rs
Public functions: 48
Public structs: 2
use std::{
collections::{HashMap, HashSet},
fmt::Debug,
str::FromStr,
};
use ::payment_methods::{
configs::payment_connector_required_fields::{
get_billing_required_fields, get_shipping_required_fields,
},
controller::PaymentMethodsController,
};
#[cfg(feature = "v1")]
use api_models::admin::PaymentMethodsEnabled;
use api_models::{
enums as api_enums,
payment_methods::{
BankAccountTokenData, Card, CardDetailUpdate, CardDetailsPaymentMethod, CardNetworkTypes,
CountryCodeWithName, ListCountriesCurrenciesRequest, ListCountriesCurrenciesResponse,
MaskedBankDetails, PaymentExperienceTypes, PaymentMethodsData, RequestPaymentMethodTypes,
RequiredFieldInfo, ResponsePaymentMethodIntermediate, ResponsePaymentMethodTypes,
ResponsePaymentMethodsEnabled,
},
payments::BankCodeResponse,
pm_auth::PaymentMethodAuthConfig,
surcharge_decision_configs as api_surcharge_decision_configs,
};
use common_enums::{enums::MerchantStorageScheme, ConnectorType};
use common_utils::{
consts,
crypto::{self, Encryptable},
encryption::Encryption,
ext_traits::{AsyncExt, BytesExt, Encode, StringExt, ValueExt},
generate_id, id_type,
request::Request,
type_name,
types::{
keymanager::{Identifier, KeyManagerState},
MinorUnit,
},
};
use diesel_models::payment_method;
use error_stack::{report, ResultExt};
use euclid::{
dssa::graph::{AnalysisContext, CgraphExt},
frontend::dir,
};
use hyperswitch_constraint_graph as cgraph;
#[cfg(feature = "v1")]
use hyperswitch_domain_models::customer::CustomerUpdate;
use hyperswitch_domain_models::mandates::CommonMandateReference;
use hyperswitch_interfaces::secrets_interface::secret_state::RawSecret;
#[cfg(feature = "v1")]
use kgraph_utils::transformers::IntoDirValue;
use masking::Secret;
use router_env::{instrument, tracing};
use scheduler::errors as sch_errors;
use strum::IntoEnumIterator;
#[cfg(feature = "v1")]
use super::surcharge_decision_configs::{
perform_surcharge_decision_management_for_payment_method_list,
perform_surcharge_decision_management_for_saved_cards,
};
#[cfg(feature = "v1")]
use super::tokenize::NetworkTokenizationProcess;
#[cfg(feature = "v1")]
use crate::core::payment_methods::{
add_payment_method_status_update_task, tokenize,
utils::{get_merchant_pm_filter_graph, make_pm_graph, refresh_pm_filters_cache},
};
#[cfg(feature = "v1")]
use crate::routes::app::SessionStateInfo;
#[cfg(feature = "payouts")]
use crate::types::domain::types::AsyncLift;
use crate::{
configs::settings,
consts as router_consts,
core::{
errors::{self, StorageErrorExt},
payment_methods::{network_tokenization, transformers as payment_methods, vault},
payments::{
helpers,
routing::{self, SessionFlowRoutingInput},
},
utils as core_utils,
},
db, logger,
pii::prelude::*,
routes::{self, metrics, payment_methods::ParentPaymentMethodToken},
services,
types::{
api::{self, routing as routing_types, PaymentMethodCreateExt},
domain::{self, Profile},
storage::{self, enums, PaymentMethodListContext, PaymentTokenData},
transformers::{ForeignFrom, ForeignTryFrom},
},
utils,
utils::OptionExt,
};
#[cfg(feature = "v2")]
use crate::{
core::payment_methods as pm_core, headers, types::payment_methods as pm_types,
utils::ConnectorResponseExt,
};
pub struct PmCards<'a> {
pub state: &'a routes::SessionState,
pub merchant_context: &'a domain::MerchantContext,
}
#[async_trait::async_trait]
impl PaymentMethodsController for PmCards<'_> {
#[cfg(feature = "v1")]
#[instrument(skip_all)]
#[allow(clippy::too_many_arguments)]
async fn create_payment_method(
&self,
req: &api::PaymentMethodCreate,
customer_id: &id_type::CustomerId,
payment_method_id: &str,
locker_id: Option<String>,
merchant_id: &id_type::MerchantId,
pm_metadata: Option<serde_json::Value>,
customer_acceptance: Option<serde_json::Value>,
payment_method_data: crypto::OptionalEncryptableValue,
connector_mandate_details: Option<serde_json::Value>,
status: Option<enums::PaymentMethodStatus>,
network_transaction_id: Option<String>,
payment_method_billing_address: crypto::OptionalEncryptableValue,
card_scheme: Option<String>,
network_token_requestor_reference_id: Option<String>,
network_token_locker_id: Option<String>,
network_token_payment_method_data: crypto::OptionalEncryptableValue,
) -> errors::CustomResult<domain::PaymentMethod, errors::ApiErrorResponse> {
let db = &*self.state.store;
let customer = db
.find_customer_by_customer_id_merchant_id(
&self.state.into(),
customer_id,
merchant_id,
self.merchant_context.get_merchant_key_store(),
self.merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?;
let client_secret = generate_id(
consts::ID_LENGTH,
format!("{payment_method_id}_secret").as_str(),
);
let current_time = common_utils::date_time::now();
let response = db
.insert_payment_method(
&self.state.into(),
self.merchant_context.get_merchant_key_store(),
domain::PaymentMethod {
customer_id: customer_id.to_owned(),
merchant_id: merchant_id.to_owned(),
payment_method_id: payment_method_id.to_string(),
locker_id,
payment_method: req.payment_method,
payment_method_type: req.payment_method_type,
payment_method_issuer: req.payment_method_issuer.clone(),
scheme: req.card_network.clone().or(card_scheme),
metadata: pm_metadata.map(Secret::new),
payment_method_data,
connector_mandate_details,
customer_acceptance: customer_acceptance.map(Secret::new),
client_secret: Some(client_secret),
status: status.unwrap_or(enums::PaymentMethodStatus::Active),
network_transaction_id: network_transaction_id.to_owned(),
payment_method_issuer_code: None,
accepted_currency: None,
token: None,
cardholder_name: None,
issuer_name: None,
issuer_country: None,
payer_country: None,
is_stored: None,
swift_code: None,
direct_debit_token: None,
created_at: current_time,
last_modified: current_time,
last_used_at: current_time,
payment_method_billing_address,
updated_by: None,
version: common_types::consts::API_VERSION,
network_token_requestor_reference_id,
network_token_locker_id,
network_token_payment_method_data,
},
self.merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to add payment method in db")?;
if customer.default_payment_method_id.is_none() && req.payment_method.is_some() {
let _ = self
.set_default_payment_method(merchant_id, customer_id, payment_method_id.to_owned())
.await
.map_err(|error| {
logger::error!(?error, "Failed to set the payment method as default")
});
}
Ok(response)
}
#[cfg(feature = "v1")]
fn store_default_payment_method(
&self,
req: &api::PaymentMethodCreate,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
) -> (
api::PaymentMethodResponse,
Option<payment_methods::DataDuplicationCheck>,
) {
let pm_id = generate_id(consts::ID_LENGTH, "pm");
let payment_method_response = api::PaymentMethodResponse {
merchant_id: merchant_id.to_owned(),
customer_id: Some(customer_id.to_owned()),
payment_method_id: pm_id,
payment_method: req.payment_method,
payment_method_type: req.payment_method_type,
#[cfg(feature = "payouts")]
bank_transfer: None,
card: None,
metadata: req.metadata.clone(),
created: Some(common_utils::date_time::now()),
recurring_enabled: Some(false), //[#219]
installment_payment_enabled: Some(false), //[#219]
payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]),
last_used_at: Some(common_utils::date_time::now()),
client_secret: None,
};
(payment_method_response, None)
}
#[cfg(feature = "v2")]
fn store_default_payment_method(
&self,
_req: &api::PaymentMethodCreate,
_customer_id: &id_type::CustomerId,
_merchant_id: &id_type::MerchantId,
) -> (
api::PaymentMethodResponse,
Option<payment_methods::DataDuplicationCheck>,
) {
todo!()
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn get_or_insert_payment_method(
&self,
req: api::PaymentMethodCreate,
resp: &mut api::PaymentMethodResponse,
customer_id: &id_type::CustomerId,
key_store: &domain::MerchantKeyStore,
) -> errors::RouterResult<domain::PaymentMethod> {
let mut payment_method_id = resp.payment_method_id.clone();
let mut locker_id = None;
let db = &*self.state.store;
let key_manager_state = &(self.state.into());
let payment_method = {
let existing_pm_by_pmid = db
.find_payment_method(
key_manager_state,
key_store,
&payment_method_id,
self.merchant_context.get_merchant_account().storage_scheme,
)
.await;
if let Err(err) = existing_pm_by_pmid {
if err.current_context().is_db_not_found() {
locker_id = Some(payment_method_id.clone());
let existing_pm_by_locker_id = db
.find_payment_method_by_locker_id(
key_manager_state,
key_store,
&payment_method_id,
self.merchant_context.get_merchant_account().storage_scheme,
)
.await;
match &existing_pm_by_locker_id {
Ok(pm) => payment_method_id.clone_from(pm.get_id()),
Err(_) => payment_method_id = generate_id(consts::ID_LENGTH, "pm"),
};
existing_pm_by_locker_id
} else {
Err(err)
}
} else {
existing_pm_by_pmid
}
};
payment_method_id.clone_into(&mut resp.payment_method_id);
match payment_method {
Ok(pm) => Ok(pm),
Err(err) => {
if err.current_context().is_db_not_found() {
self.insert_payment_method(
resp,
&req,
key_store,
self.merchant_context.get_merchant_account().get_id(),
customer_id,
resp.metadata.clone().map(|val| val.expose()),
None,
locker_id,
None,
req.network_transaction_id.clone(),
None,
None,
None,
None,
)
.await
} else {
Err(err)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error while finding payment method")
}
}
}
}
#[cfg(feature = "v2")]
async fn get_or_insert_payment_method(
&self,
_req: api::PaymentMethodCreate,
_resp: &mut api::PaymentMethodResponse,
_customer_id: &id_type::CustomerId,
_key_store: &domain::MerchantKeyStore,
) -> errors::RouterResult<domain::PaymentMethod> {
todo!()
}
#[cfg(feature = "v1")]
#[allow(clippy::too_many_arguments)]
async fn save_network_token_and_update_payment_method(
&self,
req: &api::PaymentMethodMigrate,
key_store: &domain::MerchantKeyStore,
network_token_data: &api_models::payment_methods::MigrateNetworkTokenData,
network_token_requestor_ref_id: String,
pm_id: String,
) -> errors::RouterResult<bool> {
let payment_method_create_request =
api::PaymentMethodCreate::get_payment_method_create_from_payment_method_migrate(
network_token_data.network_token_number.clone(),
req,
);
let customer_id = req.customer_id.clone().get_required_value("customer_id")?;
let network_token_details = api::CardDetail {
card_number: network_token_data.network_token_number.clone(),
card_exp_month: network_token_data.network_token_exp_month.clone(),
card_exp_year: network_token_data.network_token_exp_year.clone(),
card_holder_name: network_token_data.card_holder_name.clone(),
nick_name: network_token_data.nick_name.clone(),
card_issuing_country: network_token_data.card_issuing_country.clone(),
card_network: network_token_data.card_network.clone(),
card_issuer: network_token_data.card_issuer.clone(),
card_type: network_token_data.card_type.clone(),
};
logger::debug!(
"Adding network token to locker for customer_id: {:?}",
customer_id
);
let token_resp = Box::pin(self.add_card_to_locker(
payment_method_create_request.clone(),
&network_token_details,
&customer_id,
None,
))
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Add Network Token failed");
let key_manager_state = &self.state.into();
match token_resp {
Ok(resp) => {
logger::debug!("Network token added to locker");
let (token_pm_resp, _duplication_check) = resp;
let pm_token_details = token_pm_resp.card.as_ref().map(|card| {
PaymentMethodsData::Card(CardDetailsPaymentMethod::from((card.clone(), None)))
});
let pm_network_token_data_encrypted = pm_token_details
.async_map(|pm_card| {
create_encrypted_data(key_manager_state, key_store, pm_card)
})
.await
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt payment method data")?;
let pm_update = storage::PaymentMethodUpdate::NetworkTokenDataUpdate {
network_token_requestor_reference_id: Some(network_token_requestor_ref_id),
network_token_locker_id: Some(token_pm_resp.payment_method_id),
network_token_payment_method_data: pm_network_token_data_encrypted
.map(Into::into),
};
let db = &*self.state.store;
let existing_pm = db
.find_payment_method(
&self.state.into(),
key_store,
&pm_id,
self.merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(format!(
"Failed to fetch payment method for existing pm_id: {pm_id:?} in db",
))?;
db.update_payment_method(
&self.state.into(),
key_store,
existing_pm,
pm_update,
self.merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(format!(
"Failed to update payment method for existing pm_id: {pm_id:?} in db",
))?;
logger::debug!("Network token added to locker and payment method updated");
Ok(true)
}
Err(err) => {
logger::debug!("Network token added to locker failed {:?}", err);
Ok(false)
}
}
}
#[cfg(feature = "v1")]
#[allow(clippy::too_many_arguments)]
async fn insert_payment_method(
&self,
resp: &api::PaymentMethodResponse,
req: &api::PaymentMethodCreate,
key_store: &domain::MerchantKeyStore,
merchant_id: &id_type::MerchantId,
customer_id: &id_type::CustomerId,
pm_metadata: Option<serde_json::Value>,
customer_acceptance: Option<serde_json::Value>,
locker_id: Option<String>,
connector_mandate_details: Option<serde_json::Value>,
network_transaction_id: Option<String>,
payment_method_billing_address: crypto::OptionalEncryptableValue,
network_token_requestor_reference_id: Option<String>,
network_token_locker_id: Option<String>,
network_token_payment_method_data: crypto::OptionalEncryptableValue,
) -> errors::RouterResult<domain::PaymentMethod> {
let pm_card_details = resp.card.clone().map(|card| {
PaymentMethodsData::Card(CardDetailsPaymentMethod::from((card.clone(), None)))
});
let key_manager_state = self.state.into();
let pm_data_encrypted: crypto::OptionalEncryptableValue = pm_card_details
.clone()
.async_map(|pm_card| create_encrypted_data(&key_manager_state, key_store, pm_card))
.await
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt payment method data")?;
self.create_payment_method(
req,
customer_id,
&resp.payment_method_id,
locker_id,
merchant_id,
pm_metadata,
customer_acceptance,
pm_data_encrypted,
connector_mandate_details,
None,
network_transaction_id,
payment_method_billing_address,
resp.card.clone().and_then(|card| {
card.card_network
.map(|card_network| card_network.to_string())
}),
network_token_requestor_reference_id,
network_token_locker_id,
network_token_payment_method_data,
)
.await
}
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments)]
async fn insert_payment_method(
&self,
resp: &api::PaymentMethodResponse,
req: &api::PaymentMethodCreate,
key_store: &domain::MerchantKeyStore,
merchant_id: &id_type::MerchantId,
customer_id: &id_type::CustomerId,
pm_metadata: Option<serde_json::Value>,
customer_acceptance: Option<serde_json::Value>,
locker_id: Option<String>,
connector_mandate_details: Option<serde_json::Value>,
network_transaction_id: Option<String>,
payment_method_billing_address: Option<Encryption>,
) -> errors::RouterResult<domain::PaymentMethod> {
todo!()
}
#[cfg(feature = "payouts")]
async fn add_bank_to_locker(
&self,
req: api::PaymentMethodCreate,
key_store: &domain::MerchantKeyStore,
bank: &api::BankPayout,
customer_id: &id_type::CustomerId,
) -> errors::CustomResult<
(
api::PaymentMethodResponse,
Option<payment_methods::DataDuplicationCheck>,
),
errors::VaultError,
> {
let key = key_store.key.get_inner().peek();
let payout_method_data = api::PayoutMethodData::Bank(bank.clone());
let key_manager_state: KeyManagerState = self.state.into();
let enc_data = async {
serde_json::to_value(payout_method_data.to_owned())
.map_err(|err| {
logger::error!("Error while encoding payout method data: {err:?}");
errors::VaultError::SavePaymentMethodFailed
})
.change_context(errors::VaultError::SavePaymentMethodFailed)
.attach_printable("Unable to encode payout method data")
.ok()
.map(|v| {
let secret: Secret<String> = Secret::new(v.to_string());
secret
})
.async_lift(|inner| async {
domain::types::crypto_operation(
&key_manager_state,
type_name!(payment_method::PaymentMethod),
domain::types::CryptoOperation::EncryptOptional(inner),
Identifier::Merchant(key_store.merchant_id.clone()),
key,
)
.await
.and_then(|val| val.try_into_optionaloperation())
})
.await
}
.await
.change_context(errors::VaultError::SavePaymentMethodFailed)
.attach_printable("Failed to encrypt payout method data")?
.map(Encryption::from)
.map(|e| e.into_inner())
.map_or(Err(errors::VaultError::SavePaymentMethodFailed), |e| {
Ok(hex::encode(e.peek()))
})?;
let payload =
payment_methods::StoreLockerReq::LockerGeneric(payment_methods::StoreGenericReq {
merchant_id: self
.merchant_context
.get_merchant_account()
.get_id()
.to_owned(),
merchant_customer_id: customer_id.to_owned(),
enc_data,
ttl: self.state.conf.locker.ttl_for_storage_in_secs,
});
let store_resp = add_card_to_hs_locker(
self.state,
&payload,
customer_id,
api_enums::LockerChoice::HyperswitchCardVault,
)
.await?;
let payment_method_resp = payment_methods::mk_add_bank_response_hs(
bank.clone(),
store_resp.card_reference,
req,
self.merchant_context.get_merchant_account().get_id(),
);
Ok((payment_method_resp, store_resp.duplication_check))
}
/// The response will be the tuple of PaymentMethodResponse and the duplication check of payment_method
async fn add_card_to_locker(
&self,
req: api::PaymentMethodCreate,
card: &api::CardDetail,
customer_id: &id_type::CustomerId,
card_reference: Option<&str>,
) -> errors::CustomResult<
(
api::PaymentMethodResponse,
Option<payment_methods::DataDuplicationCheck>,
),
errors::VaultError,
> {
metrics::STORED_TO_LOCKER.add(1, &[]);
let add_card_to_hs_resp = Box::pin(common_utils::metrics::utils::record_operation_time(
async {
self.add_card_hs(
req.clone(),
card,
customer_id,
api_enums::LockerChoice::HyperswitchCardVault,
card_reference,
)
.await
.inspect_err(|_| {
metrics::CARD_LOCKER_FAILURES.add(
1,
router_env::metric_attributes!(("locker", "rust"), ("operation", "add")),
);
})
},
&metrics::CARD_ADD_TIME,
router_env::metric_attributes!(("locker", "rust")),
))
.await?;
logger::debug!("card added to hyperswitch-card-vault");
Ok(add_card_to_hs_resp)
}
async fn delete_card_from_locker(
&self,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
card_reference: &str,
) -> errors::RouterResult<payment_methods::DeleteCardResp> {
metrics::DELETE_FROM_LOCKER.add(1, &[]);
common_utils::metrics::utils::record_operation_time(
async move {
delete_card_from_hs_locker(self.state, customer_id, merchant_id, card_reference)
.await
.inspect_err(|_| {
metrics::CARD_LOCKER_FAILURES.add(
1,
router_env::metric_attributes!(
("locker", "rust"),
("operation", "delete")
),
);
})
},
&metrics::CARD_DELETE_TIME,
&[],
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while deleting card from locker")
}
#[instrument(skip_all)]
async fn add_card_hs(
&self,
req: api::PaymentMethodCreate,
card: &api::CardDetail,
customer_id: &id_type::CustomerId,
locker_choice: api_enums::LockerChoice,
card_reference: Option<&str>,
) -> errors::CustomResult<
(
api::PaymentMethodResponse,
Option<payment_methods::DataDuplicationCheck>,
),
errors::VaultError,
> {
let payload = payment_methods::StoreLockerReq::LockerCard(payment_methods::StoreCardReq {
merchant_id: self
.merchant_context
.get_merchant_account()
.get_id()
.to_owned(),
merchant_customer_id: customer_id.to_owned(),
requestor_card_reference: card_reference.map(str::to_string),
card: Card {
card_number: card.card_number.to_owned(),
name_on_card: card.card_holder_name.to_owned(),
card_exp_month: card.card_exp_month.to_owned(),
card_exp_year: card.card_exp_year.to_owned(),
card_brand: card.card_network.as_ref().map(ToString::to_string),
card_isin: None,
nick_name: card.nick_name.as_ref().map(Secret::peek).cloned(),
},
ttl: self.state.conf.locker.ttl_for_storage_in_secs,
});
let store_card_payload =
add_card_to_hs_locker(self.state, &payload, customer_id, locker_choice).await?;
let payment_method_resp = payment_methods::mk_add_card_response_hs(
card.clone(),
store_card_payload.card_reference,
req,
self.merchant_context.get_merchant_account().get_id(),
);
Ok((payment_method_resp, store_card_payload.duplication_check))
}
#[cfg(feature = "v1")]
async fn get_card_details_with_locker_fallback(
&self,
pm: &domain::PaymentMethod,
) -> errors::RouterResult<Option<api::CardDetailFromLocker>> {
let card_decrypted = pm
.payment_method_data
.clone()
.map(|x| x.into_inner().expose())
.and_then(|v| serde_json::from_value::<PaymentMethodsData>(v).ok())
.and_then(|pmd| match pmd {
PaymentMethodsData::Card(crd) => Some(api::CardDetailFromLocker::from(crd)),
_ => None,
});
Ok(if let Some(mut crd) = card_decrypted {
crd.scheme.clone_from(&pm.scheme);
Some(crd)
} else {
logger::debug!(
"Getting card details from locker as it is not found in payment methods table"
);
Some(get_card_details_from_locker(self.state, pm).await?)
})
}
#[cfg(feature = "v1")]
async fn get_card_details_without_locker_fallback(
&self,
pm: &domain::PaymentMethod,
) -> errors::RouterResult<api::CardDetailFromLocker> {
let card_decrypted = pm
.payment_method_data
.clone()
.map(|x| x.into_inner().expose())
.and_then(|v| serde_json::from_value::<PaymentMethodsData>(v).ok())
.and_then(|pmd| match pmd {
PaymentMethodsData::Card(crd) => Some(api::CardDetailFromLocker::from(crd)),
_ => None,
});
Ok(if let Some(mut crd) = card_decrypted {
crd.scheme.clone_from(&pm.scheme);
crd
} else {
logger::debug!(
"Getting card details from locker as it is not found in payment methods table"
);
get_card_details_from_locker(self.state, pm).await?
})
}
#[cfg(feature = "v1")]
async fn set_default_payment_method(
&self,
merchant_id: &id_type::MerchantId,
customer_id: &id_type::CustomerId,
payment_method_id: String,
) -> errors::RouterResponse<api_models::payment_methods::CustomerDefaultPaymentMethodResponse>
{
let db = &*self.state.store;
let key_manager_state = &self.state.into();
// check for the customer
// TODO: customer need not be checked again here, this function can take an optional customer and check for existence of customer based on the optional value
let customer = db
.find_customer_by_customer_id_merchant_id(
key_manager_state,
customer_id,
merchant_id,
self.merchant_context.get_merchant_key_store(),
self.merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?;
// check for the presence of payment_method
let payment_method = db
.find_payment_method(
&(self.state.into()),
self.merchant_context.get_merchant_key_store(),
&payment_method_id,
self.merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
let pm = payment_method
.get_payment_method_type()
.get_required_value("payment_method")?;
utils::when(
&payment_method.customer_id != customer_id
|| payment_method.merchant_id != *merchant_id,
|| {
Err(errors::ApiErrorResponse::PreconditionFailed {
message: "The payment_method_id is not valid".to_string(),
})
},
)?;
utils::when(
Some(payment_method_id.clone()) == customer.default_payment_method_id,
|| {
Err(errors::ApiErrorResponse::PreconditionFailed {
message: "Payment Method is already set as default".to_string(),
})
},
)?;
let customer_id = customer.customer_id.clone();
let customer_update = CustomerUpdate::UpdateDefaultPaymentMethod {
default_payment_method_id: Some(Some(payment_method_id.to_owned())),
};
// update the db with the default payment method id
let updated_customer_details = db
.update_customer_by_customer_id_merchant_id(
key_manager_state,
customer_id.to_owned(),
merchant_id.to_owned(),
customer,
customer_update,
self.merchant_context.get_merchant_key_store(),
self.merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update the default payment method id for the customer")?;
let resp = api_models::payment_methods::CustomerDefaultPaymentMethodResponse {
default_payment_method_id: updated_customer_details.default_payment_method_id,
customer_id,
payment_method_type: payment_method.get_payment_method_subtype(),
payment_method: pm,
};
Ok(services::ApplicationResponse::Json(resp))
}
#[cfg(feature = "v1")]
async fn add_payment_method_status_update_task(
&self,
payment_method: &domain::PaymentMethod,
prev_status: common_enums::PaymentMethodStatus,
curr_status: common_enums::PaymentMethodStatus,
merchant_id: &id_type::MerchantId,
) -> Result<(), sch_errors::ProcessTrackerError> {
add_payment_method_status_update_task(
&*self.state.store,
payment_method,
prev_status,
curr_status,
merchant_id,
)
.await
}
#[cfg(feature = "v1")]
async fn validate_merchant_connector_ids_in_connector_mandate_details(
&self,
key_store: &domain::MerchantKeyStore,
connector_mandate_details: &api_models::payment_methods::CommonMandateReference,
merchant_id: &id_type::MerchantId,
card_network: Option<common_enums::CardNetwork>,
) -> errors::RouterResult<()> {
helpers::validate_merchant_connector_ids_in_connector_mandate_details(
self.state,
key_store,
connector_mandate_details,
merchant_id,
card_network,
)
.await
}
#[cfg(feature = "v1")]
async fn get_card_details_from_locker(
&self,
pm: &domain::PaymentMethod,
) -> errors::RouterResult<api::CardDetailFromLocker> {
get_card_details_from_locker(self.state, pm).await
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn retrieve_payment_method(
&self,
pm: api::PaymentMethodId,
) -> errors::RouterResponse<api::PaymentMethodResponse> {
let db = self.state.store.as_ref();
let pm = db
.find_payment_method(
&self.state.into(),
self.merchant_context.get_merchant_key_store(),
&pm.payment_method_id,
self.merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
let card = if pm.get_payment_method_type() == Some(enums::PaymentMethod::Card) {
let card_detail = if self.state.conf.locker.locker_enabled {
let card = get_card_from_locker(
self.state,
&pm.customer_id,
&pm.merchant_id,
pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error getting card from card vault")?;
payment_methods::get_card_detail(&pm, card)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while getting card details from locker")?
} else {
self.get_card_details_without_locker_fallback(&pm).await?
};
Some(card_detail)
} else {
None
};
Ok(services::ApplicationResponse::Json(
api::PaymentMethodResponse {
merchant_id: pm.merchant_id.clone(),
customer_id: Some(pm.customer_id.clone()),
payment_method_id: pm.payment_method_id.clone(),
payment_method: pm.get_payment_method_type(),
payment_method_type: pm.get_payment_method_subtype(),
#[cfg(feature = "payouts")]
bank_transfer: None,
card,
metadata: pm.metadata,
created: Some(pm.created_at),
recurring_enabled: Some(false),
installment_payment_enabled: Some(false),
payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]),
last_used_at: Some(pm.last_used_at),
client_secret: pm.client_secret,
},
))
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn delete_payment_method(
&self,
pm_id: api::PaymentMethodId,
) -> errors::RouterResponse<api::PaymentMethodDeleteResponse> {
let db = self.state.store.as_ref();
let key_manager_state = &(self.state.into());
let key = db
.find_payment_method(
key_manager_state,
self.merchant_context.get_merchant_key_store(),
pm_id.payment_method_id.as_str(),
self.merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
let customer = db
.find_customer_by_customer_id_merchant_id(
key_manager_state,
&key.customer_id,
self.merchant_context.get_merchant_account().get_id(),
self.merchant_context.get_merchant_key_store(),
self.merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Customer not found for the payment method")?;
if key.get_payment_method_type() == Some(enums::PaymentMethod::Card) {
let response = self
.delete_card_from_locker(
&key.customer_id,
&key.merchant_id,
key.locker_id.as_ref().unwrap_or(&key.payment_method_id),
)
.await?;
if let Some(network_token_ref_id) = key.network_token_requestor_reference_id {
let resp =
network_tokenization::delete_network_token_from_locker_and_token_service(
self.state,
&key.customer_id,
&key.merchant_id,
key.payment_method_id.clone(),
key.network_token_locker_id,
network_token_ref_id,
self.merchant_context,
)
.await?;
if resp.status == "Ok" {
logger::info!("Token From locker deleted Successfully!");
} else {
logger::error!("Error: Deleting Token From Locker!\n{:#?}", resp);
}
}
if response.status == "Ok" {
logger::info!("Card From locker deleted Successfully!");
} else {
logger::error!("Error: Deleting Card From Locker!\n{:#?}", response);
Err(errors::ApiErrorResponse::InternalServerError)?
}
}
db.delete_payment_method_by_merchant_id_payment_method_id(
&(self.state.into()),
self.merchant_context.get_merchant_key_store(),
self.merchant_context.get_merchant_account().get_id(),
pm_id.payment_method_id.as_str(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
if customer.default_payment_method_id.as_ref() == Some(&pm_id.payment_method_id) {
let customer_update = CustomerUpdate::UpdateDefaultPaymentMethod {
default_payment_method_id: Some(None),
};
db.update_customer_by_customer_id_merchant_id(
key_manager_state,
key.customer_id,
key.merchant_id,
customer,
customer_update,
self.merchant_context.get_merchant_key_store(),
self.merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update the default payment method id for the customer")?;
};
Ok(services::ApplicationResponse::Json(
api::PaymentMethodDeleteResponse {
|
crates/router/src/core/payment_methods/cards.rs#chunk0
|
router
|
chunk
| 8,187
| null | null | null | null | null | null | null | null | null | null | null | null | null |
OpenAPI Block Path: components.schemas.PaymentListConstraints
{
"type": "object",
"properties": {
"customer_id": {
"type": "string",
"description": "The identifier for customer",
"example": "cus_y3oqhf46pyzuxjbcn2giaqnb44",
"nullable": true,
"maxLength": 64,
"minLength": 1
},
"starting_after": {
"type": "string",
"description": "A cursor for use in pagination, fetch the next list after some object",
"example": "pay_fafa124123",
"nullable": true
},
"ending_before": {
"type": "string",
"description": "A cursor for use in pagination, fetch the previous list before some object",
"example": "pay_fafa124123",
"nullable": true
},
"limit": {
"type": "integer",
"format": "int32",
"description": "limit on the number of objects to return",
"default": 10,
"maximum": 100,
"minimum": 0
},
"created": {
"type": "string",
"format": "date-time",
"description": "The time at which payment is created",
"example": "2022-09-10T10:11:12Z",
"nullable": true
},
"created.lt": {
"type": "string",
"format": "date-time",
"description": "Time less than the payment created time",
"example": "2022-09-10T10:11:12Z",
"nullable": true
},
"created.gt": {
"type": "string",
"format": "date-time",
"description": "Time greater than the payment created time",
"example": "2022-09-10T10:11:12Z",
"nullable": true
},
"created.lte": {
"type": "string",
"format": "date-time",
"description": "Time less than or equals to the payment created time",
"example": "2022-09-10T10:11:12Z",
"nullable": true
},
"created.gte": {
"type": "string",
"format": "date-time",
"description": "Time greater than or equals to the payment created time",
"example": "2022-09-10T10:11:12Z",
"nullable": true
}
},
"additionalProperties": false
}
|
./hyperswitch/api-reference/v1/openapi_spec_v1.json
| null |
openapi_block
| 628
|
.json
| null | null | null | null | null |
openapi_spec
|
components
|
[
"schemas",
"PaymentListConstraints"
] | null | null | null | null |
pub(crate) fn get_webhook_object_from_body(
body: &[u8],
) -> CustomResult<SantanderWebhookBody, common_utils::errors::ParsingError> {
let webhook: SantanderWebhookBody = body.parse_struct("SantanderIncomingWebhook")?;
Ok(webhook)
}
|
crates/hyperswitch_connectors/src/connectors/santander/transformers.rs
|
hyperswitch_connectors
|
function_signature
| 66
|
rust
| null | null | null | null |
get_webhook_object_from_body
| null | null | null | null | null | null | null |
impl api::PayoutRecipientAccount for Nomupay {}
|
crates/hyperswitch_connectors/src/connectors/nomupay.rs
|
hyperswitch_connectors
|
impl_block
| 12
|
rust
| null |
Nomupay
|
api::PayoutRecipientAccount for
|
impl api::PayoutRecipientAccount for for Nomupay
| null | null | null | null | null | null | null | null |
pub struct BarclaycardThreeDSMetadata {
three_ds_data: BarclaycardConsumerAuthValidateResponse,
}
|
crates/hyperswitch_connectors/src/connectors/barclaycard/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 23
|
rust
|
BarclaycardThreeDSMetadata
| null | null | null | null | null | null | null | null | null | null | null |
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>,
}
|
crates/hyperswitch_connectors/src/connectors/nordea/requests.rs
|
hyperswitch_connectors
|
struct_definition
| 126
|
rust
|
NordeaPaymentsConfirmRequest
| null | null | null | null | null | null | null | null | null | null | null |
pub fn validate(&self) -> Result<(), ApplicationError> {
use common_utils::fp_utils::when;
when(self.host.is_default_or_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"server host must not be empty".into(),
))
})?;
when(self.workers == 0, || {
Err(ApplicationError::InvalidConfigurationValueError(
"number of workers must be greater than 0".into(),
))
})
}
|
crates/router/src/configs/validations.rs
|
router
|
function_signature
| 101
|
rust
| null | null | null | null |
validate
| null | null | null | null | null | null | null |
impl api::Payment for Boku {}
|
crates/hyperswitch_connectors/src/connectors/boku.rs
|
hyperswitch_connectors
|
impl_block
| 8
|
rust
| null |
Boku
|
api::Payment for
|
impl api::Payment for for Boku
| null | null | null | null | null | null | null | null |
pub async fn insert_resource<D, R, M>(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
create_resource_fut: R,
resource_new: M,
InsertResourceParams {
insertable,
reverse_lookups,
key,
identifier,
resource_type,
}: InsertResourceParams<'_>,
) -> error_stack::Result<D, errors::StorageError>
where
D: Debug + Sync + Conversion,
M: StorageModel<D>,
R: futures::Future<Output = error_stack::Result<M, DatabaseError>> + Send,
{
let storage_scheme = Box::pin(decide_storage_scheme::<_, M>(
self,
storage_scheme,
Op::Insert,
))
.await;
match storage_scheme {
MerchantStorageScheme::PostgresOnly => create_resource_fut.await.map_err(|error| {
let new_err = diesel_error_to_data_error(*error.current_context());
error.change_context(new_err)
}),
MerchantStorageScheme::RedisKv => {
let key_str = key.to_string();
let reverse_lookup_entry = |v: String| diesel_models::ReverseLookupNew {
sk_id: identifier.clone(),
pk_id: key_str.clone(),
lookup_id: v,
source: resource_type.to_string(),
updated_by: storage_scheme.to_string(),
};
let results = reverse_lookups
.into_iter()
.map(|v| self.insert_reverse_lookup(reverse_lookup_entry(v), storage_scheme));
futures::future::try_join_all(results).await?;
let redis_entry = kv::TypedSql {
op: kv::DBOperation::Insert {
insertable: Box::new(insertable),
},
};
match Box::pin(kv_wrapper::<M, _, _>(
self,
KvOperation::<M>::HSetNx(&identifier, &resource_new, redis_entry),
key.clone(),
))
.await
.map_err(|err| err.to_redis_failed_response(&key.to_string()))?
.try_into_hsetnx()
{
Ok(HsetnxReply::KeyNotSet) => Err(errors::StorageError::DuplicateValue {
entity: resource_type,
key: Some(key_str),
}
.into()),
Ok(HsetnxReply::KeySet) => Ok(resource_new),
Err(er) => Err(er).change_context(errors::StorageError::KVError),
}
}
}?
.convert(
state,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
}
|
crates/storage_impl/src/kv_router_store.rs
|
storage_impl
|
function_signature
| 577
|
rust
| null | null | null | null |
insert_resource
| null | null | null | null | null | null | null |
pub struct GetDisputeFilterRequest {
pub time_range: TimeRange,
#[serde(default)]
pub group_by_names: Vec<DisputeDimensions>,
}
|
crates/api_models/src/analytics.rs
|
api_models
|
struct_definition
| 34
|
rust
|
GetDisputeFilterRequest
| null | null | null | null | null | null | null | null | null | null | null |
/// get_pm_filters_cgraph_key
pub fn get_pm_filters_cgraph_key(&self) -> String {
format!("pm_filters_cgraph_{}", self.get_string_repr())
}
|
crates/common_utils/src/id_type/merchant.rs
|
common_utils
|
function_signature
| 39
|
rust
| null | null | null | null |
get_pm_filters_cgraph_key
| null | null | null | null | null | null | null |
pub fn build(self) -> Request {
Request {
method: self.method,
url: self.url,
headers: self.headers,
certificate: self.certificate,
certificate_key: self.certificate_key,
body: self.body,
ca_certificate: self.ca_certificate,
}
}
|
crates/common_utils/src/request.rs
|
common_utils
|
function_signature
| 63
|
rust
| null | null | null | null |
build
| null | null | null | null | null | null | null |
pub struct RoutingPayloadWrapper {
pub updated_config: Vec<RoutableConnectorChoice>,
pub profile_id: common_utils::id_type::ProfileId,
}
|
crates/api_models/src/routing.rs
|
api_models
|
struct_definition
| 33
|
rust
|
RoutingPayloadWrapper
| null | null | null | null | null | null | null | null | null | null | null |
pub async fn routing_unlink_config() {}
|
crates/openapi/src/routes/routing.rs
|
openapi
|
function_signature
| 9
|
rust
| null | null | null | null |
routing_unlink_config
| null | null | null | null | null | null | null |
impl<T: ForeignIDRef> RemoteStorageObject<T> {
pub fn get_id(&self) -> String {
match self {
Self::ForeignID(id) => id.clone(),
Self::Object(i) => i.foreign_id(),
}
}
}
|
crates/hyperswitch_domain_models/src/lib.rs
|
hyperswitch_domain_models
|
impl_block
| 56
|
rust
| null |
RemoteStorageObject
| null |
impl RemoteStorageObject
| null | null | null | null | null | null | null | null |
pub fn authenticate_authentication_client_secret_and_check_expiry(
req_client_secret: &String,
authentication: &diesel_models::authentication::Authentication,
) -> RouterResult<()> {
let stored_client_secret = authentication
.authentication_client_secret
.clone()
.get_required_value("authentication_client_secret")
.change_context(ApiErrorResponse::MissingRequiredField {
field_name: "client_secret",
})
.attach_printable("client secret not found in db")?;
if req_client_secret != &stored_client_secret {
Err(report!(ApiErrorResponse::ClientSecretInvalid))
} else {
let current_timestamp = common_utils::date_time::now();
let session_expiry = authentication
.created_at
.saturating_add(time::Duration::seconds(DEFAULT_SESSION_EXPIRY));
if current_timestamp > session_expiry {
Err(report!(ApiErrorResponse::ClientSecretExpired))
} else {
Ok(())
}
}
}
|
crates/router/src/core/unified_authentication_service/utils.rs
|
router
|
function_signature
| 197
|
rust
| null | null | null | null |
authenticate_authentication_client_secret_and_check_expiry
| null | null | null | null | null | null | null |
File: crates/router/tests/connectors/iatapay.rs
use hyperswitch_domain_models::address::{Address, AddressDetails, PhoneDetails};
use masking::Secret;
use router::types::{self, api, storage::enums, AccessToken};
use crate::{
connector_auth,
utils::{
self, get_connector_transaction_id, Connector, ConnectorActions, PaymentAuthorizeType,
},
};
#[derive(Clone, Copy)]
struct IatapayTest;
impl ConnectorActions for IatapayTest {}
impl Connector for IatapayTest {
fn get_data(&self) -> api::ConnectorData {
use router::connector::Iatapay;
utils::construct_connector_data_old(
Box::new(Iatapay::new()),
types::Connector::Iatapay,
api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.iatapay
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"iatapay".to_string()
}
}
fn get_access_token() -> Option<AccessToken> {
let connector = IatapayTest {};
match connector.get_auth_token() {
types::ConnectorAuthType::SignatureKey {
api_key,
key1: _,
api_secret: _,
} => Some(AccessToken {
token: api_key,
expires: 60 * 5,
}),
_ => None,
}
}
static CONNECTOR: IatapayTest = IatapayTest {};
fn get_default_payment_info() -> Option<utils::PaymentInfo> {
Some(utils::PaymentInfo {
address: Some(types::PaymentAddress::new(
None,
Some(Address {
address: Some(AddressDetails {
first_name: Some(Secret::new("first".to_string())),
last_name: Some(Secret::new("last".to_string())),
line1: Some(Secret::new("line1".to_string())),
line2: Some(Secret::new("line2".to_string())),
city: Some("city".to_string()),
zip: Some(Secret::new("zip".to_string())),
country: Some(api_models::enums::CountryAlpha2::NL),
..Default::default()
}),
phone: Some(PhoneDetails {
number: Some(Secret::new("9123456789".to_string())),
country_code: Some("+91".to_string()),
}),
email: None,
}),
None,
None,
)),
access_token: get_access_token(),
..Default::default()
})
}
fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
Some(types::PaymentsAuthorizeData {
router_return_url: Some("https://hyperswitch.io".to_string()),
webhook_url: Some("https://hyperswitch.io".to_string()),
currency: enums::Currency::EUR,
..PaymentAuthorizeType::default().0
})
}
// Cards Positive Tests
// Creates a payment checking if its status is "requires_customer_action" for redirectinal flow
#[actix_web::test]
async fn should_only_create_payment() {
let response = CONNECTOR
.authorize_payment(payment_method_details(), get_default_payment_info())
.await
.expect("Authorize payment response");
assert_eq!(response.status, enums::AttemptStatus::AuthenticationPending);
}
//refund on an unsuccessed payments
#[actix_web::test]
async fn should_fail_for_refund_on_unsuccessed_payment() {
let response = CONNECTOR
.authorize_payment(payment_method_details(), get_default_payment_info())
.await
.expect("Authorize payment response");
let refund_response = CONNECTOR
.refund_payment(
get_connector_transaction_id(response.response).unwrap(),
Some(types::RefundsData {
refund_amount: response.request.amount,
webhook_url: Some("https://hyperswitch.io".to_string()),
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
refund_response.response.unwrap_err().code,
"BAD_REQUEST".to_string(),
);
}
// Refunds a payment with refund amount higher than payment amount.
#[actix_web::test]
async fn should_fail_for_refund_amount_higher_than_payment_amount() {
let response = CONNECTOR
.refund_payment(
"PWGKCZ91M4JJ0".to_string(),
Some(types::RefundsData {
refund_amount: 150,
webhook_url: Some("https://hyperswitch.io".to_string()),
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"The amount to be refunded (100) is greater than the unrefunded amount (10.00): the amount of the payment is 10.00 and the refunded amount is 0.00",
);
}
#[actix_web::test]
async fn should_sync_payment() {
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
"PE9OTYNP639XW".to_string(),
),
..Default::default()
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Charged,);
}
#[actix_web::test]
async fn should_sync_refund() {
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
"R5DNXUW4EY6PQ".to_string(),
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
|
crates/router/tests/connectors/iatapay.rs
|
router
|
full_file
| 1,346
| null | null | null | null | null | null | null | null | null | null | null | null | null |
pub struct GenericVariableInput<T> {
input: T,
}
|
crates/hyperswitch_connectors/src/connectors/braintree/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 14
|
rust
|
GenericVariableInput
| null | null | null | null | null | null | null | null | null | null | null |
File: crates/test_utils/src/newman_runner.rs
Public functions: 8
Public structs: 2
use std::{
env,
fs::{self, OpenOptions},
io::{self, Write},
path::Path,
process::{exit, Command},
};
use anyhow::{Context, Result};
use clap::{arg, command, Parser, ValueEnum};
use masking::PeekInterface;
use regex::Regex;
use crate::connector_auth::{
ConnectorAuthType, ConnectorAuthentication, ConnectorAuthenticationMap,
};
#[derive(ValueEnum, Clone, Copy)]
pub enum Module {
Connector,
Users,
}
#[derive(Parser)]
#[command(version, about = "Postman collection runner using newman!", long_about = None)]
pub struct Args {
/// Admin API Key of the environment
#[arg(short, long)]
admin_api_key: String,
/// Base URL of the Hyperswitch environment
#[arg(short, long)]
base_url: String,
/// Name of the connector
#[arg(short, long)]
connector_name: Option<String>,
/// Name of the module
#[arg(short, long)]
module_name: Option<Module>,
/// Custom headers
#[arg(short = 'H', long = "header")]
custom_headers: Option<Vec<String>>,
/// Minimum delay in milliseconds to be added before sending a request
/// By default, 7 milliseconds will be the delay
#[arg(short, long, default_value_t = 7)]
delay_request: u32,
/// Folder name of specific tests
#[arg(short, long = "folder")]
folders: Option<String>,
/// Optional Verbose logs
#[arg(short, long)]
verbose: bool,
}
impl Args {
/// Getter for the `module_name` field
pub fn get_module_name(&self) -> Option<Module> {
self.module_name
}
}
pub struct ReturnArgs {
pub newman_command: Command,
pub modified_file_paths: Vec<Option<String>>,
pub collection_path: String,
}
// Generates the name of the collection JSON file for the specified connector.
// Example: CONNECTOR_NAME="stripe" -> OUTPUT: postman/collection-json/stripe.postman_collection.json
#[inline]
fn get_collection_path(name: impl AsRef<str>) -> String {
format!(
"postman/collection-json/{}.postman_collection.json",
name.as_ref()
)
}
// Generates the name of the collection directory for the specified connector.
// Example: CONNECTOR_NAME="stripe" -> OUTPUT: postman/collection-dir/stripe
#[inline]
fn get_dir_path(name: impl AsRef<str>) -> String {
format!("postman/collection-dir/{}", name.as_ref())
}
// This function currently allows you to add only custom headers.
// In future, as we scale, this can be modified based on the need
fn insert_content<T, U>(dir: T, content_to_insert: U) -> io::Result<()>
where
T: AsRef<Path>,
U: AsRef<str>,
{
let file_name = "event.prerequest.js";
let file_path = dir.as_ref().join(file_name);
// Open the file in write mode or create it if it doesn't exist
let mut file = OpenOptions::new()
.append(true)
.create(true)
.open(file_path)?;
write!(file, "{}", content_to_insert.as_ref())?;
Ok(())
}
// This function gives runner for connector or a module
pub fn generate_runner() -> Result<ReturnArgs> {
let args = Args::parse();
match args.get_module_name() {
Some(Module::Users) => generate_newman_command_for_users(),
Some(Module::Connector) => generate_newman_command_for_connector(),
// Running connector tests when no module is passed to keep the previous test behavior same
None => generate_newman_command_for_connector(),
}
}
pub fn generate_newman_command_for_users() -> Result<ReturnArgs> {
let args = Args::parse();
let base_url = args.base_url;
let admin_api_key = args.admin_api_key;
let path = env::var("CONNECTOR_AUTH_FILE_PATH")
.with_context(|| "connector authentication file path not set")?;
let authentication: ConnectorAuthentication = toml::from_str(
&fs::read_to_string(path)
.with_context(|| "connector authentication config file not found")?,
)
.with_context(|| "connector authentication file path not set")?;
let users_configs = authentication
.users
.with_context(|| "user configs not found in authentication file")?;
let collection_path = get_collection_path("users");
let mut newman_command = Command::new("newman");
newman_command.args(["run", &collection_path]);
newman_command.args(["--env-var", &format!("admin_api_key={admin_api_key}")]);
newman_command.args(["--env-var", &format!("baseUrl={base_url}")]);
newman_command.args([
"--env-var",
&format!("user_email={}", users_configs.user_email),
]);
newman_command.args([
"--env-var",
&format!(
"user_base_email_for_signup={}",
users_configs.user_base_email_for_signup
),
]);
newman_command.args([
"--env-var",
&format!(
"user_domain_for_signup={}",
users_configs.user_domain_for_signup
),
]);
newman_command.args([
"--env-var",
&format!("user_password={}", users_configs.user_password),
]);
newman_command.args([
"--env-var",
&format!("wrong_password={}", users_configs.wrong_password),
]);
newman_command.args([
"--delay-request",
format!("{}", &args.delay_request).as_str(),
]);
newman_command.arg("--color").arg("on");
if args.verbose {
newman_command.arg("--verbose");
}
Ok(ReturnArgs {
newman_command,
modified_file_paths: vec![],
collection_path,
})
}
pub fn generate_newman_command_for_connector() -> Result<ReturnArgs> {
let args = Args::parse();
let connector_name = args
.connector_name
.with_context(|| "invalid parameters: connector/module name not found in arguments")?;
let base_url = args.base_url;
let admin_api_key = args.admin_api_key;
let collection_path = get_collection_path(&connector_name);
let collection_dir_path = get_dir_path(&connector_name);
let auth_map = ConnectorAuthenticationMap::new();
let inner_map = auth_map.inner();
/*
Newman runner
Certificate keys are added through secrets in CI, so there's no need to explicitly pass it as arguments.
It can be overridden by explicitly passing certificates as arguments.
If the collection requires certificates (Stripe collection for example) during the merchant connector account create step,
then Stripe's certificates will be passed implicitly (for now).
If any other connector requires certificates to be passed, that has to be passed explicitly for now.
*/
let mut newman_command = Command::new("newman");
newman_command.args(["run", &collection_path]);
newman_command.args(["--env-var", &format!("admin_api_key={admin_api_key}")]);
newman_command.args(["--env-var", &format!("baseUrl={base_url}")]);
let custom_header_exist = check_for_custom_headers(args.custom_headers, &collection_dir_path);
// validation of connector is needed here as a work around to the limitation of the fork of newman that Hyperswitch uses
let (connector_name, modified_collection_file_paths) =
check_connector_for_dynamic_amount(&connector_name);
if let Some(auth_type) = inner_map.get(connector_name) {
match auth_type {
ConnectorAuthType::HeaderKey { api_key } => {
newman_command.args([
"--env-var",
&format!("connector_api_key={}", api_key.peek()),
]);
}
ConnectorAuthType::BodyKey { api_key, key1 } => {
newman_command.args([
"--env-var",
&format!("connector_api_key={}", api_key.peek()),
"--env-var",
&format!("connector_key1={}", key1.peek()),
]);
}
ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} => {
newman_command.args([
"--env-var",
&format!("connector_api_key={}", api_key.peek()),
"--env-var",
&format!("connector_key1={}", key1.peek()),
"--env-var",
&format!("connector_api_secret={}", api_secret.peek()),
]);
}
ConnectorAuthType::MultiAuthKey {
api_key,
key1,
key2,
api_secret,
} => {
newman_command.args([
"--env-var",
&format!("connector_api_key={}", api_key.peek()),
"--env-var",
&format!("connector_key1={}", key1.peek()),
"--env-var",
&format!("connector_key2={}", key2.peek()),
"--env-var",
&format!("connector_api_secret={}", api_secret.peek()),
]);
}
// Handle other ConnectorAuthType variants
_ => {
eprintln!("Invalid authentication type.");
}
}
} else {
eprintln!("Connector not found.");
}
// Add additional environment variables if present
if let Ok(gateway_merchant_id) = env::var("GATEWAY_MERCHANT_ID") {
newman_command.args([
"--env-var",
&format!("gateway_merchant_id={gateway_merchant_id}"),
]);
}
if let Ok(gpay_certificate) = env::var("GPAY_CERTIFICATE") {
newman_command.args(["--env-var", &format!("certificate={gpay_certificate}")]);
}
if let Ok(gpay_certificate_keys) = env::var("GPAY_CERTIFICATE_KEYS") {
newman_command.args([
"--env-var",
&format!("certificate_keys={gpay_certificate_keys}"),
]);
}
if let Ok(merchant_api_key) = env::var("MERCHANT_API_KEY") {
newman_command.args(["--env-var", &format!("merchant_api_key={merchant_api_key}")]);
}
newman_command.args([
"--delay-request",
format!("{}", &args.delay_request).as_str(),
]);
newman_command.arg("--color").arg("on");
// Add flags for running specific folders
if let Some(folders) = &args.folders {
let folder_names: Vec<String> = folders.split(',').map(|s| s.trim().to_string()).collect();
for folder_name in folder_names {
if !folder_name.contains("QuickStart") {
// This is a quick fix, "QuickStart" is intentional to have merchant account and API keys set up
// This will be replaced by a more robust and efficient account creation or reuse existing old account
newman_command.args(["--folder", "QuickStart"]);
}
newman_command.args(["--folder", &folder_name]);
}
}
if args.verbose {
newman_command.arg("--verbose");
}
Ok(ReturnArgs {
newman_command,
modified_file_paths: vec![modified_collection_file_paths, custom_header_exist],
collection_path,
})
}
pub fn check_for_custom_headers(headers: Option<Vec<String>>, path: &str) -> Option<String> {
if let Some(headers) = &headers {
for header in headers {
if let Some((key, value)) = header.split_once(':') {
let content_to_insert =
format!(r#"pm.request.headers.add({{key: "{key}", value: "{value}"}});"#);
if let Err(err) = insert_content(path, &content_to_insert) {
eprintln!("An error occurred while inserting the custom header: {err}");
}
} else {
eprintln!("Invalid header format: {header}");
}
}
return Some(format!("{path}/event.prerequest.js"));
}
None
}
// If the connector name exists in dynamic_amount_connectors,
// the corresponding collection is modified at runtime to remove double quotes
pub fn check_connector_for_dynamic_amount(connector_name: &str) -> (&str, Option<String>) {
let collection_dir_path = get_dir_path(connector_name);
let dynamic_amount_connectors = ["nmi", "powertranz"];
if dynamic_amount_connectors.contains(&connector_name) {
return remove_quotes_for_integer_values(connector_name).unwrap_or((connector_name, None));
}
/*
If connector name does not exist in dynamic_amount_connectors but we want to run it with custom headers,
since we're running from collections directly, we'll have to export the collection again and it is much simpler.
We could directly inject the custom-headers using regex, but it is not encouraged as it is hard
to determine the place of edit.
*/
export_collection(connector_name, collection_dir_path);
(connector_name, None)
}
/*
Existing issue with the fork of newman is that, it requires you to pass variables like `{{value}}` within
double quotes without which it fails to execute.
For integer values like `amount`, this is a bummer as it flags the value stating it is of type
string and not integer.
Refactoring is done in 2 steps:
- Export the collection to json (although the json will be up-to-date, we export it again for safety)
- Use regex to replace the values which removes double quotes from integer values
Ex: \"{{amount}}\" -> {{amount}}
*/
pub fn remove_quotes_for_integer_values(
connector_name: &str,
) -> Result<(&str, Option<String>), io::Error> {
let collection_path = get_collection_path(connector_name);
let collection_dir_path = get_dir_path(connector_name);
let values_to_replace = [
"amount",
"another_random_number",
"capture_amount",
"random_number",
"refund_amount",
];
export_collection(connector_name, collection_dir_path);
let mut contents = fs::read_to_string(&collection_path)?;
for value_to_replace in values_to_replace {
if let Ok(re) = Regex::new(&format!(
r#"\\"(?P<field>\{{\{{{value_to_replace}\}}\}})\\""#,
)) {
contents = re.replace_all(&contents, "$field").to_string();
} else {
eprintln!("Regex validation failed.");
}
let mut file = OpenOptions::new()
.write(true)
.truncate(true)
.open(&collection_path)?;
file.write_all(contents.as_bytes())?;
}
Ok((connector_name, Some(collection_path)))
}
pub fn export_collection(connector_name: &str, collection_dir_path: String) {
let collection_path = get_collection_path(connector_name);
let mut newman_command = Command::new("newman");
newman_command.args([
"dir-import".to_owned(),
collection_dir_path,
"-o".to_owned(),
collection_path.clone(),
]);
match newman_command.spawn().and_then(|mut child| child.wait()) {
Ok(exit_status) => {
if exit_status.success() {
println!("Conversion of collection from directory structure to json successful!");
} else {
eprintln!("Conversion of collection from directory structure to json failed!");
exit(exit_status.code().unwrap_or(1));
}
}
Err(err) => {
eprintln!("Failed to execute dir-import: {err:?}");
exit(1);
}
}
}
|
crates/test_utils/src/newman_runner.rs
|
test_utils
|
full_file
| 3,336
| null | null | null | null | null | null | null | null | null | null | null | null | null |
pub struct PaymentAuthConnectorData {
pub connector: BoxedPaymentAuthConnector,
pub connector_name: super::PaymentMethodAuthConnectors,
}
|
crates/pm_auth/src/types/api.rs
|
pm_auth
|
struct_definition
| 31
|
rust
|
PaymentAuthConnectorData
| null | null | null | null | null | null | null | null | null | null | null |
#[cfg(feature = "v1")]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, diesel::AsExpression)]
#[diesel(sql_type = diesel::sql_types::Jsonb)]
pub struct PaymentsMandateReference(
pub HashMap<common_utils::id_type::MerchantConnectorAccountId, PaymentsMandateReferenceRecord>,
);
#[cfg(feature = "v1")]
impl std::ops::Deref for PaymentsMandateReference {
type Target =
HashMap<common_utils::id_type::MerchantConnectorAccountId, PaymentsMandateReferenceRecord>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[cfg(feature = "v1")]
impl std::ops::DerefMut for PaymentsMandateReference {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
#[cfg(feature = "v2")]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, diesel::AsExpression)]
#[diesel(sql_type = diesel::sql_types::Jsonb)]
pub struct PaymentsTokenReference(
pub HashMap<common_utils::id_type::MerchantConnectorAccountId, ConnectorTokenReferenceRecord>,
);
#[cfg(feature = "v2")]
impl std::ops::Deref for PaymentsTokenReference {
type Target =
HashMap<common_utils::id_type::MerchantConnectorAccountId, ConnectorTokenReferenceRecord>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[cfg(feature = "v2")]
impl std::ops::DerefMut for PaymentsTokenReference {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
#[cfg(feature = "v1")]
common_utils::impl_to_sql_from_sql_json!(PaymentsMandateReference);
#[cfg(feature = "v2")]
common_utils::impl_to_sql_from_sql_json!(PaymentsTokenReference);
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
pub struct PayoutsMandateReferenceRecord {
pub transfer_method_id: Option<String>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, diesel::AsExpression)]
#[diesel(sql_type = diesel::sql_types::Jsonb)]
pub struct PayoutsMandateReference(
pub HashMap<common_utils::id_type::MerchantConnectorAccountId, PayoutsMandateReferenceRecord>,
);
impl std::ops::Deref for PayoutsMandateReference {
type Target =
HashMap<common_utils::id_type::MerchantConnectorAccountId, PayoutsMandateReferenceRecord>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl std::ops::DerefMut for PayoutsMandateReference {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
#[cfg(feature = "v1")]
#[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize, diesel::AsExpression)]
#[diesel(sql_type = diesel::sql_types::Jsonb)]
pub struct CommonMandateReference {
pub payments: Option<PaymentsMandateReference>,
pub payouts: Option<PayoutsMandateReference>,
}
#[cfg(feature = "v2")]
#[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize, diesel::AsExpression)]
#[diesel(sql_type = diesel::sql_types::Jsonb)]
pub struct CommonMandateReference {
pub payments: Option<PaymentsTokenReference>,
pub payouts: Option<PayoutsMandateReference>,
}
impl CommonMandateReference {
pub fn get_mandate_details_value(&self) -> CustomResult<serde_json::Value, ParsingError> {
let mut payments = self
.payments
.as_ref()
.map_or_else(|| Ok(serde_json::json!({})), serde_json::to_value)
.change_context(ParsingError::StructParseFailure("payment mandate details"))?;
self.payouts
.as_ref()
.map(|payouts_mandate| {
serde_json::to_value(payouts_mandate).map(|payouts_mandate_value| {
payments.as_object_mut().map(|payments_object| {
payments_object.insert("payouts".to_string(), payouts_mandate_value);
})
})
})
.transpose()
.change_context(ParsingError::StructParseFailure("payout mandate details"))?;
Ok(payments)
}
#[cfg(feature = "v2")]
/// Insert a new payment token reference for the given connector_id
pub fn insert_payment_token_reference_record(
&mut self,
connector_id: &common_utils::id_type::MerchantConnectorAccountId,
record: ConnectorTokenReferenceRecord,
) {
match self.payments {
Some(ref mut payments_reference) => {
payments_reference.insert(connector_id.clone(), record);
}
None => {
let mut payments_reference = HashMap::new();
payments_reference.insert(connector_id.clone(), record);
self.payments = Some(PaymentsTokenReference(payments_reference));
}
}
}
}
impl diesel::serialize::ToSql<diesel::sql_types::Jsonb, diesel::pg::Pg> for CommonMandateReference {
fn to_sql<'b>(
&'b self,
out: &mut diesel::serialize::Output<'b, '_, diesel::pg::Pg>,
) -> diesel::serialize::Result {
let payments = self.get_mandate_details_value()?;
<serde_json::Value as diesel::serialize::ToSql<
diesel::sql_types::Jsonb,
diesel::pg::Pg,
>>::to_sql(&payments, &mut out.reborrow())
}
}
#[cfg(feature = "v1")]
impl<DB: diesel::backend::Backend> diesel::deserialize::FromSql<diesel::sql_types::Jsonb, DB>
for CommonMandateReference
where
serde_json::Value: diesel::deserialize::FromSql<diesel::sql_types::Jsonb, DB>,
{
fn from_sql(bytes: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> {
let value = <serde_json::Value as diesel::deserialize::FromSql<
diesel::sql_types::Jsonb,
DB,
>>::from_sql(bytes)?;
let payments_data = value
.clone()
.as_object_mut()
.map(|obj| {
obj.remove("payouts");
serde_json::from_value::<PaymentsMandateReference>(serde_json::Value::Object(
obj.clone(),
))
.inspect_err(|err| {
router_env::logger::error!("Failed to parse payments data: {}", err);
})
.change_context(ParsingError::StructParseFailure(
"Failed to parse payments data",
))
})
.transpose()?;
let payouts_data = serde_json::from_value::<Option<Self>>(value)
.inspect_err(|err| {
router_env::logger::error!("Failed to parse payouts data: {}", err);
})
.change_context(ParsingError::StructParseFailure(
"Failed to parse payouts data",
))
.map(|optional_common_mandate_details| {
optional_common_mandate_details
.and_then(|common_mandate_details| common_mandate_details.payouts)
})?;
Ok(Self {
payments: payments_data,
payouts: payouts_data,
})
}
}
#[cfg(feature = "v2")]
impl<DB: diesel::backend::Backend> diesel::deserialize::FromSql<diesel::sql_types::Jsonb, DB>
for CommonMandateReference
where
serde_json::Value: diesel::deserialize::FromSql<diesel::sql_types::Jsonb, DB>,
{
fn from_sql(bytes: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> {
let value = <serde_json::Value as diesel::deserialize::FromSql<
diesel::sql_types::Jsonb,
DB,
>>::from_sql(bytes)?;
let payments_data = value
.clone()
.as_object_mut()
.map(|obj| {
obj.remove("payouts");
serde_json::from_value::<PaymentsTokenReference>(serde_json::Value::Object(
obj.clone(),
))
.inspect_err(|err| {
router_env::logger::error!("Failed to parse payments data: {}", err);
})
.change_context(ParsingError::StructParseFailure(
"Failed to parse payments data",
))
})
.transpose()?;
let payouts_data = serde_json::from_value::<Option<Self>>(value)
.inspect_err(|err| {
router_env::logger::error!("Failed to parse payouts data: {}", err);
})
.change_context(ParsingError::StructParseFailure(
"Failed to parse payouts data",
))
.map(|optional_common_mandate_details| {
optional_common_mandate_details
.and_then(|common_mandate_details| common_mandate_details.payouts)
})?;
Ok(Self {
payments: payments_data,
payouts: payouts_data,
})
}
}
#[cfg(feature = "v1")]
impl From<PaymentsMandateReference> for CommonMandateReference {
fn from(payment_reference: PaymentsMandateReference) -> Self {
Self {
payments: Some(payment_reference),
payouts: None,
}
}
}
|
crates/diesel_models/src/payment_method.rs#chunk1
|
diesel_models
|
chunk
| 2,069
| null | null | null | null | null | null | null | null | null | null | null | null | null |
pub struct ApplePayRecurringDetails {
/// A description of the recurring payment that Apple Pay displays to the user in the payment sheet
pub payment_description: String,
/// The regular billing cycle for the recurring payment, including start and end dates, an interval, and an interval count
pub regular_billing: ApplePayRegularBillingDetails,
/// A localized billing agreement that the payment sheet displays to the user before the user authorizes the payment
pub billing_agreement: Option<String>,
/// A URL to a web page where the user can update or delete the payment method for the recurring payment
pub management_url: common_utils::types::Url,
}
|
crates/diesel_models/src/types.rs
|
diesel_models
|
struct_definition
| 138
|
rust
|
ApplePayRecurringDetails
| null | null | null | null | null | null | null | null | null | null | null |
pub struct BluesnapWallet {
wallet_type: BluesnapWalletTypes,
encoded_payment_token: Secret<String>,
}
|
crates/hyperswitch_connectors/src/connectors/bluesnap/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 24
|
rust
|
BluesnapWallet
| null | null | null | null | null | null | null | null | null | null | null |
pub struct CardsNon3DSRequest {
card: CardPayment,
description: Option<String>,
}
|
crates/hyperswitch_connectors/src/connectors/shift4/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 21
|
rust
|
CardsNon3DSRequest
| null | null | null | null | null | null | null | null | null | null | null |
pub fn update_requestor_card_reference(&mut self, card_reference: Option<String>) {
match self {
Self::LockerCard(c) => c.requestor_card_reference = card_reference,
Self::LockerGeneric(_) => (),
}
}
|
crates/router/src/core/payment_methods/transformers.rs
|
router
|
function_signature
| 51
|
rust
| null | null | null | null |
update_requestor_card_reference
| null | null | null | null | null | null | null |
File: crates/router/tests/connectors/paypal.rs
use std::str::FromStr;
use common_utils::types::MinorUnit;
use masking::Secret;
use router::types::{self, domain, storage::enums, AccessToken, ConnectorAuthType};
use crate::{
connector_auth,
utils::{self, Connector, ConnectorActions},
};
struct PaypalTest;
impl ConnectorActions for PaypalTest {}
impl Connector for PaypalTest {
fn get_data(&self) -> types::api::ConnectorData {
use router::connector::Paypal;
utils::construct_connector_data_old(
Box::new(Paypal::new()),
types::Connector::Paypal,
types::api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.paypal
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"paypal".to_string()
}
}
static CONNECTOR: PaypalTest = PaypalTest {};
fn get_access_token() -> Option<AccessToken> {
let connector = PaypalTest {};
match connector.get_auth_token() {
ConnectorAuthType::BodyKey { api_key, key1: _ } => Some(AccessToken {
token: api_key,
expires: 18600,
}),
_ => None,
}
}
fn get_default_payment_info() -> Option<utils::PaymentInfo> {
Some(utils::PaymentInfo {
access_token: get_access_token(),
..Default::default()
})
}
fn get_payment_data() -> Option<types::PaymentsAuthorizeData> {
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_number: cards::CardNumber::from_str("4000020000000000").unwrap(),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
})
}
// Cards Positive Tests
// Creates a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_only_authorize_payment() {
let response = CONNECTOR
.authorize_payment(get_payment_data(), get_default_payment_info())
.await
.expect("Authorize payment response");
assert_eq!(response.status, enums::AttemptStatus::Authorized);
}
// Captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_capture_authorized_payment() {
let authorize_response = CONNECTOR
.authorize_payment(get_payment_data(), get_default_payment_info())
.await
.expect("Authorize payment response");
let txn_id = "".to_string();
let connector_meta = utils::get_connector_metadata(authorize_response.response);
let response = CONNECTOR
.capture_payment(
txn_id,
Some(types::PaymentsCaptureData {
connector_meta,
..utils::PaymentCaptureType::default().0
}),
get_default_payment_info(),
)
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Pending);
}
// Partially captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_capture_authorized_payment() {
let authorize_response = CONNECTOR
.authorize_payment(get_payment_data(), get_default_payment_info())
.await
.expect("Authorize payment response");
let txn_id = "".to_string();
let connector_meta = utils::get_connector_metadata(authorize_response.response);
let response = CONNECTOR
.capture_payment(
txn_id,
Some(types::PaymentsCaptureData {
connector_meta,
amount_to_capture: 50,
..utils::PaymentCaptureType::default().0
}),
get_default_payment_info(),
)
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Pending);
}
// Synchronizes a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_authorized_payment() {
let authorize_response = CONNECTOR
.authorize_payment(get_payment_data(), get_default_payment_info())
.await
.expect("Authorize payment response");
let txn_id = "".to_string();
let connector_meta = utils::get_connector_metadata(authorize_response.response);
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
mandate_id: None,
connector_transaction_id: types::ResponseId::ConnectorTransactionId(txn_id),
encoded_data: None,
capture_method: None,
sync_type: types::SyncRequestType::SinglePaymentSync,
connector_meta,
payment_method_type: None,
currency: enums::Currency::USD,
payment_experience: None,
integrity_object: None,
amount: MinorUnit::new(100),
..Default::default()
}),
get_default_payment_info(),
)
.await
.expect("PSync response");
assert_eq!(response.status, enums::AttemptStatus::Authorized,);
}
// Voids a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_void_authorized_payment() {
let authorize_response = CONNECTOR
.authorize_payment(get_payment_data(), get_default_payment_info())
.await
.expect("Authorize payment response");
let txn_id = "".to_string();
let connector_meta = utils::get_connector_metadata(authorize_response.response);
let response = CONNECTOR
.void_payment(
txn_id,
Some(types::PaymentsCancelData {
connector_transaction_id: String::from(""),
cancellation_reason: Some("requested_by_customer".to_string()),
connector_meta,
..Default::default()
}),
get_default_payment_info(),
)
.await
.expect("Void payment response");
assert_eq!(response.status, enums::AttemptStatus::Voided);
}
// Refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
#[ignore = "Since Payment status is in pending status, cannot refund"]
async fn should_refund_manually_captured_payment() {
let authorize_response = CONNECTOR
.authorize_payment(get_payment_data(), get_default_payment_info())
.await
.expect("Authorize payment response");
let txn_id = "".to_string();
let capture_connector_meta = utils::get_connector_metadata(authorize_response.response);
let capture_response = CONNECTOR
.capture_payment(
txn_id,
Some(types::PaymentsCaptureData {
connector_meta: capture_connector_meta,
..utils::PaymentCaptureType::default().0
}),
get_default_payment_info(),
)
.await
.expect("Capture payment response");
let refund_txn_id =
utils::get_connector_transaction_id(capture_response.response.clone()).unwrap();
let response = CONNECTOR
.refund_payment(
refund_txn_id,
Some(types::RefundsData {
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Partially refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
#[ignore = "Since Payment status is in pending status, cannot refund"]
async fn should_partially_refund_manually_captured_payment() {
let authorize_response = CONNECTOR
.authorize_payment(get_payment_data(), get_default_payment_info())
.await
.expect("Authorize payment response");
let txn_id = "".to_string();
let capture_connector_meta = utils::get_connector_metadata(authorize_response.response);
let capture_response = CONNECTOR
.capture_payment(
txn_id,
Some(types::PaymentsCaptureData {
connector_meta: capture_connector_meta,
..utils::PaymentCaptureType::default().0
}),
get_default_payment_info(),
)
.await
.expect("Capture payment response");
let refund_txn_id =
utils::get_connector_transaction_id(capture_response.response.clone()).unwrap();
let response = CONNECTOR
.refund_payment(
refund_txn_id,
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Synchronizes a refund using the manual capture flow (Non 3DS).
#[actix_web::test]
#[ignore = "Since Payment status is in pending status, cannot refund"]
async fn should_sync_manually_captured_refund() {
let authorize_response = CONNECTOR
.authorize_payment(get_payment_data(), get_default_payment_info())
.await
.expect("Authorize payment response");
let txn_id = "".to_string();
let capture_connector_meta = utils::get_connector_metadata(authorize_response.response);
let capture_response = CONNECTOR
.capture_payment(
txn_id,
Some(types::PaymentsCaptureData {
connector_meta: capture_connector_meta,
..utils::PaymentCaptureType::default().0
}),
get_default_payment_info(),
)
.await
.expect("Capture payment response");
let refund_txn_id =
utils::get_connector_transaction_id(capture_response.response.clone()).unwrap();
let refund_response = CONNECTOR
.refund_payment(
refund_txn_id,
Some(types::RefundsData {
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Creates a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_make_payment() {
let authorize_response = CONNECTOR
.make_payment(get_payment_data(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Pending);
}
// Synchronizes a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_auto_captured_payment() {
let authorize_response = CONNECTOR
.make_payment(get_payment_data(), get_default_payment_info())
.await
.unwrap();
assert_eq!(
authorize_response.status.clone(),
enums::AttemptStatus::Pending
);
let txn_id = utils::get_connector_transaction_id(authorize_response.response.clone());
assert_ne!(txn_id, None, "Empty connector transaction id");
let connector_meta = utils::get_connector_metadata(authorize_response.response);
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
mandate_id: None,
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
encoded_data: None,
capture_method: Some(enums::CaptureMethod::Automatic),
sync_type: types::SyncRequestType::SinglePaymentSync,
connector_meta,
payment_method_type: None,
currency: enums::Currency::USD,
payment_experience: None,
amount: MinorUnit::new(100),
integrity_object: None,
..Default::default()
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Pending);
}
// Refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
#[ignore = "Since Payment status is in pending status, cannot refund"]
async fn should_refund_auto_captured_payment() {
let response = CONNECTOR
.make_payment_and_refund(get_payment_data(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Partially refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
#[ignore = "Since Payment status is in pending status, cannot refund"]
async fn should_partially_refund_succeeded_payment() {
let authorize_response = CONNECTOR
.make_payment(get_payment_data(), get_default_payment_info())
.await
.unwrap();
let txn_id = utils::get_connector_transaction_id(authorize_response.response.clone()).unwrap();
let refund_response = CONNECTOR
.refund_payment(
txn_id,
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
refund_response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Creates multiple refunds against a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
#[ignore = "Since Payment status is in pending status, cannot refund"]
async fn should_refund_succeeded_payment_multiple_times() {
let authorize_response = CONNECTOR
.make_payment(get_payment_data(), get_default_payment_info())
.await
.unwrap();
let txn_id = utils::get_connector_transaction_id(authorize_response.response.clone()).unwrap();
for _x in 0..2 {
let refund_response = CONNECTOR
.refund_payment(
txn_id.clone(),
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
refund_response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
}
// Synchronizes a refund using the automatic capture flow (Non 3DS).
#[actix_web::test]
#[ignore = "Since Payment status is in pending status, cannot refund"]
async fn should_sync_refund() {
let refund_response = CONNECTOR
.make_payment_and_refund(get_payment_data(), None, get_default_payment_info())
.await
.unwrap();
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Cards Negative scenarios
// Creates a payment with incorrect CVC.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_cvc() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_cvc: Secret::new("12345".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.clone().unwrap_err().message,
"Request is not well-formed, syntactically incorrect, or violates schema.",
);
assert_eq!(
response.response.unwrap_err().reason.unwrap(),
"description - The value of a field does not conform to the expected format., value - 12345, field - security_code;",
);
}
// Creates a payment with incorrect expiry month.
#[actix_web::test]
async fn should_fail_payment_for_invalid_exp_month() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_month: Secret::new("20".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.clone().unwrap_err().message,
"Request is not well-formed, syntactically incorrect, or violates schema.",
);
assert_eq!(
response.response.unwrap_err().reason.unwrap(),
"description - The value of a field does not conform to the expected format., value - 2025-20, field - expiry;",
);
}
// Creates a payment with incorrect expiry year.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_expiry_year() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_year: Secret::new("2000".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.clone().unwrap_err().message,
"The requested action could not be performed, semantically incorrect, or failed business validation.",
);
assert_eq!(
response.response.unwrap_err().reason.unwrap(),
"description - The card is expired., field - expiry;",
);
}
// Voids a payment using automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_fail_void_payment_for_auto_capture() {
let authorize_response = CONNECTOR
.authorize_payment(get_payment_data(), get_default_payment_info())
.await
.expect("Authorize payment response");
let txn_id = "".to_string();
let capture_connector_meta = utils::get_connector_metadata(authorize_response.response);
let capture_response = CONNECTOR
.capture_payment(
txn_id,
Some(types::PaymentsCaptureData {
connector_meta: capture_connector_meta,
..utils::PaymentCaptureType::default().0
}),
get_default_payment_info(),
)
.await
.expect("Capture payment response");
let txn_id = utils::get_connector_transaction_id(capture_response.clone().response).unwrap();
let connector_meta = utils::get_connector_metadata(capture_response.response);
let void_response = CONNECTOR
.void_payment(
txn_id,
Some(types::PaymentsCancelData {
cancellation_reason: Some("requested_by_customer".to_string()),
connector_meta,
..Default::default()
}),
get_default_payment_info(),
)
.await
.expect("Void payment response");
assert_eq!(
void_response.response.clone().unwrap_err().message,
"The requested action could not be performed, semantically incorrect, or failed business validation."
);
assert_eq!(
void_response.response.unwrap_err().reason.unwrap(),
"description - Authorization has been previously captured and hence cannot be voided. ; "
);
}
// Captures a payment using invalid connector payment id.
#[actix_web::test]
async fn should_fail_capture_for_invalid_payment() {
let connector_meta = Some(serde_json::json!({
"authorize_id": "56YH8TZ",
"order_id":"02569315XM5003146",
"psync_flow":"AUTHORIZE",
}));
let capture_response = CONNECTOR
.capture_payment(
"".to_string(),
Some(types::PaymentsCaptureData {
connector_meta,
..utils::PaymentCaptureType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
capture_response.response.clone().unwrap_err().message,
"The specified resource does not exist.",
);
assert_eq!(
capture_response.response.unwrap_err().reason.unwrap(),
"description - Specified resource ID does not exist. Please check the resource ID and try again. ; ",
);
}
// Refunds a payment with refund amount higher than payment amount.
#[actix_web::test]
#[ignore = "Since Payment status is in pending status, cannot refund"]
async fn should_fail_for_refund_amount_higher_than_payment_amount() {
let authorize_response = CONNECTOR
.make_payment(get_payment_data(), get_default_payment_info())
.await
.unwrap();
let txn_id = utils::get_connector_transaction_id(authorize_response.response.clone()).unwrap();
let response = CONNECTOR
.refund_payment(
txn_id,
Some(types::RefundsData {
refund_amount: 150,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(&response.response.clone().unwrap_err().message, "The requested action could not be performed, semantically incorrect, or failed business validation.");
assert_eq!(
response.response.unwrap_err().reason.unwrap(),
"description - The refund amount must be less than or equal to the capture amount that has not yet been refunded. ; ",
);
}
// Connector dependent test cases goes here
// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
|
crates/router/tests/connectors/paypal.rs
|
router
|
full_file
| 4,671
| null | null | null | null | null | null | null | null | null | null | null | null | null |
pub async fn find_by_merchant_id_connector_txn_id(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
connector_txn_id: &str,
) -> StorageResult<Self> {
let (txn_id, txn_data) = common_utils::types::ConnectorTransactionId::form_id_and_data(
connector_txn_id.to_string(),
);
let connector_transaction_id = txn_id
.get_txn_id(txn_data.as_ref())
.change_context(DatabaseError::Others)
.attach_printable_lazy(|| {
format!("Failed to retrieve txn_id for ({txn_id:?}, {txn_data:?})")
})?;
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::connector_transaction_id.eq(connector_transaction_id.to_owned())),
)
.await
}
|
crates/diesel_models/src/query/payment_attempt.rs
|
diesel_models
|
function_signature
| 206
|
rust
| null | null | null | null |
find_by_merchant_id_connector_txn_id
| null | null | null | null | null | null | null |
OpenAPI Block Path: components.schemas.TaxStatus
{
"type": "string",
"enum": [
"taxable",
"exempt"
]
}
|
./hyperswitch/api-reference/v1/openapi_spec_v1.json
| null |
openapi_block
| 38
|
.json
| null | null | null | null | null |
openapi_spec
|
components
|
[
"schemas",
"TaxStatus"
] | null | null | null | null |
pub fn get_http_status_code_type(
status_code: u16,
) -> CustomResult<String, errors::ApiErrorResponse> {
let status_code_type = match status_code {
100..=199 => "1xx",
200..=299 => "2xx",
300..=399 => "3xx",
400..=499 => "4xx",
500..=599 => "5xx",
_ => Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Invalid http status code")?,
};
Ok(status_code_type.to_string())
}
|
crates/router/src/utils.rs
|
router
|
function_signature
| 147
|
rust
| null | null | null | null |
get_http_status_code_type
| null | null | null | null | null | null | null |
&self,
req: &SubmitEvidenceRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Put)
.url(&SubmitEvidenceType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(SubmitEvidenceType::get_headers(self, req, connectors)?)
.set_body(SubmitEvidenceType::get_request_body(self, req, connectors)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &SubmitEvidenceRouterData,
_event_builder: Option<&mut ConnectorEvent>,
_res: Response,
) -> CustomResult<SubmitEvidenceRouterData, errors::ConnectorError> {
Ok(SubmitEvidenceRouterData {
response: Ok(SubmitEvidenceResponse {
dispute_status: api_models::enums::DisputeStatus::DisputeChallenged,
connector_status: None,
}),
..data.clone()
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Defend, DefendDisputeRequestData, DefendDisputeResponse> for Checkout {
fn get_headers(
&self,
req: &DefendDisputeRouterData,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
DefendDisputeType::get_content_type(self).to_string().into(),
)];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
Ok(header)
}
fn get_url(
&self,
req: &DefendDisputeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}disputes/{}/evidence",
self.base_url(connectors),
req.request.connector_dispute_id,
))
}
fn build_request(
&self,
req: &DefendDisputeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&DefendDisputeType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(DefendDisputeType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &DefendDisputeRouterData,
_event_builder: Option<&mut ConnectorEvent>,
_res: Response,
) -> CustomResult<DefendDisputeRouterData, errors::ConnectorError> {
Ok(DefendDisputeRouterData {
response: Ok(DefendDisputeResponse {
dispute_status: enums::DisputeStatus::DisputeChallenged,
connector_status: None,
}),
..data.clone()
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Checkout {
fn get_webhook_source_verification_algorithm(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> {
Ok(Box::new(crypto::HmacSha256))
}
fn get_webhook_source_verification_signature(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let signature = utils::get_header_key_value("cko-signature", request.headers)
.change_context(errors::ConnectorError::WebhookSignatureNotFound)?;
hex::decode(signature).change_context(errors::ConnectorError::WebhookSignatureNotFound)
}
fn get_webhook_source_verification_message(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
_merchant_id: &common_utils::id_type::MerchantId,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
Ok(format!("{}", String::from_utf8_lossy(request.body)).into_bytes())
}
fn get_webhook_object_reference_id(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
let details: checkout::CheckoutWebhookBody = request
.body
.parse_struct("CheckoutWebhookBody")
.change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;
let ref_id: api_models::webhooks::ObjectReferenceId =
if checkout::is_chargeback_event(&details.transaction_type) {
let reference = match details.data.reference {
Some(reference) => {
api_models::payments::PaymentIdType::PaymentAttemptId(reference)
}
None => api_models::payments::PaymentIdType::ConnectorTransactionId(
details
.data
.payment_id
.ok_or(errors::ConnectorError::WebhookReferenceIdNotFound)?,
),
};
api_models::webhooks::ObjectReferenceId::PaymentId(reference)
} else if checkout::is_refund_event(&details.transaction_type) {
let refund_reference = match details.data.reference {
Some(reference) => api_models::webhooks::RefundIdType::RefundId(reference),
None => api_models::webhooks::RefundIdType::ConnectorRefundId(
details
.data
.action_id
.ok_or(errors::ConnectorError::WebhookReferenceIdNotFound)?,
),
};
api_models::webhooks::ObjectReferenceId::RefundId(refund_reference)
} else {
let reference_id = match details.data.reference {
Some(reference) => {
api_models::payments::PaymentIdType::PaymentAttemptId(reference)
}
None => {
api_models::payments::PaymentIdType::ConnectorTransactionId(details.data.id)
}
};
api_models::webhooks::ObjectReferenceId::PaymentId(reference_id)
};
Ok(ref_id)
}
fn get_webhook_event_type(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
let details: checkout::CheckoutWebhookEventTypeBody = request
.body
.parse_struct("CheckoutWebhookBody")
.change_context(errors::ConnectorError::WebhookEventTypeNotFound)?;
Ok(api_models::webhooks::IncomingWebhookEvent::from(
details.transaction_type,
))
}
fn get_webhook_resource_object(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let event_type_data: checkout::CheckoutWebhookEventTypeBody = request
.body
.parse_struct("CheckoutWebhookBody")
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
if checkout::is_chargeback_event(&event_type_data.transaction_type) {
let dispute_webhook_body: checkout::CheckoutDisputeWebhookBody = request
.body
.parse_struct("CheckoutDisputeWebhookBody")
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
Ok(Box::new(dispute_webhook_body.data))
} else if checkout::is_refund_event(&event_type_data.transaction_type) {
Ok(Box::new(checkout::RefundResponse::try_from(request)?))
} else {
Ok(Box::new(checkout::PaymentsResponse::try_from(request)?))
}
}
fn get_dispute_details(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<DisputePayload, errors::ConnectorError> {
let dispute_details: checkout::CheckoutDisputeWebhookBody = request
.body
.parse_struct("CheckoutWebhookBody")
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
let amount = utils::convert_amount(
self.amount_converter_webhooks,
dispute_details.data.amount,
dispute_details.data.currency,
)?;
Ok(DisputePayload {
amount,
currency: dispute_details.data.currency,
dispute_stage: api_models::enums::DisputeStage::from(
dispute_details.transaction_type.clone(),
),
connector_dispute_id: dispute_details.data.id,
connector_reason: None,
connector_reason_code: dispute_details.data.reason_code,
challenge_required_by: dispute_details.data.evidence_required_by,
connector_status: dispute_details.transaction_type.to_string(),
created_at: dispute_details.created_on,
updated_at: dispute_details.data.date,
})
}
}
impl api::ConnectorRedirectResponse for Checkout {
fn get_flow_type(
&self,
_query_params: &str,
_json_payload: Option<serde_json::Value>,
action: PaymentAction,
) -> CustomResult<CallConnectorAction, errors::ConnectorError> {
match action {
PaymentAction::PSync
| PaymentAction::CompleteAuthorize
| PaymentAction::PaymentAuthenticateCompleteAuthorize => {
Ok(CallConnectorAction::Trigger)
}
}
}
}
impl utils::ConnectorErrorTypeMapping for Checkout {
fn get_connector_error_type(
&self,
error_code: String,
_error_message: String,
) -> ConnectorErrorType {
match error_code.as_str() {
"action_failure_limit_exceeded" => ConnectorErrorType::BusinessError,
"address_invalid" => ConnectorErrorType::UserError,
"amount_exceeds_balance" => ConnectorErrorType::BusinessError,
"amount_invalid" => ConnectorErrorType::UserError,
"api_calls_quota_exceeded" => ConnectorErrorType::TechnicalError,
"billing_descriptor_city_invalid" => ConnectorErrorType::UserError,
"billing_descriptor_city_required" => ConnectorErrorType::UserError,
"billing_descriptor_name_invalid" => ConnectorErrorType::UserError,
"billing_descriptor_name_required" => ConnectorErrorType::UserError,
"business_invalid" => ConnectorErrorType::BusinessError,
"business_settings_missing" => ConnectorErrorType::BusinessError,
"capture_value_greater_than_authorized" => ConnectorErrorType::BusinessError,
"capture_value_greater_than_remaining_authorized" => ConnectorErrorType::BusinessError,
"card_authorization_failed" => ConnectorErrorType::UserError,
"card_disabled" => ConnectorErrorType::UserError,
"card_expired" => ConnectorErrorType::UserError,
"card_expiry_month_invalid" => ConnectorErrorType::UserError,
"card_expiry_month_required" => ConnectorErrorType::UserError,
"card_expiry_year_invalid" => ConnectorErrorType::UserError,
"card_expiry_year_required" => ConnectorErrorType::UserError,
"card_holder_invalid" => ConnectorErrorType::UserError,
"card_not_found" => ConnectorErrorType::UserError,
"card_number_invalid" => ConnectorErrorType::UserError,
"card_number_required" => ConnectorErrorType::UserError,
"channel_details_invalid" => ConnectorErrorType::BusinessError,
"channel_url_missing" => ConnectorErrorType::BusinessError,
"charge_details_invalid" => ConnectorErrorType::BusinessError,
"city_invalid" => ConnectorErrorType::BusinessError,
"country_address_invalid" => ConnectorErrorType::UserError,
"country_invalid" => ConnectorErrorType::UserError,
"country_phone_code_invalid" => ConnectorErrorType::UserError,
"country_phone_code_length_invalid" => ConnectorErrorType::UserError,
"currency_invalid" => ConnectorErrorType::UserError,
"currency_required" => ConnectorErrorType::UserError,
"customer_already_exists" => ConnectorErrorType::BusinessError,
"customer_email_invalid" => ConnectorErrorType::UserError,
"customer_id_invalid" => ConnectorErrorType::BusinessError,
"customer_not_found" => ConnectorErrorType::BusinessError,
"customer_number_invalid" => ConnectorErrorType::UserError,
"customer_plan_edit_failed" => ConnectorErrorType::BusinessError,
"customer_plan_id_invalid" => ConnectorErrorType::BusinessError,
"cvv_invalid" => ConnectorErrorType::UserError,
"email_in_use" => ConnectorErrorType::BusinessError,
"email_invalid" => ConnectorErrorType::UserError,
"email_required" => ConnectorErrorType::UserError,
"endpoint_invalid" => ConnectorErrorType::TechnicalError,
"expiry_date_format_invalid" => ConnectorErrorType::UserError,
"fail_url_invalid" => ConnectorErrorType::TechnicalError,
"first_name_required" => ConnectorErrorType::UserError,
"last_name_required" => ConnectorErrorType::UserError,
"ip_address_invalid" => ConnectorErrorType::UserError,
"issuer_network_unavailable" => ConnectorErrorType::TechnicalError,
"metadata_key_invalid" => ConnectorErrorType::BusinessError,
"parameter_invalid" => ConnectorErrorType::UserError,
"password_invalid" => ConnectorErrorType::UserError,
"payment_expired" => ConnectorErrorType::BusinessError,
"payment_invalid" => ConnectorErrorType::BusinessError,
"payment_method_invalid" => ConnectorErrorType::UserError,
"payment_source_required" => ConnectorErrorType::UserError,
"payment_type_invalid" => ConnectorErrorType::UserError,
"phone_number_invalid" => ConnectorErrorType::UserError,
"phone_number_length_invalid" => ConnectorErrorType::UserError,
"previous_payment_id_invalid" => ConnectorErrorType::BusinessError,
"recipient_account_number_invalid" => ConnectorErrorType::BusinessError,
"recipient_account_number_required" => ConnectorErrorType::UserError,
"recipient_dob_required" => ConnectorErrorType::UserError,
"recipient_last_name_required" => ConnectorErrorType::UserError,
"recipient_zip_invalid" => ConnectorErrorType::UserError,
"recipient_zip_required" => ConnectorErrorType::UserError,
"recurring_plan_exists" => ConnectorErrorType::BusinessError,
"recurring_plan_not_exist" => ConnectorErrorType::BusinessError,
"recurring_plan_removal_failed" => ConnectorErrorType::BusinessError,
"request_invalid" => ConnectorErrorType::UserError,
"request_json_invalid" => ConnectorErrorType::UserError,
"risk_enabled_required" => ConnectorErrorType::BusinessError,
"server_api_not_allowed" => ConnectorErrorType::TechnicalError,
"source_email_invalid" => ConnectorErrorType::UserError,
"source_email_required" => ConnectorErrorType::UserError,
"source_id_invalid" => ConnectorErrorType::BusinessError,
"source_id_or_email_required" => ConnectorErrorType::UserError,
"source_id_required" => ConnectorErrorType::UserError,
"source_id_unknown" => ConnectorErrorType::BusinessError,
"source_invalid" => ConnectorErrorType::BusinessError,
"source_or_destination_required" => ConnectorErrorType::BusinessError,
"source_token_invalid" => ConnectorErrorType::BusinessError,
"source_token_required" => ConnectorErrorType::UserError,
"source_token_type_required" => ConnectorErrorType::UserError,
"source_token_type_invalid" => ConnectorErrorType::BusinessError,
"source_type_required" => ConnectorErrorType::UserError,
"sub_entities_count_invalid" => ConnectorErrorType::BusinessError,
"success_url_invalid" => ConnectorErrorType::BusinessError,
"3ds_malfunction" => ConnectorErrorType::TechnicalError,
"3ds_not_configured" => ConnectorErrorType::BusinessError,
"3ds_not_enabled_for_card" => ConnectorErrorType::BusinessError,
"3ds_not_supported" => ConnectorErrorType::BusinessError,
"3ds_payment_required" => ConnectorErrorType::BusinessError,
"token_expired" => ConnectorErrorType::BusinessError,
"token_in_use" => ConnectorErrorType::BusinessError,
"token_invalid" => ConnectorErrorType::BusinessError,
"token_required" => ConnectorErrorType::UserError,
"token_type_required" => ConnectorErrorType::UserError,
"token_used" => ConnectorErrorType::BusinessError,
"void_amount_invalid" => ConnectorErrorType::BusinessError,
"wallet_id_invalid" => ConnectorErrorType::BusinessError,
"zip_invalid" => ConnectorErrorType::UserError,
"processing_key_required" => ConnectorErrorType::BusinessError,
"processing_value_required" => ConnectorErrorType::BusinessError,
"3ds_version_invalid" => ConnectorErrorType::BusinessError,
"3ds_version_not_supported" => ConnectorErrorType::BusinessError,
"processing_error" => ConnectorErrorType::TechnicalError,
"service_unavailable" => ConnectorErrorType::TechnicalError,
"token_type_invalid" => ConnectorErrorType::UserError,
"token_data_invalid" => ConnectorErrorType::UserError,
_ => ConnectorErrorType::UnknownError,
}
}
}
static CHECKOUT_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> =
LazyLock::new(|| {
let supported_capture_methods = vec![
enums::CaptureMethod::Automatic,
enums::CaptureMethod::Manual,
enums::CaptureMethod::SequentialAutomatic,
enums::CaptureMethod::ManualMultiple,
];
let supported_card_network = vec![
common_enums::CardNetwork::AmericanExpress,
common_enums::CardNetwork::CartesBancaires,
common_enums::CardNetwork::DinersClub,
common_enums::CardNetwork::Discover,
common_enums::CardNetwork::JCB,
common_enums::CardNetwork::Mastercard,
common_enums::CardNetwork::Visa,
common_enums::CardNetwork::UnionPay,
];
let mut checkout_supported_payment_methods = SupportedPaymentMethods::new();
checkout_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Credit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::Supported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
checkout_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Debit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::Supported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
checkout_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
enums::PaymentMethodType::GooglePay,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
checkout_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
enums::PaymentMethodType::ApplePay,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
checkout_supported_payment_methods
});
static CHECKOUT_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Checkout",
description:
"Checkout.com is a British multinational financial technology company that processes payments for other companies.",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: enums::ConnectorIntegrationStatus::Live,
};
static CHECKOUT_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 3] = [
enums::EventClass::Payments,
enums::EventClass::Refunds,
enums::EventClass::Disputes,
];
impl ConnectorSpecifications for Checkout {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&CHECKOUT_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*CHECKOUT_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&CHECKOUT_SUPPORTED_WEBHOOK_FLOWS)
}
}
|
crates/hyperswitch_connectors/src/connectors/checkout.rs#chunk1
|
hyperswitch_connectors
|
chunk
| 4,713
| null | null | null | null | null | null | null | null | null | null | null | null | null |
pub(crate) async fn shutdown_listener(&self, mut rx: mpsc::Receiver<()
|
crates/drainer/src/handler.rs
|
drainer
|
function_signature
| 19
|
rust
| null | null | null | null |
shutdown_listener
| null | null | null | null | null | null | null |
impl MasterKeyInterface for MockDb {
fn get_master_key(&self) -> &[u8] {
&[
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25, 26, 27, 28, 29, 30, 31, 32,
]
}
}
|
crates/router/src/db.rs
|
router
|
impl_block
| 151
|
rust
| null |
MockDb
|
MasterKeyInterface for
|
impl MasterKeyInterface for for MockDb
| null | null | null | null | null | null | null | null |
pub struct CeleroCustomer {
id: Option<CustomerId>,
payment_method_id: Option<String>,
}
|
crates/hyperswitch_connectors/src/connectors/celero/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 22
|
rust
|
CeleroCustomer
| null | null | null | null | null | null | null | null | null | null | null |
pub async fn payout_create_db_entries(
_state: &SessionState,
_merchant_context: &domain::MerchantContext,
_req: &payouts::PayoutCreateRequest,
_payout_id: &str,
_profile_id: &str,
_stored_payout_method_data: Option<&payouts::PayoutMethodData>,
_locale: &str,
_customer: Option<&domain::Customer>,
_payment_method: Option<PaymentMethod>,
) -> RouterResult<PayoutData> {
todo!()
}
|
crates/router/src/core/payouts.rs
|
router
|
function_signature
| 118
|
rust
| null | null | null | null |
payout_create_db_entries
| null | null | null | null | null | null | null |
OpenAPI Block Path: components.schemas.CardDiscovery
{
"type": "string",
"description": "Indicates the method by which a card is discovered during a payment",
"enum": [
"manual",
"saved_card",
"click_to_pay"
]
}
|
./hyperswitch/api-reference/v1/openapi_spec_v1.json
| null |
openapi_block
| 61
|
.json
| null | null | null | null | null |
openapi_spec
|
components
|
[
"schemas",
"CardDiscovery"
] | null | null | null | null |
/// fn set_response_body
pub fn set_response_body<T: Serialize>(&mut self, response: &T) {
match masking::masked_serialize(response) {
Ok(masked) => {
self.response = Some(masked.to_string());
}
Err(er) => self.set_error(json!({"error": er.to_string()})),
}
}
|
crates/hyperswitch_interfaces/src/events/routing_api_logs.rs
|
hyperswitch_interfaces
|
function_signature
| 75
|
rust
| null | null | null | null |
set_response_body
| null | null | null | null | null | null | null |
pub struct TokenizePaymentMethodRequest {
pub payment_method_id: String,
pub card_cvc: Option<masking::Secret<String>>,
}
|
crates/hyperswitch_domain_models/src/bulk_tokenization.rs
|
hyperswitch_domain_models
|
struct_definition
| 31
|
rust
|
TokenizePaymentMethodRequest
| null | null | null | null | null | null | null | null | null | null | null |
pub struct ToggleKVResponse {
/// The identifier for the Merchant Account
#[schema(max_length = 255, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = String)]
pub merchant_id: id_type::MerchantId,
/// Status of KV for the specific merchant
#[schema(example = true)]
pub kv_enabled: bool,
}
|
crates/api_models/src/admin.rs
|
api_models
|
struct_definition
| 90
|
rust
|
ToggleKVResponse
| null | null | null | null | null | null | null | null | null | null | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.