text stringlengths 70 351k | source stringclasses 4 values |
|---|---|
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/forte.rs<|crate|> router<|connector|> forte anchor=get_payment_data kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/tests/connectors/forte.rs" role="context" start="44" end="52">
fn get_payment_data() -> Option<types::PaymentsAuthorizeData> {
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_number: CardNumber::from_str("4111111111111111").unwrap(),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
})
}
<file_sep path="hyperswitch/crates/router/tests/connectors/forte.rs" role="context" start="43" end="43">
use common_utils::types::MinorUnit;
use router::types::{self, api, domain, storage::enums};
<file_sep path="hyperswitch/crates/router/tests/connectors/forte.rs" role="context" start="85" end="91">
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);
}
<file_sep path="hyperswitch/crates/router/tests/connectors/forte.rs" role="context" start="54" end="80">
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::IN),
..Default::default()
}),
phone: Some(PhoneDetails {
number: Some(Secret::new("9123456789".to_string())),
country_code: Some("+91".to_string()),
}),
email: None,
}),
None,
None,
)),
..Default::default()
})
}
<file_sep path="hyperswitch/crates/router/tests/connectors/forte.rs" role="context" start="37" end="39">
fn get_name(&self) -> String {
"forte".to_string()
}
<file_sep path="hyperswitch/crates/router/tests/connectors/forte.rs" role="context" start="28" end="35">
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.forte
.expect("Missing connector authentication configuration")
.into(),
)
}
<file_sep path="hyperswitch/crates/router/tests/connectors/forte.rs" role="context" start="347" end="370">
async fn should_refund_auto_captured_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();
tokio::time::sleep(Duration::from_secs(10)).await;
let refund_connector_metadata = utils::get_connector_metadata(authorize_response.response);
let response = CONNECTOR
.refund_payment(
txn_id,
Some(types::RefundsData {
connector_metadata: refund_connector_metadata,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Pending,
);
}
<file_sep path="hyperswitch/crates/router/tests/connectors/forte.rs" role="context" start="95" end="115">
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 = utils::get_connector_transaction_id(authorize_response.response.clone()).unwrap();
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");
//Status of the Payments is always in Pending State, Forte has to settle the sandbox transaction manually
assert_eq!(response.status, enums::AttemptStatus::Pending);
}
<file_sep path="hyperswitch/crates/router/src/compatibility/stripe/customers/types.rs" role="context" start="202" end="207">
pub struct PaymentMethodData {
pub id: Option<String>,
pub object: &'static str,
pub card: Option<CardDetails>,
pub created: Option<time::PrimitiveDateTime>,
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/bambora.rs<|crate|> router<|connector|> bambora anchor=get_default_payment_authorize_data kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|>
<file_sep path="hyperswitch/crates/router/tests/connectors/bambora.rs" role="context" start="42" end="52">
fn get_default_payment_authorize_data() -> Option<types::PaymentsAuthorizeData> {
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_number: cards::CardNumber::from_str("4030000010001234").unwrap(),
card_exp_year: Secret::new("25".to_string()),
card_cvc: Secret::new("123".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
})
}
<file_sep path="hyperswitch/crates/router/tests/connectors/bambora.rs" role="context" start="41" end="41">
use common_utils::types::MinorUnit;
use masking::Secret;
use router::types::{self, domain, storage::enums};
<file_sep path="hyperswitch/crates/router/tests/connectors/bambora.rs" role="context" start="67" end="73">
async fn should_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(get_default_payment_authorize_data(), None, None)
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
<file_sep path="hyperswitch/crates/router/tests/connectors/bambora.rs" role="context" start="57" end="63">
async fn should_only_authorize_payment() {
let response = CONNECTOR
.authorize_payment(get_default_payment_authorize_data(), None)
.await
.expect("Authorize payment response");
assert_eq!(response.status, enums::AttemptStatus::Authorized);
}
<file_sep path="hyperswitch/crates/router/tests/connectors/bambora.rs" role="context" start="35" end="37">
fn get_name(&self) -> String {
"bambora".to_string()
}
<file_sep path="hyperswitch/crates/router/tests/connectors/bambora.rs" role="context" start="26" end="33">
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.bambora
.expect("Missing connector authentication configuration")
.into(),
)
}
<file_sep path="hyperswitch/crates/router/tests/connectors/bambora.rs" role="context" start="212" end="244">
async fn should_sync_auto_captured_payment() {
let authorize_response = CONNECTOR
.make_payment(get_default_payment_authorize_data(), None)
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
assert_ne!(txn_id, None, "Empty connector transaction id");
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: None,
payment_method_type: None,
currency: enums::Currency::USD,
payment_experience: None,
integrity_object: None,
amount: MinorUnit::new(100),
..Default::default()
}),
None,
)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Charged,);
}
<file_sep path="hyperswitch/crates/router/tests/connectors/bambora.rs" role="context" start="128" end="142">
async fn should_void_authorized_payment() {
let response = CONNECTOR
.authorize_and_void_payment(
get_default_payment_authorize_data(),
Some(types::PaymentsCancelData {
connector_transaction_id: String::from(""),
cancellation_reason: Some("requested_by_customer".to_string()),
..Default::default()
}),
None,
)
.await
.expect("Void payment response");
assert_eq!(response.status, enums::AttemptStatus::Voided);
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/forte.rs<|crate|> router<|connector|> forte anchor=get_default_payment_info kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/tests/connectors/forte.rs" role="context" start="54" end="80">
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::IN),
..Default::default()
}),
phone: Some(PhoneDetails {
number: Some(Secret::new("9123456789".to_string())),
country_code: Some("+91".to_string()),
}),
email: None,
}),
None,
None,
)),
..Default::default()
})
}
<file_sep path="hyperswitch/crates/router/tests/connectors/forte.rs" role="context" start="53" end="53">
use common_utils::types::MinorUnit;
use hyperswitch_domain_models::address::{Address, AddressDetails, PhoneDetails};
use masking::Secret;
use router::types::{self, api, domain, storage::enums};
<file_sep path="hyperswitch/crates/router/tests/connectors/forte.rs" role="context" start="95" end="115">
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 = utils::get_connector_transaction_id(authorize_response.response.clone()).unwrap();
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");
//Status of the Payments is always in Pending State, Forte has to settle the sandbox transaction manually
assert_eq!(response.status, enums::AttemptStatus::Pending);
}
<file_sep path="hyperswitch/crates/router/tests/connectors/forte.rs" role="context" start="85" end="91">
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);
}
<file_sep path="hyperswitch/crates/router/tests/connectors/forte.rs" role="context" start="44" end="52">
fn get_payment_data() -> Option<types::PaymentsAuthorizeData> {
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_number: CardNumber::from_str("4111111111111111").unwrap(),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
})
}
<file_sep path="hyperswitch/crates/router/tests/connectors/forte.rs" role="context" start="37" end="39">
fn get_name(&self) -> String {
"forte".to_string()
}
<file_sep path="hyperswitch/crates/router/tests/connectors/forte.rs" role="context" start="144" end="174">
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 = utils::get_connector_transaction_id(authorize_response.response);
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
encoded_data: None,
capture_method: None,
sync_type: types::SyncRequestType::SinglePaymentSync,
connector_meta: None,
mandate_id: None,
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,);
}
<file_sep path="hyperswitch/crates/router/tests/connectors/forte.rs" role="context" start="284" end="302">
async fn should_sync_manually_captured_refund() {
let refund_response = CONNECTOR
.capture_payment_and_refund(None, None, 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,
);
}
<file_sep path="hyperswitch/crates/router/tests/macros.rs" role="context" start="17" end="21">
struct Address {
line1: String,
zip: String,
city: String,
}
<file_sep path="hyperswitch/migrations/2025-02-06-111828_drop_int_id_column_accross_database/up.sql" role="context" start="20" end="36">
------------------------ Payment Attempt -----------------------
ALTER TABLE payment_attempt DROP COLUMN id;
------------------------ Payment Methods -----------------------
ALTER TABLE payment_methods DROP COLUMN IF EXISTS id;
------------------------ Address -----------------------
ALTER TABLE address DROP COLUMN IF EXISTS id;
------------------------ Dispute -----------------------
ALTER TABLE dispute DROP COLUMN IF EXISTS id;
------------------------ Mandate -----------------------
ALTER TABLE mandate DROP COLUMN IF EXISTS id;
------------------------ Refund -----------------------
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/adyen.rs<|crate|> router<|connector|> adyen anchor=get_payment_info kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|>
<file_sep path="hyperswitch/crates/router/tests/connectors/adyen.rs" role="context" start="52" end="79">
fn get_payment_info() -> Option<PaymentInfo> {
Some(PaymentInfo {
address: Some(PaymentAddress::new(
None,
Some(Address {
address: Some(AddressDetails {
country: Some(api_models::enums::CountryAlpha2::US),
state: Some(Secret::new("California".to_string())),
city: Some("San Francisco".to_string()),
zip: Some(Secret::new("94122".to_string())),
line1: Some(Secret::new("1467".to_string())),
line2: Some(Secret::new("Harrison Street".to_string())),
line3: None,
first_name: Some(Secret::new("John".to_string())),
last_name: Some(Secret::new("Dough".to_string())),
}),
phone: Some(PhoneDetails {
number: Some(Secret::new("9123456789".to_string())),
country_code: Some("+351".to_string()),
}),
email: None,
}),
None,
None,
)),
..Default::default()
})
}
<file_sep path="hyperswitch/crates/router/tests/connectors/adyen.rs" role="context" start="51" end="51">
use hyperswitch_domain_models::address::{Address, AddressDetails, PhoneDetails};
use masking::Secret;
use router::types::{self, storage::enums, PaymentAddress};
<file_sep path="hyperswitch/crates/router/tests/connectors/adyen.rs" role="context" start="135" end="187">
fn get_payment_authorize_data(
card_number: &str,
card_exp_month: &str,
card_exp_year: &str,
card_cvc: &str,
capture_method: enums::CaptureMethod,
) -> Option<types::PaymentsAuthorizeData> {
Some(types::PaymentsAuthorizeData {
amount: 3500,
currency: enums::Currency::USD,
payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card {
card_number: cards::CardNumber::from_str(card_number).unwrap(),
card_exp_month: Secret::new(card_exp_month.to_string()),
card_exp_year: Secret::new(card_exp_year.to_string()),
card_cvc: Secret::new(card_cvc.to_string()),
card_issuer: None,
card_network: None,
card_type: None,
card_issuing_country: None,
bank_code: None,
nick_name: Some(Secret::new("nick_name".into())),
card_holder_name: Some(Secret::new("card holder name".into())),
}),
confirm: true,
statement_descriptor_suffix: None,
statement_descriptor: None,
setup_future_usage: None,
mandate_id: None,
off_session: None,
setup_mandate_details: None,
capture_method: Some(capture_method),
browser_info: None,
order_details: None,
order_category: None,
email: None,
customer_name: None,
payment_experience: None,
payment_method_type: None,
session_token: None,
enrolled_for_3ds: false,
related_transaction_id: None,
router_return_url: Some(String::from("http://localhost:8080")),
webhook_url: None,
complete_authorize_url: None,
customer_id: None,
surcharge_details: None,
request_incremental_authorization: false,
metadata: None,
authentication_data: None,
customer_acceptance: None,
..utils::PaymentAuthorizeType::default().0
})
}
<file_sep path="hyperswitch/crates/router/tests/connectors/adyen.rs" role="context" start="82" end="133">
fn get_payout_info(payout_type: enums::PayoutType) -> Option<PaymentInfo> {
use common_utils::pii::Email;
Some(PaymentInfo {
currency: Some(enums::Currency::EUR),
address: Some(PaymentAddress::new(
None,
Some(Address {
address: Some(AddressDetails {
country: Some(api_models::enums::CountryAlpha2::US),
state: Some(Secret::new("California".to_string())),
city: Some("San Francisco".to_string()),
zip: Some(Secret::new("94122".to_string())),
line1: Some(Secret::new("1467".to_string())),
line2: Some(Secret::new("Harrison Street".to_string())),
..Default::default()
}),
phone: None,
email: None,
}),
None,
None,
)),
payout_method_data: match payout_type {
enums::PayoutType::Card => Some(types::api::PayoutMethodData::Card(
types::api::payouts::CardPayout {
card_number: cards::CardNumber::from_str("4111111111111111").unwrap(),
expiry_month: Secret::new("3".to_string()),
expiry_year: Secret::new("2030".to_string()),
card_holder_name: Some(Secret::new("John Doe".to_string())),
},
)),
enums::PayoutType::Bank => Some(types::api::PayoutMethodData::Bank(
types::api::payouts::BankPayout::Sepa(types::api::SepaBankTransfer {
iban: "NL46TEST0136169112".to_string().into(),
bic: Some("ABNANL2A".to_string().into()),
bank_name: Some("Deutsche Bank".to_string()),
bank_country_code: Some(enums::CountryAlpha2::NL),
bank_city: Some("Amsterdam".to_string()),
}),
)),
enums::PayoutType::Wallet => Some(types::api::PayoutMethodData::Wallet(
types::api::payouts::WalletPayout::Paypal(api_models::payouts::Paypal {
email: Email::from_str("EmailUsedForPayPalAccount@example.com").ok(),
telephone_number: None,
paypal_id: None,
}),
)),
},
..Default::default()
})
}
<file_sep path="hyperswitch/crates/router/tests/connectors/adyen.rs" role="context" start="46" end="48">
fn get_name(&self) -> String {
"adyen".to_string()
}
<file_sep path="hyperswitch/crates/router/tests/connectors/adyen.rs" role="context" start="37" end="44">
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.adyen_uk
.expect("Missing connector authentication configuration")
.into(),
)
}
<file_sep path="hyperswitch/crates/router/tests/connectors/adyen.rs" role="context" start="214" end="230">
async fn should_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(
AdyenTest::get_payment_authorize_data(
"370000000000002",
"03",
"2030",
"7373",
enums::CaptureMethod::Manual,
),
None,
AdyenTest::get_payment_info(),
)
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Pending);
}
<file_sep path="hyperswitch/crates/router/tests/connectors/adyen.rs" role="context" start="383" end="406">
async fn should_partially_refund_succeeded_payment() {
let refund_response = CONNECTOR
.make_payment_and_refund(
AdyenTest::get_payment_authorize_data(
"4293189100000008",
"03",
"2030",
"737",
enums::CaptureMethod::Automatic,
),
Some(types::RefundsData {
refund_amount: 500,
reason: Some("CUSTOMER REQUEST".to_string()),
..utils::PaymentRefundType::default().0
}),
AdyenTest::get_payment_info(),
)
.await
.unwrap();
assert_eq!(
refund_response.response.unwrap().refund_status,
enums::RefundStatus::Pending,
);
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/cybersource.rs<|crate|> router<|connector|> cybersource anchor=get_default_payment_authorize_data kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|>
<file_sep path="hyperswitch/crates/router/tests/connectors/cybersource.rs" role="context" start="64" end="70">
fn get_default_payment_authorize_data() -> Option<types::PaymentsAuthorizeData> {
Some(types::PaymentsAuthorizeData {
currency: enums::Currency::USD,
email: Some(Email::from_str("abc@gmail.com").unwrap()),
..PaymentAuthorizeType::default().0
})
}
<file_sep path="hyperswitch/crates/router/tests/connectors/cybersource.rs" role="context" start="63" end="63">
use router::types::{self, api, domain, storage::enums};
<file_sep path="hyperswitch/crates/router/tests/connectors/cybersource.rs" role="context" start="83" end="92">
async fn should_make_payment() {
let response = Cybersource {}
.make_payment(
get_default_payment_authorize_data(),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Pending);
}
<file_sep path="hyperswitch/crates/router/tests/connectors/cybersource.rs" role="context" start="72" end="81">
async fn should_only_authorize_payment() {
let response = Cybersource {}
.authorize_payment(
get_default_payment_authorize_data(),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Authorized);
}
<file_sep path="hyperswitch/crates/router/tests/connectors/cybersource.rs" role="context" start="37" end="63">
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::IN),
..Default::default()
}),
phone: Some(PhoneDetails {
number: Some(Secret::new("9123456789".to_string())),
country_code: Some("+91".to_string()),
}),
email: None,
}),
None,
None,
)),
..Default::default()
})
}
<file_sep path="hyperswitch/crates/router/tests/connectors/cybersource.rs" role="context" start="32" end="34">
fn get_name(&self) -> String {
"cybersource".to_string()
}
<file_sep path="hyperswitch/crates/router/tests/connectors/cybersource.rs" role="context" start="183" end="199">
async fn should_fail_payment_for_invalid_exp_year() {
let response = Cybersource {}
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_year: Secret::new("2022".to_string()),
..utils::CCardType::default().0
}),
..get_default_payment_authorize_data().unwrap()
}),
get_default_payment_info(),
)
.await
.unwrap();
let x = response.response.unwrap_err();
assert_eq!(x.message, "Decline - Expired card. You might also receive this if the expiration date you provided does not match the date the issuing bank has on file.",);
}
<file_sep path="hyperswitch/crates/router/tests/connectors/cybersource.rs" role="context" start="299" end="316">
async fn should_partially_refund_succeeded_payment() {
let connector = Cybersource {};
let refund_response = connector
.make_payment_and_refund(
get_default_payment_authorize_data(),
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::Pending,
);
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/nuvei.rs<|crate|> router<|connector|> nuvei anchor=get_payment_data kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/tests/connectors/nuvei.rs" role="context" start="42" end="50">
fn get_payment_data() -> Option<types::PaymentsAuthorizeData> {
Some(types::PaymentsAuthorizeData {
payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card {
card_number: cards::CardNumber::from_str("4444 3333 2222 1111").unwrap(),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
})
}
<file_sep path="hyperswitch/crates/router/tests/connectors/nuvei.rs" role="context" start="41" end="41">
use router::types::{self, storage::enums};
<file_sep path="hyperswitch/crates/router/tests/connectors/nuvei.rs" role="context" start="65" end="71">
async fn should_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(get_payment_data(), None, None)
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
<file_sep path="hyperswitch/crates/router/tests/connectors/nuvei.rs" role="context" start="55" end="61">
async fn should_only_authorize_payment() {
let response = CONNECTOR
.authorize_payment(get_payment_data(), None)
.await
.expect("Authorize payment response");
assert_eq!(response.status, enums::AttemptStatus::Authorized);
}
<file_sep path="hyperswitch/crates/router/tests/connectors/nuvei.rs" role="context" start="35" end="37">
fn get_name(&self) -> String {
"nuvei".to_string()
}
<file_sep path="hyperswitch/crates/router/tests/connectors/nuvei.rs" role="context" start="26" end="33">
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.nuvei
.expect("Missing connector authentication configuration")
.into(),
)
}
<file_sep path="hyperswitch/crates/router/tests/connectors/nuvei.rs" role="context" start="92" end="115">
async fn should_sync_authorized_payment() {
let authorize_response = CONNECTOR
.authorize_payment(get_payment_data(), None)
.await
.expect("Authorize payment response");
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
connector_meta: Some(json!({
"session_token": authorize_response.session_token.unwrap()
})),
..Default::default()
}),
None,
)
.await
.expect("PSync response");
assert_eq!(response.status, enums::AttemptStatus::Authorized,);
}
<file_sep path="hyperswitch/crates/router/tests/connectors/nuvei.rs" role="context" start="138" end="147">
async fn should_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(get_payment_data(), None, None, None)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
<file_sep path="hyperswitch/crates/router/src/compatibility/stripe/customers/types.rs" role="context" start="202" end="207">
pub struct PaymentMethodData {
pub id: Option<String>,
pub object: &'static str,
pub card: Option<CardDetails>,
pub created: Option<time::PrimitiveDateTime>,
}
<file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="2504" end="2539">
pub enum PaymentMethodData {
#[schema(title = "Card")]
Card(Card),
#[schema(title = "CardRedirect")]
CardRedirect(CardRedirectData),
#[schema(title = "Wallet")]
Wallet(WalletData),
#[schema(title = "PayLater")]
PayLater(PayLaterData),
#[schema(title = "BankRedirect")]
BankRedirect(BankRedirectData),
#[schema(title = "BankDebit")]
BankDebit(BankDebitData),
#[schema(title = "BankTransfer")]
BankTransfer(Box<BankTransferData>),
#[schema(title = "RealTimePayment")]
RealTimePayment(Box<RealTimePaymentData>),
#[schema(title = "Crypto")]
Crypto(CryptoData),
#[schema(title = "MandatePayment")]
MandatePayment,
#[schema(title = "Reward")]
Reward,
#[schema(title = "Upi")]
Upi(UpiData),
#[schema(title = "Voucher")]
Voucher(VoucherData),
#[schema(title = "GiftCard")]
GiftCard(Box<GiftCardData>),
#[schema(title = "CardToken")]
CardToken(CardToken),
#[schema(title = "OpenBanking")]
OpenBanking(OpenBankingData),
#[schema(title = "MobilePayment")]
MobilePayment(MobilePaymentData),
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/nuvei.rs<|crate|> router<|connector|> nuvei anchor=get_payment_data kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|>
<file_sep path="hyperswitch/crates/router/tests/connectors/nuvei.rs" role="context" start="42" end="50">
fn get_payment_data() -> Option<types::PaymentsAuthorizeData> {
Some(types::PaymentsAuthorizeData {
payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card {
card_number: cards::CardNumber::from_str("4444 3333 2222 1111").unwrap(),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
})
}
<file_sep path="hyperswitch/crates/router/tests/connectors/nuvei.rs" role="context" start="41" end="41">
use router::types::{self, storage::enums};
<file_sep path="hyperswitch/crates/router/tests/connectors/nuvei.rs" role="context" start="65" end="71">
async fn should_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(get_payment_data(), None, None)
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
<file_sep path="hyperswitch/crates/router/tests/connectors/nuvei.rs" role="context" start="55" end="61">
async fn should_only_authorize_payment() {
let response = CONNECTOR
.authorize_payment(get_payment_data(), None)
.await
.expect("Authorize payment response");
assert_eq!(response.status, enums::AttemptStatus::Authorized);
}
<file_sep path="hyperswitch/crates/router/tests/connectors/nuvei.rs" role="context" start="35" end="37">
fn get_name(&self) -> String {
"nuvei".to_string()
}
<file_sep path="hyperswitch/crates/router/tests/connectors/nuvei.rs" role="context" start="26" end="33">
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.nuvei
.expect("Missing connector authentication configuration")
.into(),
)
}
<file_sep path="hyperswitch/crates/router/tests/connectors/nuvei.rs" role="context" start="92" end="115">
async fn should_sync_authorized_payment() {
let authorize_response = CONNECTOR
.authorize_payment(get_payment_data(), None)
.await
.expect("Authorize payment response");
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
connector_meta: Some(json!({
"session_token": authorize_response.session_token.unwrap()
})),
..Default::default()
}),
None,
)
.await
.expect("PSync response");
assert_eq!(response.status, enums::AttemptStatus::Authorized,);
}
<file_sep path="hyperswitch/crates/router/tests/connectors/nuvei.rs" role="context" start="138" end="147">
async fn should_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(get_payment_data(), None, None, None)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payments/transformers.rs<|crate|> router anchor=foreign_from kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/payments/transformers.rs" role="context" start="4678" end="4707">
fn foreign_from(req: (Self, Option<&api_models::payments::AdditionalPaymentData>)) -> Self {
let (payment_method_type, additional_pm_data) = req;
additional_pm_data
.and_then(|pm_data| {
if let api_models::payments::AdditionalPaymentData::Card(card_info) = pm_data {
card_info.card_type.as_ref().and_then(|card_type_str| {
api_models::enums::PaymentMethodType::from_str(&card_type_str.to_lowercase()).map_err(|err| {
crate::logger::error!(
"Err - {:?}\nInvalid card_type value found in BIN DB - {:?}",
err,
card_type_str,
);
}).ok()
})
} else {
None
}
})
.map_or(payment_method_type, |card_type_in_bin_store| {
if let Some(card_type_in_req) = payment_method_type {
if card_type_in_req != card_type_in_bin_store {
crate::logger::info!(
"Mismatch in card_type\nAPI request - {}; BIN lookup - {}\nOverriding with {}",
card_type_in_req, card_type_in_bin_store, card_type_in_bin_store,
);
}
}
Some(card_type_in_bin_store)
})
}
<file_sep path="hyperswitch/crates/router/src/core/payments/transformers.rs" role="context" start="4677" end="4677">
use api_models::payments::{
Address, ConnectorMandateReferenceId, CustomerDetails, CustomerDetailsResponse, FrmMessage,
RequestSurchargeDetails,
};
use hyperswitch_domain_models::{payments::payment_intent::CustomerData, router_request_types};
use crate::{
configs::settings::ConnectorRequestReferenceIdConfig,
core::{
errors::{self, RouterResponse, RouterResult},
payments::{self, helpers},
utils as core_utils,
},
headers::X_PAYMENT_CONFIRM_SOURCE,
routes::{metrics, SessionState},
services::{self, RedirectForm},
types::{
self,
api::{self, ConnectorTransactionId},
domain,
storage::{self, enums},
transformers::{ForeignFrom, ForeignInto, ForeignTryFrom},
MultipleCaptureRequestData,
},
utils::{OptionExt, ValueExt},
};
<file_sep path="hyperswitch/crates/router/src/core/payments/transformers.rs" role="context" start="4663" end="4672">
fn foreign_from(value: diesel_models::ConnectorTokenDetails) -> Self {
let connector_token_request_reference_id =
value.connector_token_request_reference_id.clone();
value.connector_mandate_id.clone().map(|mandate_id| {
api_models::payments::ConnectorTokenDetails {
token: mandate_id,
connector_token_request_reference_id,
}
})
}
<file_sep path="hyperswitch/crates/router/src/core/payments/transformers.rs" role="context" start="4648" end="4656">
fn foreign_from(value: ConnectorMandateReferenceId) -> Self {
Self {
connector_mandate_id: value.get_connector_mandate_id(),
payment_method_id: value.get_payment_method_id(),
mandate_metadata: value.get_mandate_metadata(),
connector_mandate_request_reference_id: value
.get_connector_mandate_request_reference_id(),
}
}
<file_sep path="hyperswitch/crates/router/src/core/payments/transformers.rs" role="context" start="2890" end="2931">
fn foreign_from((pi, pa): (storage::PaymentIntent, Option<storage::PaymentAttempt>)) -> Self {
Self {
id: pi.id,
merchant_id: pi.merchant_id,
profile_id: pi.profile_id,
customer_id: pi.customer_id,
payment_method_id: pa.as_ref().and_then(|p| p.payment_method_id.clone()),
status: pi.status,
amount: api_models::payments::PaymentAmountDetailsResponse::foreign_from((
&pi.amount_details,
pa.as_ref().map(|p| &p.amount_details),
)),
created: pi.created_at,
payment_method_type: pa.as_ref().and_then(|p| p.payment_method_type.into()),
payment_method_subtype: pa.as_ref().and_then(|p| p.payment_method_subtype.into()),
connector: pa.as_ref().and_then(|p| p.connector.clone()),
merchant_connector_id: pa.as_ref().and_then(|p| p.merchant_connector_id.clone()),
customer: None,
merchant_reference_id: pi.merchant_reference_id,
connector_payment_id: pa.as_ref().and_then(|p| p.connector_payment_id.clone()),
connector_response_reference_id: pa
.as_ref()
.and_then(|p| p.connector_response_reference_id.clone()),
metadata: pi.metadata,
description: pi.description.map(|val| val.get_string_repr().to_string()),
authentication_type: pi.authentication_type,
capture_method: Some(pi.capture_method),
setup_future_usage: Some(pi.setup_future_usage),
attempt_count: pi.attempt_count,
error: pa
.as_ref()
.and_then(|p| p.error.as_ref())
.map(api_models::payments::ErrorDetails::foreign_from),
cancellation_reason: pa.as_ref().and_then(|p| p.cancellation_reason.clone()),
order_details: None,
return_url: pi.return_url,
statement_descriptor: pi.statement_descriptor,
allowed_payment_method_types: pi.allowed_payment_method_types,
authorization_count: pi.authorization_count,
modified_at: pa.as_ref().map(|p| p.modified_at),
}
}
<file_sep path="hyperswitch/crates/router/src/core/payments/transformers.rs" role="context" start="3769" end="3847">
fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> {
let payment_data = additional_data.payment_data.clone();
let order_details = additional_data
.payment_data
.payment_intent
.order_details
.map(|order_details| {
order_details
.iter()
.map(|data| {
data.to_owned()
.parse_value("OrderDetailsWithAmount")
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "OrderDetailsWithAmount",
})
.attach_printable("Unable to parse OrderDetailsWithAmount")
})
.collect::<Result<Vec<_>, _>>()
})
.transpose()?;
let surcharge_amount = payment_data
.surcharge_details
.as_ref()
.map(|surcharge_details| surcharge_details.get_total_surcharge_amount())
.unwrap_or_default();
let amount = payment_data.payment_intent.amount;
let shipping_cost = payment_data
.payment_intent
.shipping_cost
.unwrap_or_default();
// net_amount here would include amount, surcharge_amount and shipping_cost
let net_amount = amount + surcharge_amount + shipping_cost;
let required_amount_type = StringMajorUnitForConnector;
let apple_pay_amount = required_amount_type
.convert(net_amount, payment_data.currency)
.change_context(errors::ApiErrorResponse::PreconditionFailed {
message: "Failed to convert amount to string major unit for applePay".to_string(),
})?;
let apple_pay_recurring_details = payment_data
.payment_intent
.feature_metadata
.map(|feature_metadata| {
feature_metadata
.parse_value::<diesel_models::types::FeatureMetadata>("FeatureMetadata")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed parsing FeatureMetadata")
})
.transpose()?
.and_then(|feature_metadata| feature_metadata.apple_pay_recurring_details)
.map(|apple_pay_recurring_details| {
ForeignFrom::foreign_from((apple_pay_recurring_details, apple_pay_amount))
});
Ok(Self {
amount: net_amount.get_amount_as_i64(), //need to change once we move to connector module
minor_amount: amount,
currency: payment_data.currency,
country: payment_data.address.get_payment_method_billing().and_then(
|billing_address| {
billing_address
.address
.as_ref()
.and_then(|address| address.country)
},
),
order_details,
email: payment_data.email,
surcharge_details: payment_data.surcharge_details,
apple_pay_recurring_details,
})
}
<file_sep path="hyperswitch/crates/router/src/connector/payone/transformers.rs" role="context" start="117" end="121">
pub struct Card {
card_holder_name: Secret<String>,
card_number: CardNumber,
expiry_date: Secret<String>,
}
<file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="1075" end="1083">
pub struct Card {
pub card_number: CardNumber,
pub name_on_card: Option<masking::Secret<String>>,
pub card_exp_month: masking::Secret<String>,
pub card_exp_year: masking::Secret<String>,
pub card_brand: Option<String>,
pub card_isin: Option<String>,
pub nick_name: Option<String>,
}
<file_sep path="hyperswitch/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/event.test.js" role="context" start="61" end="78">
"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.",
);
}
// Response body should have value "succeeded" for "status"
if (jsonData?.status) {
pm.test(
"[POST]::/payments - Content check if value for 'status' matches 'succeeded'",
function () {
pm.expect(jsonData.status).to.eql("succeeded");
},
);
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/nmi/transformers.rs<|crate|> router anchor=new kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/connector/nmi/transformers.rs" role="context" start="435" end="449">
pub fn new(metadata: &serde_json::Value) -> Self {
let metadata_as_string = metadata.to_string();
let hash_map: std::collections::BTreeMap<String, serde_json::Value> =
serde_json::from_str(&metadata_as_string).unwrap_or(std::collections::BTreeMap::new());
let inner = hash_map
.into_iter()
.enumerate()
.map(|(index, (hs_key, hs_value))| {
let nmi_key = format!("merchant_defined_field_{}", index + 1);
let nmi_value = format!("{hs_key}={hs_value}");
(nmi_key, Secret::new(nmi_value))
})
.collect();
Self { inner }
}
<file_sep path="hyperswitch/crates/router/src/connector/nmi/transformers.rs" role="context" start="434" end="434">
use masking::{ExposeInterface, PeekInterface, Secret};
<file_sep path="hyperswitch/crates/router/src/connector/nmi/transformers.rs" role="context" start="531" end="606">
fn try_from(
item: (
&domain::PaymentMethodData,
Option<&types::PaymentsAuthorizeRouterData>,
),
) -> Result<Self, Self::Error> {
let (payment_method_data, router_data) = item;
match payment_method_data {
domain::PaymentMethodData::Card(ref card) => match router_data {
Some(data) => match data.auth_type {
common_enums::AuthenticationType::NoThreeDs => Ok(Self::try_from(card)?),
common_enums::AuthenticationType::ThreeDs => {
Ok(Self::try_from((card, &data.request))?)
}
},
None => Ok(Self::try_from(card)?),
},
domain::PaymentMethodData::Wallet(ref wallet_type) => match wallet_type {
domain::WalletData::GooglePay(ref googlepay_data) => Ok(Self::from(googlepay_data)),
domain::WalletData::ApplePay(ref applepay_data) => Ok(Self::from(applepay_data)),
domain::WalletData::AliPayQr(_)
| domain::WalletData::AliPayRedirect(_)
| domain::WalletData::AliPayHkRedirect(_)
| domain::WalletData::AmazonPayRedirect(_)
| domain::WalletData::MomoRedirect(_)
| domain::WalletData::KakaoPayRedirect(_)
| domain::WalletData::GoPayRedirect(_)
| domain::WalletData::GcashRedirect(_)
| domain::WalletData::ApplePayRedirect(_)
| domain::WalletData::ApplePayThirdPartySdk(_)
| domain::WalletData::DanaRedirect {}
| domain::WalletData::GooglePayRedirect(_)
| domain::WalletData::GooglePayThirdPartySdk(_)
| domain::WalletData::MbWayRedirect(_)
| domain::WalletData::MobilePayRedirect(_)
| domain::WalletData::PaypalRedirect(_)
| domain::WalletData::PaypalSdk(_)
| domain::WalletData::Paze(_)
| domain::WalletData::SamsungPay(_)
| domain::WalletData::TwintRedirect {}
| domain::WalletData::VippsRedirect {}
| domain::WalletData::TouchNGoRedirect(_)
| domain::WalletData::WeChatPayRedirect(_)
| domain::WalletData::WeChatPayQr(_)
| domain::WalletData::CashappQr(_)
| domain::WalletData::SwishQr(_)
| domain::WalletData::Mifinity(_) => {
Err(report!(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("nmi"),
)))
}
},
domain::PaymentMethodData::CardRedirect(_)
| domain::PaymentMethodData::PayLater(_)
| domain::PaymentMethodData::BankRedirect(_)
| domain::PaymentMethodData::BankDebit(_)
| domain::PaymentMethodData::BankTransfer(_)
| domain::PaymentMethodData::Crypto(_)
| domain::PaymentMethodData::MandatePayment
| domain::PaymentMethodData::Reward
| domain::PaymentMethodData::RealTimePayment(_)
| domain::PaymentMethodData::MobilePayment(_)
| domain::PaymentMethodData::Upi(_)
| domain::PaymentMethodData::Voucher(_)
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
| domain::PaymentMethodData::CardToken(_)
| domain::PaymentMethodData::NetworkToken(_)
| domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("nmi"),
)
.into())
}
}
}
<file_sep path="hyperswitch/crates/router/src/connector/nmi/transformers.rs" role="context" start="493" end="521">
fn try_from(
item: &NmiRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let transaction_type = match item.router_data.request.is_auto_capture()? {
true => TransactionType::Sale,
false => TransactionType::Auth,
};
let auth_type: NmiAuthType = (&item.router_data.connector_auth_type).try_into()?;
let amount = item.amount;
let payment_method = PaymentMethod::try_from((
&item.router_data.request.payment_method_data,
Some(item.router_data),
))?;
Ok(Self {
transaction_type,
security_key: auth_type.api_key,
amount,
currency: item.router_data.request.currency,
payment_method,
merchant_defined_field: item
.router_data
.request
.metadata
.as_ref()
.map(NmiMerchantDefinedField::new),
orderid: item.router_data.connector_request_reference_id.clone(),
})
}
<file_sep path="hyperswitch/crates/router/src/connector/nmi/transformers.rs" role="context" start="399" end="411">
fn foreign_from((response, http_code): (NmiCompleteResponse, u16)) -> Self {
Self {
code: response.response_code,
message: response.responsetext.to_owned(),
reason: Some(response.responsetext),
status_code: http_code,
attempt_status: None,
connector_transaction_id: Some(response.transactionid),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
}
}
<file_sep path="hyperswitch/crates/router/src/connector/nmi/transformers.rs" role="context" start="352" end="395">
fn try_from(
item: types::ResponseRouterData<
api::CompleteAuthorize,
NmiCompleteResponse,
types::CompleteAuthorizeData,
types::PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let (response, status) = match item.response.response {
Response::Approved => (
Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::ConnectorTransactionId(
item.response.transactionid,
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.orderid),
incremental_authorization_allowed: None,
charges: None,
}),
if let Some(diesel_models::enums::CaptureMethod::Automatic) =
item.data.request.capture_method
{
enums::AttemptStatus::CaptureInitiated
} else {
enums::AttemptStatus::Authorizing
},
),
Response::Declined | Response::Error => (
Err(types::ErrorResponse::foreign_from((
item.response,
item.http_code,
))),
enums::AttemptStatus::Failure,
),
};
Ok(Self {
status,
response,
..item.data
})
}
<file_sep path="hyperswitch/crates/router/src/connector/nmi/transformers.rs" role="context" start="865" end="902">
fn try_from(
item: types::ResponseRouterData<
api::SetupMandate,
StandardResponse,
T,
types::PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let (response, status) = match item.response.response {
Response::Approved => (
Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::ConnectorTransactionId(
item.response.transactionid.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.orderid),
incremental_authorization_allowed: None,
charges: None,
}),
enums::AttemptStatus::Charged,
),
Response::Declined | Response::Error => (
Err(types::ErrorResponse::foreign_from((
item.response,
item.http_code,
))),
enums::AttemptStatus::Failure,
),
};
Ok(Self {
status,
response,
..item.data
})
}
<file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="1670" end="1670">
type Value = PaymentMethodListRequest;
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/services/authentication.rs<|crate|> router anchor=get_api_key kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="3812" end="3814">
pub fn get_api_key(headers: &HeaderMap) -> RouterResult<&str> {
get_header_value_by_key("api-key".into(), headers)?.get_required_value("api_key")
}
<file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="3811" end="3811">
use std::str::FromStr;
use actix_web::http::header::HeaderMap;
use crate::{
core::{
api_keys,
errors::{self, utils::StorageErrorExt, RouterResult},
},
headers,
routes::app::SessionStateInfo,
services::api,
types::{domain, storage},
utils::OptionExt,
};
pub type AuthenticationDataWithUserId = (AuthenticationData, String);
<file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="3830" end="3843">
pub fn get_id_type_by_key_from_headers<T: FromStr>(
key: String,
headers: &HeaderMap,
) -> RouterResult<Option<T>> {
get_header_value_by_key(key.clone(), headers)?
.map(|str_value| T::from_str(str_value))
.transpose()
.map_err(|_err| {
error_stack::report!(errors::ApiErrorResponse::InvalidDataFormat {
field_name: key,
expected_format: "Valid Id String".to_string(),
})
})
}
<file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="3816" end="3829">
pub fn get_header_value_by_key(key: String, headers: &HeaderMap) -> RouterResult<Option<&str>> {
headers
.get(&key)
.map(|source_str| {
source_str
.to_str()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(format!(
"Failed to convert header value to string for header key: {}",
key
))
})
.transpose()
}
<file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="3799" end="3810">
pub async fn decode_jwt<T>(token: &str, state: &impl SessionStateInfo) -> RouterResult<T>
where
T: serde::de::DeserializeOwned,
{
let conf = state.conf();
let secret = conf.secrets.get_inner().jwt_secret.peek().as_bytes();
let key = DecodingKey::from_secret(secret);
decode::<T>(token, &key, &Validation::new(Algorithm::HS256))
.map(|decoded| decoded.claims)
.change_context(errors::ApiErrorResponse::InvalidJwtToken)
}
<file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="3789" end="3797">
pub fn is_jwt_auth(headers: &HeaderMap) -> bool {
let header_map_struct = HeaderMapStruct::new(headers);
match header_map_struct.get_auth_string_from_header() {
Ok(auth_str) => auth_str.starts_with("Bearer"),
Err(_) => get_cookie_from_header(headers)
.and_then(cookies::get_jwt_from_cookies)
.is_ok(),
}
}
<file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="3777" end="3787">
pub fn is_ephemeral_auth<A: SessionStateInfo + Sync + Send>(
headers: &HeaderMap,
) -> RouterResult<Box<dyn AuthenticateAndFetch<AuthenticationData, A>>> {
let api_key = get_api_key(headers)?;
if !api_key.starts_with("epk") {
Ok(Box::new(HeaderAuth(ApiKeyAuth)))
} else {
Ok(Box::new(EphemeralKeyAuth))
}
}
<file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="3709" end="3742">
pub fn check_client_secret_and_get_auth<T>(
headers: &HeaderMap,
payload: &impl ClientSecretFetch,
) -> RouterResult<(
Box<dyn AuthenticateAndFetch<AuthenticationData, T>>,
api::AuthFlow,
)>
where
T: SessionStateInfo + Sync + Send,
ApiKeyAuth: AuthenticateAndFetch<AuthenticationData, T>,
PublishableKeyAuth: AuthenticateAndFetch<AuthenticationData, T>,
{
let api_key = get_api_key(headers)?;
if api_key.starts_with("pk_") {
payload
.get_client_secret()
.check_value_present("client_secret")
.map_err(|_| errors::ApiErrorResponse::MissingRequiredField {
field_name: "client_secret",
})?;
return Ok((
Box::new(HeaderAuth(PublishableKeyAuth)),
api::AuthFlow::Client,
));
}
if payload.get_client_secret().is_some() {
return Err(errors::ApiErrorResponse::InvalidRequestData {
message: "client_secret is not a valid parameter".to_owned(),
}
.into());
}
Ok((Box::new(HeaderAuth(ApiKeyAuth)), api::AuthFlow::Merchant))
}
<file_sep path="hyperswitch/crates/router/src/core/errors.rs" role="context" start="31" end="31">
pub type RouterResult<T> = CustomResult<T, ApiErrorResponse>;
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/nmi.rs<|crate|> router<|connector|> nmi anchor=get_payment_authorize_data kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|>
<file_sep path="hyperswitch/crates/router/tests/connectors/nmi.rs" role="context" start="39" end="48">
fn get_payment_authorize_data() -> Option<types::PaymentsAuthorizeData> {
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_number: cards::CardNumber::from_str("4111111111111111").unwrap(),
..utils::CCardType::default().0
}),
amount: 2023,
..utils::PaymentAuthorizeType::default().0
})
}
<file_sep path="hyperswitch/crates/router/tests/connectors/nmi.rs" role="context" start="38" end="38">
use router::types::{self, domain, storage::enums};
<file_sep path="hyperswitch/crates/router/tests/connectors/nmi.rs" role="context" start="79" end="124">
async fn should_capture_authorized_payment() {
let response = CONNECTOR
.authorize_payment(get_payment_authorize_data(), None)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Authorizing);
let transaction_id = utils::get_connector_transaction_id(response.response.to_owned()).unwrap();
let sync_response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id.clone(),
),
capture_method: Some(enums::CaptureMethod::Manual),
..Default::default()
}),
None,
)
.await
.unwrap();
assert_eq!(sync_response.status, enums::AttemptStatus::Authorized);
let capture_response = CONNECTOR
.capture_payment(transaction_id.clone(), None, None)
.await
.unwrap();
assert_eq!(
capture_response.status,
enums::AttemptStatus::CaptureInitiated
);
let sync_response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Pending,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id.clone(),
),
capture_method: Some(enums::CaptureMethod::Manual),
..Default::default()
}),
None,
)
.await
.unwrap();
assert_eq!(sync_response.status, enums::AttemptStatus::Pending);
}
<file_sep path="hyperswitch/crates/router/tests/connectors/nmi.rs" role="context" start="53" end="75">
async fn should_only_authorize_payment() {
let response = CONNECTOR
.authorize_payment(get_payment_authorize_data(), None)
.await
.expect("Authorize payment response");
let transaction_id = utils::get_connector_transaction_id(response.response).unwrap();
let sync_response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id.clone(),
),
capture_method: Some(enums::CaptureMethod::Manual),
..Default::default()
}),
None,
)
.await
.unwrap();
// Assert the sync response, it will be authorized in case of manual capture, for automatic it will be Completed Success
assert_eq!(sync_response.status, enums::AttemptStatus::Authorized);
}
<file_sep path="hyperswitch/crates/router/tests/connectors/nmi.rs" role="context" start="32" end="34">
fn get_name(&self) -> String {
"nmi".to_string()
}
<file_sep path="hyperswitch/crates/router/tests/connectors/nmi.rs" role="context" start="23" end="30">
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.nmi
.expect("Missing connector authentication configuration")
.into(),
)
}
<file_sep path="hyperswitch/crates/router/tests/connectors/nmi.rs" role="context" start="393" end="416">
async fn should_make_payment() {
let response = CONNECTOR
.make_payment(get_payment_authorize_data(), None)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::CaptureInitiated);
let transaction_id = utils::get_connector_transaction_id(response.response.to_owned()).unwrap();
let sync_response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Pending,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id.clone(),
),
capture_method: Some(enums::CaptureMethod::Automatic),
..Default::default()
}),
None,
)
.await
.unwrap();
assert_eq!(sync_response.status, enums::AttemptStatus::Pending);
}
<file_sep path="hyperswitch/crates/router/tests/connectors/nmi.rs" role="context" start="591" end="620">
async fn should_fail_void_payment_for_auto_capture() {
let response = CONNECTOR
.make_payment(get_payment_authorize_data(), None)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::CaptureInitiated);
let transaction_id = utils::get_connector_transaction_id(response.response.to_owned()).unwrap();
let sync_response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Pending,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id.clone(),
),
capture_method: Some(enums::CaptureMethod::Automatic),
..Default::default()
}),
None,
)
.await
.unwrap();
assert_eq!(sync_response.status, enums::AttemptStatus::Pending);
let void_response = CONNECTOR
.void_payment(transaction_id.clone(), None, None)
.await
.unwrap();
assert_eq!(void_response.status, enums::AttemptStatus::VoidFailed);
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/services/kafka.rs<|crate|> router anchor=old kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/services/kafka.rs" role="context" start="87" end="94">
fn old(event: &'a T, tenant_id: TenantID, clickhouse_database: Option<String>) -> Self {
Self {
event,
sign_flag: -1,
tenant_id,
clickhouse_database,
}
}
<file_sep path="hyperswitch/crates/router/src/services/kafka.rs" role="context" start="86" end="86">
pub type MQResult<T> = CustomResult<T, KafkaError>;
use crate::db::kafka_store::TenantID;
<file_sep path="hyperswitch/crates/router/src/services/kafka.rs" role="context" start="102" end="104">
fn event_type(&self) -> EventType {
self.event.event_type()
}
<file_sep path="hyperswitch/crates/router/src/services/kafka.rs" role="context" start="98" end="100">
fn key(&self) -> String {
self.event.key()
}
<file_sep path="hyperswitch/crates/router/src/services/kafka.rs" role="context" start="79" end="86">
fn new(event: &'a T, tenant_id: TenantID, clickhouse_database: Option<String>) -> Self {
Self {
event,
sign_flag: 1,
tenant_id,
clickhouse_database,
}
}
<file_sep path="hyperswitch/crates/router/src/services/kafka.rs" role="context" start="64" end="66">
fn creation_timestamp(&self) -> Option<i64> {
None
}
<file_sep path="hyperswitch/crates/router/src/services/kafka.rs" role="context" start="462" end="491">
pub async fn log_payment_intent(
&self,
intent: &PaymentIntent,
old_intent: Option<PaymentIntent>,
tenant_id: TenantID,
) -> MQResult<()> {
if let Some(negative_event) = old_intent {
self.log_event(&KafkaEvent::old(
&KafkaPaymentIntent::from_storage(&negative_event),
tenant_id.clone(),
self.ckh_database_name.clone(),
))
.attach_printable_lazy(|| {
format!("Failed to add negative intent event {negative_event:?}")
})?;
};
self.log_event(&KafkaEvent::new(
&KafkaPaymentIntent::from_storage(intent),
tenant_id.clone(),
self.ckh_database_name.clone(),
))
.attach_printable_lazy(|| format!("Failed to add positive intent event {intent:?}"))?;
self.log_event(&KafkaConsolidatedEvent::new(
&KafkaPaymentIntentEvent::from_storage(intent),
tenant_id.clone(),
))
.attach_printable_lazy(|| format!("Failed to add consolidated intent event {intent:?}"))
}
<file_sep path="hyperswitch/crates/router/src/services/kafka.rs" role="context" start="412" end="425">
pub async fn log_payment_attempt_delete(
&self,
delete_old_attempt: &PaymentAttempt,
tenant_id: TenantID,
) -> MQResult<()> {
self.log_event(&KafkaEvent::old(
&KafkaPaymentAttempt::from_storage(delete_old_attempt),
tenant_id.clone(),
self.ckh_database_name.clone(),
))
.attach_printable_lazy(|| {
format!("Failed to add negative attempt event {delete_old_attempt:?}")
})
}
<file_sep path="hyperswitch/crates/router/src/db/kafka_store.rs" role="context" start="92" end="92">
pub struct TenantID(pub String);
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/worldline.rs<|crate|> router<|connector|> worldline anchor=get_payment_authorize_data kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/tests/connectors/worldline.rs" role="context" start="65" end="117">
fn get_payment_authorize_data(
card_number: &str,
card_exp_month: &str,
card_exp_year: &str,
card_cvc: &str,
capture_method: enums::CaptureMethod,
) -> Option<types::PaymentsAuthorizeData> {
Some(types::PaymentsAuthorizeData {
amount: 3500,
currency: enums::Currency::USD,
payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card {
card_number: cards::CardNumber::from_str(card_number).unwrap(),
card_exp_month: Secret::new(card_exp_month.to_string()),
card_exp_year: Secret::new(card_exp_year.to_string()),
card_cvc: Secret::new(card_cvc.to_string()),
card_issuer: None,
card_network: None,
card_type: None,
card_issuing_country: None,
bank_code: None,
nick_name: Some(Secret::new("nick_name".into())),
card_holder_name: Some(Secret::new("card holder name".into())),
}),
confirm: true,
statement_descriptor_suffix: None,
statement_descriptor: None,
setup_future_usage: None,
mandate_id: None,
off_session: None,
setup_mandate_details: None,
capture_method: Some(capture_method),
browser_info: None,
order_details: None,
order_category: None,
email: None,
customer_name: None,
session_token: None,
enrolled_for_3ds: false,
related_transaction_id: None,
payment_experience: None,
payment_method_type: None,
router_return_url: None,
webhook_url: None,
complete_authorize_url: None,
customer_id: None,
surcharge_details: None,
request_incremental_authorization: false,
metadata: None,
authentication_data: None,
customer_acceptance: None,
..utils::PaymentAuthorizeType::default().0
})
}
<file_sep path="hyperswitch/crates/router/tests/connectors/worldline.rs" role="context" start="64" end="64">
use masking::Secret;
use router::{
connector::Worldline,
core::errors,
types::{self, storage::enums, PaymentAddress},
};
<file_sep path="hyperswitch/crates/router/tests/connectors/worldline.rs" role="context" start="136" end="149">
async fn should_auto_authorize_and_request_capture() {
let authorize_data = WorldlineTest::get_payment_authorize_data(
"4012000033330026",
"10",
"2025",
"123",
enums::CaptureMethod::Automatic,
);
let response = WorldlineTest {}
.make_payment(authorize_data, WorldlineTest::get_payment_info())
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Pending);
}
<file_sep path="hyperswitch/crates/router/tests/connectors/worldline.rs" role="context" start="121" end="133">
async fn should_requires_manual_authorization() {
let authorize_data = WorldlineTest::get_payment_authorize_data(
"5424 1802 7979 1732",
"10",
"25",
"123",
enums::CaptureMethod::Manual,
);
let response = WorldlineTest {}
.authorize_payment(authorize_data, WorldlineTest::get_payment_info())
.await;
assert_eq!(response.unwrap().status, enums::AttemptStatus::Authorized);
}
<file_sep path="hyperswitch/crates/router/tests/connectors/worldline.rs" role="context" start="44" end="63">
fn get_payment_info() -> Option<PaymentInfo> {
Some(PaymentInfo {
address: Some(PaymentAddress::new(
None,
Some(Address {
address: Some(AddressDetails {
country: Some(api_models::enums::CountryAlpha2::US),
first_name: Some(Secret::new(String::from("John"))),
last_name: Some(Secret::new(String::from("Dough"))),
..Default::default()
}),
phone: None,
email: None,
}),
None,
None,
)),
..Default::default()
})
}
<file_sep path="hyperswitch/crates/router/tests/connectors/worldline.rs" role="context" start="38" end="40">
fn get_name(&self) -> String {
String::from("worldline")
}
<file_sep path="hyperswitch/crates/router/src/compatibility/stripe/customers/types.rs" role="context" start="202" end="207">
pub struct PaymentMethodData {
pub id: Option<String>,
pub object: &'static str,
pub card: Option<CardDetails>,
pub created: Option<time::PrimitiveDateTime>,
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/riskified.rs<|crate|> router anchor=new kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/connector/riskified.rs" role="context" start="47" end="51">
pub fn new() -> &'static Self {
&Self {
amount_converter: &StringMajorUnitForConnector,
}
}
<file_sep path="hyperswitch/crates/router/src/connector/riskified.rs" role="context" start="46" end="46">
use common_utils::types::{
AmountConvertor, MinorUnit, StringMajorUnit, StringMajorUnitForConnector,
};
<file_sep path="hyperswitch/crates/router/src/connector/riskified.rs" role="context" start="77" end="114">
fn build_headers(
&self,
req: &types::RouterData<Flow, Request, Response>,
connectors: &settings::Connectors,
) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
let auth: riskified::RiskifiedAuthType =
riskified::RiskifiedAuthType::try_from(&req.connector_auth_type)?;
let riskified_req = self.get_request_body(req, connectors)?;
let binding = riskified_req.get_inner_value();
let payload = binding.peek();
let digest = self
.generate_authorization_signature(&auth, payload)
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
let header = vec![
(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
),
(
"X-RISKIFIED-SHOP-DOMAIN".to_string(),
auth.domain_name.clone().into(),
),
(
"X-RISKIFIED-HMAC-SHA256".to_string(),
request::Mask::into_masked(digest),
),
(
"Accept".to_string(),
"application/vnd.riskified.com; version=2".into(),
),
];
Ok(header)
}
<file_sep path="hyperswitch/crates/router/src/connector/riskified.rs" role="context" start="54" end="69">
pub fn generate_authorization_signature(
&self,
auth: &riskified::RiskifiedAuthType,
payload: &str,
) -> CustomResult<String, errors::ConnectorError> {
let key = hmac::Key::new(
hmac::HMAC_SHA256,
auth.secret_token.clone().expose().as_bytes(),
);
let signature_value = hmac::sign(&key, payload.as_bytes());
let digest = signature_value.as_ref();
Ok(hex::encode(digest))
}
<file_sep path="hyperswitch/crates/router/src/connector/riskified.rs" role="context" start="587" end="592">
fn get_webhook_source_verification_algorithm(
&self,
_request: &api::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> {
Ok(Box::new(crypto::HmacSha256))
}
<file_sep path="hyperswitch/crates/router/src/connector/riskified.rs" role="context" start="672" end="681">
fn get_webhook_resource_object(
&self,
request: &api::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let resource: riskified::RiskifiedWebhookBody = request
.body
.parse_struct("RiskifiedWebhookBody")
.change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?;
Ok(Box::new(resource))
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/adyen.rs<|crate|> router<|connector|> adyen anchor=get_payment_authorize_data kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/tests/connectors/adyen.rs" role="context" start="135" end="187">
fn get_payment_authorize_data(
card_number: &str,
card_exp_month: &str,
card_exp_year: &str,
card_cvc: &str,
capture_method: enums::CaptureMethod,
) -> Option<types::PaymentsAuthorizeData> {
Some(types::PaymentsAuthorizeData {
amount: 3500,
currency: enums::Currency::USD,
payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card {
card_number: cards::CardNumber::from_str(card_number).unwrap(),
card_exp_month: Secret::new(card_exp_month.to_string()),
card_exp_year: Secret::new(card_exp_year.to_string()),
card_cvc: Secret::new(card_cvc.to_string()),
card_issuer: None,
card_network: None,
card_type: None,
card_issuing_country: None,
bank_code: None,
nick_name: Some(Secret::new("nick_name".into())),
card_holder_name: Some(Secret::new("card holder name".into())),
}),
confirm: true,
statement_descriptor_suffix: None,
statement_descriptor: None,
setup_future_usage: None,
mandate_id: None,
off_session: None,
setup_mandate_details: None,
capture_method: Some(capture_method),
browser_info: None,
order_details: None,
order_category: None,
email: None,
customer_name: None,
payment_experience: None,
payment_method_type: None,
session_token: None,
enrolled_for_3ds: false,
related_transaction_id: None,
router_return_url: Some(String::from("http://localhost:8080")),
webhook_url: None,
complete_authorize_url: None,
customer_id: None,
surcharge_details: None,
request_incremental_authorization: false,
metadata: None,
authentication_data: None,
customer_acceptance: None,
..utils::PaymentAuthorizeType::default().0
})
}
<file_sep path="hyperswitch/crates/router/tests/connectors/adyen.rs" role="context" start="134" end="134">
use masking::Secret;
use router::types::{self, storage::enums, PaymentAddress};
<file_sep path="hyperswitch/crates/router/tests/connectors/adyen.rs" role="context" start="214" end="230">
async fn should_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(
AdyenTest::get_payment_authorize_data(
"370000000000002",
"03",
"2030",
"7373",
enums::CaptureMethod::Manual,
),
None,
AdyenTest::get_payment_info(),
)
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Pending);
}
<file_sep path="hyperswitch/crates/router/tests/connectors/adyen.rs" role="context" start="195" end="210">
async fn should_only_authorize_payment() {
let response = CONNECTOR
.authorize_payment(
AdyenTest::get_payment_authorize_data(
"4111111111111111",
"03",
"2030",
"737",
enums::CaptureMethod::Manual,
),
AdyenTest::get_payment_info(),
)
.await
.expect("Authorize payment response");
assert_eq!(response.status, enums::AttemptStatus::Authorized);
}
<file_sep path="hyperswitch/crates/router/tests/connectors/adyen.rs" role="context" start="82" end="133">
fn get_payout_info(payout_type: enums::PayoutType) -> Option<PaymentInfo> {
use common_utils::pii::Email;
Some(PaymentInfo {
currency: Some(enums::Currency::EUR),
address: Some(PaymentAddress::new(
None,
Some(Address {
address: Some(AddressDetails {
country: Some(api_models::enums::CountryAlpha2::US),
state: Some(Secret::new("California".to_string())),
city: Some("San Francisco".to_string()),
zip: Some(Secret::new("94122".to_string())),
line1: Some(Secret::new("1467".to_string())),
line2: Some(Secret::new("Harrison Street".to_string())),
..Default::default()
}),
phone: None,
email: None,
}),
None,
None,
)),
payout_method_data: match payout_type {
enums::PayoutType::Card => Some(types::api::PayoutMethodData::Card(
types::api::payouts::CardPayout {
card_number: cards::CardNumber::from_str("4111111111111111").unwrap(),
expiry_month: Secret::new("3".to_string()),
expiry_year: Secret::new("2030".to_string()),
card_holder_name: Some(Secret::new("John Doe".to_string())),
},
)),
enums::PayoutType::Bank => Some(types::api::PayoutMethodData::Bank(
types::api::payouts::BankPayout::Sepa(types::api::SepaBankTransfer {
iban: "NL46TEST0136169112".to_string().into(),
bic: Some("ABNANL2A".to_string().into()),
bank_name: Some("Deutsche Bank".to_string()),
bank_country_code: Some(enums::CountryAlpha2::NL),
bank_city: Some("Amsterdam".to_string()),
}),
)),
enums::PayoutType::Wallet => Some(types::api::PayoutMethodData::Wallet(
types::api::payouts::WalletPayout::Paypal(api_models::payouts::Paypal {
email: Email::from_str("EmailUsedForPayPalAccount@example.com").ok(),
telephone_number: None,
paypal_id: None,
}),
)),
},
..Default::default()
})
}
<file_sep path="hyperswitch/crates/router/tests/connectors/adyen.rs" role="context" start="52" end="79">
fn get_payment_info() -> Option<PaymentInfo> {
Some(PaymentInfo {
address: Some(PaymentAddress::new(
None,
Some(Address {
address: Some(AddressDetails {
country: Some(api_models::enums::CountryAlpha2::US),
state: Some(Secret::new("California".to_string())),
city: Some("San Francisco".to_string()),
zip: Some(Secret::new("94122".to_string())),
line1: Some(Secret::new("1467".to_string())),
line2: Some(Secret::new("Harrison Street".to_string())),
line3: None,
first_name: Some(Secret::new("John".to_string())),
last_name: Some(Secret::new("Dough".to_string())),
}),
phone: Some(PhoneDetails {
number: Some(Secret::new("9123456789".to_string())),
country_code: Some("+351".to_string()),
}),
email: None,
}),
None,
None,
)),
..Default::default()
})
}
<file_sep path="hyperswitch/crates/router/tests/connectors/adyen.rs" role="context" start="234" end="253">
async fn should_partially_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(
AdyenTest::get_payment_authorize_data(
"4293189100000008",
"03",
"2030",
"737",
enums::CaptureMethod::Manual,
),
Some(types::PaymentsCaptureData {
amount_to_capture: 50,
..utils::PaymentCaptureType::default().0
}),
AdyenTest::get_payment_info(),
)
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Pending);
}
<file_sep path="hyperswitch/crates/router/tests/connectors/adyen.rs" role="context" start="281" end="305">
async fn should_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(
AdyenTest::get_payment_authorize_data(
"370000000000002",
"03",
"2030",
"7373",
enums::CaptureMethod::Manual,
),
None,
Some(types::RefundsData {
refund_amount: 1500,
reason: Some("CUSTOMER REQUEST".to_string()),
..utils::PaymentRefundType::default().0
}),
AdyenTest::get_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Pending,
);
}
<file_sep path="hyperswitch/crates/router/src/compatibility/stripe/customers/types.rs" role="context" start="202" end="207">
pub struct PaymentMethodData {
pub id: Option<String>,
pub object: &'static str,
pub card: Option<CardDetails>,
pub created: Option<time::PrimitiveDateTime>,
}
<file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="2504" end="2539">
pub enum PaymentMethodData {
#[schema(title = "Card")]
Card(Card),
#[schema(title = "CardRedirect")]
CardRedirect(CardRedirectData),
#[schema(title = "Wallet")]
Wallet(WalletData),
#[schema(title = "PayLater")]
PayLater(PayLaterData),
#[schema(title = "BankRedirect")]
BankRedirect(BankRedirectData),
#[schema(title = "BankDebit")]
BankDebit(BankDebitData),
#[schema(title = "BankTransfer")]
BankTransfer(Box<BankTransferData>),
#[schema(title = "RealTimePayment")]
RealTimePayment(Box<RealTimePaymentData>),
#[schema(title = "Crypto")]
Crypto(CryptoData),
#[schema(title = "MandatePayment")]
MandatePayment,
#[schema(title = "Reward")]
Reward,
#[schema(title = "Upi")]
Upi(UpiData),
#[schema(title = "Voucher")]
Voucher(VoucherData),
#[schema(title = "GiftCard")]
GiftCard(Box<GiftCardData>),
#[schema(title = "CardToken")]
CardToken(CardToken),
#[schema(title = "OpenBanking")]
OpenBanking(OpenBankingData),
#[schema(title = "MobilePayment")]
MobilePayment(MobilePaymentData),
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/adyen.rs<|crate|> router<|connector|> adyen anchor=get_payment_authorize_data kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|>
<file_sep path="hyperswitch/crates/router/tests/connectors/adyen.rs" role="context" start="135" end="187">
fn get_payment_authorize_data(
card_number: &str,
card_exp_month: &str,
card_exp_year: &str,
card_cvc: &str,
capture_method: enums::CaptureMethod,
) -> Option<types::PaymentsAuthorizeData> {
Some(types::PaymentsAuthorizeData {
amount: 3500,
currency: enums::Currency::USD,
payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card {
card_number: cards::CardNumber::from_str(card_number).unwrap(),
card_exp_month: Secret::new(card_exp_month.to_string()),
card_exp_year: Secret::new(card_exp_year.to_string()),
card_cvc: Secret::new(card_cvc.to_string()),
card_issuer: None,
card_network: None,
card_type: None,
card_issuing_country: None,
bank_code: None,
nick_name: Some(Secret::new("nick_name".into())),
card_holder_name: Some(Secret::new("card holder name".into())),
}),
confirm: true,
statement_descriptor_suffix: None,
statement_descriptor: None,
setup_future_usage: None,
mandate_id: None,
off_session: None,
setup_mandate_details: None,
capture_method: Some(capture_method),
browser_info: None,
order_details: None,
order_category: None,
email: None,
customer_name: None,
payment_experience: None,
payment_method_type: None,
session_token: None,
enrolled_for_3ds: false,
related_transaction_id: None,
router_return_url: Some(String::from("http://localhost:8080")),
webhook_url: None,
complete_authorize_url: None,
customer_id: None,
surcharge_details: None,
request_incremental_authorization: false,
metadata: None,
authentication_data: None,
customer_acceptance: None,
..utils::PaymentAuthorizeType::default().0
})
}
<file_sep path="hyperswitch/crates/router/tests/connectors/adyen.rs" role="context" start="134" end="134">
use masking::Secret;
use router::types::{self, storage::enums, PaymentAddress};
<file_sep path="hyperswitch/crates/router/tests/connectors/adyen.rs" role="context" start="214" end="230">
async fn should_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(
AdyenTest::get_payment_authorize_data(
"370000000000002",
"03",
"2030",
"7373",
enums::CaptureMethod::Manual,
),
None,
AdyenTest::get_payment_info(),
)
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Pending);
}
<file_sep path="hyperswitch/crates/router/tests/connectors/adyen.rs" role="context" start="195" end="210">
async fn should_only_authorize_payment() {
let response = CONNECTOR
.authorize_payment(
AdyenTest::get_payment_authorize_data(
"4111111111111111",
"03",
"2030",
"737",
enums::CaptureMethod::Manual,
),
AdyenTest::get_payment_info(),
)
.await
.expect("Authorize payment response");
assert_eq!(response.status, enums::AttemptStatus::Authorized);
}
<file_sep path="hyperswitch/crates/router/tests/connectors/adyen.rs" role="context" start="82" end="133">
fn get_payout_info(payout_type: enums::PayoutType) -> Option<PaymentInfo> {
use common_utils::pii::Email;
Some(PaymentInfo {
currency: Some(enums::Currency::EUR),
address: Some(PaymentAddress::new(
None,
Some(Address {
address: Some(AddressDetails {
country: Some(api_models::enums::CountryAlpha2::US),
state: Some(Secret::new("California".to_string())),
city: Some("San Francisco".to_string()),
zip: Some(Secret::new("94122".to_string())),
line1: Some(Secret::new("1467".to_string())),
line2: Some(Secret::new("Harrison Street".to_string())),
..Default::default()
}),
phone: None,
email: None,
}),
None,
None,
)),
payout_method_data: match payout_type {
enums::PayoutType::Card => Some(types::api::PayoutMethodData::Card(
types::api::payouts::CardPayout {
card_number: cards::CardNumber::from_str("4111111111111111").unwrap(),
expiry_month: Secret::new("3".to_string()),
expiry_year: Secret::new("2030".to_string()),
card_holder_name: Some(Secret::new("John Doe".to_string())),
},
)),
enums::PayoutType::Bank => Some(types::api::PayoutMethodData::Bank(
types::api::payouts::BankPayout::Sepa(types::api::SepaBankTransfer {
iban: "NL46TEST0136169112".to_string().into(),
bic: Some("ABNANL2A".to_string().into()),
bank_name: Some("Deutsche Bank".to_string()),
bank_country_code: Some(enums::CountryAlpha2::NL),
bank_city: Some("Amsterdam".to_string()),
}),
)),
enums::PayoutType::Wallet => Some(types::api::PayoutMethodData::Wallet(
types::api::payouts::WalletPayout::Paypal(api_models::payouts::Paypal {
email: Email::from_str("EmailUsedForPayPalAccount@example.com").ok(),
telephone_number: None,
paypal_id: None,
}),
)),
},
..Default::default()
})
}
<file_sep path="hyperswitch/crates/router/tests/connectors/adyen.rs" role="context" start="52" end="79">
fn get_payment_info() -> Option<PaymentInfo> {
Some(PaymentInfo {
address: Some(PaymentAddress::new(
None,
Some(Address {
address: Some(AddressDetails {
country: Some(api_models::enums::CountryAlpha2::US),
state: Some(Secret::new("California".to_string())),
city: Some("San Francisco".to_string()),
zip: Some(Secret::new("94122".to_string())),
line1: Some(Secret::new("1467".to_string())),
line2: Some(Secret::new("Harrison Street".to_string())),
line3: None,
first_name: Some(Secret::new("John".to_string())),
last_name: Some(Secret::new("Dough".to_string())),
}),
phone: Some(PhoneDetails {
number: Some(Secret::new("9123456789".to_string())),
country_code: Some("+351".to_string()),
}),
email: None,
}),
None,
None,
)),
..Default::default()
})
}
<file_sep path="hyperswitch/crates/router/tests/connectors/adyen.rs" role="context" start="234" end="253">
async fn should_partially_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(
AdyenTest::get_payment_authorize_data(
"4293189100000008",
"03",
"2030",
"737",
enums::CaptureMethod::Manual,
),
Some(types::PaymentsCaptureData {
amount_to_capture: 50,
..utils::PaymentCaptureType::default().0
}),
AdyenTest::get_payment_info(),
)
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Pending);
}
<file_sep path="hyperswitch/crates/router/tests/connectors/adyen.rs" role="context" start="281" end="305">
async fn should_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(
AdyenTest::get_payment_authorize_data(
"370000000000002",
"03",
"2030",
"7373",
enums::CaptureMethod::Manual,
),
None,
Some(types::RefundsData {
refund_amount: 1500,
reason: Some("CUSTOMER REQUEST".to_string()),
..utils::PaymentRefundType::default().0
}),
AdyenTest::get_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Pending,
);
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payment_methods/cards.rs<|crate|> router anchor=create_encrypted_data kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="5907" end="5937">
pub async fn create_encrypted_data<T>(
key_manager_state: &KeyManagerState,
key_store: &domain::MerchantKeyStore,
data: T,
) -> Result<Encryptable<Secret<serde_json::Value>>, error_stack::Report<errors::StorageError>>
where
T: Debug + serde::Serialize,
{
let key = key_store.key.get_inner().peek();
let identifier = Identifier::Merchant(key_store.merchant_id.clone());
let encoded_data = Encode::encode_to_value(&data)
.change_context(errors::StorageError::SerializationFailed)
.attach_printable("Unable to encode data")?;
let secret_data = Secret::<_, masking::WithType>::new(encoded_data);
let encrypted_data = domain::types::crypto_operation(
key_manager_state,
type_name!(payment_method::PaymentMethod),
domain::types::CryptoOperation::Encrypt(secret_data),
identifier.clone(),
key,
)
.await
.and_then(|val| val.try_into_operation())
.change_context(errors::StorageError::EncryptionError)
.attach_printable("Unable to encrypt data")?;
Ok(encrypted_data)
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="5906" end="5906">
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update the default payment method id for the customer")?;
};
Ok(services::ApplicationResponse::Json(
api::PaymentMethodDeleteResponse {
payment_method_id: key.payment_method_id.clone(),
deleted: true,
},
))
}
pub async fn create_encrypted_data<T>(
key_manager_state: &KeyManagerState,
key_store: &domain::MerchantKeyStore,
data: T,
) -> Result<Encryptable<Secret<serde_json::Value>>, error_stack::Report<errors::StorageError>>
where
T: Debug + serde::Serialize,
{
let key = key_store.key.get_inner().peek();
let identifier = Identifier::Merchant(key_store.merchant_id.clone());
let encoded_data = Encode::encode_to_value(&data)
.change_context(errors::StorageError::SerializationFailed)
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="5956" end="5994">
pub async fn list_countries_currencies_for_connector_payment_method_util(
connector_filters: settings::ConnectorFilters,
connector: api_enums::Connector,
payment_method_type: api_enums::PaymentMethodType,
) -> ListCountriesCurrenciesResponse {
let payment_method_type =
settings::PaymentMethodFilterKey::PaymentMethodType(payment_method_type);
let (currencies, country_codes) = connector_filters
.0
.get(&connector.to_string())
.and_then(|filter| filter.0.get(&payment_method_type))
.map(|filter| (filter.currency.clone(), filter.country.clone()))
.unwrap_or_else(|| {
connector_filters
.0
.get("default")
.and_then(|filter| filter.0.get(&payment_method_type))
.map_or((None, None), |filter| {
(filter.currency.clone(), filter.country.clone())
})
});
let currencies =
currencies.unwrap_or_else(|| api_enums::Currency::iter().collect::<HashSet<_>>());
let country_codes =
country_codes.unwrap_or_else(|| api_enums::CountryAlpha2::iter().collect::<HashSet<_>>());
ListCountriesCurrenciesResponse {
currencies,
countries: country_codes
.into_iter()
.map(|country_code| CountryCodeWithName {
code: country_code,
name: common_enums::Country::from_alpha2(country_code),
})
.collect(),
}
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="5939" end="5952">
pub async fn list_countries_currencies_for_connector_payment_method(
state: routes::SessionState,
req: ListCountriesCurrenciesRequest,
_profile_id: Option<id_type::ProfileId>,
) -> errors::RouterResponse<ListCountriesCurrenciesResponse> {
Ok(services::ApplicationResponse::Json(
list_countries_currencies_for_connector_payment_method_util(
state.conf.pm_filters.clone(),
req.connector,
req.payment_method_type,
)
.await,
))
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="5807" end="5905">
pub async fn delete_payment_method(
state: routes::SessionState,
merchant_account: domain::MerchantAccount,
pm_id: api::PaymentMethodId,
key_store: domain::MerchantKeyStore,
) -> errors::RouterResponse<api::PaymentMethodDeleteResponse> {
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
let key = db
.find_payment_method(
&((&state).into()),
&key_store,
pm_id.payment_method_id.as_str(),
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,
merchant_account.get_id(),
&key_store,
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 = delete_card_from_locker(
&state,
&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(
&state,
&key.customer_id,
&key.merchant_id,
key.payment_method_id.clone(),
key.network_token_locker_id,
network_token_ref_id,
)
.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(
&((&state).into()),
&key_store,
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,
&key_store,
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 {
payment_method_id: key.payment_method_id.clone(),
deleted: true,
},
))
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="5746" end="5803">
pub async fn retrieve_payment_method(
state: routes::SessionState,
pm: api::PaymentMethodId,
key_store: domain::MerchantKeyStore,
merchant_account: domain::MerchantAccount,
) -> errors::RouterResponse<api::PaymentMethodResponse> {
let db = state.store.as_ref();
let pm = db
.find_payment_method(
&((&state).into()),
&key_store,
&pm.payment_method_id,
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 state.conf.locker.locker_enabled {
let card = get_card_from_locker(
&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 {
get_card_details_without_locker_fallback(&pm, &state).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: false,
installment_payment_enabled: false,
payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]),
last_used_at: Some(pm.last_used_at),
client_secret: pm.client_secret,
},
))
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="1712" end="1981">
pub async fn save_migration_payment_method(
state: &routes::SessionState,
req: api::PaymentMethodCreate,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
migration_status: &mut migration::RecordMigrationStatusBuilder,
) -> errors::RouterResponse<api::PaymentMethodResponse> {
req.validate()?;
let db = &*state.store;
let merchant_id = merchant_account.get_id();
let customer_id = req.customer_id.clone().get_required_value("customer_id")?;
let payment_method = req.payment_method.get_required_value("payment_method")?;
let key_manager_state = state.into();
let payment_method_billing_address: Option<Encryptable<Secret<serde_json::Value>>> = req
.billing
.clone()
.async_map(|billing| create_encrypted_data(&key_manager_state, key_store, billing))
.await
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt Payment method billing address")?;
let connector_mandate_details = req
.connector_mandate_details
.clone()
.map(serde_json::to_value)
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let network_transaction_id = req.network_transaction_id.clone();
let response = match payment_method {
#[cfg(feature = "payouts")]
api_enums::PaymentMethod::BankTransfer => match req.bank_transfer.clone() {
Some(bank) => add_bank_to_locker(
state,
req.clone(),
merchant_account,
key_store,
&bank,
&customer_id,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Add PaymentMethod Failed"),
_ => Ok(store_default_payment_method(
&req,
&customer_id,
merchant_id,
)),
},
api_enums::PaymentMethod::Card => match req.card.clone() {
Some(card) => {
let mut card_details = card;
card_details = helpers::populate_bin_details_for_payment_method_create(
card_details.clone(),
db,
)
.await;
migration::validate_card_expiry(
&card_details.card_exp_month,
&card_details.card_exp_year,
)?;
Box::pin(add_card_to_locker(
state,
req.clone(),
&card_details,
&customer_id,
merchant_account,
None,
))
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Add Card Failed")
}
_ => Ok(store_default_payment_method(
&req,
&customer_id,
merchant_id,
)),
},
_ => Ok(store_default_payment_method(
&req,
&customer_id,
merchant_id,
)),
};
let (mut resp, duplication_check) = response?;
migration_status.card_migrated(true);
match duplication_check {
Some(duplication_check) => match duplication_check {
payment_methods::DataDuplicationCheck::Duplicated => {
let existing_pm = get_or_insert_payment_method(
state,
req.clone(),
&mut resp,
merchant_account,
&customer_id,
key_store,
)
.await?;
resp.client_secret = existing_pm.client_secret;
}
payment_methods::DataDuplicationCheck::MetaDataChanged => {
if let Some(card) = req.card.clone() {
let existing_pm = get_or_insert_payment_method(
state,
req.clone(),
&mut resp,
merchant_account,
&customer_id,
key_store,
)
.await?;
let client_secret = existing_pm.client_secret.clone();
delete_card_from_locker(
state,
&customer_id,
merchant_id,
existing_pm
.locker_id
.as_ref()
.unwrap_or(&existing_pm.payment_method_id),
)
.await?;
let add_card_resp = add_card_hs(
state,
req.clone(),
&card,
&customer_id,
merchant_account,
api::enums::LockerChoice::HyperswitchCardVault,
Some(
existing_pm
.locker_id
.as_ref()
.unwrap_or(&existing_pm.payment_method_id),
),
)
.await;
if let Err(err) = add_card_resp {
logger::error!(vault_err=?err);
db.delete_payment_method_by_merchant_id_payment_method_id(
&(state.into()),
key_store,
merchant_id,
&resp.payment_method_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
Err(report!(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while updating card metadata changes"))?
};
let existing_pm_data =
get_card_details_without_locker_fallback(&existing_pm, state).await?;
let updated_card = Some(api::CardDetailFromLocker {
scheme: existing_pm.scheme.clone(),
last4_digits: Some(card.card_number.get_last4()),
issuer_country: card
.card_issuing_country
.or(existing_pm_data.issuer_country),
card_isin: Some(card.card_number.get_card_isin()),
card_number: Some(card.card_number),
expiry_month: Some(card.card_exp_month),
expiry_year: Some(card.card_exp_year),
card_token: None,
card_fingerprint: None,
card_holder_name: card
.card_holder_name
.or(existing_pm_data.card_holder_name),
nick_name: card.nick_name.or(existing_pm_data.nick_name),
card_network: card.card_network.or(existing_pm_data.card_network),
card_issuer: card.card_issuer.or(existing_pm_data.card_issuer),
card_type: card.card_type.or(existing_pm_data.card_type),
saved_to_locker: true,
});
let updated_pmd = updated_card.as_ref().map(|card| {
PaymentMethodsData::Card(CardDetailsPaymentMethod::from(card.clone()))
});
let pm_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>> =
updated_pmd
.async_map(|updated_pmd| {
create_encrypted_data(&key_manager_state, key_store, updated_pmd)
})
.await
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt payment method data")?;
let pm_update = storage::PaymentMethodUpdate::PaymentMethodDataUpdate {
payment_method_data: pm_data_encrypted.map(Into::into),
};
db.update_payment_method(
&(state.into()),
key_store,
existing_pm,
pm_update,
merchant_account.storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to add payment method in db")?;
resp.client_secret = client_secret;
}
}
},
None => {
let pm_metadata = resp.metadata.as_ref().map(|data| data.peek());
let locker_id = if resp.payment_method == Some(api_enums::PaymentMethod::Card)
|| resp.payment_method == Some(api_enums::PaymentMethod::BankTransfer)
{
Some(resp.payment_method_id)
} else {
None
};
resp.payment_method_id = generate_id(consts::ID_LENGTH, "pm");
let pm = insert_payment_method(
state,
&resp,
&req,
key_store,
merchant_id,
&customer_id,
pm_metadata.cloned(),
None,
locker_id,
connector_mandate_details.clone(),
network_transaction_id.clone(),
merchant_account.storage_scheme,
payment_method_billing_address,
None,
None,
None,
)
.await?;
resp.client_secret = pm.client_secret;
}
}
migration_status.card_migrated(true);
migration_status.network_transaction_id_migrated(
network_transaction_id.and_then(|val| (!val.is_empty_after_trim()).then_some(true)),
);
migration_status.connector_mandate_details_migrated(
connector_mandate_details
.and_then(|val| if val == json!({}) { None } else { Some(true) })
.or_else(|| {
req.connector_mandate_details
.and_then(|val| (!val.0.is_empty()).then_some(false))
}),
);
Ok(services::ApplicationResponse::Json(resp))
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="1988" end="2044">
pub async fn insert_payment_method(
state: &routes::SessionState,
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>,
storage_scheme: MerchantStorageScheme,
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())));
let key_manager_state = 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")?;
create_payment_method(
state,
req,
customer_id,
&resp.payment_method_id,
locker_id,
merchant_id,
pm_metadata,
customer_acceptance,
pm_data_encrypted,
key_store,
connector_mandate_details,
None,
network_transaction_id,
storage_scheme,
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
}
<file_sep path="hyperswitch/v2_compatible_migrations/2024-08-28-081721_add_v2_columns/up.sql" role="context" start="54" end="70">
ADD COLUMN redirection_data JSONB,
ADD COLUMN connector_payment_data TEXT,
ADD COLUMN connector_token_details JSONB;
-- Change the type of the column from JSON to JSONB
ALTER TABLE merchant_connector_account
ADD COLUMN IF NOT EXISTS feature_metadata JSONB;
ALTER TABLE payment_methods
ADD COLUMN IF NOT EXISTS locker_fingerprint_id VARCHAR(64),
ADD COLUMN IF NOT EXISTS payment_method_type_v2 VARCHAR(64),
ADD COLUMN IF NOT EXISTS payment_method_subtype VARCHAR(64);
ALTER TABLE refund
ADD COLUMN IF NOT EXISTS id VARCHAR(64),
ADD COLUMN IF NOT EXISTS merchant_reference_id VARCHAR(64),
ADD COLUMN IF NOT EXISTS connector_id VARCHAR(64);
<file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="1670" end="1670">
type Value = PaymentMethodListRequest;
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/stripe/transformers.rs<|crate|> router anchor=from kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="3253" end="3260">
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Succeeded => Self::Success,
RefundStatus::Failed => Self::Failure,
RefundStatus::Pending => Self::Pending,
RefundStatus::RequiresAction => Self::ManualReview,
}
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="3317" end="3348">
fn try_from(
item: types::RefundsResponseRouterData<api::RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
let refund_status = enums::RefundStatus::from(item.response.status);
let response = if connector_util::is_refund_failure(refund_status) {
Err(types::ErrorResponse {
code: consts::NO_ERROR_CODE.to_string(),
message: item
.response
.failure_reason
.clone()
.unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()),
reason: item.response.failure_reason,
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(item.response.id),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
})
} else {
Ok(types::RefundsResponseData {
connector_refund_id: item.response.id,
refund_status,
})
};
Ok(Self {
response,
..item.data
})
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="3279" end="3310">
fn try_from(
item: types::RefundsResponseRouterData<api::Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
let refund_status = enums::RefundStatus::from(item.response.status);
let response = if connector_util::is_refund_failure(refund_status) {
Err(types::ErrorResponse {
code: consts::NO_ERROR_CODE.to_string(),
message: item
.response
.failure_reason
.clone()
.unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()),
reason: item.response.failure_reason,
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(item.response.id),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
})
} else {
Ok(types::RefundsResponseData {
connector_refund_id: item.response.id,
refund_status,
})
};
Ok(Self {
response,
..item.data
})
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="3199" end="3237">
fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> {
let amount = item.request.minor_refund_amount;
match item.request.split_refunds.as_ref() {
None => Err(errors::ConnectorError::MissingRequiredField {
field_name: "split_refunds",
}
.into()),
Some(split_refunds) => match split_refunds {
types::SplitRefundsRequest::StripeSplitRefund(stripe_refund) => {
let (refund_application_fee, reverse_transfer) = match &stripe_refund.options {
types::ChargeRefundsOptions::Direct(types::DirectChargeRefund {
revert_platform_fee,
}) => (Some(*revert_platform_fee), None),
types::ChargeRefundsOptions::Destination(
types::DestinationChargeRefund {
revert_platform_fee,
revert_transfer,
},
) => (Some(*revert_platform_fee), Some(*revert_transfer)),
};
Ok(Self {
charge: stripe_refund.charge_id.clone(),
refund_application_fee,
reverse_transfer,
amount: Some(amount),
meta_data: StripeMetadata {
order_id: Some(item.request.refund_id.clone()),
is_refund_id_as_reference: Some("true".to_string()),
},
})
}
_ => Err(errors::ConnectorError::MissingRequiredField {
field_name: "stripe_split_refund",
})?,
},
}
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="3172" end="3184">
fn try_from(
(item, refund_amount): (&types::RefundsRouterData<F>, MinorUnit),
) -> Result<Self, Self::Error> {
let payment_intent = item.request.connector_transaction_id.clone();
Ok(Self {
amount: Some(refund_amount),
payment_intent,
meta_data: StripeMetadata {
order_id: Some(item.request.refund_id.clone()),
is_refund_id_as_reference: Some("true".to_string()),
},
})
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="3244" end="3250">
pub enum RefundStatus {
Succeeded,
Failed,
#[default]
Pending,
RequiresAction,
}
<file_sep path="hyperswitch/crates/api_models/src/refunds.rs" role="context" start="378" end="384">
pub enum RefundStatus {
Succeeded,
Failed,
#[default]
Pending,
Review,
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/wise.rs<|crate|> router anchor=new kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/connector/wise.rs" role="context" start="37" end="41">
pub fn new() -> &'static Self {
&Self {
amount_converter: &MinorUnitForConnector,
}
}
<file_sep path="hyperswitch/crates/router/src/connector/wise.rs" role="context" start="36" end="36">
use common_utils::types::{AmountConvertor, MinorUnit, MinorUnitForConnector};
<file_sep path="hyperswitch/crates/router/src/connector/wise.rs" role="context" start="72" end="74">
fn id(&self) -> &'static str {
"wise"
}
<file_sep path="hyperswitch/crates/router/src/connector/wise.rs" role="context" start="49" end="68">
fn build_headers(
&self,
req: &types::RouterData<Flow, Request, Response>,
_connectors: &settings::Connectors,
) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
types::PayoutQuoteType::get_content_type(self)
.to_string()
.into(),
)];
let auth = wise::WiseAuthType::try_from(&req.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let mut api_key = vec![(
headers::AUTHORIZATION.to_string(),
auth.api_key.into_masked(),
)];
header.append(&mut api_key);
Ok(header)
}
<file_sep path="hyperswitch/crates/router/src/connector/wise.rs" role="context" start="483" end="501">
fn build_request(
&self,
req: &types::PayoutsRouterData<api::PoRecipient>,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
let request = services::RequestBuilder::new()
.method(services::Method::Post)
.url(&types::PayoutRecipientType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PayoutRecipientType::get_headers(
self, req, connectors,
)?)
.set_body(types::PayoutRecipientType::get_request_body(
self, req, connectors,
)?)
.build();
Ok(Some(request))
}
<file_sep path="hyperswitch/crates/router/src/connector/wise.rs" role="context" start="468" end="481">
fn get_request_body(
&self,
req: &types::PayoutsRouterData<api::PoRecipient>,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.source_currency,
)?;
let connector_router_data = wise::WiseRouterData::from((amount, req));
let connector_req = wise::WiseRecipientCreateRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/payu.rs<|crate|> router<|connector|> payu anchor=get_default_payment_info kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|>
<file_sep path="hyperswitch/crates/router/tests/connectors/payu.rs" role="context" start="45" end="50">
fn get_default_payment_info() -> Option<utils::PaymentInfo> {
Some(utils::PaymentInfo {
access_token: get_access_token(),
..Default::default()
})
}
<file_sep path="hyperswitch/crates/router/tests/connectors/payu.rs" role="context" start="88" end="130">
async fn should_authorize_gpay_payment() {
let authorize_response = Payu {}
.authorize_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Wallet(domain::WalletData::GooglePay(
domain::GooglePayWalletData {
pm_type: "CARD".to_string(),
description: "Visa1234567890".to_string(),
info: domain::GooglePayPaymentMethodInfo {
card_network: "VISA".to_string(),
card_details: "1234".to_string(),
assurance_details: None,
},
tokenization_data: domain::GpayTokenizationData {
token_type: "payu".to_string(),
token: r#"{"signature":"MEUCIQD7Ta+d9+buesrH2KKkF+03AqTen+eHHN8KFleHoKaiVAIgGvAXyI0Vg3ws8KlF7agW/gmXJhpJOOPkqiNVbn/4f0Y\u003d","protocolVersion":"ECv1","signedMessage":"{\"encryptedMessage\":\"UcdGP9F/1loU0aXvVj6VqGRPA5EAjHYfJrXD0N+5O13RnaJXKWIjch1zzjpy9ONOZHqEGAqYKIcKcpe5ppN4Fpd0dtbm1H4u+lA+SotCff3euPV6sne22/Pl/MNgbz5QvDWR0UjcXvIKSPNwkds1Ib7QMmH4GfZ3vvn6s534hxAmcv/LlkeM4FFf6py9crJK5fDIxtxRJncfLuuPeAXkyy+u4zE33HmT34Oe5MSW/kYZVz31eWqFy2YCIjbJcC9ElMluoOKSZ305UG7tYGB1LCFGQLtLxphrhPu1lEmGEZE1t2cVDoCzjr3rm1OcfENc7eNC4S+ko6yrXh1ZX06c/F9kunyLn0dAz8K5JLIwLdjw3wPADVSd3L0eM7jkzhH80I6nWkutO0x8BFltxWl+OtzrnAe093OUncH6/DK1pCxtJaHdw1WUWrzULcdaMZmPfA\\u003d\\u003d\",\"ephemeralPublicKey\":\"BH7A1FUBWiePkjh/EYmsjY/63D/6wU+4UmkLh7WW6v7PnoqQkjrFpc4kEP5a1Op4FkIlM9LlEs3wGdFB8xIy9cM\\u003d\",\"tag\":\"e/EOsw2Y2wYpJngNWQqH7J62Fhg/tzmgDl6UFGuAN+A\\u003d\"}"}"# .to_string()//Generate new GooglePay token this is bound to expire
},
},
)),
currency: enums::Currency::PLN,
..PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Pending);
if let Some(transaction_id) = utils::get_connector_transaction_id(authorize_response.response) {
let sync_response = Payu {}
.sync_payment(
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id.clone(),
),
..Default::default()
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(sync_response.status, enums::AttemptStatus::Authorized);
}
}
<file_sep path="hyperswitch/crates/router/tests/connectors/payu.rs" role="context" start="54" end="85">
async fn should_authorize_card_payment() {
//Authorize Card Payment in PLN currency
let authorize_response = Payu {}
.authorize_payment(
Some(types::PaymentsAuthorizeData {
currency: enums::Currency::PLN,
..PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
// in Payu need Psync to get status therefore set to pending
assert_eq!(authorize_response.status, enums::AttemptStatus::Pending);
if let Some(transaction_id) = utils::get_connector_transaction_id(authorize_response.response) {
let sync_response = Payu {}
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id.clone(),
),
..Default::default()
}),
get_default_payment_info(),
)
.await
.unwrap();
// Assert the sync response, it will be authorized in case of manual capture, for automatic it will be Completed Success
assert_eq!(sync_response.status, enums::AttemptStatus::Authorized);
}
}
<file_sep path="hyperswitch/crates/router/tests/connectors/payu.rs" role="context" start="35" end="44">
fn get_access_token() -> Option<AccessToken> {
let connector = Payu {};
match connector.get_auth_token() {
ConnectorAuthType::BodyKey { api_key, key1 } => Some(AccessToken {
token: api_key,
expires: key1.peek().parse::<i64>().unwrap(),
}),
_ => None,
}
}
<file_sep path="hyperswitch/crates/router/tests/connectors/payu.rs" role="context" start="30" end="32">
fn get_name(&self) -> String {
"payu".to_string()
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/services/kafka.rs<|crate|> router anchor=new kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/services/kafka.rs" role="context" start="125" end="130">
fn new(event: &'a T, tenant_id: TenantID) -> Self {
Self {
log: KafkaConsolidatedLog { event, tenant_id },
log_type: event.event_type(),
}
}
<file_sep path="hyperswitch/crates/router/src/services/kafka.rs" role="context" start="124" end="124">
pub type MQResult<T> = CustomResult<T, KafkaError>;
use crate::db::kafka_store::TenantID;
<file_sep path="hyperswitch/crates/router/src/services/kafka.rs" role="context" start="138" end="140">
fn event_type(&self) -> EventType {
EventType::Consolidated
}
<file_sep path="hyperswitch/crates/router/src/services/kafka.rs" role="context" start="134" end="136">
fn key(&self) -> String {
self.log.event.key()
}
<file_sep path="hyperswitch/crates/router/src/services/kafka.rs" role="context" start="106" end="108">
fn creation_timestamp(&self) -> Option<i64> {
self.event.creation_timestamp()
}
<file_sep path="hyperswitch/crates/router/src/services/kafka.rs" role="context" start="102" end="104">
fn event_type(&self) -> EventType {
self.event.event_type()
}
<file_sep path="hyperswitch/crates/router/src/services/kafka.rs" role="context" start="427" end="460">
pub async fn log_authentication(
&self,
authentication: &Authentication,
old_authentication: Option<Authentication>,
tenant_id: TenantID,
) -> MQResult<()> {
if let Some(negative_event) = old_authentication {
self.log_event(&KafkaEvent::old(
&KafkaAuthentication::from_storage(&negative_event),
tenant_id.clone(),
self.ckh_database_name.clone(),
))
.attach_printable_lazy(|| {
format!("Failed to add negative authentication event {negative_event:?}")
})?;
};
self.log_event(&KafkaEvent::new(
&KafkaAuthentication::from_storage(authentication),
tenant_id.clone(),
self.ckh_database_name.clone(),
))
.attach_printable_lazy(|| {
format!("Failed to add positive authentication event {authentication:?}")
})?;
self.log_event(&KafkaConsolidatedEvent::new(
&KafkaAuthenticationEvent::from_storage(authentication),
tenant_id.clone(),
))
.attach_printable_lazy(|| {
format!("Failed to add consolidated authentication event {authentication:?}")
})
}
<file_sep path="hyperswitch/crates/router/src/services/kafka.rs" role="context" start="508" end="537">
pub async fn log_refund(
&self,
refund: &Refund,
old_refund: Option<Refund>,
tenant_id: TenantID,
) -> MQResult<()> {
if let Some(negative_event) = old_refund {
self.log_event(&KafkaEvent::old(
&KafkaRefund::from_storage(&negative_event),
tenant_id.clone(),
self.ckh_database_name.clone(),
))
.attach_printable_lazy(|| {
format!("Failed to add negative refund event {negative_event:?}")
})?;
};
self.log_event(&KafkaEvent::new(
&KafkaRefund::from_storage(refund),
tenant_id.clone(),
self.ckh_database_name.clone(),
))
.attach_printable_lazy(|| format!("Failed to add positive refund event {refund:?}"))?;
self.log_event(&KafkaConsolidatedEvent::new(
&KafkaRefundEvent::from_storage(refund),
tenant_id.clone(),
))
.attach_printable_lazy(|| format!("Failed to add consolidated refund event {refund:?}"))
}
<file_sep path="hyperswitch/crates/router/src/services/kafka.rs" role="context" start="112" end="116">
struct KafkaConsolidatedLog<'a, T: KafkaMessage> {
#[serde(flatten)]
event: &'a T,
tenant_id: TenantID,
}
<file_sep path="hyperswitch/crates/router/src/db/kafka_store.rs" role="context" start="92" end="92">
pub struct TenantID(pub String);
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/nmi.rs<|crate|> router anchor=get_request_body kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/connector/nmi.rs" role="context" start="811" end="818">
fn get_request_body(
&self,
req: &types::RefundsRouterData<api::RSync>,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = nmi::NmiSyncRequest::try_from(req)?;
Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))
}
<file_sep path="hyperswitch/crates/router/src/connector/nmi.rs" role="context" start="810" end="810">
use common_utils::{
crypto,
ext_traits::ByteSliceExt,
request::RequestContent,
types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector},
};
use transformers as nmi;
use crate::{
configs::settings,
core::{
errors::{self, CustomResult},
payments,
},
events::connector_api_logs::ConnectorEvent,
services::{self, request, ConnectorIntegration, ConnectorSpecifications, ConnectorValidation},
types::{
self,
api::{self, ConnectorCommon, ConnectorCommonExt},
transformers::ForeignFrom,
ErrorResponse,
},
};
<file_sep path="hyperswitch/crates/router/src/connector/nmi.rs" role="context" start="837" end="853">
fn handle_response(
&self,
data: &types::RefundsRouterData<api::RSync>,
event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::RefundsRouterData<api::RSync>, errors::ConnectorError> {
let response = nmi::NmiRefundSyncResponse::try_from(res.response.to_vec())?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
<file_sep path="hyperswitch/crates/router/src/connector/nmi.rs" role="context" start="820" end="835">
fn build_request(
&self,
req: &types::RefundsRouterData<api::RSync>,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Post)
.url(&types::RefundSyncType::get_url(self, req, connectors)?)
.headers(types::RefundSyncType::get_headers(self, req, connectors)?)
.set_body(types::RefundSyncType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
<file_sep path="hyperswitch/crates/router/src/connector/nmi.rs" role="context" start="803" end="809">
fn get_url(
&self,
_req: &types::RefundsRouterData<api::RSync>,
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}api/query.php", self.base_url(connectors)))
}
<file_sep path="hyperswitch/crates/router/src/connector/nmi.rs" role="context" start="795" end="801">
fn get_headers(
&self,
req: &types::RefundsRouterData<api::RSync>,
connectors: &settings::Connectors,
) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
<file_sep path="hyperswitch/crates/router/src/connector/nmi.rs" role="context" start="749" end="766">
fn build_request(
&self,
req: &types::RefundsRouterData<api::Execute>,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Post)
.url(&types::RefundExecuteType::get_url(self, req, connectors)?)
.headers(types::RefundExecuteType::get_headers(
self, req, connectors,
)?)
.set_body(types::RefundExecuteType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
<file_sep path="hyperswitch/crates/router/src/connector/nmi.rs" role="context" start="37" end="41">
pub const fn new() -> &'static Self {
&Self {
amount_converter: &FloatMajorUnitForConnector,
}
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/services/authentication.rs<|crate|> router anchor=throw_error_if_platform_merchant_authentication_required kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="4034" end="4044">
fn throw_error_if_platform_merchant_authentication_required(
request_headers: &HeaderMap,
) -> RouterResult<()> {
HeaderMapStruct::new(request_headers)
.get_id_type_from_header_if_present::<id_type::MerchantId>(
headers::X_CONNECTED_MERCHANT_ID,
)?
.map_or(Ok(()), |_| {
Err(errors::ApiErrorResponse::PlatformAccountAuthNotSupported.into())
})
}
<file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="4033" end="4033">
use actix_web::http::header::HeaderMap;
use common_utils::{date_time, fp_utils, id_type};
use crate::core::errors::UserResult;
use crate::{
core::{
api_keys,
errors::{self, utils::StorageErrorExt, RouterResult},
},
headers,
routes::app::SessionStateInfo,
services::api,
types::{domain, storage},
utils::OptionExt,
};
<file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="4103" end="4131">
pub async fn new_token(
user_id: String,
merchant_id: id_type::MerchantId,
settings: &Settings,
org_id: id_type::OrganizationId,
profile_id: id_type::ProfileId,
tenant_id: Option<id_type::TenantId>,
role_info: authorization::roles::RoleInfo,
) -> UserResult<String> {
let exp_duration = std::time::Duration::from_secs(consts::JWT_TOKEN_TIME_IN_SECS);
let exp = jwt::generate_exp(exp_duration)?.as_secs();
let acl = role_info.get_recon_acl();
let optional_acl_str = serde_json::to_string(&acl)
.inspect_err(|err| logger::error!("Failed to serialize acl to string: {}", err))
.change_context(errors::UserErrors::InternalServerError)
.attach_printable("Failed to serialize acl to string. Using empty ACL")
.ok();
let token_payload = Self {
user_id,
merchant_id,
role_id: role_info.get_role_id().to_string(),
exp,
org_id,
profile_id,
tenant_id,
acl: optional_acl_str,
};
jwt::generate_jwt(&token_payload, settings).await
}
<file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="4052" end="4084">
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(UserFromTokenWithRoleInfo, AuthenticationType)> {
let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?;
if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
authorization::check_tenant(
payload.tenant_id.clone(),
&state.session_state().tenant.tenant_id,
)?;
let role_info = authorization::get_role_info(state, &payload).await?;
authorization::check_permission(self.permission, &role_info)?;
let user = UserFromToken {
user_id: payload.user_id.clone(),
merchant_id: payload.merchant_id.clone(),
org_id: payload.org_id,
role_id: payload.role_id,
profile_id: payload.profile_id,
tenant_id: payload.tenant_id,
};
Ok((
UserFromTokenWithRoleInfo { user, role_info },
AuthenticationType::MerchantJwt {
merchant_id: payload.merchant_id,
user_id: Some(payload.user_id),
},
))
}
<file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="4016" end="4032">
fn get_and_validate_connected_merchant_id(
request_headers: &HeaderMap,
merchant_account: &domain::MerchantAccount,
) -> RouterResult<Option<id_type::MerchantId>> {
HeaderMapStruct::new(request_headers)
.get_id_type_from_header_if_present::<id_type::MerchantId>(
headers::X_CONNECTED_MERCHANT_ID,
)?
.map(|merchant_id| {
merchant_account
.is_platform_account
.then_some(merchant_id)
.ok_or(errors::ApiErrorResponse::InvalidPlatformOperation)
})
.transpose()
.attach_printable("Non platform_merchant_account using X_CONNECTED_MERCHANT_ID header")
}
<file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="3991" end="4014">
async fn get_platform_merchant_account<A>(
state: &A,
request_headers: &HeaderMap,
merchant_account: domain::MerchantAccount,
) -> RouterResult<(domain::MerchantAccount, Option<domain::MerchantAccount>)>
where
A: SessionStateInfo + Sync,
{
let connected_merchant_id =
get_and_validate_connected_merchant_id(request_headers, &merchant_account)?;
match connected_merchant_id {
Some(merchant_id) => {
let connected_merchant_account = get_connected_merchant_account(
state,
merchant_id,
merchant_account.organization_id.clone(),
)
.await?;
Ok((connected_merchant_account, Some(merchant_account)))
}
None => Ok((merchant_account, None)),
}
}
<file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="1855" end="1906">
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(AuthenticationData, AuthenticationType)> {
if state.conf().platform.enabled {
throw_error_if_platform_merchant_authentication_required(request_headers)?;
}
let key_manager_state = &(&state.session_state()).into();
let profile_id =
get_id_type_by_key_from_headers(headers::X_PROFILE_ID.to_string(), request_headers)?
.get_required_value(headers::X_PROFILE_ID)?;
let key_store = state
.store()
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&self.0,
&state.store().get_master_key().to_vec().into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
let profile = state
.store()
.find_business_profile_by_merchant_id_profile_id(
key_manager_state,
&key_store,
&self.0,
&profile_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
let merchant = state
.store()
.find_merchant_account_by_merchant_id(key_manager_state, &self.0, &key_store)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
let auth = AuthenticationData {
merchant_account: merchant,
key_store,
profile,
platform_merchant_account: None,
};
Ok((
auth.clone(),
AuthenticationType::MerchantId {
merchant_id: auth.merchant_account.get_id().clone(),
},
))
}
<file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="1808" end="1846">
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(AuthenticationData, AuthenticationType)> {
if state.conf().platform.enabled {
throw_error_if_platform_merchant_authentication_required(request_headers)?;
}
let key_manager_state = &(&state.session_state()).into();
let key_store = state
.store()
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&self.0,
&state.store().get_master_key().to_vec().into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
let merchant = state
.store()
.find_merchant_account_by_merchant_id(key_manager_state, &self.0, &key_store)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
let auth = AuthenticationData {
merchant_account: merchant,
platform_merchant_account: None,
key_store,
profile_id: None,
};
Ok((
auth.clone(),
AuthenticationType::MerchantId {
merchant_id: auth.merchant_account.get_id().clone(),
},
))
}
<file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="1506" end="1508">
pub fn new(headers: &'a HeaderMap) -> Self {
HeaderMapStruct { headers }
}
<file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="1501" end="1503">
pub(crate) struct HeaderMapStruct<'a> {
headers: &'a HeaderMap,
}
<file_sep path="hyperswitch/crates/router/tests/utils.rs" role="context" start="389" end="391">
pub struct MerchantId {
merchant_id: common_utils::id_type::MerchantId,
}
<file_sep path="hyperswitch/crates/api_models/src/errors/types.rs" role="context" start="86" end="100">
pub enum ApiErrorResponse {
Unauthorized(ApiError),
ForbiddenCommonResource(ApiError),
ForbiddenPrivateResource(ApiError),
Conflict(ApiError),
Gone(ApiError),
Unprocessable(ApiError),
InternalServerError(ApiError),
NotImplemented(ApiError),
ConnectorError(ApiError, #[serde(skip_serializing)] StatusCode),
NotFound(ApiError),
MethodNotAllowed(ApiError),
BadRequest(ApiError),
DomainError(ApiError),
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/services/authentication.rs<|crate|> router anchor=get_id_type_by_key_from_headers kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="3830" end="3843">
pub fn get_id_type_by_key_from_headers<T: FromStr>(
key: String,
headers: &HeaderMap,
) -> RouterResult<Option<T>> {
get_header_value_by_key(key.clone(), headers)?
.map(|str_value| T::from_str(str_value))
.transpose()
.map_err(|_err| {
error_stack::report!(errors::ApiErrorResponse::InvalidDataFormat {
field_name: key,
expected_format: "Valid Id String".to_string(),
})
})
}
<file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="3829" end="3829">
use std::str::FromStr;
use actix_web::http::header::HeaderMap;
use error_stack::{report, ResultExt};
use crate::core::errors::UserResult;
use crate::{
core::{
api_keys,
errors::{self, utils::StorageErrorExt, RouterResult},
},
headers,
routes::app::SessionStateInfo,
services::api,
types::{domain, storage},
utils::OptionExt,
};
pub type AuthenticationDataWithUserId = (AuthenticationData, String);
<file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="3856" end="3864">
pub fn get_cookie_from_header(headers: &HeaderMap) -> RouterResult<&str> {
let cookie = headers
.get(cookies::get_cookie_header())
.ok_or(report!(errors::ApiErrorResponse::CookieNotFound))?;
cookie
.to_str()
.change_context(errors::ApiErrorResponse::InvalidCookie)
}
<file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="3845" end="3854">
pub fn get_jwt_from_authorization_header(headers: &HeaderMap) -> RouterResult<&str> {
headers
.get(headers::AUTHORIZATION)
.get_required_value(headers::AUTHORIZATION)?
.to_str()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to convert JWT token to string")?
.strip_prefix("Bearer ")
.ok_or(errors::ApiErrorResponse::InvalidJwtToken.into())
}
<file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="3816" end="3829">
pub fn get_header_value_by_key(key: String, headers: &HeaderMap) -> RouterResult<Option<&str>> {
headers
.get(&key)
.map(|source_str| {
source_str
.to_str()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(format!(
"Failed to convert header value to string for header key: {}",
key
))
})
.transpose()
}
<file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="3812" end="3814">
pub fn get_api_key(headers: &HeaderMap) -> RouterResult<&str> {
get_header_value_by_key("api-key".into(), headers)?.get_required_value("api_key")
}
<file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="2669" end="2741">
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(AuthenticationData, AuthenticationType)> {
let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?;
if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
let profile_id =
get_id_type_by_key_from_headers(headers::X_PROFILE_ID.to_string(), request_headers)?
.get_required_value(headers::X_PROFILE_ID)?;
let role_info = authorization::get_role_info(state, &payload).await?;
authorization::check_permission(self.required_permission, &role_info)?;
let merchant_id_from_header = HeaderMapStruct::new(request_headers)
.get_id_type_from_header::<id_type::MerchantId>(headers::X_MERCHANT_ID)?;
// Check if token has access to MerchantId that has been requested through headers
if payload.merchant_id != merchant_id_from_header {
return Err(report!(errors::ApiErrorResponse::InvalidJwtToken));
}
let key_manager_state = &(&state.session_state()).into();
let key_store = state
.store()
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&payload.merchant_id,
&state.store().get_master_key().to_vec().into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken)
.attach_printable("Failed to fetch merchant key store for the merchant id")?;
let profile = state
.store()
.find_business_profile_by_merchant_id_profile_id(
key_manager_state,
&key_store,
&payload.merchant_id,
&profile_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
let merchant = state
.store()
.find_merchant_account_by_merchant_id(
key_manager_state,
&payload.merchant_id,
&key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken)
.attach_printable("Failed to fetch merchant account for the merchant id")?;
let auth = AuthenticationData {
merchant_account: merchant,
key_store,
profile,
platform_merchant_account: None,
};
Ok((
auth,
AuthenticationType::MerchantJwt {
merchant_id: payload.merchant_id,
user_id: Some(payload.user_id),
},
))
}
<file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="1662" end="1717">
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(AuthenticationData, AuthenticationType)> {
if state.conf().platform.enabled {
throw_error_if_platform_merchant_authentication_required(request_headers)?;
}
V2AdminApiAuth
.authenticate_and_fetch(request_headers, state)
.await?;
let merchant_id = HeaderMapStruct::new(request_headers)
.get_id_type_from_header::<id_type::MerchantId>(headers::X_MERCHANT_ID)?;
let profile_id =
get_id_type_by_key_from_headers(headers::X_PROFILE_ID.to_string(), request_headers)?
.get_required_value(headers::X_PROFILE_ID)?;
let key_manager_state = &(&state.session_state()).into();
let key_store = state
.store()
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&merchant_id,
&state.store().get_master_key().to_vec().into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
let profile = state
.store()
.find_business_profile_by_merchant_id_profile_id(
key_manager_state,
&key_store,
&merchant_id,
&profile_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
let merchant = state
.store()
.find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
let auth = AuthenticationData {
merchant_account: merchant,
key_store,
profile,
platform_merchant_account: None,
};
Ok((
auth,
AuthenticationType::AdminApiAuthWithMerchantId { merchant_id },
))
}
<file_sep path="hyperswitch/crates/router/src/core/errors.rs" role="context" start="31" end="31">
pub type RouterResult<T> = CustomResult<T, ApiErrorResponse>;
<file_sep path="hyperswitch/crates/api_models/src/errors/types.rs" role="context" start="86" end="100">
pub enum ApiErrorResponse {
Unauthorized(ApiError),
ForbiddenCommonResource(ApiError),
ForbiddenPrivateResource(ApiError),
Conflict(ApiError),
Gone(ApiError),
Unprocessable(ApiError),
InternalServerError(ApiError),
NotImplemented(ApiError),
ConnectorError(ApiError, #[serde(skip_serializing)] StatusCode),
NotFound(ApiError),
MethodNotAllowed(ApiError),
BadRequest(ApiError),
DomainError(ApiError),
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/services/email/types.rs<|crate|> router anchor=new kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/services/email/types.rs" role="context" start="568" end="591">
pub fn new(
state: &SessionState,
data: ProdIntent,
theme_id: Option<String>,
theme_config: EmailThemeConfig,
) -> UserResult<Self> {
Ok(Self {
recipient_email: domain::UserEmail::from_pii_email(
state.conf.email.prod_intent_recipient_email.clone(),
)?,
settings: state.conf.clone(),
user_name: data.poc_name.unwrap_or_default().into(),
poc_email: data.poc_email.unwrap_or_default(),
legal_business_name: data.legal_business_name.unwrap_or_default(),
business_location: data
.business_location
.unwrap_or(common_enums::CountryAlpha2::AD)
.to_string(),
business_website: data.business_website.unwrap_or_default(),
theme_id,
theme_config,
product_type: data.product_type,
})
}
<file_sep path="hyperswitch/crates/router/src/services/email/types.rs" role="context" start="567" end="567">
use api_models::user::dashboard_metadata::ProdIntent;
use common_enums::{EntityType, MerchantProductType};
use common_utils::{errors::CustomResult, pii, types::theme::EmailThemeConfig};
use external_services::email::{EmailContents, EmailData, EmailError};
use crate::{configs, consts, routes::SessionState};
use crate::{
core::errors::{UserErrors, UserResult},
services::jwt,
types::domain,
};
<file_sep path="hyperswitch/crates/router/src/services/email/types.rs" role="context" start="627" end="642">
async fn get_email_data(&self, _base_url: &str) -> CustomResult<EmailContents, EmailError> {
let recipient = self.recipient_email.clone().into_inner();
let body = html::get_html_body(EmailBody::ProFeatureRequest {
user_name: self.user_name.clone().get_secret().expose(),
feature_name: self.feature_name.clone(),
merchant_id: self.merchant_id.clone(),
user_email: self.user_email.clone().get_secret().expose(),
});
Ok(EmailContents {
subject: self.subject.clone(),
body: external_services::email::IntermediateString::new(body),
recipient,
})
}
<file_sep path="hyperswitch/crates/router/src/services/email/types.rs" role="context" start="596" end="611">
async fn get_email_data(&self, _base_url: &str) -> CustomResult<EmailContents, EmailError> {
let body = html::get_html_body(EmailBody::BizEmailProd {
user_name: self.user_name.clone().expose(),
poc_email: self.poc_email.clone().expose(),
legal_business_name: self.legal_business_name.clone(),
business_location: self.business_location.clone(),
business_website: self.business_website.clone(),
product_type: self.product_type,
});
Ok(EmailContents {
subject: "New Prod Intent".to_string(),
body: external_services::email::IntermediateString::new(body),
recipient: self.recipient_email.clone().into_inner(),
})
}
<file_sep path="hyperswitch/crates/router/src/services/email/types.rs" role="context" start="541" end="551">
async fn get_email_data(&self, _base_url: &str) -> CustomResult<EmailContents, EmailError> {
let body = html::get_html_body(EmailBody::ReconActivation {
user_name: self.user_name.clone().get_secret().expose(),
});
Ok(EmailContents {
subject: self.subject.to_string(),
body: external_services::email::IntermediateString::new(body),
recipient: self.recipient_email.clone().into_inner(),
})
}
<file_sep path="hyperswitch/crates/router/src/services/email/types.rs" role="context" start="493" end="528">
async fn get_email_data(&self, base_url: &str) -> CustomResult<EmailContents, EmailError> {
let token = EmailToken::new_token(
self.recipient_email.clone(),
Some(self.entity.clone()),
domain::Origin::AcceptInvitationFromEmail,
&self.settings,
)
.await
.change_context(EmailError::TokenGenerationFailure)?;
let invite_user_link = get_link_with_token(
base_url,
token,
"accept_invite_from_email",
&self.auth_id,
&self.theme_id,
);
let body = html::get_html_body(EmailBody::AcceptInviteFromEmail {
link: invite_user_link,
user_name: self.user_name.clone().get_secret().expose(),
entity_name: self.theme_config.entity_name.clone(),
entity_logo_url: self.theme_config.entity_logo_url.clone(),
primary_color: self.theme_config.primary_color.clone(),
background_color: self.theme_config.background_color.clone(),
foreground_color: self.theme_config.foreground_color.clone(),
});
Ok(EmailContents {
subject: format!(
"You have been invited to join {} Community!",
self.theme_config.entity_name
),
body: external_services::email::IntermediateString::new(body),
recipient: self.recipient_email.clone().into_inner(),
})
}
<file_sep path="hyperswitch/crates/router/src/services/email/types.rs" role="context" start="442" end="478">
async fn get_email_data(&self, base_url: &str) -> CustomResult<EmailContents, EmailError> {
let token = EmailToken::new_token(
self.recipient_email.clone(),
None,
domain::Origin::MagicLink,
&self.settings,
)
.await
.change_context(EmailError::TokenGenerationFailure)?;
let magic_link_login = get_link_with_token(
base_url,
token,
"verify_email",
&self.auth_id,
&self.theme_id,
);
let body = html::get_html_body(EmailBody::MagicLink {
link: magic_link_login,
user_name: self.user_name.clone().get_secret().expose(),
entity_name: self.theme_config.entity_name.clone(),
entity_logo_url: self.theme_config.entity_logo_url.clone(),
primary_color: self.theme_config.primary_color.clone(),
background_color: self.theme_config.background_color.clone(),
foreground_color: self.theme_config.foreground_color.clone(),
});
Ok(EmailContents {
subject: format!(
"Unlock {}: Use Your Magic Link to Sign In",
self.theme_config.entity_name
),
body: external_services::email::IntermediateString::new(body),
recipient: self.recipient_email.clone().into_inner(),
})
}
<file_sep path="hyperswitch/crates/router/src/services/email/types.rs" role="context" start="392" end="428">
async fn get_email_data(&self, base_url: &str) -> CustomResult<EmailContents, EmailError> {
let token = EmailToken::new_token(
self.recipient_email.clone(),
None,
domain::Origin::ResetPassword,
&self.settings,
)
.await
.change_context(EmailError::TokenGenerationFailure)?;
let reset_password_link = get_link_with_token(
base_url,
token,
"set_password",
&self.auth_id,
&self.theme_id,
);
let body = html::get_html_body(EmailBody::Reset {
link: reset_password_link,
user_name: self.user_name.clone().get_secret().expose(),
entity_name: self.theme_config.entity_name.clone(),
entity_logo_url: self.theme_config.entity_logo_url.clone(),
primary_color: self.theme_config.primary_color.clone(),
background_color: self.theme_config.background_color.clone(),
foreground_color: self.theme_config.foreground_color.clone(),
});
Ok(EmailContents {
subject: format!(
"Get back to {} - Reset Your Password Now!",
self.theme_config.entity_name
),
body: external_services::email::IntermediateString::new(body),
recipient: self.recipient_email.clone().into_inner(),
})
}
<file_sep path="hyperswitch/crates/api_models/src/user/dashboard_metadata.rs" role="context" start="93" end="108">
pub struct ProdIntent {
pub legal_business_name: Option<String>,
pub business_label: Option<String>,
pub business_location: Option<CountryAlpha2>,
pub display_name: Option<String>,
pub poc_email: Option<Secret<String>>,
pub business_type: Option<String>,
pub business_identifier: Option<String>,
pub business_website: Option<String>,
pub poc_name: Option<String>,
pub poc_contact: Option<String>,
pub comments: Option<String>,
pub is_completed: bool,
#[serde(default)]
pub product_type: MerchantProductType,
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/utils.rs<|crate|> router<|connector|> utils anchor=call_connector kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/tests/connectors/utils.rs" role="context" start="856" end="893">
async fn call_connector<
T: Debug + Clone + 'static,
ResourceCommonData: Debug
+ Clone
+ services::connector_integration_interface::RouterDataConversion<T, Req, Resp>
+ 'static,
Req: Debug + Clone + 'static,
Resp: Debug + Clone + 'static,
>(
request: RouterData<T, Req, Resp>,
integration: BoxedConnectorIntegrationInterface<T, ResourceCommonData, Req, Resp>,
) -> Result<RouterData<T, Req, Resp>, Report<ConnectorError>> {
let conf = Settings::new().unwrap();
let tx: oneshot::Sender<()> = oneshot::channel().0;
let app_state = Box::pin(routes::AppState::with_storage(
conf,
StorageImpl::PostgresqlTest,
tx,
Box::new(services::MockApiClient),
))
.await;
let state = Arc::new(app_state)
.get_session_state(
&common_utils::id_type::TenantId::try_from_string("public".to_string()).unwrap(),
None,
|| {},
)
.unwrap();
services::api::execute_connector_processing_step(
&state,
integration,
&request,
payments::CallConnectorAction::Trigger,
None,
)
.await
}
<file_sep path="hyperswitch/crates/router/tests/connectors/utils.rs" role="context" start="855" end="855">
use std::{fmt::Debug, marker::PhantomData, str::FromStr, sync::Arc, time::Duration};
use error_stack::Report;
use router::{
configs::settings::Settings,
core::{errors::ConnectorError, payments},
db::StorageImpl,
routes,
services::{
self,
connector_integration_interface::{BoxedConnectorIntegrationInterface, ConnectorEnum},
},
types::{self, storage::enums, AccessToken, MinorUnit, PaymentAddress, RouterData},
};
<file_sep path="hyperswitch/crates/router/tests/connectors/utils.rs" role="context" start="930" end="944">
fn default() -> Self {
Self(types::domain::Card {
card_number: cards::CardNumber::from_str("4200000000000000").unwrap(),
card_exp_month: Secret::new("10".to_string()),
card_exp_year: Secret::new("2025".to_string()),
card_cvc: Secret::new("999".to_string()),
card_issuer: None,
card_network: None,
card_type: None,
card_issuing_country: None,
bank_code: None,
nick_name: Some(Secret::new("nick_name".into())),
card_holder_name: Some(Secret::new("card holder name".into())),
})
}
<file_sep path="hyperswitch/crates/router/tests/connectors/utils.rs" role="context" start="902" end="916">
async fn start_server(&self, config: MockConfig) -> MockServer {
let address = config
.address
.unwrap_or_else(|| "127.0.0.1:9090".to_string());
let listener = std::net::TcpListener::bind(address).unwrap();
let expected_server_address = listener
.local_addr()
.expect("Failed to get server address.");
let mock_server = MockServer::builder().listener(listener).start().await;
assert_eq!(&expected_server_address, mock_server.address());
for mock in config.mocks {
mock_server.register(mock).await;
}
mock_server
}
<file_sep path="hyperswitch/crates/router/tests/connectors/utils.rs" role="context" start="813" end="853">
async fn create_payout_recipient(
&self,
payout_type: enums::PayoutType,
payment_info: Option<PaymentInfo>,
) -> Result<types::PayoutsResponseData, Report<ConnectorError>> {
let connector_integration: services::BoxedPayoutConnectorIntegrationInterface<
types::api::PoRecipient,
types::PayoutsData,
types::PayoutsResponseData,
> = self
.get_payout_data()
.ok_or(ConnectorError::FailedToObtainPreferredConnector)?
.connector
.get_connector_integration();
let request = self.get_payout_request(None, payout_type, payment_info);
let tx = oneshot::channel().0;
let app_state = Box::pin(routes::AppState::with_storage(
Settings::new().unwrap(),
StorageImpl::PostgresqlTest,
tx,
Box::new(services::MockApiClient),
))
.await;
let state = Arc::new(app_state)
.get_session_state(
&common_utils::id_type::TenantId::try_from_string("public".to_string()).unwrap(),
None,
|| {},
)
.unwrap();
let res = services::api::execute_connector_processing_step(
&state,
connector_integration,
&request,
payments::CallConnectorAction::Trigger,
None,
)
.await?;
Ok(res.response.unwrap())
}
<file_sep path="hyperswitch/crates/router/tests/connectors/utils.rs" role="context" start="785" end="810">
async fn create_and_cancel_payout(
&self,
connector_customer: Option<String>,
payout_type: enums::PayoutType,
payment_info: Option<PaymentInfo>,
) -> Result<types::PayoutsResponseData, Report<ConnectorError>> {
let create_res = self
.create_payout(connector_customer, payout_type, payment_info.to_owned())
.await?;
assert_eq!(
create_res.status.unwrap(),
enums::PayoutStatus::RequiresFulfillment
);
let cancel_res = self
.cancel_payout(
create_res
.connector_payout_id
.ok_or(ConnectorError::MissingRequiredField {
field_name: "connector_payout_id",
})?,
payout_type,
payment_info.to_owned(),
)
.await?;
Ok(cancel_res)
}
<file_sep path="hyperswitch/crates/router/tests/connectors/utils.rs" role="context" start="385" end="417">
async fn sync_refund(
&self,
refund_id: String,
payment_data: Option<types::RefundsData>,
payment_info: Option<PaymentInfo>,
) -> Result<types::RefundSyncRouterData, Report<ConnectorError>> {
let integration = self.get_data().connector.get_connector_integration();
let request = self.generate_data(
payment_data.unwrap_or_else(|| types::RefundsData {
payment_amount: 1000,
minor_payment_amount: MinorUnit::new(1000),
currency: enums::Currency::USD,
refund_id: uuid::Uuid::new_v4().to_string(),
connector_transaction_id: "".to_string(),
webhook_url: None,
refund_amount: 100,
minor_refund_amount: MinorUnit::new(100),
connector_metadata: None,
refund_connector_metadata: None,
reason: None,
connector_refund_id: Some(refund_id),
browser_info: None,
split_refunds: None,
integrity_object: None,
refund_status: enums::RefundStatus::Pending,
merchant_account_id: None,
merchant_config_currency: None,
capture_method: None,
}),
payment_info,
);
Box::pin(call_connector(request, integration)).await
}
<file_sep path="hyperswitch/crates/router/tests/connectors/utils.rs" role="context" start="117" end="130">
async fn create_connector_customer(
&self,
payment_data: Option<types::ConnectorCustomerData>,
payment_info: Option<PaymentInfo>,
) -> Result<types::ConnectorCustomerRouterData, Report<ConnectorError>> {
let integration = self.get_data().connector.get_connector_integration();
let request = self.generate_data(
types::ConnectorCustomerData {
..(payment_data.unwrap_or(CustomerType::default().0))
},
payment_info,
);
Box::pin(call_connector(request, integration)).await
}
<file_sep path="hyperswitch/crates/api_models/src/user/theme.rs" role="context" start="63" end="70">
struct Settings {
colors: Colors,
sidebar: Option<Sidebar>,
typography: Option<Typography>,
buttons: Buttons,
borders: Option<Borders>,
spacing: Option<Spacing>,
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/routing.rs<|crate|> router anchor=new kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/routing.rs" role="context" start="75" end="93">
pub fn new(
setup_mandate: Option<&'a mandates::MandateData>,
payment_attempt: &'a storage::PaymentAttempt,
payment_intent: &'a storage::PaymentIntent,
payment_method_data: Option<&'a domain::PaymentMethodData>,
address: &'a payment_address::PaymentAddress,
recurring_details: Option<&'a mandates_api::RecurringDetails>,
currency: storage_enums::Currency,
) -> Self {
Self {
setup_mandate,
payment_attempt,
payment_intent,
payment_method_data,
address,
recurring_details,
currency,
}
}
<file_sep path="hyperswitch/crates/router/src/core/routing.rs" role="context" start="74" end="74">
use api_models::{
enums, mandates as mandates_api, routing,
routing::{self as routing_types, RoutingRetrieveQuery},
};
use hyperswitch_domain_models::{mandates, payment_address};
use crate::{
core::{
errors::{self, CustomResult, RouterResponse, StorageErrorExt},
metrics, utils as core_utils,
},
db::StorageInterface,
routes::SessionState,
services::api as service_api,
types::{
api, domain,
storage::{self, enums as storage_enums},
transformers::{ForeignInto, ForeignTryFrom},
},
utils::{self, OptionExt},
};
<file_sep path="hyperswitch/crates/router/src/core/routing.rs" role="context" start="123" end="133">
pub async fn fetch_routing_algo(
merchant_id: &common_utils::id_type::MerchantId,
algorithm_id: &common_utils::id_type::RoutingId,
db: &dyn StorageInterface,
) -> RouterResult<Self> {
let routing_algo = db
.find_routing_algorithm_by_algorithm_id_merchant_id(algorithm_id, merchant_id)
.await
.change_context(errors::ApiErrorResponse::ResourceIdNotFound)?;
Ok(Self(routing_algo))
}
<file_sep path="hyperswitch/crates/router/src/core/routing.rs" role="context" start="101" end="122">
pub fn create_new_routing_algorithm(
request: &routing_types::RoutingConfigRequest,
merchant_id: &common_utils::id_type::MerchantId,
profile_id: common_utils::id_type::ProfileId,
transaction_type: enums::TransactionType,
) -> Self {
let algorithm_id = common_utils::generate_routing_id_of_default_length();
let timestamp = common_utils::date_time::now();
let algo = RoutingAlgorithm {
algorithm_id,
profile_id,
merchant_id: merchant_id.clone(),
name: request.name.clone(),
description: Some(request.description.clone()),
kind: request.algorithm.get_kind().foreign_into(),
algorithm_data: serde_json::json!(request.algorithm),
created_at: timestamp,
modified_at: timestamp,
algorithm_for: transaction_type,
};
Self(algo)
}
<file_sep path="hyperswitch/crates/router/src/core/routing.rs" role="context" start="1878" end="1934">
pub async fn construct_dsl_and_perform_eligibility_analysis<F, D>(
self,
state: &SessionState,
key_store: &domain::MerchantKeyStore,
payment_data: &D,
profile_id: &common_utils::id_type::ProfileId,
) -> RouterResult<Vec<api::ConnectorData>>
where
F: Send + Clone,
D: OperationSessionGetters<F>,
{
let payments_dsl_input = PaymentsDslInput::new(
payment_data.get_setup_mandate(),
payment_data.get_payment_attempt(),
payment_data.get_payment_intent(),
payment_data.get_payment_method_data(),
payment_data.get_address(),
payment_data.get_recurring_details(),
payment_data.get_currency(),
);
let routable_connector_choice = self.0.clone();
let backend_input = payments_routing::make_dsl_input(&payments_dsl_input)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to construct dsl input")?;
let connectors = payments_routing::perform_cgraph_filtering(
state,
key_store,
routable_connector_choice,
backend_input,
None,
profile_id,
&common_enums::TransactionType::Payment,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Eligibility analysis failed for routable connectors")?;
let connector_data = connectors
.into_iter()
.map(|conn| {
api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
&conn.connector.to_string(),
api::GetToken::Connector,
conn.merchant_connector_id.clone(),
)
})
.collect::<CustomResult<Vec<_>, _>>()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Invalid connector name received")?;
Ok(connector_data)
}
<file_sep path="hyperswitch/crates/router/src/core/routing.rs" role="context" start="949" end="973">
pub async fn retrieve_default_fallback_algorithm_for_profile(
state: SessionState,
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
profile_id: common_utils::id_type::ProfileId,
) -> RouterResponse<Vec<routing_types::RoutableConnectorChoice>> {
metrics::ROUTING_RETRIEVE_DEFAULT_CONFIG.add(1, &[]);
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
let profile = core_utils::validate_and_get_business_profile(
db,
key_manager_state,
&key_store,
Some(&profile_id),
merchant_account.get_id(),
)
.await?
.get_required_value("Profile")?;
let connectors_choice = admin::ProfileWrapper::new(profile)
.get_default_fallback_list_of_connector_under_profile()?;
metrics::ROUTING_RETRIEVE_DEFAULT_CONFIG_SUCCESS_RESPONSE.add(1, &[]);
Ok(service_api::ApplicationResponse::Json(connectors_choice))
}
<file_sep path="hyperswitch/crates/router/src/compatibility/stripe/customers/types.rs" role="context" start="202" end="207">
pub struct PaymentMethodData {
pub id: Option<String>,
pub object: &'static str,
pub card: Option<CardDetails>,
pub created: Option<time::PrimitiveDateTime>,
}
<file_sep path="hyperswitch/v2_compatible_migrations/2024-08-28-081721_add_v2_columns/up.sql" role="context" start="19" end="35">
-- Intentionally not adding a default value here since we would have to
-- check if any merchants have enabled this from configs table,
-- before filling data for this column.
-- If no merchants have enabled this, then we can use `false` as the default value
-- when adding the column, later we can drop the default added for the column
-- so that we ensure new records inserted always have a value for the column.
ADD COLUMN should_collect_cvv_during_payment BOOLEAN;
ALTER TABLE payment_intent
ADD COLUMN merchant_reference_id VARCHAR(64),
ADD COLUMN billing_address BYTEA DEFAULT NULL,
ADD COLUMN shipping_address BYTEA DEFAULT NULL,
ADD COLUMN capture_method "CaptureMethod",
ADD COLUMN authentication_type "AuthenticationType",
ADD COLUMN amount_to_capture bigint,
ADD COLUMN prerouting_algorithm JSONB,
ADD COLUMN surcharge_amount bigint,
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/routing.rs<|crate|> router anchor=new kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/routing.rs" role="context" start="75" end="93">
pub fn new(
setup_mandate: Option<&'a mandates::MandateData>,
payment_attempt: &'a storage::PaymentAttempt,
payment_intent: &'a storage::PaymentIntent,
payment_method_data: Option<&'a domain::PaymentMethodData>,
address: &'a payment_address::PaymentAddress,
recurring_details: Option<&'a mandates_api::RecurringDetails>,
currency: storage_enums::Currency,
) -> Self {
Self {
setup_mandate,
payment_attempt,
payment_intent,
payment_method_data,
address,
recurring_details,
currency,
}
}
<file_sep path="hyperswitch/crates/router/src/core/routing.rs" role="context" start="74" end="74">
use api_models::{
enums, mandates as mandates_api, routing,
routing::{self as routing_types, RoutingRetrieveQuery},
};
use hyperswitch_domain_models::{mandates, payment_address};
use crate::{
core::{
errors::{self, CustomResult, RouterResponse, StorageErrorExt},
metrics, utils as core_utils,
},
db::StorageInterface,
routes::SessionState,
services::api as service_api,
types::{
api, domain,
storage::{self, enums as storage_enums},
transformers::{ForeignInto, ForeignTryFrom},
},
utils::{self, OptionExt},
};
<file_sep path="hyperswitch/crates/router/src/core/routing.rs" role="context" start="123" end="133">
pub async fn fetch_routing_algo(
merchant_id: &common_utils::id_type::MerchantId,
algorithm_id: &common_utils::id_type::RoutingId,
db: &dyn StorageInterface,
) -> RouterResult<Self> {
let routing_algo = db
.find_routing_algorithm_by_algorithm_id_merchant_id(algorithm_id, merchant_id)
.await
.change_context(errors::ApiErrorResponse::ResourceIdNotFound)?;
Ok(Self(routing_algo))
}
<file_sep path="hyperswitch/crates/router/src/core/routing.rs" role="context" start="101" end="122">
pub fn create_new_routing_algorithm(
request: &routing_types::RoutingConfigRequest,
merchant_id: &common_utils::id_type::MerchantId,
profile_id: common_utils::id_type::ProfileId,
transaction_type: enums::TransactionType,
) -> Self {
let algorithm_id = common_utils::generate_routing_id_of_default_length();
let timestamp = common_utils::date_time::now();
let algo = RoutingAlgorithm {
algorithm_id,
profile_id,
merchant_id: merchant_id.clone(),
name: request.name.clone(),
description: Some(request.description.clone()),
kind: request.algorithm.get_kind().foreign_into(),
algorithm_data: serde_json::json!(request.algorithm),
created_at: timestamp,
modified_at: timestamp,
algorithm_for: transaction_type,
};
Self(algo)
}
<file_sep path="hyperswitch/crates/router/src/core/routing.rs" role="context" start="1878" end="1934">
pub async fn construct_dsl_and_perform_eligibility_analysis<F, D>(
self,
state: &SessionState,
key_store: &domain::MerchantKeyStore,
payment_data: &D,
profile_id: &common_utils::id_type::ProfileId,
) -> RouterResult<Vec<api::ConnectorData>>
where
F: Send + Clone,
D: OperationSessionGetters<F>,
{
let payments_dsl_input = PaymentsDslInput::new(
payment_data.get_setup_mandate(),
payment_data.get_payment_attempt(),
payment_data.get_payment_intent(),
payment_data.get_payment_method_data(),
payment_data.get_address(),
payment_data.get_recurring_details(),
payment_data.get_currency(),
);
let routable_connector_choice = self.0.clone();
let backend_input = payments_routing::make_dsl_input(&payments_dsl_input)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to construct dsl input")?;
let connectors = payments_routing::perform_cgraph_filtering(
state,
key_store,
routable_connector_choice,
backend_input,
None,
profile_id,
&common_enums::TransactionType::Payment,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Eligibility analysis failed for routable connectors")?;
let connector_data = connectors
.into_iter()
.map(|conn| {
api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
&conn.connector.to_string(),
api::GetToken::Connector,
conn.merchant_connector_id.clone(),
)
})
.collect::<CustomResult<Vec<_>, _>>()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Invalid connector name received")?;
Ok(connector_data)
}
<file_sep path="hyperswitch/crates/router/src/core/routing.rs" role="context" start="949" end="973">
pub async fn retrieve_default_fallback_algorithm_for_profile(
state: SessionState,
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
profile_id: common_utils::id_type::ProfileId,
) -> RouterResponse<Vec<routing_types::RoutableConnectorChoice>> {
metrics::ROUTING_RETRIEVE_DEFAULT_CONFIG.add(1, &[]);
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
let profile = core_utils::validate_and_get_business_profile(
db,
key_manager_state,
&key_store,
Some(&profile_id),
merchant_account.get_id(),
)
.await?
.get_required_value("Profile")?;
let connectors_choice = admin::ProfileWrapper::new(profile)
.get_default_fallback_list_of_connector_under_profile()?;
metrics::ROUTING_RETRIEVE_DEFAULT_CONFIG_SUCCESS_RESPONSE.add(1, &[]);
Ok(service_api::ApplicationResponse::Json(connectors_choice))
}
<file_sep path="hyperswitch/crates/router/src/compatibility/stripe/customers/types.rs" role="context" start="202" end="207">
pub struct PaymentMethodData {
pub id: Option<String>,
pub object: &'static str,
pub card: Option<CardDetails>,
pub created: Option<time::PrimitiveDateTime>,
}
<file_sep path="hyperswitch/v2_compatible_migrations/2024-08-28-081721_add_v2_columns/up.sql" role="context" start="19" end="35">
-- Intentionally not adding a default value here since we would have to
-- check if any merchants have enabled this from configs table,
-- before filling data for this column.
-- If no merchants have enabled this, then we can use `false` as the default value
-- when adding the column, later we can drop the default added for the column
-- so that we ensure new records inserted always have a value for the column.
ADD COLUMN should_collect_cvv_during_payment BOOLEAN;
ALTER TABLE payment_intent
ADD COLUMN merchant_reference_id VARCHAR(64),
ADD COLUMN billing_address BYTEA DEFAULT NULL,
ADD COLUMN shipping_address BYTEA DEFAULT NULL,
ADD COLUMN capture_method "CaptureMethod",
ADD COLUMN authentication_type "AuthenticationType",
ADD COLUMN amount_to_capture bigint,
ADD COLUMN prerouting_algorithm JSONB,
ADD COLUMN surcharge_amount bigint,
<file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="2504" end="2539">
pub enum PaymentMethodData {
#[schema(title = "Card")]
Card(Card),
#[schema(title = "CardRedirect")]
CardRedirect(CardRedirectData),
#[schema(title = "Wallet")]
Wallet(WalletData),
#[schema(title = "PayLater")]
PayLater(PayLaterData),
#[schema(title = "BankRedirect")]
BankRedirect(BankRedirectData),
#[schema(title = "BankDebit")]
BankDebit(BankDebitData),
#[schema(title = "BankTransfer")]
BankTransfer(Box<BankTransferData>),
#[schema(title = "RealTimePayment")]
RealTimePayment(Box<RealTimePaymentData>),
#[schema(title = "Crypto")]
Crypto(CryptoData),
#[schema(title = "MandatePayment")]
MandatePayment,
#[schema(title = "Reward")]
Reward,
#[schema(title = "Upi")]
Upi(UpiData),
#[schema(title = "Voucher")]
Voucher(VoucherData),
#[schema(title = "GiftCard")]
GiftCard(Box<GiftCardData>),
#[schema(title = "CardToken")]
CardToken(CardToken),
#[schema(title = "OpenBanking")]
OpenBanking(OpenBankingData),
#[schema(title = "MobilePayment")]
MobilePayment(MobilePaymentData),
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/admin.rs<|crate|> router anchor=process_open_banking_connectors kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/admin.rs" role="context" start="4700" end="4781">
async fn process_open_banking_connectors(
state: &SessionState,
merchant_id: &id_type::MerchantId,
auth: &types::ConnectorAuthType,
connector_type: &api_enums::ConnectorType,
connector: &api_enums::Connector,
additional_merchant_data: types::AdditionalMerchantData,
) -> RouterResult<types::MerchantRecipientData> {
let new_merchant_data = match additional_merchant_data {
types::AdditionalMerchantData::OpenBankingRecipientData(merchant_data) => {
if connector_type != &api_enums::ConnectorType::PaymentProcessor {
return Err(errors::ApiErrorResponse::InvalidConnectorConfiguration {
config:
"OpenBanking connector for Payment Initiation should be a payment processor"
.to_string(),
}
.into());
}
match &merchant_data {
types::MerchantRecipientData::AccountData(acc_data) => {
validate_bank_account_data(acc_data)?;
let connector_name = api_enums::Connector::to_string(connector);
let recipient_creation_not_supported = state
.conf
.locker_based_open_banking_connectors
.connector_list
.contains(connector_name.as_str());
let recipient_id = if recipient_creation_not_supported {
locker_recipient_create_call(state, merchant_id, acc_data).await
} else {
connector_recipient_create_call(
state,
merchant_id,
connector_name,
auth,
acc_data,
)
.await
}
.attach_printable("failed to get recipient_id")?;
let conn_recipient_id = if recipient_creation_not_supported {
Some(types::RecipientIdType::LockerId(Secret::new(recipient_id)))
} else {
Some(types::RecipientIdType::ConnectorId(Secret::new(
recipient_id,
)))
};
let account_data = match &acc_data {
types::MerchantAccountData::Iban { iban, name, .. } => {
types::MerchantAccountData::Iban {
iban: iban.clone(),
name: name.clone(),
connector_recipient_id: conn_recipient_id.clone(),
}
}
types::MerchantAccountData::Bacs {
account_number,
sort_code,
name,
..
} => types::MerchantAccountData::Bacs {
account_number: account_number.clone(),
sort_code: sort_code.clone(),
name: name.clone(),
connector_recipient_id: conn_recipient_id.clone(),
},
};
types::MerchantRecipientData::AccountData(account_data)
}
_ => merchant_data.clone(),
}
}
};
Ok(new_merchant_data)
}
<file_sep path="hyperswitch/crates/router/src/core/admin.rs" role="context" start="4699" end="4699">
state: SessionState,
req: admin_types::MerchantKeyTransferRequest,
) -> RouterResponse<admin_types::TransferKeyResponse> {
let resp = transfer_encryption_key(&state, req).await?;
Ok(service_api::ApplicationResponse::Json(
admin_types::TransferKeyResponse {
total_transferred: resp,
},
))
}
async fn process_open_banking_connectors(
state: &SessionState,
merchant_id: &id_type::MerchantId,
auth: &types::ConnectorAuthType,
connector_type: &api_enums::ConnectorType,
connector: &api_enums::Connector,
additional_merchant_data: types::AdditionalMerchantData,
) -> RouterResult<types::MerchantRecipientData> {
let new_merchant_data = match additional_merchant_data {
types::AdditionalMerchantData::OpenBankingRecipientData(merchant_data) => {
if connector_type != &api_enums::ConnectorType::PaymentProcessor {
return Err(errors::ApiErrorResponse::InvalidConnectorConfiguration {
config:
<file_sep path="hyperswitch/crates/router/src/core/admin.rs" role="context" start="4864" end="4947">
async fn connector_recipient_create_call(
state: &SessionState,
merchant_id: &id_type::MerchantId,
connector_name: String,
auth: &types::ConnectorAuthType,
data: &types::MerchantAccountData,
) -> RouterResult<String> {
let connector = pm_auth_types::api::PaymentAuthConnectorData::get_connector_by_name(
connector_name.as_str(),
)?;
let auth = pm_auth_types::ConnectorAuthType::foreign_try_from(auth.clone())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while converting ConnectorAuthType")?;
let connector_integration: pm_auth_types::api::BoxedConnectorIntegration<
'_,
pm_auth_types::api::auth_service::RecipientCreate,
pm_auth_types::RecipientCreateRequest,
pm_auth_types::RecipientCreateResponse,
> = connector.connector.get_connector_integration();
let req = match data {
types::MerchantAccountData::Iban { iban, name, .. } => {
pm_auth_types::RecipientCreateRequest {
name: name.clone(),
account_data: pm_auth_types::RecipientAccountData::Iban(iban.clone()),
address: None,
}
}
types::MerchantAccountData::Bacs {
account_number,
sort_code,
name,
..
} => pm_auth_types::RecipientCreateRequest {
name: name.clone(),
account_data: pm_auth_types::RecipientAccountData::Bacs {
sort_code: sort_code.clone(),
account_number: account_number.clone(),
},
address: None,
},
};
let router_data = pm_auth_types::RecipientCreateRouterData {
flow: std::marker::PhantomData,
merchant_id: Some(merchant_id.to_owned()),
connector: Some(connector_name),
request: req,
response: Err(pm_auth_types::ErrorResponse {
status_code: http::StatusCode::INTERNAL_SERVER_ERROR.as_u16(),
code: consts::NO_ERROR_CODE.to_string(),
message: consts::UNSUPPORTED_ERROR_MESSAGE.to_string(),
reason: None,
}),
connector_http_status_code: None,
connector_auth_type: auth,
};
let resp = payment_initiation_service::execute_connector_processing_step(
state,
connector_integration,
&router_data,
&connector.connector_name,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while calling recipient create connector api")?;
let recipient_create_resp =
resp.response
.map_err(|err| errors::ApiErrorResponse::ExternalConnectorError {
code: err.code,
message: err.message,
connector: connector.connector_name.to_string(),
status_code: err.status_code,
reason: err.reason,
})?;
let recipient_id = recipient_create_resp.recipient_id;
Ok(recipient_id)
}
<file_sep path="hyperswitch/crates/router/src/core/admin.rs" role="context" start="4783" end="4862">
fn validate_bank_account_data(data: &types::MerchantAccountData) -> RouterResult<()> {
match data {
types::MerchantAccountData::Iban { iban, .. } => {
// IBAN check algorithm
if iban.peek().len() > IBAN_MAX_LENGTH {
return Err(errors::ApiErrorResponse::InvalidRequestData {
message: "IBAN length must be up to 34 characters".to_string(),
}
.into());
}
let pattern = Regex::new(r"^[A-Z0-9]*$")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed to create regex pattern")?;
let mut iban = iban.peek().to_string();
if !pattern.is_match(iban.as_str()) {
return Err(errors::ApiErrorResponse::InvalidRequestData {
message: "IBAN data must be alphanumeric".to_string(),
}
.into());
}
// MOD check
let first_4 = iban.chars().take(4).collect::<String>();
iban.push_str(first_4.as_str());
let len = iban.len();
let rearranged_iban = iban
.chars()
.rev()
.take(len - 4)
.collect::<String>()
.chars()
.rev()
.collect::<String>();
let mut result = String::new();
rearranged_iban.chars().for_each(|c| {
if c.is_ascii_uppercase() {
let digit = (u32::from(c) - u32::from('A')) + 10;
result.push_str(&format!("{:02}", digit));
} else {
result.push(c);
}
});
let num = result
.parse::<u128>()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed to validate IBAN")?;
if num % 97 != 1 {
return Err(errors::ApiErrorResponse::InvalidRequestData {
message: "Invalid IBAN".to_string(),
}
.into());
}
Ok(())
}
types::MerchantAccountData::Bacs {
account_number,
sort_code,
..
} => {
if account_number.peek().len() > BACS_MAX_ACCOUNT_NUMBER_LENGTH
|| sort_code.peek().len() != BACS_SORT_CODE_LENGTH
{
return Err(errors::ApiErrorResponse::InvalidRequestData {
message: "Invalid BACS numbers".to_string(),
}
.into());
}
Ok(())
}
}
}
<file_sep path="hyperswitch/crates/router/src/core/admin.rs" role="context" start="4687" end="4698">
pub async fn transfer_key_store_to_key_manager(
state: SessionState,
req: admin_types::MerchantKeyTransferRequest,
) -> RouterResponse<admin_types::TransferKeyResponse> {
let resp = transfer_encryption_key(&state, req).await?;
Ok(service_api::ApplicationResponse::Json(
admin_types::TransferKeyResponse {
total_transferred: resp,
},
))
}
<file_sep path="hyperswitch/crates/router/src/core/admin.rs" role="context" start="4631" end="4685">
pub async fn connector_agnostic_mit_toggle(
state: SessionState,
merchant_id: &id_type::MerchantId,
profile_id: &id_type::ProfileId,
connector_agnostic_mit_choice: admin_types::ConnectorAgnosticMitChoice,
) -> RouterResponse<admin_types::ConnectorAgnosticMitChoice> {
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
let key_store = db
.get_merchant_key_store_by_merchant_id(
key_manager_state,
merchant_id,
&state.store.get_master_key().to_vec().into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)
.attach_printable("Error while fetching the key store by merchant_id")?;
let business_profile = db
.find_business_profile_by_profile_id(key_manager_state, &key_store, profile_id)
.await
.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
if business_profile.merchant_id != *merchant_id {
Err(errors::ApiErrorResponse::AccessForbidden {
resource: profile_id.get_string_repr().to_owned(),
})?
}
if business_profile.is_connector_agnostic_mit_enabled
!= Some(connector_agnostic_mit_choice.enabled)
{
let profile_update = domain::ProfileUpdate::ConnectorAgnosticMitUpdate {
is_connector_agnostic_mit_enabled: connector_agnostic_mit_choice.enabled,
};
db.update_profile_by_profile_id(
key_manager_state,
&key_store,
business_profile,
profile_update,
)
.await
.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
}
Ok(service_api::ApplicationResponse::Json(
connector_agnostic_mit_choice,
))
}
<file_sep path="hyperswitch/crates/router/src/core/admin.rs" role="context" start="2675" end="2819">
async fn create_domain_model_from_request(
self,
state: &SessionState,
key_store: domain::MerchantKeyStore,
business_profile: &domain::Profile,
key_manager_state: &KeyManagerState,
) -> RouterResult<domain::MerchantConnectorAccount> {
// If connector label is not passed in the request, generate one
let connector_label = self
.connector_label
.clone()
.or(core_utils::get_connector_label(
self.business_country,
self.business_label.as_ref(),
self.business_sub_label.as_ref(),
&self.connector_name.to_string(),
))
.unwrap_or(format!(
"{}_{}",
self.connector_name, business_profile.profile_name
));
let payment_methods_enabled = PaymentMethodsEnabled {
payment_methods_enabled: &self.payment_methods_enabled,
};
let payment_methods_enabled = payment_methods_enabled.get_payment_methods_enabled()?;
let frm_configs = self.get_frm_config_as_secret();
// Validate Merchant api details and return error if not in correct format
let auth = types::ConnectorAuthType::from_option_secret_value(
self.connector_account_details.clone(),
)
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "connector_account_details".to_string(),
expected_format: "auth_type and api_key".to_string(),
})?;
let connector_auth_type_and_metadata_validation = ConnectorAuthTypeAndMetadataValidation {
connector_name: &self.connector_name,
auth_type: &auth,
connector_meta_data: &self.metadata,
};
connector_auth_type_and_metadata_validation.validate_auth_and_metadata_type()?;
let connector_status_and_disabled_validation = ConnectorStatusAndDisabledValidation {
status: &self.status,
disabled: &self.disabled,
auth: &auth,
current_status: &api_enums::ConnectorStatus::Active,
};
let (connector_status, disabled) =
connector_status_and_disabled_validation.validate_status_and_disabled()?;
let identifier = km_types::Identifier::Merchant(business_profile.merchant_id.clone());
let merchant_recipient_data = if let Some(data) = &self.additional_merchant_data {
Some(
process_open_banking_connectors(
state,
&business_profile.merchant_id,
&auth,
&self.connector_type,
&self.connector_name,
types::AdditionalMerchantData::foreign_from(data.clone()),
)
.await?,
)
} else {
None
}
.map(|data| {
serde_json::to_value(types::AdditionalMerchantData::OpenBankingRecipientData(
data,
))
})
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to serialize MerchantRecipientData")?;
let encrypted_data = domain_types::crypto_operation(
key_manager_state,
type_name!(domain::MerchantConnectorAccount),
domain_types::CryptoOperation::BatchEncrypt(
FromRequestEncryptableMerchantConnectorAccount::to_encryptable(
FromRequestEncryptableMerchantConnectorAccount {
connector_account_details: self.connector_account_details.ok_or(
errors::ApiErrorResponse::MissingRequiredField {
field_name: "connector_account_details",
},
)?,
connector_wallets_details:
helpers::get_connector_wallets_details_with_apple_pay_certificates(
&self.metadata,
&self.connector_wallets_details,
)
.await?,
additional_merchant_data: merchant_recipient_data.map(Secret::new),
},
),
),
identifier.clone(),
key_store.key.peek(),
)
.await
.and_then(|val| val.try_into_batchoperation())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while decrypting connector account details".to_string())?;
let encrypted_data =
FromRequestEncryptableMerchantConnectorAccount::from_encryptable(encrypted_data)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while decrypting connector account details")?;
Ok(domain::MerchantConnectorAccount {
merchant_id: business_profile.merchant_id.clone(),
connector_type: self.connector_type,
connector_name: self.connector_name.to_string(),
merchant_connector_id: common_utils::generate_merchant_connector_account_id_of_default_length(),
connector_account_details: encrypted_data.connector_account_details,
payment_methods_enabled,
disabled,
metadata: self.metadata.clone(),
frm_configs,
connector_label: Some(connector_label.clone()),
created_at: date_time::now(),
modified_at: date_time::now(),
connector_webhook_details: match self.connector_webhook_details {
Some(connector_webhook_details) => {
connector_webhook_details.encode_to_value(
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(format!("Failed to serialize api_models::admin::MerchantConnectorWebhookDetails for Merchant: {:?}", business_profile.merchant_id))
.map(Some)?
.map(Secret::new)
}
None => None,
},
profile_id: business_profile.get_id().to_owned(),
applepay_verified_domains: None,
pm_auth_config: self.pm_auth_config.clone(),
status: connector_status,
connector_wallets_details: encrypted_data.connector_wallets_details,
test_mode: self.test_mode,
business_country: self.business_country,
business_label: self.business_label.clone(),
business_sub_label: self.business_sub_label.clone(),
additional_merchant_data: encrypted_data.additional_merchant_data,
version: common_types::consts::API_VERSION,
})
}
<file_sep path="hyperswitch/crates/router/src/core/admin.rs" role="context" start="2483" end="2615">
async fn create_domain_model_from_request(
self,
state: &SessionState,
key_store: domain::MerchantKeyStore,
business_profile: &domain::Profile,
key_manager_state: &KeyManagerState,
) -> RouterResult<domain::MerchantConnectorAccount> {
// If connector label is not passed in the request, generate one
let connector_label = self.get_connector_label(business_profile.profile_name.clone());
let frm_configs = self.get_frm_config_as_secret();
let payment_methods_enabled = self.payment_methods_enabled;
// Validate Merchant api details and return error if not in correct format
let auth = types::ConnectorAuthType::from_option_secret_value(
self.connector_account_details.clone(),
)
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "connector_account_details".to_string(),
expected_format: "auth_type and api_key".to_string(),
})?;
let connector_auth_type_and_metadata_validation = ConnectorAuthTypeAndMetadataValidation {
connector_name: &self.connector_name,
auth_type: &auth,
connector_meta_data: &self.metadata,
};
connector_auth_type_and_metadata_validation.validate_auth_and_metadata_type()?;
let connector_status_and_disabled_validation = ConnectorStatusAndDisabledValidation {
status: &self.status,
disabled: &self.disabled,
auth: &auth,
current_status: &api_enums::ConnectorStatus::Active,
};
let (connector_status, disabled) =
connector_status_and_disabled_validation.validate_status_and_disabled()?;
let identifier = km_types::Identifier::Merchant(business_profile.merchant_id.clone());
let merchant_recipient_data = if let Some(data) = &self.additional_merchant_data {
Some(
process_open_banking_connectors(
state,
&business_profile.merchant_id,
&auth,
&self.connector_type,
&self.connector_name,
types::AdditionalMerchantData::foreign_from(data.clone()),
)
.await?,
)
} else {
None
}
.map(|data| {
serde_json::to_value(types::AdditionalMerchantData::OpenBankingRecipientData(
data,
))
})
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to serialize MerchantRecipientData")?;
let encrypted_data = domain_types::crypto_operation(
key_manager_state,
type_name!(domain::MerchantConnectorAccount),
domain_types::CryptoOperation::BatchEncrypt(
FromRequestEncryptableMerchantConnectorAccount::to_encryptable(
FromRequestEncryptableMerchantConnectorAccount {
connector_account_details: self.connector_account_details.ok_or(
errors::ApiErrorResponse::MissingRequiredField {
field_name: "connector_account_details",
},
)?,
connector_wallets_details:
helpers::get_connector_wallets_details_with_apple_pay_certificates(
&self.metadata,
&self.connector_wallets_details,
)
.await?,
additional_merchant_data: merchant_recipient_data.map(Secret::new),
},
),
),
identifier.clone(),
key_store.key.peek(),
)
.await
.and_then(|val| val.try_into_batchoperation())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while decrypting connector account details".to_string())?;
let encrypted_data =
FromRequestEncryptableMerchantConnectorAccount::from_encryptable(encrypted_data)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while decrypting connector account details")?;
let feature_metadata = self
.feature_metadata
.as_ref()
.map(ForeignTryFrom::foreign_try_from)
.transpose()?;
Ok(domain::MerchantConnectorAccount {
merchant_id: business_profile.merchant_id.clone(),
connector_type: self.connector_type,
connector_name: self.connector_name,
connector_account_details: encrypted_data.connector_account_details,
payment_methods_enabled,
disabled,
metadata: self.metadata.clone(),
frm_configs,
connector_label: Some(connector_label.clone()),
created_at: date_time::now(),
modified_at: date_time::now(),
id: common_utils::generate_merchant_connector_account_id_of_default_length(),
connector_webhook_details: match self.connector_webhook_details {
Some(connector_webhook_details) => {
connector_webhook_details.encode_to_value(
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(format!("Failed to serialize api_models::admin::MerchantConnectorWebhookDetails for Merchant: {:?}", business_profile.merchant_id))
.map(Some)?
.map(Secret::new)
}
None => None,
},
profile_id: business_profile.get_id().to_owned(),
applepay_verified_domains: None,
pm_auth_config: self.pm_auth_config.clone(),
status: connector_status,
connector_wallets_details: encrypted_data.connector_wallets_details,
additional_merchant_data: encrypted_data.additional_merchant_data,
version: common_types::consts::API_VERSION,
feature_metadata,
})
}
<file_sep path="hyperswitch/crates/router/src/core/admin.rs" role="context" start="4949" end="4982">
async fn locker_recipient_create_call(
state: &SessionState,
merchant_id: &id_type::MerchantId,
data: &types::MerchantAccountData,
) -> RouterResult<String> {
let enc_data = serde_json::to_string(data)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to convert to MerchantAccountData json to String")?;
let merchant_id_string = merchant_id.get_string_repr().to_owned();
let cust_id = id_type::CustomerId::try_from(std::borrow::Cow::from(merchant_id_string))
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to convert to CustomerId")?;
let payload = transformers::StoreLockerReq::LockerGeneric(transformers::StoreGenericReq {
merchant_id: merchant_id.to_owned(),
merchant_customer_id: cust_id.clone(),
enc_data,
ttl: state.conf.locker.ttl_for_storage_in_secs,
});
let store_resp = cards::add_card_to_hs_locker(
state,
&payload,
&cust_id,
api_enums::LockerChoice::HyperswitchCardVault,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to encrypt merchant bank account data")?;
Ok(store_resp.card_reference)
}
<file_sep path="hyperswitch/crates/api_models/src/errors/types.rs" role="context" start="86" end="100">
pub enum ApiErrorResponse {
Unauthorized(ApiError),
ForbiddenCommonResource(ApiError),
ForbiddenPrivateResource(ApiError),
Conflict(ApiError),
Gone(ApiError),
Unprocessable(ApiError),
InternalServerError(ApiError),
NotImplemented(ApiError),
ConnectorError(ApiError, #[serde(skip_serializing)] StatusCode),
NotFound(ApiError),
MethodNotAllowed(ApiError),
BadRequest(ApiError),
DomainError(ApiError),
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/nmi.rs<|crate|> router anchor=get_url kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/connector/nmi.rs" role="context" start="803" end="809">
fn get_url(
&self,
_req: &types::RefundsRouterData<api::RSync>,
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}api/query.php", self.base_url(connectors)))
}
<file_sep path="hyperswitch/crates/router/src/connector/nmi.rs" role="context" start="802" end="802">
use common_utils::{
crypto,
ext_traits::ByteSliceExt,
request::RequestContent,
types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector},
};
use crate::{
configs::settings,
core::{
errors::{self, CustomResult},
payments,
},
events::connector_api_logs::ConnectorEvent,
services::{self, request, ConnectorIntegration, ConnectorSpecifications, ConnectorValidation},
types::{
self,
api::{self, ConnectorCommon, ConnectorCommonExt},
transformers::ForeignFrom,
ErrorResponse,
},
};
<file_sep path="hyperswitch/crates/router/src/connector/nmi.rs" role="context" start="820" end="835">
fn build_request(
&self,
req: &types::RefundsRouterData<api::RSync>,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Post)
.url(&types::RefundSyncType::get_url(self, req, connectors)?)
.headers(types::RefundSyncType::get_headers(self, req, connectors)?)
.set_body(types::RefundSyncType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
<file_sep path="hyperswitch/crates/router/src/connector/nmi.rs" role="context" start="811" end="818">
fn get_request_body(
&self,
req: &types::RefundsRouterData<api::RSync>,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = nmi::NmiSyncRequest::try_from(req)?;
Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))
}
<file_sep path="hyperswitch/crates/router/src/connector/nmi.rs" role="context" start="795" end="801">
fn get_headers(
&self,
req: &types::RefundsRouterData<api::RSync>,
connectors: &settings::Connectors,
) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
<file_sep path="hyperswitch/crates/router/src/connector/nmi.rs" role="context" start="785" end="791">
fn get_error_response(
&self,
res: types::Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
<file_sep path="hyperswitch/crates/router/src/connector/nmi.rs" role="context" start="360" end="379">
fn build_request(
&self,
req: &types::PaymentsAuthorizeRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Post)
.url(&types::PaymentsAuthorizeType::get_url(
self, req, connectors,
)?)
.headers(types::PaymentsAuthorizeType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
<file_sep path="hyperswitch/crates/router/src/types.rs" role="context" start="160" end="160">
pub type RefundsRouterData<F> = RouterData<F, RefundsData, RefundsResponseData>;
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/nmi.rs<|crate|> router anchor=get_headers kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/connector/nmi.rs" role="context" start="795" end="801">
fn get_headers(
&self,
req: &types::RefundsRouterData<api::RSync>,
connectors: &settings::Connectors,
) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
<file_sep path="hyperswitch/crates/router/src/connector/nmi.rs" role="context" start="794" end="794">
use common_utils::{
crypto,
ext_traits::ByteSliceExt,
request::RequestContent,
types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector},
};
use crate::{
configs::settings,
core::{
errors::{self, CustomResult},
payments,
},
events::connector_api_logs::ConnectorEvent,
services::{self, request, ConnectorIntegration, ConnectorSpecifications, ConnectorValidation},
types::{
self,
api::{self, ConnectorCommon, ConnectorCommonExt},
transformers::ForeignFrom,
ErrorResponse,
},
};
<file_sep path="hyperswitch/crates/router/src/connector/nmi.rs" role="context" start="811" end="818">
fn get_request_body(
&self,
req: &types::RefundsRouterData<api::RSync>,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = nmi::NmiSyncRequest::try_from(req)?;
Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))
}
<file_sep path="hyperswitch/crates/router/src/connector/nmi.rs" role="context" start="803" end="809">
fn get_url(
&self,
_req: &types::RefundsRouterData<api::RSync>,
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}api/query.php", self.base_url(connectors)))
}
<file_sep path="hyperswitch/crates/router/src/connector/nmi.rs" role="context" start="785" end="791">
fn get_error_response(
&self,
res: types::Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
<file_sep path="hyperswitch/crates/router/src/connector/nmi.rs" role="context" start="768" end="783">
fn handle_response(
&self,
data: &types::RefundsRouterData<api::Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
let response: nmi::StandardResponse = serde_urlencoded::from_bytes(&res.response)
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
<file_sep path="hyperswitch/crates/router/src/connector/nmi.rs" role="context" start="749" end="766">
fn build_request(
&self,
req: &types::RefundsRouterData<api::Execute>,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Post)
.url(&types::RefundExecuteType::get_url(self, req, connectors)?)
.headers(types::RefundExecuteType::get_headers(
self, req, connectors,
)?)
.set_body(types::RefundExecuteType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
<file_sep path="hyperswitch/crates/router/src/connector/nmi.rs" role="context" start="820" end="835">
fn build_request(
&self,
req: &types::RefundsRouterData<api::RSync>,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Post)
.url(&types::RefundSyncType::get_url(self, req, connectors)?)
.headers(types::RefundSyncType::get_headers(self, req, connectors)?)
.set_body(types::RefundSyncType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
<file_sep path="hyperswitch/crates/router/src/types.rs" role="context" start="160" end="160">
pub type RefundsRouterData<F> = RouterData<F, RefundsData, RefundsResponseData>;
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/types/domain/user.rs<|crate|> router anchor=from kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/types/domain/user.rs" role="context" start="1414" end="1423">
fn from(value: ProfileLevel) -> Self {
Self {
entity_id: value.profile_id.get_string_repr().to_owned(),
entity_type: EntityType::Profile,
tenant_id: value.tenant_id,
org_id: Some(value.org_id),
merchant_id: Some(value.merchant_id),
profile_id: Some(value.profile_id),
}
}
<file_sep path="hyperswitch/crates/router/src/types/domain/user.rs" role="context" start="1413" end="1413">
use common_enums::EntityType;
<file_sep path="hyperswitch/crates/router/src/types/domain/user.rs" role="context" start="1449" end="1459">
pub async fn insert_in_v2(self, state: &SessionState) -> UserResult<UserRole> {
let entity = self.entity.clone();
let new_v2_role = self.convert_to_new_v2_role(entity.into());
state
.global_store
.insert_user_role(new_v2_role)
.await
.change_context(UserErrors::InternalServerError)
}
<file_sep path="hyperswitch/crates/router/src/types/domain/user.rs" role="context" start="1430" end="1447">
fn convert_to_new_v2_role(self, entity: EntityInfo) -> UserRoleNew {
UserRoleNew {
user_id: self.user_id,
role_id: self.role_id,
status: self.status,
created_by: self.created_by,
last_modified_by: self.last_modified_by,
created_at: self.created_at,
last_modified: self.last_modified,
org_id: entity.org_id,
merchant_id: entity.merchant_id,
profile_id: entity.profile_id,
entity_id: Some(entity.entity_id),
entity_type: Some(entity.entity_type),
version: UserRoleVersion::V2,
tenant_id: entity.tenant_id,
}
}
<file_sep path="hyperswitch/crates/router/src/types/domain/user.rs" role="context" start="1401" end="1410">
fn from(value: MerchantLevel) -> Self {
Self {
entity_id: value.merchant_id.get_string_repr().to_owned(),
entity_type: EntityType::Merchant,
tenant_id: value.tenant_id,
org_id: Some(value.org_id),
merchant_id: Some(value.merchant_id),
profile_id: None,
}
}
<file_sep path="hyperswitch/crates/router/src/types/domain/user.rs" role="context" start="1388" end="1397">
fn from(value: OrganizationLevel) -> Self {
Self {
entity_id: value.org_id.get_string_repr().to_owned(),
entity_type: EntityType::Organization,
tenant_id: value.tenant_id,
org_id: Some(value.org_id),
merchant_id: None,
profile_id: None,
}
}
<file_sep path="hyperswitch/crates/router/src/types/domain/user.rs" role="context" start="700" end="719">
fn try_from(value: UserMerchantCreateRequestWithToken) -> UserResult<Self> {
let merchant_id = if matches!(env::which(), env::Env::Production) {
id_type::MerchantId::try_from(MerchantId::new(value.1.company_name.clone())?)?
} else {
id_type::MerchantId::new_from_unix_timestamp()
};
let (user_from_storage, user_merchant_create, user_from_token) = value;
Ok(Self {
merchant_id,
company_name: Some(UserCompanyName::new(
user_merchant_create.company_name.clone(),
)?),
product_type: user_merchant_create.product_type,
new_organization: NewUserOrganization::from((
user_from_storage,
user_merchant_create,
user_from_token,
)),
})
}
<file_sep path="hyperswitch/crates/router/src/types/domain/user.rs" role="context" start="650" end="664">
fn try_from(
value: (user_api::CreateInternalUserRequest, id_type::OrganizationId),
) -> UserResult<Self> {
let merchant_id = id_type::MerchantId::get_internal_user_merchant_id(
consts::user_role::INTERNAL_USER_MERCHANT_ID,
);
let new_organization = NewUserOrganization::from(value);
Ok(Self {
company_name: None,
merchant_id,
new_organization,
product_type: None,
})
}
<file_sep path="hyperswitch/crates/router/src/types/domain/user.rs" role="context" start="1328" end="1333">
pub struct ProfileLevel {
pub tenant_id: id_type::TenantId,
pub org_id: id_type::OrganizationId,
pub merchant_id: id_type::MerchantId,
pub profile_id: id_type::ProfileId,
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/payeezy.rs<|crate|> router<|connector|> payeezy anchor=get_payment_info kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/tests/connectors/payeezy.rs" role="context" start="57" end="73">
fn get_payment_info() -> Option<PaymentInfo> {
Some(PaymentInfo {
address: Some(types::PaymentAddress::new(
None,
Some(Address {
address: Some(AddressDetails {
..Default::default()
}),
phone: None,
email: None,
}),
None,
None,
)),
..Default::default()
})
}
<file_sep path="hyperswitch/crates/router/tests/connectors/payeezy.rs" role="context" start="56" end="56">
use hyperswitch_domain_models::address::{Address, AddressDetails};
use router::{
core::errors,
types::{self, storage::enums, PaymentsAuthorizeData},
};
<file_sep path="hyperswitch/crates/router/tests/connectors/payeezy.rs" role="context" start="82" end="88">
async fn should_only_authorize_payment() {
let response = CONNECTOR
.authorize_payment(PayeezyTest::get_payment_data(), None)
.await
.expect("Authorize payment response");
assert_eq!(response.status, enums::AttemptStatus::Authorized);
}
<file_sep path="hyperswitch/crates/router/tests/connectors/payeezy.rs" role="context" start="74" end="76">
fn get_request_interval(self) -> u64 {
20
}
<file_sep path="hyperswitch/crates/router/tests/connectors/payeezy.rs" role="context" start="47" end="55">
fn get_payment_data() -> Option<PaymentsAuthorizeData> {
Some(PaymentsAuthorizeData {
payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card {
card_number: CardNumber::from_str("4012000033330026").unwrap(),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
})
}
<file_sep path="hyperswitch/crates/router/tests/connectors/payeezy.rs" role="context" start="41" end="43">
fn get_name(&self) -> String {
"payeezy".to_string()
}
<file_sep path="hyperswitch/crates/router/tests/connectors/payeezy.rs" role="context" start="218" end="259">
async fn should_partially_refund_manually_captured_payment() {
let authorize_response = CONNECTOR
.authorize_payment(
PayeezyTest::get_payment_data(),
PayeezyTest::get_payment_info(),
)
.await
.expect("Authorize payment response");
let txn_id = utils::get_connector_transaction_id(authorize_response.response.clone()).unwrap();
let capture_connector_meta = utils::get_connector_metadata(authorize_response.response);
let capture_response = CONNECTOR
.capture_payment(
txn_id.clone(),
Some(types::PaymentsCaptureData {
connector_meta: capture_connector_meta,
..utils::PaymentCaptureType::default().0
}),
PayeezyTest::get_payment_info(),
)
.await
.expect("Capture payment response");
let capture_txn_id =
utils::get_connector_transaction_id(capture_response.response.clone()).unwrap();
let refund_connector_metadata = utils::get_connector_metadata(capture_response.response);
let response = CONNECTOR
.refund_payment(
capture_txn_id.clone(),
Some(types::RefundsData {
refund_amount: 50,
connector_transaction_id: capture_txn_id,
connector_metadata: refund_connector_metadata,
..utils::PaymentRefundType::default().0
}),
PayeezyTest::get_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
<file_sep path="hyperswitch/crates/router/tests/connectors/payeezy.rs" role="context" start="373" end="392">
async fn should_throw_not_implemented_for_unsupported_issuer() {
let authorize_data = Some(PaymentsAuthorizeData {
payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card {
card_number: CardNumber::from_str("630495060000000000").unwrap(),
..utils::CCardType::default().0
}),
capture_method: Some(enums::CaptureMethod::Automatic),
..utils::PaymentAuthorizeType::default().0
});
let response = CONNECTOR
.make_payment(authorize_data, PayeezyTest::get_payment_info())
.await;
assert_eq!(
*response.unwrap_err().current_context(),
errors::ConnectorError::NotSupported {
message: "card".to_string(),
connector: "Payeezy",
}
)
}
<file_sep path="hyperswitch/crates/router/tests/macros.rs" role="context" start="17" end="21">
struct Address {
line1: String,
zip: String,
city: String,
}
<file_sep path="hyperswitch/migrations/2025-02-06-111828_drop_int_id_column_accross_database/up.sql" role="context" start="20" end="36">
------------------------ Payment Attempt -----------------------
ALTER TABLE payment_attempt DROP COLUMN id;
------------------------ Payment Methods -----------------------
ALTER TABLE payment_methods DROP COLUMN IF EXISTS id;
------------------------ Address -----------------------
ALTER TABLE address DROP COLUMN IF EXISTS id;
------------------------ Dispute -----------------------
ALTER TABLE dispute DROP COLUMN IF EXISTS id;
------------------------ Mandate -----------------------
ALTER TABLE mandate DROP COLUMN IF EXISTS id;
------------------------ Refund -----------------------
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/authorizedotnet.rs<|crate|> router<|connector|> authorizedotnet anchor=get_payment_method_data kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/tests/connectors/authorizedotnet.rs" role="context" start="40" end="48">
fn get_payment_method_data() -> domain::Card {
domain::Card {
card_number: cards::CardNumber::from_str("5424000000000015").unwrap(),
card_exp_month: Secret::new("02".to_string()),
card_exp_year: Secret::new("2035".to_string()),
card_cvc: Secret::new("123".to_string()),
..Default::default()
}
}
<file_sep path="hyperswitch/crates/router/tests/connectors/authorizedotnet.rs" role="context" start="39" end="39">
use masking::Secret;
use router::types::{self, domain, storage::enums};
<file_sep path="hyperswitch/crates/router/tests/connectors/authorizedotnet.rs" role="context" start="88" end="144">
async fn should_capture_authorized_payment() {
let authorize_response = CONNECTOR
.authorize_payment(
Some(types::PaymentsAuthorizeData {
amount: 301,
payment_method_data: domain::PaymentMethodData::Card(get_payment_method_data()),
capture_method: Some(diesel_models::enums::CaptureMethod::Manual),
..utils::PaymentAuthorizeType::default().0
}),
Some(PaymentInfo::with_default_billing_name()),
)
.await
.expect("Authorize payment response");
assert_eq!(authorize_response.status, enums::AttemptStatus::Pending);
let txn_id =
utils::get_connector_transaction_id(authorize_response.response).unwrap_or_default();
let psync_response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(txn_id.clone()),
encoded_data: None,
capture_method: None,
..Default::default()
}),
None,
)
.await
.expect("PSync response");
assert_eq!(psync_response.status, enums::AttemptStatus::Authorized);
let cap_response = CONNECTOR
.capture_payment(
txn_id.clone(),
Some(types::PaymentsCaptureData {
amount_to_capture: 301,
..utils::PaymentCaptureType::default().0
}),
None,
)
.await
.expect("Capture payment response");
assert_eq!(cap_response.status, enums::AttemptStatus::Pending);
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::CaptureInitiated,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(txn_id),
encoded_data: None,
capture_method: None,
..Default::default()
}),
None,
)
.await
.expect("PSync response");
assert_eq!(response.status, enums::AttemptStatus::CaptureInitiated);
}
<file_sep path="hyperswitch/crates/router/tests/connectors/authorizedotnet.rs" role="context" start="53" end="84">
async fn should_only_authorize_payment() {
let authorize_response = CONNECTOR
.authorize_payment(
Some(types::PaymentsAuthorizeData {
amount: 300,
payment_method_data: domain::PaymentMethodData::Card(get_payment_method_data()),
capture_method: Some(diesel_models::enums::CaptureMethod::Manual),
..utils::PaymentAuthorizeType::default().0
}),
Some(PaymentInfo::with_default_billing_name()),
)
.await
.expect("Authorize payment response");
assert_eq!(authorize_response.status, enums::AttemptStatus::Pending);
let txn_id =
utils::get_connector_transaction_id(authorize_response.response).unwrap_or_default();
let psync_response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(txn_id),
encoded_data: None,
capture_method: None,
..Default::default()
}),
None,
)
.await
.expect("PSync response");
assert_eq!(psync_response.status, enums::AttemptStatus::Authorized);
}
<file_sep path="hyperswitch/crates/router/tests/connectors/authorizedotnet.rs" role="context" start="34" end="36">
fn get_name(&self) -> String {
"authorizedotnet".to_string()
}
<file_sep path="hyperswitch/crates/router/tests/connectors/authorizedotnet.rs" role="context" start="25" end="32">
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.authorizedotnet
.expect("Missing connector authentication configuration")
.into(),
)
}
<file_sep path="hyperswitch/crates/router/tests/connectors/authorizedotnet.rs" role="context" start="148" end="204">
async fn should_partially_capture_authorized_payment() {
let authorize_response = CONNECTOR
.authorize_payment(
Some(types::PaymentsAuthorizeData {
amount: 302,
payment_method_data: domain::PaymentMethodData::Card(get_payment_method_data()),
capture_method: Some(diesel_models::enums::CaptureMethod::Manual),
..utils::PaymentAuthorizeType::default().0
}),
Some(PaymentInfo::with_default_billing_name()),
)
.await
.expect("Authorize payment response");
assert_eq!(authorize_response.status, enums::AttemptStatus::Pending);
let txn_id =
utils::get_connector_transaction_id(authorize_response.response).unwrap_or_default();
let psync_response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(txn_id.clone()),
encoded_data: None,
capture_method: None,
..Default::default()
}),
None,
)
.await
.expect("PSync response");
assert_eq!(psync_response.status, enums::AttemptStatus::Authorized);
let cap_response = CONNECTOR
.capture_payment(
txn_id.clone(),
Some(types::PaymentsCaptureData {
amount_to_capture: 150,
..utils::PaymentCaptureType::default().0
}),
None,
)
.await
.expect("Capture payment response");
assert_eq!(cap_response.status, enums::AttemptStatus::Pending);
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::CaptureInitiated,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(txn_id),
encoded_data: None,
capture_method: None,
..Default::default()
}),
None,
)
.await
.expect("PSync response");
assert_eq!(response.status, enums::AttemptStatus::CaptureInitiated);
}
<file_sep path="hyperswitch/crates/router/tests/connectors/authorizedotnet.rs" role="context" start="289" end="321">
async fn should_make_payment() {
let cap_response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
amount: 310,
payment_method_data: domain::PaymentMethodData::Card(get_payment_method_data()),
capture_method: Some(diesel_models::enums::CaptureMethod::Manual),
..utils::PaymentAuthorizeType::default().0
}),
None,
)
.await
.unwrap();
assert_eq!(cap_response.status, enums::AttemptStatus::Pending);
let txn_id = utils::get_connector_transaction_id(cap_response.response).unwrap_or_default();
let psync_response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::CaptureInitiated,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(txn_id.clone()),
encoded_data: None,
capture_method: None,
..Default::default()
}),
None,
)
.await
.expect("PSync response");
assert_eq!(
psync_response.status,
enums::AttemptStatus::CaptureInitiated
);
}
<file_sep path="hyperswitch/crates/router/src/connector/payone/transformers.rs" role="context" start="117" end="121">
pub struct Card {
card_holder_name: Secret<String>,
card_number: CardNumber,
expiry_date: Secret<String>,
}
<file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="1075" end="1083">
pub struct Card {
pub card_number: CardNumber,
pub name_on_card: Option<masking::Secret<String>>,
pub card_exp_month: masking::Secret<String>,
pub card_exp_year: masking::Secret<String>,
pub card_brand: Option<String>,
pub card_isin: Option<String>,
pub nick_name: Option<String>,
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/configs/settings.rs<|crate|> router anchor=deserialize kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/configs/settings.rs" role="context" start="1330" end="1362">
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
#[derive(Deserialize)]
struct Inner {
base_url: String,
schema: String,
accounts_schema: String,
redis_key_prefix: String,
clickhouse_database: String,
user: TenantUserConfig,
}
let hashmap = <HashMap<id_type::TenantId, Inner>>::deserialize(deserializer)?;
Ok(Self(
hashmap
.into_iter()
.map(|(key, value)| {
(
key.clone(),
Tenant {
tenant_id: key,
base_url: value.base_url,
schema: value.schema,
accounts_schema: value.accounts_schema,
redis_key_prefix: value.redis_key_prefix,
clickhouse_database: value.clickhouse_database,
user: value.user,
},
)
})
.collect(),
))
}
<file_sep path="hyperswitch/crates/router/src/configs/settings.rs" role="context" start="1329" end="1329">
use std::{
collections::{HashMap, HashSet},
path::PathBuf,
sync::Arc,
};
use common_utils::{ext_traits::ConfigExt, id_type, types::theme::EmailThemeConfig};
use serde::Deserialize;
<file_sep path="hyperswitch/crates/router/src/configs/settings.rs" role="context" start="1407" end="1437">
fn test_payment_method_and_payment_method_types_with_spaces() {
use diesel_models::enums::{PaymentMethod, PaymentMethodType};
let input_map: HashMap<String, String> = HashMap::from([
(" bank_transfer ".to_string(), " ach , bacs ".to_string()),
("wallet ".to_string(), " paypal , pix , venmo ".to_string()),
]);
let deserializer: MapDeserializer<
'_,
std::collections::hash_map::IntoIter<String, String>,
ValueError,
> = input_map.into_deserializer();
let result = deserialize_hashmap::<'_, _, PaymentMethod, PaymentMethodType>(deserializer);
let expected_result = HashMap::from([
(
PaymentMethod::BankTransfer,
HashSet::from([PaymentMethodType::Ach, PaymentMethodType::Bacs]),
),
(
PaymentMethod::Wallet,
HashSet::from([
PaymentMethodType::Paypal,
PaymentMethodType::Pix,
PaymentMethodType::Venmo,
]),
),
]);
assert!(result.is_ok());
assert_eq!(result.unwrap(), expected_result);
}
<file_sep path="hyperswitch/crates/router/src/configs/settings.rs" role="context" start="1378" end="1404">
fn test_payment_method_and_payment_method_types() {
use diesel_models::enums::{PaymentMethod, PaymentMethodType};
let input_map: HashMap<String, String> = HashMap::from([
("bank_transfer".to_string(), "ach,bacs".to_string()),
("wallet".to_string(), "paypal,venmo".to_string()),
]);
let deserializer: MapDeserializer<
'_,
std::collections::hash_map::IntoIter<String, String>,
ValueError,
> = input_map.into_deserializer();
let result = deserialize_hashmap::<'_, _, PaymentMethod, PaymentMethodType>(deserializer);
let expected_result = HashMap::from([
(
PaymentMethod::BankTransfer,
HashSet::from([PaymentMethodType::Ach, PaymentMethodType::Bacs]),
),
(
PaymentMethod::Wallet,
HashSet::from([PaymentMethodType::Paypal, PaymentMethodType::Venmo]),
),
]);
assert!(result.is_ok());
assert_eq!(result.unwrap(), expected_result);
}
<file_sep path="hyperswitch/crates/router/src/configs/settings.rs" role="context" start="1319" end="1327">
fn deserialize_merchant_ids<'de, D>(
deserializer: D,
) -> Result<HashSet<id_type::MerchantId>, D::Error>
where
D: serde::Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
deserialize_merchant_ids_inner(s).map_err(serde::de::Error::custom)
}
<file_sep path="hyperswitch/crates/router/src/configs/settings.rs" role="context" start="1282" end="1317">
fn deserialize_merchant_ids_inner(
value: impl AsRef<str>,
) -> Result<HashSet<id_type::MerchantId>, String> {
let (values, errors) = value
.as_ref()
.trim()
.split(',')
.map(|s| {
let trimmed = s.trim();
id_type::MerchantId::wrap(trimmed.to_owned()).map_err(|error| {
format!(
"Unable to deserialize `{}` as `MerchantId`: {error}",
trimmed
)
})
})
.fold(
(HashSet::new(), Vec::new()),
|(mut values, mut errors), result| match result {
Ok(t) => {
values.insert(t);
(values, errors)
}
Err(error) => {
errors.push(error);
(values, errors)
}
},
);
if !errors.is_empty() {
Err(format!("Some errors occurred:\n{}", errors.join("\n")))
} else {
Ok(values)
}
}
<file_sep path="hyperswitch/crates/router/src/configs/settings.rs" role="context" start="1201" end="1212">
fn deserialize_hashmap<'a, D, K, V>(deserializer: D) -> Result<HashMap<K, HashSet<V>>, D::Error>
where
D: serde::Deserializer<'a>,
K: Eq + std::str::FromStr + std::hash::Hash,
V: Eq + std::str::FromStr + std::hash::Hash,
<K as std::str::FromStr>::Err: std::fmt::Display,
<V as std::str::FromStr>::Err: std::fmt::Display,
{
use serde::de::Error;
deserialize_hashmap_inner(<HashMap<String, String>>::deserialize(deserializer)?)
.map_err(D::Error::custom)
}
<file_sep path="hyperswitch/crates/router/src/configs/settings.rs" role="context" start="1252" end="1261">
fn deserialize_hashset<'a, D, T>(deserializer: D) -> Result<HashSet<T>, D::Error>
where
D: serde::Deserializer<'a>,
T: Eq + std::str::FromStr + std::hash::Hash,
<T as std::str::FromStr>::Err: std::fmt::Display,
{
use serde::de::Error;
deserialize_hashset_inner(<String>::deserialize(deserializer)?).map_err(D::Error::custom)
}
<file_sep path="hyperswitch/crates/router/src/configs/settings.rs" role="context" start="1087" end="1090">
struct Inner {
redis_lock_expiry_seconds: u32,
delay_between_retries_in_milliseconds: u32,
}
<file_sep path="hyperswitch/crates/router/src/configs/settings.rs" role="context" start="276" end="278">
pub struct TenantUserConfig {
pub control_center_url: String,
}
<file_sep path="hyperswitch/crates/router/tests/utils.rs" role="context" start="399" end="401">
pub struct Error {
pub message: Message,
}
<file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="2478" end="2478">
type Error = error_stack::Report<errors::ValidationError>;
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/db/dispute.rs<|crate|> router anchor=create_dispute_new kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/db/dispute.rs" role="context" start="486" end="511">
fn create_dispute_new(dispute_ids: DisputeNewIds) -> DisputeNew {
DisputeNew {
dispute_id: dispute_ids.dispute_id,
amount: "amount".into(),
currency: "currency".into(),
dispute_stage: DisputeStage::Dispute,
dispute_status: DisputeStatus::DisputeOpened,
payment_id: dispute_ids.payment_id,
attempt_id: dispute_ids.attempt_id,
merchant_id: dispute_ids.merchant_id,
connector_status: "connector_status".into(),
connector_dispute_id: dispute_ids.connector_dispute_id,
connector_reason: Some("connector_reason".into()),
connector_reason_code: Some("connector_reason_code".into()),
challenge_required_by: Some(datetime!(2019-01-01 0:00)),
connector_created_at: Some(datetime!(2019-01-02 0:00)),
connector_updated_at: Some(datetime!(2019-01-03 0:00)),
connector: "connector".into(),
evidence: Some(Secret::from(Value::String("evidence".into()))),
profile_id: Some(common_utils::generate_profile_id_of_default_length()),
merchant_connector_id: None,
dispute_amount: 1040,
organization_id: common_utils::id_type::OrganizationId::default(),
dispute_currency: Some(common_enums::Currency::default()),
}
}
<file_sep path="hyperswitch/crates/router/src/db/dispute.rs" role="context" start="550" end="599">
async fn test_find_by_merchant_id_payment_id_connector_dispute_id() {
let merchant_id =
common_utils::id_type::MerchantId::try_from(Cow::from("merchant_1")).unwrap();
let mockdb = MockDb::new(&RedisSettings::default())
.await
.expect("Failed to create Mock store");
let created_dispute = mockdb
.insert_dispute(create_dispute_new(DisputeNewIds {
dispute_id: "dispute_1".into(),
attempt_id: "attempt_1".into(),
merchant_id: merchant_id.clone(),
payment_id: common_utils::id_type::PaymentId::try_from(Cow::Borrowed(
"payment_1",
))
.unwrap(),
connector_dispute_id: "connector_dispute_1".into(),
}))
.await
.unwrap();
let _ = mockdb
.insert_dispute(create_dispute_new(DisputeNewIds {
dispute_id: "dispute_2".into(),
attempt_id: "attempt_1".into(),
merchant_id: merchant_id.clone(),
payment_id: common_utils::id_type::PaymentId::try_from(Cow::Borrowed(
"payment_1",
))
.unwrap(),
connector_dispute_id: "connector_dispute_2".into(),
}))
.await
.unwrap();
let found_dispute = mockdb
.find_by_merchant_id_payment_id_connector_dispute_id(
&merchant_id,
&common_utils::id_type::PaymentId::try_from(Cow::Borrowed("payment_1"))
.unwrap(),
"connector_dispute_1",
)
.await
.unwrap();
assert!(found_dispute.is_some());
assert_eq!(created_dispute, found_dispute.unwrap());
}
<file_sep path="hyperswitch/crates/router/src/db/dispute.rs" role="context" start="514" end="547">
async fn test_insert_dispute() {
let mockdb = MockDb::new(&RedisSettings::default())
.await
.expect("Failed to create a mock DB");
let merchant_id =
common_utils::id_type::MerchantId::try_from(Cow::from("merchant_1")).unwrap();
let created_dispute = mockdb
.insert_dispute(create_dispute_new(DisputeNewIds {
dispute_id: "dispute_1".into(),
attempt_id: "attempt_1".into(),
merchant_id: merchant_id.clone(),
payment_id: common_utils::id_type::PaymentId::try_from(Cow::Borrowed(
"payment_1",
))
.unwrap(),
connector_dispute_id: "connector_dispute_1".into(),
}))
.await
.unwrap();
let found_dispute = mockdb
.disputes
.lock()
.await
.iter()
.find(|d| d.dispute_id == created_dispute.dispute_id)
.cloned();
assert!(found_dispute.is_some());
assert_eq!(created_dispute, found_dispute.unwrap());
}
<file_sep path="hyperswitch/crates/router/src/db/dispute.rs" role="context" start="415" end="457">
async fn get_dispute_status_with_count(
&self,
merchant_id: &common_utils::id_type::MerchantId,
profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
time_range: &common_utils::types::TimeRange,
) -> CustomResult<Vec<(common_enums::DisputeStatus, i64)>, errors::StorageError> {
let locked_disputes = self.disputes.lock().await;
let filtered_disputes_data = locked_disputes
.iter()
.filter(|d| {
d.merchant_id == *merchant_id
&& d.created_at >= time_range.start_time
&& time_range
.end_time
.as_ref()
.map(|received_end_time| received_end_time >= &d.created_at)
.unwrap_or(true)
&& profile_id_list
.as_ref()
.zip(d.profile_id.as_ref())
.map(|(received_profile_list, received_profile_id)| {
received_profile_list.contains(received_profile_id)
})
.unwrap_or(true)
})
.cloned()
.collect::<Vec<storage::Dispute>>();
Ok(filtered_disputes_data
.into_iter()
.fold(
HashMap::new(),
|mut acc: HashMap<common_enums::DisputeStatus, i64>, value| {
acc.entry(value.dispute_status)
.and_modify(|value| *value += 1)
.or_insert(1);
acc
},
)
.into_iter()
.collect::<Vec<(common_enums::DisputeStatus, i64)>>())
}
<file_sep path="hyperswitch/crates/router/src/db/dispute.rs" role="context" start="352" end="413">
async fn update_dispute(
&self,
this: storage::Dispute,
dispute: storage::DisputeUpdate,
) -> CustomResult<storage::Dispute, errors::StorageError> {
let mut locked_disputes = self.disputes.lock().await;
let dispute_to_update = locked_disputes
.iter_mut()
.find(|d| d.dispute_id == this.dispute_id)
.ok_or(errors::StorageError::MockDbError)?;
let now = common_utils::date_time::now();
match dispute {
storage::DisputeUpdate::Update {
dispute_stage,
dispute_status,
connector_status,
connector_reason,
connector_reason_code,
challenge_required_by,
connector_updated_at,
} => {
if connector_reason.is_some() {
dispute_to_update.connector_reason = connector_reason;
}
if connector_reason_code.is_some() {
dispute_to_update.connector_reason_code = connector_reason_code;
}
if challenge_required_by.is_some() {
dispute_to_update.challenge_required_by = challenge_required_by;
}
if connector_updated_at.is_some() {
dispute_to_update.connector_updated_at = connector_updated_at;
}
dispute_to_update.dispute_stage = dispute_stage;
dispute_to_update.dispute_status = dispute_status;
dispute_to_update.connector_status = connector_status;
}
storage::DisputeUpdate::StatusUpdate {
dispute_status,
connector_status,
} => {
if let Some(status) = connector_status {
dispute_to_update.connector_status = status;
}
dispute_to_update.dispute_status = dispute_status;
}
storage::DisputeUpdate::EvidenceUpdate { evidence } => {
dispute_to_update.evidence = evidence;
}
}
dispute_to_update.modified_at = now;
Ok(dispute_to_update.clone())
}
<file_sep path="hyperswitch/crates/router/src/db/dispute.rs" role="context" start="767" end="848">
async fn test_update_dispute_update() {
let merchant_id =
common_utils::id_type::MerchantId::try_from(Cow::from("merchant_1")).unwrap();
let payment_id =
common_utils::id_type::PaymentId::try_from(Cow::Borrowed("payment_1")).unwrap();
let mockdb = MockDb::new(&redis_interface::RedisSettings::default())
.await
.expect("Failed to create Mock store");
let created_dispute = mockdb
.insert_dispute(create_dispute_new(DisputeNewIds {
dispute_id: "dispute_1".into(),
attempt_id: "attempt_1".into(),
merchant_id: merchant_id.clone(),
payment_id: payment_id.clone(),
connector_dispute_id: "connector_dispute_1".into(),
}))
.await
.unwrap();
let updated_dispute = mockdb
.update_dispute(
created_dispute.clone(),
DisputeUpdate::Update {
dispute_stage: DisputeStage::PreDispute,
dispute_status: DisputeStatus::DisputeAccepted,
connector_status: "updated_connector_status".into(),
connector_reason: Some("updated_connector_reason".into()),
connector_reason_code: Some("updated_connector_reason_code".into()),
challenge_required_by: Some(datetime!(2019-01-10 0:00)),
connector_updated_at: Some(datetime!(2019-01-11 0:00)),
},
)
.await
.unwrap();
assert_eq!(created_dispute.dispute_id, updated_dispute.dispute_id);
assert_eq!(created_dispute.amount, updated_dispute.amount);
assert_eq!(created_dispute.currency, updated_dispute.currency);
assert_ne!(created_dispute.dispute_stage, updated_dispute.dispute_stage);
assert_ne!(
created_dispute.dispute_status,
updated_dispute.dispute_status
);
assert_eq!(created_dispute.payment_id, updated_dispute.payment_id);
assert_eq!(created_dispute.attempt_id, updated_dispute.attempt_id);
assert_eq!(created_dispute.merchant_id, updated_dispute.merchant_id);
assert_ne!(
created_dispute.connector_status,
updated_dispute.connector_status
);
assert_eq!(
created_dispute.connector_dispute_id,
updated_dispute.connector_dispute_id
);
assert_ne!(
created_dispute.connector_reason,
updated_dispute.connector_reason
);
assert_ne!(
created_dispute.connector_reason_code,
updated_dispute.connector_reason_code
);
assert_ne!(
created_dispute.challenge_required_by,
updated_dispute.challenge_required_by
);
assert_eq!(
created_dispute.connector_created_at,
updated_dispute.connector_created_at
);
assert_ne!(
created_dispute.connector_updated_at,
updated_dispute.connector_updated_at
);
assert_eq!(created_dispute.created_at, updated_dispute.created_at);
assert_ne!(created_dispute.modified_at, updated_dispute.modified_at);
assert_eq!(created_dispute.connector, updated_dispute.connector);
assert_eq!(created_dispute.evidence, updated_dispute.evidence);
}
<file_sep path="hyperswitch/crates/router/src/db/dispute.rs" role="context" start="478" end="484">
pub struct DisputeNewIds {
dispute_id: String,
payment_id: common_utils::id_type::PaymentId,
attempt_id: String,
merchant_id: common_utils::id_type::MerchantId,
connector_dispute_id: String,
}
<file_sep path="hyperswitch/migrations/2024-08-20-112035_add-profile-id-to-txn-tables/up.sql" role="context" start="10" end="26">
ALTER TABLE payment_intent
ADD COLUMN IF NOT EXISTS organization_id VARCHAR(32) NOT NULL DEFAULT 'default_org';
-- Add organization_id to refund table
ALTER TABLE refund
ADD COLUMN IF NOT EXISTS organization_id VARCHAR(32) NOT NULL DEFAULT 'default_org';
-- Add organization_id to dispute table
ALTER TABLE dispute
ADD COLUMN IF NOT EXISTS organization_id VARCHAR(32) NOT NULL DEFAULT 'default_org';
-- This doesn't work on V2
-- The below backfill step has to be run after the code deployment
-- UPDATE payment_attempt pa
-- SET organization_id = ma.organization_id
-- FROM merchant_account ma
-- WHERE pa.merchant_id = ma.merchant_id;
<file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="1670" end="1670">
type Value = PaymentMethodListRequest;
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payment_methods.rs<|crate|> router anchor=new kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/payment_methods.rs" role="context" start="1388" end="1392">
fn new(required_fields_config: settings::RequiredFields) -> Self {
Self {
required_fields_config,
}
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods.rs" role="context" start="1387" end="1387">
use crate::{
configs::settings,
core::{payment_methods::transformers as pm_transforms, payments as payments_core},
db::errors::ConnectorErrorExt,
headers, logger,
routes::{self, payment_methods as pm_routes},
services::encryption,
types::{
self,
api::{self, payment_methods::PaymentMethodCreateExt},
domain::types as domain_types,
payment_methods as pm_types,
storage::{ephemeral_key, PaymentMethodListContext},
transformers::{ForeignFrom, ForeignTryFrom},
Tokenizable,
},
utils::ext_traits::OptionExt,
};
<file_sep path="hyperswitch/crates/router/src/core/payment_methods.rs" role="context" start="1431" end="1477">
fn get_required_fields(
self,
input: RequiredFieldsInput,
) -> RequiredFieldsForEnabledPaymentMethodTypes {
let required_fields_config = input.required_fields_config;
let required_fields_info = self
.0
.into_iter()
.map(|payment_methods_enabled| {
let required_fields =
required_fields_config.get_required_fields(&payment_methods_enabled);
let required_fields = required_fields
.map(|required_fields| {
let common_required_fields = required_fields
.common
.iter()
.flatten()
.map(ToOwned::to_owned);
// Collect mandate required fields because this is for zero auth mandates only
let mandate_required_fields = required_fields
.mandate
.iter()
.flatten()
.map(ToOwned::to_owned);
// Combine both common and mandate required fields
common_required_fields
.chain(mandate_required_fields)
.collect::<Vec<_>>()
})
.unwrap_or_default();
RequiredFieldsForEnabledPaymentMethod {
required_fields,
payment_method_type: payment_methods_enabled.payment_method,
payment_method_subtype: payment_methods_enabled
.payment_methods_enabled
.payment_method_subtype,
}
})
.collect();
RequiredFieldsForEnabledPaymentMethodTypes(required_fields_info)
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods.rs" role="context" start="1411" end="1426">
fn get_required_fields(
&self,
payment_method_enabled: &hyperswitch_domain_models::merchant_connector_account::PaymentMethodsEnabledForConnector,
) -> Option<&settings::RequiredFieldFinal> {
self.0
.get(&payment_method_enabled.payment_method)
.and_then(|required_fields_for_payment_method| {
required_fields_for_payment_method.0.get(
&payment_method_enabled
.payment_methods_enabled
.payment_method_subtype,
)
})
.map(|connector_fields| &connector_fields.fields)
.and_then(|connector_hashmap| connector_hashmap.get(&payment_method_enabled.connector))
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods.rs" role="context" start="1368" end="1378">
pub async fn get_total_saved_payment_methods_for_merchant(
state: SessionState,
merchant_account: domain::MerchantAccount,
) -> RouterResponse<api::TotalPaymentMethodCountResponse> {
let total_payment_method_count =
get_total_payment_method_count_core(&state, &merchant_account).await?;
Ok(hyperswitch_domain_models::api::ApplicationResponse::Json(
total_payment_method_count,
))
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods.rs" role="context" start="1351" end="1364">
pub async fn list_saved_payment_methods_for_customer(
state: SessionState,
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
customer_id: id_type::GlobalCustomerId,
) -> RouterResponse<api::CustomerPaymentMethodsListResponse> {
let customer_payment_methods =
list_customer_payment_method_core(&state, &merchant_account, &key_store, &customer_id)
.await?;
Ok(hyperswitch_domain_models::api::ApplicationResponse::Json(
customer_payment_methods,
))
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods.rs" role="context" start="293" end="455">
pub async fn render_pm_collect_link(
state: SessionState,
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
req: payment_methods::PaymentMethodCollectLinkRenderRequest,
) -> RouterResponse<services::GenericLinkFormData> {
let db: &dyn StorageInterface = &*state.store;
// Fetch pm collect link
let pm_collect_link = db
.find_pm_collect_link_by_link_id(&req.pm_collect_link_id)
.await
.to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError {
message: "payment method collect link not found".to_string(),
})?;
// Check status and return form data accordingly
let has_expired = common_utils::date_time::now() > pm_collect_link.expiry;
let status = pm_collect_link.link_status;
let link_data = pm_collect_link.link_data;
let default_config = &state.conf.generic_link.payment_method_collect;
let default_ui_config = default_config.ui_config.clone();
let ui_config_data = common_utils::link_utils::GenericLinkUiConfigFormData {
merchant_name: link_data
.ui_config
.merchant_name
.unwrap_or(default_ui_config.merchant_name),
logo: link_data.ui_config.logo.unwrap_or(default_ui_config.logo),
theme: link_data
.ui_config
.theme
.clone()
.unwrap_or(default_ui_config.theme.clone()),
};
match status {
common_utils::link_utils::PaymentMethodCollectStatus::Initiated => {
// if expired, send back expired status page
if has_expired {
let expired_link_data = services::GenericExpiredLinkData {
title: "Payment collect link has expired".to_string(),
message: "This payment collect link has expired.".to_string(),
theme: link_data.ui_config.theme.unwrap_or(default_ui_config.theme),
};
Ok(services::ApplicationResponse::GenericLinkForm(Box::new(
GenericLinks {
allowed_domains: HashSet::from([]),
data: GenericLinksData::ExpiredLink(expired_link_data),
locale: DEFAULT_LOCALE.to_string(),
},
)))
// else, send back form link
} else {
let customer_id = id_type::CustomerId::try_from(Cow::from(
pm_collect_link.primary_reference.clone(),
))
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "customer_id",
})?;
// Fetch customer
let customer = db
.find_customer_by_customer_id_merchant_id(
&(&state).into(),
&customer_id,
&req.merchant_id,
&key_store,
merchant_account.storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InvalidRequestData {
message: format!(
"Customer [{}] not found for link_id - {}",
pm_collect_link.primary_reference, pm_collect_link.link_id
),
})
.attach_printable(format!(
"customer [{}] not found",
pm_collect_link.primary_reference
))?;
let js_data = payment_methods::PaymentMethodCollectLinkDetails {
publishable_key: Secret::new(merchant_account.publishable_key),
client_secret: link_data.client_secret.clone(),
pm_collect_link_id: pm_collect_link.link_id,
customer_id: customer.customer_id,
session_expiry: pm_collect_link.expiry,
return_url: pm_collect_link.return_url,
ui_config: ui_config_data,
enabled_payment_methods: link_data.enabled_payment_methods,
};
let serialized_css_content = String::new();
let serialized_js_content = format!(
"window.__PM_COLLECT_DETAILS = {}",
js_data
.encode_to_string_of_json()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to serialize PaymentMethodCollectLinkDetails")?
);
let generic_form_data = services::GenericLinkFormData {
js_data: serialized_js_content,
css_data: serialized_css_content,
sdk_url: default_config.sdk_url.to_string(),
html_meta_tags: String::new(),
};
Ok(services::ApplicationResponse::GenericLinkForm(Box::new(
GenericLinks {
allowed_domains: HashSet::from([]),
data: GenericLinksData::PaymentMethodCollect(generic_form_data),
locale: DEFAULT_LOCALE.to_string(),
},
)))
}
}
// Send back status page
status => {
let js_data = payment_methods::PaymentMethodCollectLinkStatusDetails {
pm_collect_link_id: pm_collect_link.link_id,
customer_id: link_data.customer_id,
session_expiry: pm_collect_link.expiry,
return_url: pm_collect_link
.return_url
.as_ref()
.map(|url| url::Url::parse(url))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Failed to parse return URL for payment method collect's status link",
)?,
ui_config: ui_config_data,
status,
};
let serialized_css_content = String::new();
let serialized_js_content = format!(
"window.__PM_COLLECT_DETAILS = {}",
js_data
.encode_to_string_of_json()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Failed to serialize PaymentMethodCollectLinkStatusDetails"
)?
);
let generic_status_data = services::GenericLinkStatusData {
js_data: serialized_js_content,
css_data: serialized_css_content,
};
Ok(services::ApplicationResponse::GenericLinkForm(Box::new(
GenericLinks {
allowed_domains: HashSet::from([]),
data: GenericLinksData::PaymentMethodCollectStatus(generic_status_data),
locale: DEFAULT_LOCALE.to_string(),
},
)))
}
}
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods.rs" role="context" start="2719" end="2863">
async fn create_single_use_tokenization_flow(
state: SessionState,
req_state: routes::app::ReqState,
merchant_account: domain::MerchantAccount,
profile: domain::Profile,
key_store: domain::MerchantKeyStore,
payment_method_create_request: &payment_methods::PaymentMethodCreate,
payment_method: &api::PaymentMethodResponse,
payment_method_session: &domain::payment_methods::PaymentMethodSession,
) -> RouterResult<()> {
let customer_id = payment_method_create_request.customer_id.to_owned();
let connector_id = payment_method_create_request
.get_tokenize_connector_id()
.change_context(errors::ApiErrorResponse::MissingRequiredField {
field_name: "psp_tokenization.connector_id",
})
.attach_printable("Failed to get tokenize connector id")?;
let db = &state.store;
let merchant_connector_account_details = db
.find_merchant_connector_account_by_id(&(&state).into(), &connector_id, &key_store)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: connector_id.get_string_repr().to_owned(),
})
.attach_printable("error while fetching merchant_connector_account from connector_id")?;
let auth_type = merchant_connector_account_details
.get_connector_account_details()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while parsing value for ConnectorAuthType")?;
let payment_method_data_request = types::PaymentMethodTokenizationData {
payment_method_data: payment_method_data::PaymentMethodData::try_from(
payment_method_create_request.payment_method_data.clone(),
)
.change_context(errors::ApiErrorResponse::MissingRequiredField {
field_name: "card_cvc",
})
.attach_printable(
"Failed to convert type from Payment Method Create Data to Payment Method Data",
)?,
browser_info: None,
currency: api_models::enums::Currency::default(),
amount: None,
};
let payment_method_session_address = types::PaymentAddress::new(
None,
payment_method_session
.billing
.clone()
.map(|address| address.into_inner()),
None,
None,
);
let mut router_data =
types::RouterData::<api::PaymentMethodToken, _, types::PaymentsResponseData> {
flow: std::marker::PhantomData,
merchant_id: merchant_account.get_id().clone(),
customer_id: None,
connector_customer: None,
connector: merchant_connector_account_details
.connector_name
.to_string(),
payment_id: consts::IRRELEVANT_PAYMENT_INTENT_ID.to_string(), //Static
attempt_id: consts::IRRELEVANT_PAYMENT_ATTEMPT_ID.to_string(), //Static
tenant_id: state.tenant.tenant_id.clone(),
status: common_enums::enums::AttemptStatus::default(),
payment_method: common_enums::enums::PaymentMethod::Card,
connector_auth_type: auth_type,
description: None,
address: payment_method_session_address,
auth_type: common_enums::enums::AuthenticationType::default(),
connector_meta_data: None,
connector_wallets_details: None,
amount_captured: None,
access_token: None,
session_token: None,
reference_id: None,
payment_method_token: None,
recurring_mandate_payment_data: None,
preprocessing_id: None,
payment_method_balance: None,
connector_api_version: None,
request: payment_method_data_request.clone(),
response: Err(hyperswitch_domain_models::router_data::ErrorResponse::default()),
connector_request_reference_id: payment_method_session.id.get_string_repr().to_string(),
#[cfg(feature = "payouts")]
payout_method_data: None,
#[cfg(feature = "payouts")]
quote_id: None,
test_mode: None,
connector_http_status_code: None,
external_latency: None,
apple_pay_flow: None,
frm_metadata: None,
dispute_id: None,
refund_id: None,
connector_response: None,
payment_method_status: None,
minor_amount_captured: None,
integrity_check: Ok(()),
additional_merchant_data: None,
header_payload: None,
connector_mandate_request_reference_id: None,
authentication_id: None,
psd2_sca_exemption_type: None,
};
let payment_method_token_response = tokenization::add_token_for_payment_method(
&mut router_data,
payment_method_data_request.clone(),
state.clone(),
&merchant_connector_account_details.clone(),
)
.await?;
let token_response = payment_method_token_response.token.map_err(|err| {
errors::ApiErrorResponse::ExternalConnectorError {
code: err.code,
message: err.message,
connector: (merchant_connector_account_details.clone())
.connector_name
.to_string(),
status_code: err.status_code,
reason: err.reason,
}
})?;
let value = payment_method_data::SingleUsePaymentMethodToken::get_single_use_token_from_payment_method_token(
token_response.clone().into(),
connector_id.clone()
);
let key = payment_method_data::SingleUseTokenKey::store_key(&payment_method.id);
add_single_use_token_to_store(&state, key, value)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to store single use token")?;
Ok(())
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/nmi/transformers.rs<|crate|> router anchor=try_from kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/connector/nmi/transformers.rs" role="context" start="1350" end="1357">
fn try_from(item: &NmiWebhookBody) -> Result<Self, Self::Error> {
let transaction = Some(SyncTransactionResponse {
transaction_id: item.event_body.transaction_id.to_owned(),
condition: item.event_body.condition.to_owned(),
});
Ok(Self { transaction })
}
<file_sep path="hyperswitch/crates/router/src/connector/nmi/transformers.rs" role="context" start="1349" end="1349">
type Error = Report<errors::ConnectorError>;
<file_sep path="hyperswitch/crates/router/src/connector/nmi/transformers.rs" role="context" start="1314" end="1332">
fn foreign_from(status: NmiWebhookEventType) -> Self {
match status {
NmiWebhookEventType::SaleSuccess => Self::PaymentIntentSuccess,
NmiWebhookEventType::SaleFailure => Self::PaymentIntentFailure,
NmiWebhookEventType::RefundSuccess => Self::RefundSuccess,
NmiWebhookEventType::RefundFailure => Self::RefundFailure,
NmiWebhookEventType::VoidSuccess => Self::PaymentIntentCancelled,
NmiWebhookEventType::AuthSuccess => Self::PaymentIntentAuthorizationSuccess,
NmiWebhookEventType::CaptureSuccess => Self::PaymentIntentCaptureSuccess,
NmiWebhookEventType::AuthFailure => Self::PaymentIntentAuthorizationFailure,
NmiWebhookEventType::CaptureFailure => Self::PaymentIntentCaptureFailure,
NmiWebhookEventType::VoidFailure => Self::PaymentIntentCancelFailure,
NmiWebhookEventType::SaleUnknown
| NmiWebhookEventType::RefundUnknown
| NmiWebhookEventType::AuthUnknown
| NmiWebhookEventType::VoidUnknown
| NmiWebhookEventType::CaptureUnknown => Self::EventNotSupported,
}
}
<file_sep path="hyperswitch/crates/router/src/connector/nmi/transformers.rs" role="context" start="1210" end="1222">
fn from(value: String) -> Self {
match value.as_str() {
"abandoned" => Self::Abandoned,
"canceled" => Self::Cancelled,
"in_progress" => Self::InProgress,
"pendingsettlement" => Self::Pendingsettlement,
"complete" => Self::Complete,
"failed" => Self::Failed,
"unknown" => Self::Unknown,
// Other than above values only pending is possible, since value is a string handling this as default
_ => Self::Pending,
}
}
<file_sep path="hyperswitch/crates/router/src/connector/nmi/transformers.rs" role="context" start="1163" end="1174">
fn try_from(item: &types::RefundSyncRouterData) -> Result<Self, Self::Error> {
let auth = NmiAuthType::try_from(&item.connector_auth_type)?;
Ok(Self {
security_key: auth.api_key,
order_id: item
.request
.connector_refund_id
.clone()
.ok_or(errors::ConnectorError::MissingConnectorRefundID)?,
})
}
<file_sep path="hyperswitch/crates/router/src/connector/nmi/transformers.rs" role="context" start="702" end="708">
fn try_from(item: &types::PaymentsSyncRouterData) -> Result<Self, Self::Error> {
let auth = NmiAuthType::try_from(&item.connector_auth_type)?;
Ok(Self {
security_key: auth.api_key,
order_id: item.attempt_id.clone(),
})
}
<file_sep path="hyperswitch/crates/router/src/connector/nmi/transformers.rs" role="context" start="19" end="19">
type Error = Report<errors::ConnectorError>;
<file_sep path="hyperswitch/crates/router/src/connector/nmi/transformers.rs" role="context" start="1336" end="1338">
pub struct NmiWebhookBody {
pub event_body: NmiWebhookObject,
}
<file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="2478" end="2478">
type Error = error_stack::Report<errors::ValidationError>;
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/stripe/transformers.rs<|crate|> router anchor=try_from kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="4116" end="4164">
fn try_from(item: &types::SubmitEvidenceRouterData) -> Result<Self, Self::Error> {
let submit_evidence_request_data = item.request.clone();
Ok(Self {
access_activity_log: submit_evidence_request_data.access_activity_log,
billing_address: submit_evidence_request_data
.billing_address
.map(Secret::new),
cancellation_policy: submit_evidence_request_data.cancellation_policy_provider_file_id,
cancellation_policy_disclosure: submit_evidence_request_data
.cancellation_policy_disclosure,
cancellation_rebuttal: submit_evidence_request_data.cancellation_rebuttal,
customer_communication: submit_evidence_request_data
.customer_communication_provider_file_id,
customer_email_address: submit_evidence_request_data
.customer_email_address
.map(Secret::new),
customer_name: submit_evidence_request_data.customer_name.map(Secret::new),
customer_purchase_ip: submit_evidence_request_data
.customer_purchase_ip
.map(Secret::new),
customer_signature: submit_evidence_request_data
.customer_signature_provider_file_id
.map(Secret::new),
product_description: submit_evidence_request_data.product_description,
receipt: submit_evidence_request_data
.receipt_provider_file_id
.map(Secret::new),
refund_policy: submit_evidence_request_data.refund_policy_provider_file_id,
refund_policy_disclosure: submit_evidence_request_data.refund_policy_disclosure,
refund_refusal_explanation: submit_evidence_request_data.refund_refusal_explanation,
service_date: submit_evidence_request_data.service_date,
service_documentation: submit_evidence_request_data
.service_documentation_provider_file_id,
shipping_address: submit_evidence_request_data
.shipping_address
.map(Secret::new),
shipping_carrier: submit_evidence_request_data.shipping_carrier,
shipping_date: submit_evidence_request_data.shipping_date,
shipping_documentation: submit_evidence_request_data
.shipping_documentation_provider_file_id
.map(Secret::new),
shipping_tracking_number: submit_evidence_request_data
.shipping_tracking_number
.map(Secret::new),
uncategorized_file: submit_evidence_request_data.uncategorized_file_provider_file_id,
uncategorized_text: submit_evidence_request_data.uncategorized_text,
submit: true,
})
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="4115" end="4115">
use common_utils::{
errors::CustomResult,
ext_traits::{ByteSliceExt, Encode},
pii::{self, Email},
request::RequestContent,
types::MinorUnit,
};
use masking::{ExposeInterface, ExposeOptionInterface, Mask, PeekInterface, Secret};
use crate::{
collect_missing_value_keys,
connector::utils::{self as connector_util, ApplePay, ApplePayDecrypt, RouterData},
consts,
core::errors,
headers, services,
types::{
self, api, domain,
storage::enums,
transformers::{ForeignFrom, ForeignTryFrom},
},
utils::OptionExt,
};
<file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="4196" end="4237">
fn foreign_try_from(
(response, http_code, response_id): (&Option<ErrorDetails>, u16, String),
) -> Result<Self, Self::Error> {
let (code, error_message) = match response {
Some(error_details) => (
error_details
.code
.to_owned()
.unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()),
error_details
.message
.to_owned()
.unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()),
),
None => (
consts::NO_ERROR_CODE.to_string(),
consts::NO_ERROR_MESSAGE.to_string(),
),
};
Err(types::ErrorResponse {
code,
message: error_message.clone(),
reason: response.clone().and_then(|res| {
res.decline_code
.clone()
.map(|decline_code| {
format!(
"message - {}, decline_code - {}",
error_message, decline_code
)
})
.or(Some(error_message.clone()))
}),
status_code: http_code,
attempt_status: None,
connector_transaction_id: Some(response_id),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
})
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="4174" end="4192">
fn get_transaction_metadata(
merchant_metadata: Option<Secret<Value>>,
order_id: String,
) -> HashMap<String, String> {
let mut meta_data = HashMap::from([("metadata[order_id]".to_string(), order_id)]);
let mut request_hash_map = HashMap::new();
if let Some(metadata) = merchant_metadata {
let hashmap: HashMap<String, Value> =
serde_json::from_str(&metadata.peek().to_string()).unwrap_or(HashMap::new());
for (key, value) in hashmap {
request_hash_map.insert(format!("metadata[{}]", key), value.to_string());
}
meta_data.extend(request_hash_map)
};
meta_data
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="4080" end="4112">
fn mandatory_parameters_for_sepa_bank_debit_mandates(
billing_details: &Option<StripeBillingAddress>,
is_customer_initiated_mandate_payment: Option<bool>,
) -> Result<StripeBillingAddress, errors::ConnectorError> {
let billing_name = billing_details
.clone()
.and_then(|billing_data| billing_data.name.clone());
let billing_email = billing_details
.clone()
.and_then(|billing_data| billing_data.email.clone());
match is_customer_initiated_mandate_payment {
Some(true) => Ok(StripeBillingAddress {
name: Some(
billing_name.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "billing_name",
})?,
),
email: Some(
billing_email.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "billing_email",
})?,
),
..StripeBillingAddress::default()
}),
Some(false) | None => Ok(StripeBillingAddress {
name: billing_name,
email: billing_email,
..StripeBillingAddress::default()
}),
}
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="4006" end="4018">
pub fn construct_file_upload_request(
file_upload_router_data: types::UploadFileRouterData,
) -> CustomResult<reqwest::multipart::Form, errors::ConnectorError> {
let request = file_upload_router_data.request;
let mut multipart = reqwest::multipart::Form::new();
multipart = multipart.text("purpose", "dispute_evidence");
let file_data = reqwest::multipart::Part::bytes(request.file)
.file_name(request.file_key)
.mime_str(request.file_type.as_ref())
.map_err(|_| errors::ConnectorError::RequestEncodingFailed)?;
multipart = multipart.part("file", file_data);
Ok(multipart)
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="2083" end="2112">
fn try_from(item: &types::SetupMandateRouterData) -> Result<Self, Self::Error> {
//Only cards supported for mandates
let pm_type = StripePaymentMethodType::Card;
let payment_data = StripePaymentMethodData::try_from((item, item.auth_type, pm_type))?;
let meta_data = Some(get_transaction_metadata(
item.request.metadata.clone(),
item.connector_request_reference_id.clone(),
));
let browser_info = item
.request
.browser_info
.clone()
.map(StripeBrowserInformation::from);
Ok(Self {
confirm: true,
payment_data,
return_url: item.request.router_return_url.clone(),
off_session: item.request.off_session,
usage: item.request.setup_future_usage,
payment_method_options: None,
customer: item.connector_customer.to_owned().map(Secret::new),
meta_data,
payment_method_types: Some(pm_type),
expand: Some(ExpandableObjects::LatestAttempt),
browser_info,
})
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="3988" end="4004">
pub fn get_bank_transfer_request_data(
req: &types::PaymentsAuthorizeRouterData,
bank_transfer_data: &domain::BankTransferData,
amount: MinorUnit,
) -> CustomResult<RequestContent, errors::ConnectorError> {
match bank_transfer_data {
domain::BankTransferData::AchBankTransfer { .. }
| domain::BankTransferData::MultibancoBankTransfer { .. } => {
let req = ChargesRequest::try_from((req, amount))?;
Ok(RequestContent::FormUrlEncoded(Box::new(req)))
}
_ => {
let req = PaymentIntentRequest::try_from((req, amount))?;
Ok(RequestContent::FormUrlEncoded(Box::new(req)))
}
}
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="46" end="46">
type Error = error_stack::Report<errors::ConnectorError>;
<file_sep path="hyperswitch/crates/router/src/types.rs" role="context" start="211" end="212">
pub type SubmitEvidenceRouterData =
RouterData<Evidence, SubmitEvidenceRequestData, SubmitEvidenceResponse>;
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/wellsfargopayout.rs<|crate|> router anchor=new kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/connector/wellsfargopayout.rs" role="context" start="33" end="37">
pub fn new() -> &'static Self {
&Self {
amount_converter: &StringMinorUnitForConnector,
}
}
<file_sep path="hyperswitch/crates/router/src/connector/wellsfargopayout.rs" role="context" start="32" end="32">
use common_utils::types::{AmountConvertor, StringMinorUnit, StringMinorUnitForConnector};
<file_sep path="hyperswitch/crates/router/src/connector/wellsfargopayout.rs" role="context" start="83" end="85">
fn id(&self) -> &'static str {
"wellsfargopayout"
}
<file_sep path="hyperswitch/crates/router/src/connector/wellsfargopayout.rs" role="context" start="67" end="79">
fn build_headers(
&self,
req: &types::RouterData<Flow, Request, Response>,
_connectors: &settings::Connectors,
) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
)];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
Ok(header)
}
<file_sep path="hyperswitch/crates/router/src/connector/wellsfargopayout.rs" role="context" start="189" end="205">
fn get_request_body(
&self,
req: &types::PaymentsAuthorizeRouterData,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = connector_utils::convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data =
wellsfargopayout::WellsfargopayoutRouterData::from((amount, req));
let connector_req =
wellsfargopayout::WellsfargopayoutPaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
<file_sep path="hyperswitch/crates/router/src/connector/wellsfargopayout.rs" role="context" start="448" end="465">
fn build_request(
&self,
req: &types::RefundsRouterData<api::Execute>,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
let request = services::RequestBuilder::new()
.method(services::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))
}
<file_sep path="hyperswitch/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/event.test.js" role="context" start="61" end="78">
"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.",
);
}
// Response body should have value "succeeded" for "status"
if (jsonData?.status) {
pm.test(
"[POST]::/payments - Content check if value for 'status' matches 'succeeded'",
function () {
pm.expect(jsonData.status).to.eql("succeeded");
},
);
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/gpayments.rs<|crate|> router anchor=new kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/connector/gpayments.rs" role="context" start="32" end="36">
pub fn new() -> &'static Self {
&Self {
_amount_converter: &MinorUnitForConnector,
}
}
<file_sep path="hyperswitch/crates/router/src/connector/gpayments.rs" role="context" start="31" end="31">
use common_utils::{
request::RequestContent,
types::{AmountConvertor, MinorUnit, MinorUnitForConnector},
};
<file_sep path="hyperswitch/crates/router/src/connector/gpayments.rs" role="context" start="80" end="82">
fn id(&self) -> &'static str {
"gpayments"
}
<file_sep path="hyperswitch/crates/router/src/connector/gpayments.rs" role="context" start="66" end="76">
fn build_headers(
&self,
_req: &types::RouterData<Flow, Request, Response>,
_connectors: &settings::Connectors,
) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
let header = vec![(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
)];
Ok(header)
}
<file_sep path="hyperswitch/crates/router/src/connector/gpayments.rs" role="context" start="360" end="384">
fn build_request(
&self,
req: &types::authentication::ConnectorPostAuthenticationRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
let gpayments_auth_type = gpayments::GpaymentsAuthType::try_from(&req.connector_auth_type)?;
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Get)
.url(
&types::authentication::ConnectorPostAuthenticationType::get_url(
self, req, connectors,
)?,
)
.attach_default_headers()
.headers(
types::authentication::ConnectorPostAuthenticationType::get_headers(
self, req, connectors,
)?,
)
.add_certificate(Some(gpayments_auth_type.certificate))
.add_certificate_key(Some(gpayments_auth_type.private_key))
.build(),
))
}
<file_sep path="hyperswitch/crates/router/src/connector/gpayments.rs" role="context" start="268" end="297">
fn build_request(
&self,
req: &types::authentication::ConnectorAuthenticationRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
let gpayments_auth_type = gpayments::GpaymentsAuthType::try_from(&req.connector_auth_type)?;
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Post)
.url(
&types::authentication::ConnectorAuthenticationType::get_url(
self, req, connectors,
)?,
)
.attach_default_headers()
.headers(
types::authentication::ConnectorAuthenticationType::get_headers(
self, req, connectors,
)?,
)
.set_body(
types::authentication::ConnectorAuthenticationType::get_request_body(
self, req, connectors,
)?,
)
.add_certificate(Some(gpayments_auth_type.certificate))
.add_certificate_key(Some(gpayments_auth_type.private_key))
.build(),
))
}
<file_sep path="hyperswitch/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/event.test.js" role="context" start="61" end="78">
"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.",
);
}
// Response body should have value "succeeded" for "status"
if (jsonData?.status) {
pm.test(
"[POST]::/payments - Content check if value for 'status' matches 'succeeded'",
function () {
pm.expect(jsonData.status).to.eql("succeeded");
},
);
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/db/customers.rs<|crate|> router anchor=from kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/db/customers.rs" role="context" start="27" end="32">
fn from(value: CustomerListConstraints) -> Self {
Self {
limit: i64::from(value.limit),
offset: value.offset.map(i64::from),
}
}
<file_sep path="hyperswitch/crates/router/src/db/customers.rs" role="context" start="26" end="26">
use diesel_models::query::customers::CustomerListConstraints as DieselCustomerListConstraints;
<file_sep path="hyperswitch/crates/router/src/db/customers.rs" role="context" start="261" end="326">
async fn find_customer_optional_with_redacted_customer_details_by_customer_id_merchant_id(
&self,
state: &KeyManagerState,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
key_store: &domain::MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Option<customer::Customer>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
let database_call = || async {
storage_types::Customer::find_optional_by_customer_id_merchant_id(
&conn,
customer_id,
merchant_id,
)
.await
.map_err(|err| report!(errors::StorageError::from(err)))
};
let storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_models::Customer>(
self,
storage_scheme,
Op::Find,
))
.await;
let maybe_customer = match storage_scheme {
MerchantStorageScheme::PostgresOnly => database_call().await,
MerchantStorageScheme::RedisKv => {
let key = PartitionKey::MerchantIdCustomerId {
merchant_id,
customer_id,
};
let field = format!("cust_{}", customer_id.get_string_repr());
Box::pin(db_utils::try_redis_get_else_try_database_get(
// check for ValueNotFound
async {
Box::pin(kv_wrapper(
self,
KvOperation::<diesel_models::Customer>::HGet(&field),
key,
))
.await?
.try_into_hget()
.map(Some)
},
database_call,
))
.await
}
}?;
let maybe_result = maybe_customer
.async_map(|customer| async {
customer
.convert(
state,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
})
.await
.transpose()?;
Ok(maybe_result)
}
<file_sep path="hyperswitch/crates/router/src/db/customers.rs" role="context" start="187" end="256">
async fn find_customer_optional_by_customer_id_merchant_id(
&self,
state: &KeyManagerState,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
key_store: &domain::MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Option<customer::Customer>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
let database_call = || async {
storage_types::Customer::find_optional_by_customer_id_merchant_id(
&conn,
customer_id,
merchant_id,
)
.await
.map_err(|err| report!(errors::StorageError::from(err)))
};
let storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_models::Customer>(
self,
storage_scheme,
Op::Find,
))
.await;
let maybe_customer = match storage_scheme {
MerchantStorageScheme::PostgresOnly => database_call().await,
MerchantStorageScheme::RedisKv => {
let key = PartitionKey::MerchantIdCustomerId {
merchant_id,
customer_id,
};
let field = format!("cust_{}", customer_id.get_string_repr());
Box::pin(db_utils::try_redis_get_else_try_database_get(
// check for ValueNotFound
async {
Box::pin(kv_wrapper(
self,
KvOperation::<diesel_models::Customer>::HGet(&field),
key,
))
.await?
.try_into_hget()
.map(Some)
},
database_call,
))
.await
}
}?;
let maybe_result = maybe_customer
.async_map(|c| async {
c.convert(
state,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
})
.await
.transpose()?;
maybe_result.map_or(Ok(None), |customer: domain::Customer| match customer.name {
Some(ref name) if name.peek() == REDACTED => {
Err(errors::StorageError::CustomerRedacted)?
}
_ => Ok(Some(customer)),
})
}
<file_sep path="hyperswitch/crates/router/src/db/customers.rs" role="context" start="620" end="655">
async fn list_customers_by_merchant_id(
&self,
state: &KeyManagerState,
merchant_id: &id_type::MerchantId,
key_store: &domain::MerchantKeyStore,
constraints: super::CustomerListConstraints,
) -> CustomResult<Vec<customer::Customer>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
let customer_list_constraints =
diesel_models::query::customers::CustomerListConstraints::from(constraints);
let encrypted_customers = storage_types::Customer::list_by_merchant_id(
&conn,
merchant_id,
customer_list_constraints,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))?;
let customers = try_join_all(encrypted_customers.into_iter().map(
|encrypted_customer| async {
encrypted_customer
.convert(
state,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
},
))
.await?;
Ok(customers)
}
<file_sep path="hyperswitch/crates/router/src/db/customers.rs" role="context" start="1416" end="1446">
async fn list_customers_by_merchant_id(
&self,
state: &KeyManagerState,
merchant_id: &id_type::MerchantId,
key_store: &domain::MerchantKeyStore,
constraints: CustomerListConstraints,
) -> CustomResult<Vec<customer::Customer>, errors::StorageError> {
let customers = self.customers.lock().await;
let customers = try_join_all(
customers
.iter()
.filter(|customer| customer.merchant_id == *merchant_id)
.take(usize::from(constraints.limit))
.skip(usize::try_from(constraints.offset.unwrap_or(0)).unwrap_or(0))
.map(|customer| async {
customer
.to_owned()
.convert(
state,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
}),
)
.await?;
Ok(customers)
}
<file_sep path="hyperswitch/crates/router/src/db/customers.rs" role="context" start="21" end="24">
pub struct CustomerListConstraints {
pub limit: u16,
pub offset: Option<u32>,
}
<file_sep path="hyperswitch/postman/collection-dir/airwallex/Flow Testcases/Variation Cases/Scenario6-Create 3DS payment with greater capture/Payments - Retrieve/event.test.js" role="context" start="62" end="74">
// Response body should have value "requires_customer_action" for "status"
if (jsonData?.status) {
pm.test(
"[POST]::/payments - Content check if value for 'status' matches 'requires_customer_action'",
function () {
pm.expect(jsonData.status).to.eql("requires_customer_action");
},
);
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/signifyd/transformers/api.rs<|crate|> router anchor=from kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/connector/signifyd/transformers/api.rs" role="context" start="718" end="723">
fn from(value: ReviewDisposition) -> Self {
match value {
ReviewDisposition::Fraudulent => Self::FrmRejected,
ReviewDisposition::Good => Self::FrmApproved,
}
}
<file_sep path="hyperswitch/crates/router/src/connector/signifyd/transformers/api.rs" role="context" start="687" end="700">
fn try_from(item: &frm_types::FrmRecordReturnRouterData) -> Result<Self, Self::Error> {
let currency = item.request.get_currency()?;
let refund = SignifydRefund {
method: item.request.refund_method.clone(),
amount: item.request.amount.to_string(),
currency,
};
Ok(Self {
return_id: uuid::Uuid::new_v4().to_string(),
refund_transaction_id: item.request.refund_transaction_id.clone(),
refund,
order_id: item.attempt_id.clone(),
})
}
<file_sep path="hyperswitch/crates/router/src/connector/signifyd/transformers/api.rs" role="context" start="666" end="682">
fn try_from(
item: ResponseRouterData<
F,
SignifydPaymentsRecordReturnResponse,
T,
frm_types::FraudCheckResponseData,
>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(frm_types::FraudCheckResponseData::RecordReturnResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.order_id),
return_id: Some(item.response.return_id.to_string()),
connector_metadata: None,
}),
..item.data
})
}
<file_sep path="hyperswitch/crates/router/src/connector/signifyd/transformers/api.rs" role="context" start="325" end="340">
fn try_from(item: &frm_types::FrmTransactionRouterData) -> Result<Self, Self::Error> {
let currency = item.request.get_currency()?;
let transactions = Transactions {
amount: item.request.amount,
transaction_id: item.clone().payment_id,
gateway_status_code: GatewayStatusCode::from(item.status).to_string(),
payment_method: item.payment_method,
currency,
gateway: item.request.connector.clone(),
};
Ok(Self {
order_id: item.attempt_id.clone(),
checkout_id: item.payment_id.clone(),
transactions,
})
}
<file_sep path="hyperswitch/crates/router/src/connector/signifyd/transformers/api.rs" role="context" start="265" end="284">
fn try_from(
item: ResponseRouterData<F, SignifydPaymentsResponse, T, frm_types::FraudCheckResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(frm_types::FraudCheckResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.order_id),
status: storage_enums::FraudCheckStatus::from(
item.response.decision.checkpoint_action,
),
connector_metadata: None,
score: item.response.decision.score.and_then(|data| data.to_i32()),
reason: item
.response
.decision
.checkpoint_action_reason
.map(serde_json::Value::from),
}),
..item.data
})
}
<file_sep path="hyperswitch/crates/router/src/connector/signifyd/transformers/api.rs" role="context" start="712" end="715">
pub enum ReviewDisposition {
Fraudulent,
Good,
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/services/authentication/blacklist.rs<|crate|> router anchor=get_redis_connection kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/services/authentication/blacklist.rs" role="context" start="127" end="133">
fn get_redis_connection<A: SessionStateInfo>(state: &A) -> RouterResult<Arc<RedisConnectionPool>> {
state
.store()
.get_redis_conn()
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get redis connection")
}
<file_sep path="hyperswitch/crates/router/src/services/authentication/blacklist.rs" role="context" start="126" end="126">
use std::sync::Arc;
use redis_interface::RedisConnectionPool;
use crate::{
consts::{JWT_TOKEN_TIME_IN_SECS, ROLE_BLACKLIST_PREFIX, USER_BLACKLIST_PREFIX},
core::errors::{ApiErrorResponse, RouterResult},
routes::app::SessionStateInfo,
};
<file_sep path="hyperswitch/crates/router/src/services/authentication/blacklist.rs" role="context" start="148" end="156">
async fn check_in_blacklist<A>(&self, state: &A) -> RouterResult<bool>
where
A: SessionStateInfo + Sync,
{
Ok(
check_user_in_blacklist(state, &self.user_id, self.exp).await?
|| check_role_in_blacklist(state, &self.role_id, self.exp).await?,
)
}
<file_sep path="hyperswitch/crates/router/src/services/authentication/blacklist.rs" role="context" start="135" end="137">
fn expiry_to_i64(expiry: u64) -> RouterResult<i64> {
i64::try_from(expiry).change_context(ApiErrorResponse::InternalServerError)
}
<file_sep path="hyperswitch/crates/router/src/services/authentication/blacklist.rs" role="context" start="113" end="125">
pub async fn check_email_token_in_blacklist(state: &SessionState, token: &str) -> UserResult<()> {
let redis_conn = get_redis_connection(state).change_context(UserErrors::InternalServerError)?;
let blacklist_key = format!("{}{token}", EMAIL_TOKEN_BLACKLIST_PREFIX);
let key_exists = redis_conn
.exists::<()>(&blacklist_key.as_str().into())
.await
.change_context(UserErrors::InternalServerError)?;
if key_exists {
return Err(UserErrors::LinkInvalid.into());
}
Ok(())
}
<file_sep path="hyperswitch/crates/router/src/services/authentication/blacklist.rs" role="context" start="101" end="110">
pub async fn insert_email_token_in_blacklist(state: &SessionState, token: &str) -> UserResult<()> {
let redis_conn = get_redis_connection(state).change_context(UserErrors::InternalServerError)?;
let blacklist_key = format!("{}{token}", EMAIL_TOKEN_BLACKLIST_PREFIX);
let expiry =
expiry_to_i64(EMAIL_TOKEN_TIME_IN_SECS).change_context(UserErrors::InternalServerError)?;
redis_conn
.set_key_with_expiry(&blacklist_key.as_str().into(), true, expiry)
.await
.change_context(UserErrors::InternalServerError)
}
<file_sep path="hyperswitch/crates/router/src/services/authentication/blacklist.rs" role="context" start="26" end="39">
pub async fn insert_user_in_blacklist(state: &SessionState, user_id: &str) -> UserResult<()> {
let user_blacklist_key = format!("{}{}", USER_BLACKLIST_PREFIX, user_id);
let expiry =
expiry_to_i64(JWT_TOKEN_TIME_IN_SECS).change_context(UserErrors::InternalServerError)?;
let redis_conn = get_redis_connection(state).change_context(UserErrors::InternalServerError)?;
redis_conn
.set_key_with_expiry(
&user_blacklist_key.as_str().into(),
date_time::now_unix_timestamp(),
expiry,
)
.await
.change_context(UserErrors::InternalServerError)
}
<file_sep path="hyperswitch/crates/router/src/core/errors.rs" role="context" start="31" end="31">
pub type RouterResult<T> = CustomResult<T, ApiErrorResponse>;
<file_sep path="hyperswitch/crates/api_models/src/errors/types.rs" role="context" start="86" end="100">
pub enum ApiErrorResponse {
Unauthorized(ApiError),
ForbiddenCommonResource(ApiError),
ForbiddenPrivateResource(ApiError),
Conflict(ApiError),
Gone(ApiError),
Unprocessable(ApiError),
InternalServerError(ApiError),
NotImplemented(ApiError),
ConnectorError(ApiError, #[serde(skip_serializing)] StatusCode),
NotFound(ApiError),
MethodNotAllowed(ApiError),
BadRequest(ApiError),
DomainError(ApiError),
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/configs/settings.rs<|crate|> router anchor=from kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/configs/settings.rs" role="context" start="778" end="791">
fn from(val: Database) -> Self {
Self {
username: val.username,
password: val.password,
host: val.host,
port: val.port,
dbname: val.dbname,
pool_size: val.pool_size,
connection_timeout: val.connection_timeout,
queue_strategy: val.queue_strategy,
min_idle: val.min_idle,
max_lifetime: val.max_lifetime,
}
}
<file_sep path="hyperswitch/crates/router/src/configs/settings.rs" role="context" start="911" end="958">
pub fn with_config_path(config_path: Option<PathBuf>) -> ApplicationResult<Self> {
// Configuration values are picked up in the following priority order (1 being least
// priority):
// 1. Defaults from the implementation of the `Default` trait.
// 2. Values from config file. The config file accessed depends on the environment
// specified by the `RUN_ENV` environment variable. `RUN_ENV` can be one of
// `development`, `sandbox` or `production`. If nothing is specified for `RUN_ENV`,
// `/config/development.toml` file is read.
// 3. Environment variables prefixed with `ROUTER` and each level separated by double
// underscores.
//
// Values in config file override the defaults in `Default` trait, and the values set using
// environment variables override both the defaults and the config file values.
let environment = env::which();
let config_path = router_env::Config::config_path(&environment.to_string(), config_path);
let config = router_env::Config::builder(&environment.to_string())
.change_context(ApplicationError::ConfigurationError)?
.add_source(File::from(config_path).required(false));
#[cfg(feature = "v2")]
let config = {
let required_fields_config_file =
router_env::Config::get_config_directory().join(REQUIRED_FIELDS_CONFIG_FILE);
config.add_source(File::from(required_fields_config_file).required(false))
};
let config = config
.add_source(
Environment::with_prefix("ROUTER")
.try_parsing(true)
.separator("__")
.list_separator(",")
.with_list_parse_key("log.telemetry.route_to_trace")
.with_list_parse_key("redis.cluster_urls")
.with_list_parse_key("events.kafka.brokers")
.with_list_parse_key("connectors.supported.wallets")
.with_list_parse_key("connector_request_reference_id_config.merchant_ids_send_payment_id_as_connector_request_id"),
)
.build()
.change_context(ApplicationError::ConfigurationError)?;
serde_path_to_error::deserialize(config)
.attach_printable("Unable to deserialize application configuration")
.change_context(ApplicationError::ConfigurationError)
}
<file_sep path="hyperswitch/crates/router/src/configs/settings.rs" role="context" start="907" end="909">
pub fn new() -> ApplicationResult<Self> {
Self::with_config_path(None)
}
<file_sep path="hyperswitch/crates/router/src/configs/settings.rs" role="context" start="392" end="400">
fn default() -> Self {
Self {
#[allow(clippy::expect_used)]
logo: url::Url::parse("https://hyperswitch.io/favicon.ico")
.expect("Failed to parse default logo URL"),
merchant_name: Secret::new("HyperSwitch".to_string()),
theme: "#4285F4".to_string(),
}
}
<file_sep path="hyperswitch/crates/router/src/configs/settings.rs" role="context" start="371" end="380">
fn default() -> Self {
Self {
#[allow(clippy::expect_used)]
sdk_url: url::Url::parse("http://localhost:9050/HyperLoader.js")
.expect("Failed to parse default SDK URL"),
expiry: 900,
ui_config: GenericLinkEnvUiConfig::default(),
enabled_payment_methods: HashMap::default(),
}
}
<file_sep path="hyperswitch/crates/router/src/configs/settings.rs" role="context" start="1407" end="1437">
fn test_payment_method_and_payment_method_types_with_spaces() {
use diesel_models::enums::{PaymentMethod, PaymentMethodType};
let input_map: HashMap<String, String> = HashMap::from([
(" bank_transfer ".to_string(), " ach , bacs ".to_string()),
("wallet ".to_string(), " paypal , pix , venmo ".to_string()),
]);
let deserializer: MapDeserializer<
'_,
std::collections::hash_map::IntoIter<String, String>,
ValueError,
> = input_map.into_deserializer();
let result = deserialize_hashmap::<'_, _, PaymentMethod, PaymentMethodType>(deserializer);
let expected_result = HashMap::from([
(
PaymentMethod::BankTransfer,
HashSet::from([PaymentMethodType::Ach, PaymentMethodType::Bacs]),
),
(
PaymentMethod::Wallet,
HashSet::from([
PaymentMethodType::Paypal,
PaymentMethodType::Pix,
PaymentMethodType::Venmo,
]),
),
]);
assert!(result.is_ok());
assert_eq!(result.unwrap(), expected_result);
}
<file_sep path="hyperswitch/crates/router/src/configs/settings.rs" role="context" start="1471" end="1480">
fn test_payment_method_hashset_deserializer() {
use diesel_models::enums::PaymentMethod;
let deserializer: StrDeserializer<'_, ValueError> = "wallet,card".into_deserializer();
let payment_methods = deserialize_hashset::<'_, _, PaymentMethod>(deserializer);
let expected_payment_methods = HashSet::from([PaymentMethod::Wallet, PaymentMethod::Card]);
assert!(payment_methods.is_ok());
assert_eq!(payment_methods.unwrap(), expected_payment_methods);
}
<file_sep path="hyperswitch/crates/router/src/configs/settings.rs" role="context" start="764" end="775">
pub struct Database {
pub username: String,
pub password: Secret<String>,
pub host: String,
pub port: u16,
pub dbname: String,
pub pool_size: u32,
pub connection_timeout: u64,
pub queue_strategy: QueueStrategy,
pub min_idle: Option<u32>,
pub max_lifetime: Option<u64>,
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/payeezy.rs<|crate|> router<|connector|> payeezy anchor=get_payment_data kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/tests/connectors/payeezy.rs" role="context" start="47" end="55">
fn get_payment_data() -> Option<PaymentsAuthorizeData> {
Some(PaymentsAuthorizeData {
payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card {
card_number: CardNumber::from_str("4012000033330026").unwrap(),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
})
}
<file_sep path="hyperswitch/crates/router/tests/connectors/payeezy.rs" role="context" start="46" end="46">
use router::{
core::errors,
types::{self, storage::enums, PaymentsAuthorizeData},
};
<file_sep path="hyperswitch/crates/router/tests/connectors/payeezy.rs" role="context" start="74" end="76">
fn get_request_interval(self) -> u64 {
20
}
<file_sep path="hyperswitch/crates/router/tests/connectors/payeezy.rs" role="context" start="57" end="73">
fn get_payment_info() -> Option<PaymentInfo> {
Some(PaymentInfo {
address: Some(types::PaymentAddress::new(
None,
Some(Address {
address: Some(AddressDetails {
..Default::default()
}),
phone: None,
email: None,
}),
None,
None,
)),
..Default::default()
})
}
<file_sep path="hyperswitch/crates/router/tests/connectors/payeezy.rs" role="context" start="41" end="43">
fn get_name(&self) -> String {
"payeezy".to_string()
}
<file_sep path="hyperswitch/crates/router/tests/connectors/payeezy.rs" role="context" start="32" end="39">
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.payeezy
.expect("Missing connector authentication configuration")
.into(),
)
}
<file_sep path="hyperswitch/crates/router/tests/connectors/payeezy.rs" role="context" start="92" end="110">
async fn should_capture_authorized_payment() {
let response = CONNECTOR
.authorize_payment(PayeezyTest::get_payment_data(), None)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Authorized);
let connector_payment_id =
utils::get_connector_transaction_id(response.response.clone()).unwrap_or_default();
let connector_meta = utils::get_connector_metadata(response.response);
let capture_data = types::PaymentsCaptureData {
connector_meta,
..utils::PaymentCaptureType::default().0
};
let capture_response = CONNECTOR
.capture_payment(connector_payment_id, Some(capture_data), None)
.await
.unwrap();
assert_eq!(capture_response.status, enums::AttemptStatus::Charged);
}
<file_sep path="hyperswitch/crates/router/tests/connectors/payeezy.rs" role="context" start="114" end="133">
async fn should_partially_capture_authorized_payment() {
let response = CONNECTOR
.authorize_payment(PayeezyTest::get_payment_data(), None)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Authorized);
let connector_payment_id =
utils::get_connector_transaction_id(response.response.clone()).unwrap_or_default();
let connector_meta = utils::get_connector_metadata(response.response);
let capture_data = types::PaymentsCaptureData {
connector_meta,
amount_to_capture: 50,
..utils::PaymentCaptureType::default().0
};
let capture_response = CONNECTOR
.capture_payment(connector_payment_id, Some(capture_data), None)
.await
.unwrap();
assert_eq!(capture_response.status, enums::AttemptStatus::Charged);
}
<file_sep path="hyperswitch/crates/router/src/compatibility/stripe/customers/types.rs" role="context" start="202" end="207">
pub struct PaymentMethodData {
pub id: Option<String>,
pub object: &'static str,
pub card: Option<CardDetails>,
pub created: Option<time::PrimitiveDateTime>,
}
<file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="2504" end="2539">
pub enum PaymentMethodData {
#[schema(title = "Card")]
Card(Card),
#[schema(title = "CardRedirect")]
CardRedirect(CardRedirectData),
#[schema(title = "Wallet")]
Wallet(WalletData),
#[schema(title = "PayLater")]
PayLater(PayLaterData),
#[schema(title = "BankRedirect")]
BankRedirect(BankRedirectData),
#[schema(title = "BankDebit")]
BankDebit(BankDebitData),
#[schema(title = "BankTransfer")]
BankTransfer(Box<BankTransferData>),
#[schema(title = "RealTimePayment")]
RealTimePayment(Box<RealTimePaymentData>),
#[schema(title = "Crypto")]
Crypto(CryptoData),
#[schema(title = "MandatePayment")]
MandatePayment,
#[schema(title = "Reward")]
Reward,
#[schema(title = "Upi")]
Upi(UpiData),
#[schema(title = "Voucher")]
Voucher(VoucherData),
#[schema(title = "GiftCard")]
GiftCard(Box<GiftCardData>),
#[schema(title = "CardToken")]
CardToken(CardToken),
#[schema(title = "OpenBanking")]
OpenBanking(OpenBankingData),
#[schema(title = "MobilePayment")]
MobilePayment(MobilePaymentData),
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/payeezy.rs<|crate|> router<|connector|> payeezy anchor=get_payment_data kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/tests/connectors/payeezy.rs" role="context" start="47" end="55">
fn get_payment_data() -> Option<PaymentsAuthorizeData> {
Some(PaymentsAuthorizeData {
payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card {
card_number: CardNumber::from_str("4012000033330026").unwrap(),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
})
}
<file_sep path="hyperswitch/crates/router/tests/connectors/payeezy.rs" role="context" start="46" end="46">
use router::{
core::errors,
types::{self, storage::enums, PaymentsAuthorizeData},
};
<file_sep path="hyperswitch/crates/router/tests/connectors/payeezy.rs" role="context" start="74" end="76">
fn get_request_interval(self) -> u64 {
20
}
<file_sep path="hyperswitch/crates/router/tests/connectors/payeezy.rs" role="context" start="57" end="73">
fn get_payment_info() -> Option<PaymentInfo> {
Some(PaymentInfo {
address: Some(types::PaymentAddress::new(
None,
Some(Address {
address: Some(AddressDetails {
..Default::default()
}),
phone: None,
email: None,
}),
None,
None,
)),
..Default::default()
})
}
<file_sep path="hyperswitch/crates/router/tests/connectors/payeezy.rs" role="context" start="41" end="43">
fn get_name(&self) -> String {
"payeezy".to_string()
}
<file_sep path="hyperswitch/crates/router/tests/connectors/payeezy.rs" role="context" start="32" end="39">
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.payeezy
.expect("Missing connector authentication configuration")
.into(),
)
}
<file_sep path="hyperswitch/crates/router/tests/connectors/payeezy.rs" role="context" start="92" end="110">
async fn should_capture_authorized_payment() {
let response = CONNECTOR
.authorize_payment(PayeezyTest::get_payment_data(), None)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Authorized);
let connector_payment_id =
utils::get_connector_transaction_id(response.response.clone()).unwrap_or_default();
let connector_meta = utils::get_connector_metadata(response.response);
let capture_data = types::PaymentsCaptureData {
connector_meta,
..utils::PaymentCaptureType::default().0
};
let capture_response = CONNECTOR
.capture_payment(connector_payment_id, Some(capture_data), None)
.await
.unwrap();
assert_eq!(capture_response.status, enums::AttemptStatus::Charged);
}
<file_sep path="hyperswitch/crates/router/tests/connectors/payeezy.rs" role="context" start="114" end="133">
async fn should_partially_capture_authorized_payment() {
let response = CONNECTOR
.authorize_payment(PayeezyTest::get_payment_data(), None)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Authorized);
let connector_payment_id =
utils::get_connector_transaction_id(response.response.clone()).unwrap_or_default();
let connector_meta = utils::get_connector_metadata(response.response);
let capture_data = types::PaymentsCaptureData {
connector_meta,
amount_to_capture: 50,
..utils::PaymentCaptureType::default().0
};
let capture_response = CONNECTOR
.capture_payment(connector_payment_id, Some(capture_data), None)
.await
.unwrap();
assert_eq!(capture_response.status, enums::AttemptStatus::Charged);
}
<file_sep path="hyperswitch/crates/router/src/compatibility/stripe/customers/types.rs" role="context" start="202" end="207">
pub struct PaymentMethodData {
pub id: Option<String>,
pub object: &'static str,
pub card: Option<CardDetails>,
pub created: Option<time::PrimitiveDateTime>,
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/configs/defaults/payout_required_fields.rs<|crate|> router anchor=get_connector_payment_method_type_fields kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/configs/defaults/payout_required_fields.rs" role="context" start="70" end="185">
fn get_connector_payment_method_type_fields(
connector: PayoutConnectors,
payment_method_type: PaymentMethodType,
) -> (PaymentMethodType, ConnectorFields) {
let mut common_fields = get_billing_details(connector);
match payment_method_type {
// Card
PaymentMethodType::Debit => {
common_fields.extend(get_card_fields());
(
payment_method_type,
ConnectorFields {
fields: HashMap::from([(
connector.into(),
RequiredFieldFinal {
mandate: HashMap::new(),
non_mandate: HashMap::new(),
common: common_fields,
},
)]),
},
)
}
PaymentMethodType::Credit => {
common_fields.extend(get_card_fields());
(
payment_method_type,
ConnectorFields {
fields: HashMap::from([(
connector.into(),
RequiredFieldFinal {
mandate: HashMap::new(),
non_mandate: HashMap::new(),
common: common_fields,
},
)]),
},
)
}
// Banks
PaymentMethodType::Bacs => {
common_fields.extend(get_bacs_fields());
(
payment_method_type,
ConnectorFields {
fields: HashMap::from([(
connector.into(),
RequiredFieldFinal {
mandate: HashMap::new(),
non_mandate: HashMap::new(),
common: common_fields,
},
)]),
},
)
}
PaymentMethodType::Pix => {
common_fields.extend(get_pix_bank_transfer_fields());
(
payment_method_type,
ConnectorFields {
fields: HashMap::from([(
connector.into(),
RequiredFieldFinal {
mandate: HashMap::new(),
non_mandate: HashMap::new(),
common: common_fields,
},
)]),
},
)
}
PaymentMethodType::Sepa => {
common_fields.extend(get_sepa_fields());
(
payment_method_type,
ConnectorFields {
fields: HashMap::from([(
connector.into(),
RequiredFieldFinal {
mandate: HashMap::new(),
non_mandate: HashMap::new(),
common: common_fields,
},
)]),
},
)
}
// Wallets
PaymentMethodType::Paypal => {
common_fields.extend(get_paypal_fields());
(
payment_method_type,
ConnectorFields {
fields: HashMap::from([(
connector.into(),
RequiredFieldFinal {
mandate: HashMap::new(),
non_mandate: HashMap::new(),
common: common_fields,
},
)]),
},
)
}
_ => (
payment_method_type,
ConnectorFields {
fields: HashMap::new(),
},
),
}
}
<file_sep path="hyperswitch/crates/router/src/configs/defaults/payout_required_fields.rs" role="context" start="69" end="69">
use std::collections::HashMap;
use api_models::{
enums::{
CountryAlpha2, FieldType,
PaymentMethod::{BankTransfer, Card, Wallet},
PaymentMethodType, PayoutConnectors,
},
payment_methods::RequiredFieldInfo,
};
use crate::settings::{
ConnectorFields, PaymentMethodType as PaymentMethodTypeInfo, PayoutRequiredFields,
RequiredFieldFinal,
};
<file_sep path="hyperswitch/crates/router/src/configs/defaults/payout_required_fields.rs" role="context" start="228" end="249">
fn get_bacs_fields() -> HashMap<String, RequiredFieldInfo> {
HashMap::from([
(
"payout_method_data.bank.bank_sort_code".to_string(),
RequiredFieldInfo {
required_field: "payout_method_data.bank.bank_sort_code".to_string(),
display_name: "bank_sort_code".to_string(),
field_type: FieldType::Text,
value: None,
},
),
(
"payout_method_data.bank.bank_account_number".to_string(),
RequiredFieldInfo {
required_field: "payout_method_data.bank.bank_account_number".to_string(),
display_name: "bank_account_number".to_string(),
field_type: FieldType::Text,
value: None,
},
),
])
}
<file_sep path="hyperswitch/crates/router/src/configs/defaults/payout_required_fields.rs" role="context" start="187" end="226">
fn get_card_fields() -> HashMap<String, RequiredFieldInfo> {
HashMap::from([
(
"payout_method_data.card.card_number".to_string(),
RequiredFieldInfo {
required_field: "payout_method_data.card.card_number".to_string(),
display_name: "card_number".to_string(),
field_type: FieldType::UserCardNumber,
value: None,
},
),
(
"payout_method_data.card.expiry_month".to_string(),
RequiredFieldInfo {
required_field: "payout_method_data.card.expiry_month".to_string(),
display_name: "exp_month".to_string(),
field_type: FieldType::UserCardExpiryMonth,
value: None,
},
),
(
"payout_method_data.card.expiry_year".to_string(),
RequiredFieldInfo {
required_field: "payout_method_data.card.expiry_year".to_string(),
display_name: "exp_year".to_string(),
field_type: FieldType::UserCardExpiryYear,
value: None,
},
),
(
"payout_method_data.card.card_holder_name".to_string(),
RequiredFieldInfo {
required_field: "payout_method_data.card.card_holder_name".to_string(),
display_name: "card_holder_name".to_string(),
field_type: FieldType::UserFullName,
value: None,
},
),
])
}
<file_sep path="hyperswitch/crates/router/src/configs/defaults/payout_required_fields.rs" role="context" start="19" end="66">
fn default() -> Self {
Self(HashMap::from([
(
Card,
PaymentMethodTypeInfo(HashMap::from([
// Adyen
get_connector_payment_method_type_fields(
PayoutConnectors::Adyenplatform,
PaymentMethodType::Debit,
),
get_connector_payment_method_type_fields(
PayoutConnectors::Adyenplatform,
PaymentMethodType::Credit,
),
])),
),
(
BankTransfer,
PaymentMethodTypeInfo(HashMap::from([
// Adyen
get_connector_payment_method_type_fields(
PayoutConnectors::Adyenplatform,
PaymentMethodType::Sepa,
),
// Ebanx
get_connector_payment_method_type_fields(
PayoutConnectors::Ebanx,
PaymentMethodType::Pix,
),
// Wise
get_connector_payment_method_type_fields(
PayoutConnectors::Wise,
PaymentMethodType::Bacs,
),
])),
),
(
Wallet,
PaymentMethodTypeInfo(HashMap::from([
// Adyen
get_connector_payment_method_type_fields(
PayoutConnectors::Adyenplatform,
PaymentMethodType::Paypal,
),
])),
),
]))
}
<file_sep path="hyperswitch/crates/router/src/configs/defaults/payout_required_fields.rs" role="context" start="297" end="307">
fn get_paypal_fields() -> HashMap<String, RequiredFieldInfo> {
HashMap::from([(
"payout_method_data.wallet.telephone_number".to_string(),
RequiredFieldInfo {
required_field: "payout_method_data.wallet.telephone_number".to_string(),
display_name: "telephone_number".to_string(),
field_type: FieldType::Text,
value: None,
},
)])
}
<file_sep path="hyperswitch/crates/router/src/connector/payone/transformers.rs" role="context" start="117" end="121">
pub struct Card {
card_holder_name: Secret<String>,
card_number: CardNumber,
expiry_date: Secret<String>,
}
<file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="1075" end="1083">
pub struct Card {
pub card_number: CardNumber,
pub name_on_card: Option<masking::Secret<String>>,
pub card_exp_month: masking::Secret<String>,
pub card_exp_year: masking::Secret<String>,
pub card_brand: Option<String>,
pub card_isin: Option<String>,
pub nick_name: Option<String>,
}
<file_sep path="hyperswitch/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/event.test.js" role="context" start="61" end="78">
"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.",
);
}
// Response body should have value "succeeded" for "status"
if (jsonData?.status) {
pm.test(
"[POST]::/payments - Content check if value for 'status' matches 'succeeded'",
function () {
pm.expect(jsonData.status).to.eql("succeeded");
},
);
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payment_methods/cards.rs<|crate|> router anchor=add_card_to_locker kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="2434" end="2475">
pub async fn add_card_to_locker(
state: &routes::SessionState,
req: api::PaymentMethodCreate,
card: &api::CardDetail,
customer_id: &id_type::CustomerId,
merchant_account: &domain::MerchantAccount,
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 {
add_card_hs(
state,
req.clone(),
card,
customer_id,
merchant_account,
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)
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="2433" end="2433">
)
.await?;
let payment_method_resp = payment_methods::mk_add_bank_response_hs(
bank.clone(),
store_resp.card_reference,
req,
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
pub async fn add_card_to_locker(
state: &routes::SessionState,
req: api::PaymentMethodCreate,
card: &api::CardDetail,
customer_id: &id_type::CustomerId,
merchant_account: &domain::MerchantAccount,
card_reference: Option<&str>,
) -> errors::CustomResult<
(
api::PaymentMethodResponse,
Option<payment_methods::DataDuplicationCheck>,
),
errors::VaultError,
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="2513" end="2538">
pub async fn delete_card_from_locker(
state: &routes::SessionState,
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(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")
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="2477" end="2511">
pub async fn get_card_from_locker(
state: &routes::SessionState,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
card_reference: &str,
) -> errors::RouterResult<Card> {
metrics::GET_FROM_LOCKER.add(1, &[]);
let get_card_from_rs_locker_resp = common_utils::metrics::utils::record_operation_time(
async {
get_card_from_hs_locker(
state,
customer_id,
merchant_id,
card_reference,
api_enums::LockerChoice::HyperswitchCardVault,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while getting card from hyperswitch card vault")
.inspect_err(|_| {
metrics::CARD_LOCKER_FAILURES.add(
1,
router_env::metric_attributes!(("locker", "rust"), ("operation", "get")),
);
})
},
&metrics::CARD_GET_TIME,
router_env::metric_attributes!(("locker", "rust")),
)
.await?;
logger::debug!("card retrieved from rust locker");
Ok(get_card_from_rs_locker_resp)
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="2358" end="2431">
pub async fn add_bank_to_locker(
state: &routes::SessionState,
req: api::PaymentMethodCreate,
merchant_account: &domain::MerchantAccount,
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 = 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: merchant_account.get_id().to_owned(),
merchant_customer_id: customer_id.to_owned(),
enc_data,
ttl: state.conf.locker.ttl_for_storage_in_secs,
});
let store_resp = add_card_to_hs_locker(
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,
merchant_account.get_id(),
);
Ok((payment_method_resp, store_resp.duplication_check))
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="2348" end="2353">
pub fn validate_payment_method_update(
_card_updation_obj: CardDetailUpdate,
_existing_card_data: api::CardDetailFromLocker,
) -> bool {
todo!()
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="1712" end="1981">
pub async fn save_migration_payment_method(
state: &routes::SessionState,
req: api::PaymentMethodCreate,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
migration_status: &mut migration::RecordMigrationStatusBuilder,
) -> errors::RouterResponse<api::PaymentMethodResponse> {
req.validate()?;
let db = &*state.store;
let merchant_id = merchant_account.get_id();
let customer_id = req.customer_id.clone().get_required_value("customer_id")?;
let payment_method = req.payment_method.get_required_value("payment_method")?;
let key_manager_state = state.into();
let payment_method_billing_address: Option<Encryptable<Secret<serde_json::Value>>> = req
.billing
.clone()
.async_map(|billing| create_encrypted_data(&key_manager_state, key_store, billing))
.await
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt Payment method billing address")?;
let connector_mandate_details = req
.connector_mandate_details
.clone()
.map(serde_json::to_value)
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let network_transaction_id = req.network_transaction_id.clone();
let response = match payment_method {
#[cfg(feature = "payouts")]
api_enums::PaymentMethod::BankTransfer => match req.bank_transfer.clone() {
Some(bank) => add_bank_to_locker(
state,
req.clone(),
merchant_account,
key_store,
&bank,
&customer_id,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Add PaymentMethod Failed"),
_ => Ok(store_default_payment_method(
&req,
&customer_id,
merchant_id,
)),
},
api_enums::PaymentMethod::Card => match req.card.clone() {
Some(card) => {
let mut card_details = card;
card_details = helpers::populate_bin_details_for_payment_method_create(
card_details.clone(),
db,
)
.await;
migration::validate_card_expiry(
&card_details.card_exp_month,
&card_details.card_exp_year,
)?;
Box::pin(add_card_to_locker(
state,
req.clone(),
&card_details,
&customer_id,
merchant_account,
None,
))
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Add Card Failed")
}
_ => Ok(store_default_payment_method(
&req,
&customer_id,
merchant_id,
)),
},
_ => Ok(store_default_payment_method(
&req,
&customer_id,
merchant_id,
)),
};
let (mut resp, duplication_check) = response?;
migration_status.card_migrated(true);
match duplication_check {
Some(duplication_check) => match duplication_check {
payment_methods::DataDuplicationCheck::Duplicated => {
let existing_pm = get_or_insert_payment_method(
state,
req.clone(),
&mut resp,
merchant_account,
&customer_id,
key_store,
)
.await?;
resp.client_secret = existing_pm.client_secret;
}
payment_methods::DataDuplicationCheck::MetaDataChanged => {
if let Some(card) = req.card.clone() {
let existing_pm = get_or_insert_payment_method(
state,
req.clone(),
&mut resp,
merchant_account,
&customer_id,
key_store,
)
.await?;
let client_secret = existing_pm.client_secret.clone();
delete_card_from_locker(
state,
&customer_id,
merchant_id,
existing_pm
.locker_id
.as_ref()
.unwrap_or(&existing_pm.payment_method_id),
)
.await?;
let add_card_resp = add_card_hs(
state,
req.clone(),
&card,
&customer_id,
merchant_account,
api::enums::LockerChoice::HyperswitchCardVault,
Some(
existing_pm
.locker_id
.as_ref()
.unwrap_or(&existing_pm.payment_method_id),
),
)
.await;
if let Err(err) = add_card_resp {
logger::error!(vault_err=?err);
db.delete_payment_method_by_merchant_id_payment_method_id(
&(state.into()),
key_store,
merchant_id,
&resp.payment_method_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
Err(report!(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while updating card metadata changes"))?
};
let existing_pm_data =
get_card_details_without_locker_fallback(&existing_pm, state).await?;
let updated_card = Some(api::CardDetailFromLocker {
scheme: existing_pm.scheme.clone(),
last4_digits: Some(card.card_number.get_last4()),
issuer_country: card
.card_issuing_country
.or(existing_pm_data.issuer_country),
card_isin: Some(card.card_number.get_card_isin()),
card_number: Some(card.card_number),
expiry_month: Some(card.card_exp_month),
expiry_year: Some(card.card_exp_year),
card_token: None,
card_fingerprint: None,
card_holder_name: card
.card_holder_name
.or(existing_pm_data.card_holder_name),
nick_name: card.nick_name.or(existing_pm_data.nick_name),
card_network: card.card_network.or(existing_pm_data.card_network),
card_issuer: card.card_issuer.or(existing_pm_data.card_issuer),
card_type: card.card_type.or(existing_pm_data.card_type),
saved_to_locker: true,
});
let updated_pmd = updated_card.as_ref().map(|card| {
PaymentMethodsData::Card(CardDetailsPaymentMethod::from(card.clone()))
});
let pm_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>> =
updated_pmd
.async_map(|updated_pmd| {
create_encrypted_data(&key_manager_state, key_store, updated_pmd)
})
.await
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt payment method data")?;
let pm_update = storage::PaymentMethodUpdate::PaymentMethodDataUpdate {
payment_method_data: pm_data_encrypted.map(Into::into),
};
db.update_payment_method(
&(state.into()),
key_store,
existing_pm,
pm_update,
merchant_account.storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to add payment method in db")?;
resp.client_secret = client_secret;
}
}
},
None => {
let pm_metadata = resp.metadata.as_ref().map(|data| data.peek());
let locker_id = if resp.payment_method == Some(api_enums::PaymentMethod::Card)
|| resp.payment_method == Some(api_enums::PaymentMethod::BankTransfer)
{
Some(resp.payment_method_id)
} else {
None
};
resp.payment_method_id = generate_id(consts::ID_LENGTH, "pm");
let pm = insert_payment_method(
state,
&resp,
&req,
key_store,
merchant_id,
&customer_id,
pm_metadata.cloned(),
None,
locker_id,
connector_mandate_details.clone(),
network_transaction_id.clone(),
merchant_account.storage_scheme,
payment_method_billing_address,
None,
None,
None,
)
.await?;
resp.client_secret = pm.client_secret;
}
}
migration_status.card_migrated(true);
migration_status.network_transaction_id_migrated(
network_transaction_id.and_then(|val| (!val.is_empty_after_trim()).then_some(true)),
);
migration_status.connector_mandate_details_migrated(
connector_mandate_details
.and_then(|val| if val == json!({}) { None } else { Some(true) })
.or_else(|| {
req.connector_mandate_details
.and_then(|val| (!val.0.is_empty()).then_some(false))
}),
);
Ok(services::ApplicationResponse::Json(resp))
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="1454" end="1705">
pub async fn add_payment_method(
state: &routes::SessionState,
req: api::PaymentMethodCreate,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
) -> errors::RouterResponse<api::PaymentMethodResponse> {
req.validate()?;
let db = &*state.store;
let merchant_id = merchant_account.get_id();
let customer_id = req.customer_id.clone().get_required_value("customer_id")?;
let payment_method = req.payment_method.get_required_value("payment_method")?;
let key_manager_state = state.into();
let payment_method_billing_address: Option<Encryptable<Secret<serde_json::Value>>> = req
.billing
.clone()
.async_map(|billing| create_encrypted_data(&key_manager_state, key_store, billing))
.await
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt Payment method billing address")?;
let connector_mandate_details = req
.connector_mandate_details
.clone()
.map(serde_json::to_value)
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let response = match payment_method {
#[cfg(feature = "payouts")]
api_enums::PaymentMethod::BankTransfer => match req.bank_transfer.clone() {
Some(bank) => add_bank_to_locker(
state,
req.clone(),
merchant_account,
key_store,
&bank,
&customer_id,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Add PaymentMethod Failed"),
_ => Ok(store_default_payment_method(
&req,
&customer_id,
merchant_id,
)),
},
api_enums::PaymentMethod::Card => match req.card.clone() {
Some(card) => {
let mut card_details = card;
card_details = helpers::populate_bin_details_for_payment_method_create(
card_details.clone(),
db,
)
.await;
helpers::validate_card_expiry(
&card_details.card_exp_month,
&card_details.card_exp_year,
)?;
Box::pin(add_card_to_locker(
state,
req.clone(),
&card_details,
&customer_id,
merchant_account,
None,
))
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Add Card Failed")
}
_ => Ok(store_default_payment_method(
&req,
&customer_id,
merchant_id,
)),
},
_ => Ok(store_default_payment_method(
&req,
&customer_id,
merchant_id,
)),
};
let (mut resp, duplication_check) = response?;
match duplication_check {
Some(duplication_check) => match duplication_check {
payment_methods::DataDuplicationCheck::Duplicated => {
let existing_pm = get_or_insert_payment_method(
state,
req.clone(),
&mut resp,
merchant_account,
&customer_id,
key_store,
)
.await?;
resp.client_secret = existing_pm.client_secret;
}
payment_methods::DataDuplicationCheck::MetaDataChanged => {
if let Some(card) = req.card.clone() {
let existing_pm = get_or_insert_payment_method(
state,
req.clone(),
&mut resp,
merchant_account,
&customer_id,
key_store,
)
.await?;
let client_secret = existing_pm.client_secret.clone();
delete_card_from_locker(
state,
&customer_id,
merchant_id,
existing_pm
.locker_id
.as_ref()
.unwrap_or(&existing_pm.payment_method_id),
)
.await?;
let add_card_resp = add_card_hs(
state,
req.clone(),
&card,
&customer_id,
merchant_account,
api::enums::LockerChoice::HyperswitchCardVault,
Some(
existing_pm
.locker_id
.as_ref()
.unwrap_or(&existing_pm.payment_method_id),
),
)
.await;
if let Err(err) = add_card_resp {
logger::error!(vault_err=?err);
db.delete_payment_method_by_merchant_id_payment_method_id(
&(state.into()),
key_store,
merchant_id,
&resp.payment_method_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
Err(report!(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while updating card metadata changes"))?
};
let existing_pm_data =
get_card_details_without_locker_fallback(&existing_pm, state).await?;
let updated_card = Some(api::CardDetailFromLocker {
scheme: existing_pm.scheme.clone(),
last4_digits: Some(card.card_number.get_last4()),
issuer_country: card
.card_issuing_country
.or(existing_pm_data.issuer_country),
card_isin: Some(card.card_number.get_card_isin()),
card_number: Some(card.card_number),
expiry_month: Some(card.card_exp_month),
expiry_year: Some(card.card_exp_year),
card_token: None,
card_fingerprint: None,
card_holder_name: card
.card_holder_name
.or(existing_pm_data.card_holder_name),
nick_name: card.nick_name.or(existing_pm_data.nick_name),
card_network: card.card_network.or(existing_pm_data.card_network),
card_issuer: card.card_issuer.or(existing_pm_data.card_issuer),
card_type: card.card_type.or(existing_pm_data.card_type),
saved_to_locker: true,
});
let updated_pmd = updated_card.as_ref().map(|card| {
PaymentMethodsData::Card(CardDetailsPaymentMethod::from(card.clone()))
});
let pm_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>> =
updated_pmd
.async_map(|updated_pmd| {
create_encrypted_data(&key_manager_state, key_store, updated_pmd)
})
.await
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt payment method data")?;
let pm_update = storage::PaymentMethodUpdate::PaymentMethodDataUpdate {
payment_method_data: pm_data_encrypted.map(Into::into),
};
db.update_payment_method(
&(state.into()),
key_store,
existing_pm,
pm_update,
merchant_account.storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to add payment method in db")?;
resp.client_secret = client_secret;
}
}
},
None => {
let pm_metadata = resp.metadata.as_ref().map(|data| data.peek());
let locker_id = if resp.payment_method == Some(api_enums::PaymentMethod::Card)
|| resp.payment_method == Some(api_enums::PaymentMethod::BankTransfer)
{
Some(resp.payment_method_id)
} else {
None
};
resp.payment_method_id = generate_id(consts::ID_LENGTH, "pm");
let pm = insert_payment_method(
state,
&resp,
&req,
key_store,
merchant_id,
&customer_id,
pm_metadata.cloned(),
None,
locker_id,
connector_mandate_details,
req.network_transaction_id.clone(),
merchant_account.storage_scheme,
payment_method_billing_address,
None,
None,
None,
)
.await?;
resp.client_secret = pm.client_secret;
}
}
Ok(services::ApplicationResponse::Json(resp))
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="2550" end="2591">
pub async fn add_card_hs(
state: &routes::SessionState,
req: api::PaymentMethodCreate,
card: &api::CardDetail,
customer_id: &id_type::CustomerId,
merchant_account: &domain::MerchantAccount,
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: 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: state.conf.locker.ttl_for_storage_in_secs,
});
let store_card_payload =
add_card_to_hs_locker(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,
merchant_account.get_id(),
);
Ok((payment_method_resp, store_card_payload.duplication_check))
}
<file_sep path="hyperswitch/crates/router/src/core/errors.rs" role="context" start="121" end="158">
pub enum VaultError {
#[error("Failed to save card in card vault")]
SaveCardFailed,
#[error("Failed to fetch card details from card vault")]
FetchCardFailed,
#[error("Failed to delete card in card vault")]
DeleteCardFailed,
#[error("Failed to encode card vault request")]
RequestEncodingFailed,
#[error("Failed to deserialize card vault response")]
ResponseDeserializationFailed,
#[error("Failed to create payment method")]
PaymentMethodCreationFailed,
#[error("The given payment method is currently not supported in vault")]
PaymentMethodNotSupported,
#[error("The given payout method is currently not supported in vault")]
PayoutMethodNotSupported,
#[error("Missing required field: {field_name}")]
MissingRequiredField { field_name: &'static str },
#[error("The card vault returned an unexpected response: {0:?}")]
UnexpectedResponseError(bytes::Bytes),
#[error("Failed to update in PMD table")]
UpdateInPaymentMethodDataTableFailed,
#[error("Failed to fetch payment method in vault")]
FetchPaymentMethodFailed,
#[error("Failed to save payment method in vault")]
SavePaymentMethodFailed,
#[error("Failed to generate fingerprint")]
GenerateFingerprintFailed,
#[error("Failed to encrypt vault request")]
RequestEncryptionFailed,
#[error("Failed to decrypt vault response")]
ResponseDecryptionFailed,
#[error("Failed to call vault")]
VaultAPIError,
#[error("Failed while calling locker API")]
ApiError,
}
<file_sep path="hyperswitch/v2_compatible_migrations/2024-08-28-081757_drop_not_null_constraints_on_v1_columns/up.sql" role="context" start="5" end="21">
ALTER COLUMN org_id DROP NOT NULL;
-- Create index on org_id in organization table
-- This is done to mullify the effects of droping primary key for v1
CREATE INDEX idx_organization_org_id ON organization (org_id);
------------------------ Merchant Account -------------------
-- Drop not null in merchant_account table for v1 columns that are dropped in v2
ALTER TABLE merchant_account
DROP CONSTRAINT merchant_account_pkey,
ALTER COLUMN merchant_id DROP NOT NULL,
ALTER COLUMN primary_business_details DROP NOT NULL,
ALTER COLUMN is_recon_enabled DROP NOT NULL;
-- This is done to mullify the effects of droping primary key for v1
CREATE INDEX idx_merchant_account_merchant_id ON merchant_account (merchant_id);
<file_sep path="hyperswitch/crates/api_models/src/enums.rs" role="context" start="393" end="395">
pub enum LockerChoice {
HyperswitchCardVault,
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payments/transformers.rs<|crate|> router anchor=try_from kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/payments/transformers.rs" role="context" start="4185" end="4268">
fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> {
let payment_data = additional_data.payment_data;
let payment_method_data = payment_data.payment_method_data;
let router_base_url = &additional_data.router_base_url;
let attempt = &payment_data.payment_attempt;
let connector_name = &additional_data.connector_name;
let order_details = payment_data
.payment_intent
.order_details
.map(|order_details| {
order_details
.iter()
.map(|data| {
data.to_owned()
.parse_value("OrderDetailsWithAmount")
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "OrderDetailsWithAmount",
})
.attach_printable("Unable to parse OrderDetailsWithAmount")
})
.collect::<Result<Vec<_>, _>>()
})
.transpose()?;
let merchant_connector_account_id_or_connector_name = payment_data
.payment_attempt
.merchant_connector_id
.as_ref()
.map(|mca_id| mca_id.get_string_repr())
.unwrap_or(connector_name);
let webhook_url = Some(helpers::create_webhook_url(
router_base_url,
&attempt.merchant_id,
merchant_connector_account_id_or_connector_name,
));
let router_return_url = Some(helpers::create_redirect_url(
router_base_url,
attempt,
connector_name,
payment_data.creds_identifier.as_deref(),
));
let complete_authorize_url = Some(helpers::create_complete_authorize_url(
router_base_url,
attempt,
connector_name,
payment_data.creds_identifier.as_deref(),
));
let browser_info: Option<types::BrowserInformation> = payment_data
.payment_attempt
.browser_info
.clone()
.map(|b| b.parse_value("BrowserInformation"))
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "browser_info",
})?;
let amount = payment_data.payment_attempt.get_total_amount();
Ok(Self {
payment_method_data,
email: payment_data.email,
currency: Some(payment_data.currency),
amount: Some(amount.get_amount_as_i64()), // need to change this once we move to connector module
minor_amount: Some(amount),
payment_method_type: payment_data.payment_attempt.payment_method_type,
setup_mandate_details: payment_data.setup_mandate,
capture_method: payment_data.payment_attempt.capture_method,
order_details,
router_return_url,
webhook_url,
complete_authorize_url,
browser_info,
surcharge_details: payment_data.surcharge_details,
connector_transaction_id: payment_data
.payment_attempt
.get_connector_payment_id()
.map(ToString::to_string),
redirect_response: None,
mandate_id: payment_data.mandate_id,
related_transaction_id: None,
enrolled_for_3ds: true,
split_payments: payment_data.payment_intent.split_payments,
metadata: payment_data.payment_intent.metadata.map(Secret::new),
})
}
<file_sep path="hyperswitch/crates/router/src/core/payments/transformers.rs" role="context" start="4184" end="4184">
use common_utils::{
consts::X_HS_LATENCY,
fp_utils, pii,
types::{
self as common_utils_type, AmountConvertor, MinorUnit, StringMajorUnit,
StringMajorUnitForConnector,
},
};
use diesel_models::{
ephemeral_key,
payment_attempt::ConnectorMandateReferenceId as DieselConnectorMandateReferenceId,
};
use hyperswitch_domain_models::{payments::payment_intent::CustomerData, router_request_types};
use masking::{ExposeInterface, Maskable, Secret};
use super::{flows::Feature, types::AuthenticationData, OperationSessionGetters, PaymentData};
use crate::{
configs::settings::ConnectorRequestReferenceIdConfig,
core::{
errors::{self, RouterResponse, RouterResult},
payments::{self, helpers},
utils as core_utils,
},
headers::X_PAYMENT_CONFIRM_SOURCE,
routes::{metrics, SessionState},
services::{self, RedirectForm},
types::{
self,
api::{self, ConnectorTransactionId},
domain,
storage::{self, enums},
transformers::{ForeignFrom, ForeignInto, ForeignTryFrom},
MultipleCaptureRequestData,
},
utils::{OptionExt, ValueExt},
};
<file_sep path="hyperswitch/crates/router/src/core/payments/transformers.rs" role="context" start="4286" end="4294">
fn foreign_from(customer: CustomerDetails) -> Self {
Self {
customer_id: Some(customer.id),
name: customer.name,
email: customer.email,
phone: customer.phone,
phone_country_code: customer.phone_country_code,
}
}
<file_sep path="hyperswitch/crates/router/src/core/payments/transformers.rs" role="context" start="4272" end="4282">
fn foreign_from(fraud_check: payments::FraudCheck) -> Self {
Self {
frm_name: fraud_check.frm_name,
frm_transaction_id: fraud_check.frm_transaction_id,
frm_transaction_type: Some(fraud_check.frm_transaction_type.to_string()),
frm_status: Some(fraud_check.frm_status.to_string()),
frm_score: fraud_check.frm_score,
frm_reason: fraud_check.frm_reason,
frm_error: fraud_check.frm_error,
}
}
<file_sep path="hyperswitch/crates/router/src/core/payments/transformers.rs" role="context" start="4176" end="4178">
fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> {
todo!()
}
<file_sep path="hyperswitch/crates/router/src/core/payments/transformers.rs" role="context" start="4167" end="4169">
fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> {
todo!()
}
<file_sep path="hyperswitch/crates/router/src/core/payments/transformers.rs" role="context" start="686" end="842">
pub async fn construct_payment_router_data_for_sdk_session<'a>(
state: &'a SessionState,
payment_data: hyperswitch_domain_models::payments::PaymentIntentData<api::Session>,
connector_id: &str,
merchant_account: &domain::MerchantAccount,
_key_store: &domain::MerchantKeyStore,
customer: &'a Option<domain::Customer>,
merchant_connector_account: &domain::MerchantConnectorAccount,
_merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
) -> RouterResult<types::PaymentsSessionRouterData> {
fp_utils::when(merchant_connector_account.is_disabled(), || {
Err(errors::ApiErrorResponse::MerchantConnectorAccountDisabled)
})?;
let auth_type: types::ConnectorAuthType = merchant_connector_account
.get_connector_account_details()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while parsing value for ConnectorAuthType")?;
// TODO: Take Globalid and convert to connector reference id
let customer_id = customer
.to_owned()
.map(|customer| common_utils::id_type::CustomerId::try_from(customer.id.clone()))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Invalid global customer generated, not able to convert to reference id",
)?;
let email = customer
.as_ref()
.and_then(|customer| customer.email.clone())
.map(pii::Email::from);
let order_details = payment_data
.payment_intent
.order_details
.clone()
.map(|order_details| {
order_details
.into_iter()
.map(|order_detail| order_detail.expose())
.collect()
});
let required_amount_type = StringMajorUnitForConnector;
let apple_pay_amount = required_amount_type
.convert(
payment_data.payment_intent.amount_details.order_amount,
payment_data.payment_intent.amount_details.currency,
)
.change_context(errors::ApiErrorResponse::PreconditionFailed {
message: "Failed to convert amount to string major unit for applePay".to_string(),
})?;
let apple_pay_recurring_details = payment_data
.payment_intent
.feature_metadata
.and_then(|feature_metadata| feature_metadata.apple_pay_recurring_details)
.map(|apple_pay_recurring_details| {
ForeignInto::foreign_into((apple_pay_recurring_details, apple_pay_amount))
});
// TODO: few fields are repeated in both routerdata and request
let request = types::PaymentsSessionData {
amount: payment_data
.payment_intent
.amount_details
.order_amount
.get_amount_as_i64(),
currency: payment_data.payment_intent.amount_details.currency,
country: payment_data
.payment_intent
.billing_address
.and_then(|billing_address| {
billing_address
.get_inner()
.address
.as_ref()
.and_then(|address| address.country)
}),
// TODO: populate surcharge here
surcharge_details: None,
order_details,
email,
minor_amount: payment_data.payment_intent.amount_details.order_amount,
apple_pay_recurring_details,
};
// TODO: evaluate the fields in router data, if they are required or not
let router_data = types::RouterData {
flow: PhantomData,
merchant_id: merchant_account.get_id().clone(),
// TODO: evaluate why we need customer id at the connector level. We already have connector customer id.
customer_id,
connector: connector_id.to_owned(),
tenant_id: state.tenant.tenant_id.clone(),
// TODO: evaluate why we need payment id at the connector level. We already have connector reference id
payment_id: payment_data.payment_intent.id.get_string_repr().to_owned(),
// TODO: evaluate why we need attempt id at the connector level. We already have connector reference id
attempt_id: "".to_string(),
status: enums::AttemptStatus::Started,
payment_method: enums::PaymentMethod::Wallet,
connector_auth_type: auth_type,
description: payment_data
.payment_intent
.description
.as_ref()
.map(|description| description.get_string_repr())
.map(ToOwned::to_owned),
// TODO: Create unified address
address: hyperswitch_domain_models::payment_address::PaymentAddress::default(),
auth_type: payment_data
.payment_intent
.authentication_type
.unwrap_or_default(),
connector_meta_data: merchant_connector_account.get_metadata(),
connector_wallets_details: None,
request,
response: Err(hyperswitch_domain_models::router_data::ErrorResponse::default()),
amount_captured: None,
minor_amount_captured: None,
access_token: None,
session_token: None,
reference_id: None,
payment_method_status: None,
payment_method_token: None,
connector_customer: None,
recurring_mandate_payment_data: None,
// TODO: This has to be generated as the reference id based on the connector configuration
// Some connectros might not accept accept the global id. This has to be done when generating the reference id
connector_request_reference_id: "".to_string(),
preprocessing_id: None,
#[cfg(feature = "payouts")]
payout_method_data: None,
#[cfg(feature = "payouts")]
quote_id: None,
// TODO: take this based on the env
test_mode: Some(true),
payment_method_balance: None,
connector_api_version: None,
connector_http_status_code: None,
external_latency: None,
apple_pay_flow: None,
frm_metadata: None,
refund_id: None,
dispute_id: None,
connector_response: None,
integrity_check: Ok(()),
additional_merchant_data: None,
header_payload,
connector_mandate_request_reference_id: None,
psd2_sca_exemption_type: None,
authentication_id: None,
};
Ok(router_data)
}
<file_sep path="hyperswitch/crates/router/src/core/payments/transformers.rs" role="context" start="847" end="1043">
pub async fn construct_payment_router_data_for_setup_mandate<'a>(
state: &'a SessionState,
payment_data: hyperswitch_domain_models::payments::PaymentConfirmData<api::SetupMandate>,
connector_id: &str,
merchant_account: &domain::MerchantAccount,
_key_store: &domain::MerchantKeyStore,
customer: &'a Option<domain::Customer>,
merchant_connector_account: &domain::MerchantConnectorAccount,
_merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
) -> RouterResult<types::SetupMandateRouterData> {
fp_utils::when(merchant_connector_account.is_disabled(), || {
Err(errors::ApiErrorResponse::MerchantConnectorAccountDisabled)
})?;
let auth_type = merchant_connector_account
.get_connector_account_details()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while parsing value for ConnectorAuthType")?;
// TODO: Take Globalid and convert to connector reference id
let customer_id = customer
.to_owned()
.map(|customer| common_utils::id_type::CustomerId::try_from(customer.id.clone()))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Invalid global customer generated, not able to convert to reference id",
)?;
let connector_customer_id = customer.as_ref().and_then(|customer| {
customer
.get_connector_customer_id(&merchant_connector_account.get_id())
.map(String::from)
});
let payment_method = payment_data.payment_attempt.payment_method_type;
let router_base_url = &state.base_url;
let attempt = &payment_data.payment_attempt;
let complete_authorize_url = Some(helpers::create_complete_authorize_url(
router_base_url,
attempt,
connector_id,
None,
));
let webhook_url = Some(helpers::create_webhook_url(
router_base_url,
&attempt.merchant_id,
merchant_connector_account.get_id().get_string_repr(),
));
let router_return_url = payment_data
.payment_intent
.create_finish_redirection_url(router_base_url, &merchant_account.publishable_key)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to construct finish redirection url")?
.to_string();
let connector_request_reference_id = payment_data
.payment_intent
.merchant_reference_id
.map(|id| id.get_string_repr().to_owned())
.unwrap_or(payment_data.payment_attempt.id.get_string_repr().to_owned());
let email = customer
.as_ref()
.and_then(|customer| customer.email.clone())
.map(pii::Email::from);
let browser_info = payment_data
.payment_attempt
.browser_info
.clone()
.map(types::BrowserInformation::from);
// TODO: few fields are repeated in both routerdata and request
let request = types::SetupMandateRequestData {
currency: payment_data.payment_intent.amount_details.currency,
payment_method_data: payment_data
.payment_method_data
.get_required_value("payment_method_data")?,
amount: Some(
payment_data
.payment_attempt
.amount_details
.get_net_amount()
.get_amount_as_i64(),
),
confirm: true,
statement_descriptor_suffix: None,
customer_acceptance: None,
mandate_id: None,
setup_future_usage: Some(payment_data.payment_intent.setup_future_usage),
off_session: None,
setup_mandate_details: None,
router_return_url: Some(router_return_url.clone()),
webhook_url,
browser_info,
email,
customer_name: None,
return_url: Some(router_return_url),
payment_method_type: Some(payment_data.payment_attempt.payment_method_subtype),
request_incremental_authorization: matches!(
payment_data
.payment_intent
.request_incremental_authorization,
RequestIncrementalAuthorization::True | RequestIncrementalAuthorization::Default
),
metadata: payment_data.payment_intent.metadata,
minor_amount: Some(payment_data.payment_attempt.amount_details.get_net_amount()),
shipping_cost: payment_data.payment_intent.amount_details.shipping_cost,
capture_method: Some(payment_data.payment_intent.capture_method),
complete_authorize_url,
};
let connector_mandate_request_reference_id = payment_data
.payment_attempt
.connector_token_details
.as_ref()
.and_then(|detail| detail.get_connector_token_request_reference_id());
// TODO: evaluate the fields in router data, if they are required or not
let router_data = types::RouterData {
flow: PhantomData,
merchant_id: merchant_account.get_id().clone(),
tenant_id: state.tenant.tenant_id.clone(),
// TODO: evaluate why we need customer id at the connector level. We already have connector customer id.
customer_id,
connector: connector_id.to_owned(),
// TODO: evaluate why we need payment id at the connector level. We already have connector reference id
payment_id: payment_data
.payment_attempt
.payment_id
.get_string_repr()
.to_owned(),
// TODO: evaluate why we need attempt id at the connector level. We already have connector reference id
attempt_id: payment_data
.payment_attempt
.get_id()
.get_string_repr()
.to_owned(),
status: payment_data.payment_attempt.status,
payment_method,
connector_auth_type: auth_type,
description: payment_data
.payment_intent
.description
.as_ref()
.map(|description| description.get_string_repr())
.map(ToOwned::to_owned),
// TODO: Create unified address
address: payment_data.payment_address.clone(),
auth_type: payment_data.payment_attempt.authentication_type,
connector_meta_data: None,
connector_wallets_details: None,
request,
response: Err(hyperswitch_domain_models::router_data::ErrorResponse::default()),
amount_captured: None,
minor_amount_captured: None,
access_token: None,
session_token: None,
reference_id: None,
payment_method_status: None,
payment_method_token: None,
connector_customer: connector_customer_id,
recurring_mandate_payment_data: None,
// TODO: This has to be generated as the reference id based on the connector configuration
// Some connectros might not accept accept the global id. This has to be done when generating the reference id
connector_request_reference_id,
preprocessing_id: payment_data.payment_attempt.preprocessing_step_id,
#[cfg(feature = "payouts")]
payout_method_data: None,
#[cfg(feature = "payouts")]
quote_id: None,
// TODO: take this based on the env
test_mode: Some(true),
payment_method_balance: None,
connector_api_version: None,
connector_http_status_code: None,
external_latency: None,
apple_pay_flow: None,
frm_metadata: None,
refund_id: None,
dispute_id: None,
connector_response: None,
integrity_check: Ok(()),
additional_merchant_data: None,
header_payload,
connector_mandate_request_reference_id,
authentication_id: None,
psd2_sca_exemption_type: None,
};
Ok(router_data)
}
<file_sep path="hyperswitch/crates/router/src/core/payments/transformers.rs" role="context" start="1867" end="1867">
type Error = error_stack::Report<errors::ApiErrorResponse>;
<file_sep path="hyperswitch/crates/router/src/core/payments/transformers.rs" role="context" start="3076" end="3085">
pub struct PaymentAdditionalData<'a, F>
where
F: Clone,
{
router_base_url: String,
connector_name: String,
payment_data: PaymentData<F>,
state: &'a SessionState,
customer_data: &'a Option<domain::Customer>,
}
<file_sep path="hyperswitch/crates/api_models/src/errors/types.rs" role="context" start="86" end="100">
pub enum ApiErrorResponse {
Unauthorized(ApiError),
ForbiddenCommonResource(ApiError),
ForbiddenPrivateResource(ApiError),
Conflict(ApiError),
Gone(ApiError),
Unprocessable(ApiError),
InternalServerError(ApiError),
NotImplemented(ApiError),
ConnectorError(ApiError, #[serde(skip_serializing)] StatusCode),
NotFound(ApiError),
MethodNotAllowed(ApiError),
BadRequest(ApiError),
DomainError(ApiError),
}
<file_sep path="hyperswitch/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/event.test.js" role="context" start="61" end="78">
"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.",
);
}
// Response body should have value "succeeded" for "status"
if (jsonData?.status) {
pm.test(
"[POST]::/payments - Content check if value for 'status' matches 'succeeded'",
function () {
pm.expect(jsonData.status).to.eql("succeeded");
},
);
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/ebanx.rs<|crate|> router anchor=new kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/connector/ebanx.rs" role="context" start="37" end="42">
pub fn new() -> &'static Self {
&Self {
#[cfg(feature = "payouts")]
amount_converter: &FloatMajorUnitForConnector,
}
}
<file_sep path="hyperswitch/crates/router/src/connector/ebanx.rs" role="context" start="36" end="36">
use common_utils::types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector};
<file_sep path="hyperswitch/crates/router/src/connector/ebanx.rs" role="context" start="91" end="93">
fn id(&self) -> &'static str {
"ebanx"
}
<file_sep path="hyperswitch/crates/router/src/connector/ebanx.rs" role="context" start="77" end="87">
fn build_headers(
&self,
_req: &types::RouterData<Flow, Request, Response>,
_connectors: &settings::Connectors,
) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
let header = vec![(
headers::CONTENT_TYPE.to_string(),
self.common_get_content_type().to_string().into(),
)];
Ok(header)
}
<file_sep path="hyperswitch/crates/router/src/connector/ebanx.rs" role="context" start="250" end="268">
fn build_request(
&self,
req: &types::PayoutsRouterData<api::PoFulfill>,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
let request = services::RequestBuilder::new()
.method(services::Method::Post)
.url(&types::PayoutFulfillType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PayoutFulfillType::get_headers(
self, req, connectors,
)?)
.set_body(types::PayoutFulfillType::get_request_body(
self, req, connectors,
)?)
.build();
Ok(Some(request))
}
<file_sep path="hyperswitch/crates/router/src/connector/ebanx.rs" role="context" start="328" end="344">
fn build_request(
&self,
req: &types::PayoutsRouterData<api::PoCancel>,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
let request = services::RequestBuilder::new()
.method(services::Method::Put)
.url(&types::PayoutCancelType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PayoutCancelType::get_headers(self, req, connectors)?)
.set_body(types::PayoutCancelType::get_request_body(
self, req, connectors,
)?)
.build();
Ok(Some(request))
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/stripe/transformers.rs<|crate|> router anchor=validate_shipping_address_against_payment_method kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="991" end="1019">
fn validate_shipping_address_against_payment_method(
shipping_address: &Option<StripeShippingAddress>,
payment_method: Option<&StripePaymentMethodType>,
) -> Result<(), error_stack::Report<errors::ConnectorError>> {
match payment_method {
Some(StripePaymentMethodType::AfterpayClearpay) => match shipping_address {
Some(address) => {
let missing_fields = collect_missing_value_keys!(
("shipping.address.line1", address.line1),
("shipping.address.country", address.country),
("shipping.address.zip", address.zip)
);
if !missing_fields.is_empty() {
return Err(errors::ConnectorError::MissingRequiredFields {
field_names: missing_fields,
}
.into());
}
Ok(())
}
None => Err(errors::ConnectorError::MissingRequiredField {
field_name: "shipping.address",
}
.into()),
},
_ => Ok(()),
}
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="990" end="990">
use common_utils::{
errors::CustomResult,
ext_traits::{ByteSliceExt, Encode},
pii::{self, Email},
request::RequestContent,
types::MinorUnit,
};
use error_stack::ResultExt;
use crate::{
collect_missing_value_keys,
connector::utils::{self as connector_util, ApplePay, ApplePayDecrypt, RouterData},
consts,
core::errors,
headers, services,
types::{
self, api, domain,
storage::enums,
transformers::{ForeignFrom, ForeignTryFrom},
},
utils::OptionExt,
};
<file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="1046" end="1076">
fn try_from(bank_redirect_data: &domain::BankRedirectData) -> Result<Self, Self::Error> {
match bank_redirect_data {
domain::BankRedirectData::Giropay { .. } => Ok(Self::Giropay),
domain::BankRedirectData::Ideal { .. } => Ok(Self::Ideal),
domain::BankRedirectData::Sofort { .. } => Ok(Self::Sofort),
domain::BankRedirectData::BancontactCard { .. } => Ok(Self::Bancontact),
domain::BankRedirectData::Przelewy24 { .. } => Ok(Self::Przelewy24),
domain::BankRedirectData::Eps { .. } => Ok(Self::Eps),
domain::BankRedirectData::Blik { .. } => Ok(Self::Blik),
domain::BankRedirectData::OnlineBankingFpx { .. } => {
Err(errors::ConnectorError::NotImplemented(
connector_util::get_unimplemented_payment_method_error_message("stripe"),
))
}
domain::BankRedirectData::Bizum {}
| domain::BankRedirectData::Interac { .. }
| domain::BankRedirectData::Eft { .. }
| domain::BankRedirectData::OnlineBankingCzechRepublic { .. }
| domain::BankRedirectData::OnlineBankingFinland { .. }
| domain::BankRedirectData::OnlineBankingPoland { .. }
| domain::BankRedirectData::OnlineBankingSlovakia { .. }
| domain::BankRedirectData::OnlineBankingThailand { .. }
| domain::BankRedirectData::OpenBankingUk { .. }
| domain::BankRedirectData::Trustly { .. }
| domain::BankRedirectData::LocalBankRedirect {} => {
Err(errors::ConnectorError::NotImplemented(
connector_util::get_unimplemented_payment_method_error_message("stripe"),
))
}
}
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="1023" end="1041">
fn try_from(pay_later_data: &domain::payments::PayLaterData) -> Result<Self, Self::Error> {
match pay_later_data {
domain::payments::PayLaterData::KlarnaRedirect { .. } => Ok(Self::Klarna),
domain::payments::PayLaterData::AffirmRedirect {} => Ok(Self::Affirm),
domain::payments::PayLaterData::AfterpayClearpayRedirect { .. } => {
Ok(Self::AfterpayClearpay)
}
domain::PayLaterData::KlarnaSdk { .. }
| domain::PayLaterData::PayBrightRedirect {}
| domain::PayLaterData::WalleyRedirect {}
| domain::PayLaterData::AlmaRedirect {}
| domain::PayLaterData::AtomeRedirect {} => {
Err(errors::ConnectorError::NotImplemented(
connector_util::get_unimplemented_payment_method_error_message("stripe"),
))
}
}
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="907" end="988">
fn try_from(bank: &common_enums::enums::BankNames) -> Result<Self, Self::Error> {
Ok(match bank {
common_enums::enums::BankNames::AbnAmro => Self::AbnAmro,
common_enums::enums::BankNames::ArzteUndApothekerBank => Self::ArzteUndApothekerBank,
common_enums::enums::BankNames::AsnBank => Self::AsnBank,
common_enums::enums::BankNames::AustrianAnadiBankAg => Self::AustrianAnadiBankAg,
common_enums::enums::BankNames::BankAustria => Self::BankAustria,
common_enums::enums::BankNames::BankhausCarlSpangler => Self::BankhausCarlSpangler,
common_enums::enums::BankNames::BankhausSchelhammerUndSchatteraAg => {
Self::BankhausSchelhammerUndSchatteraAg
}
common_enums::enums::BankNames::BawagPskAg => Self::BawagPskAg,
common_enums::enums::BankNames::BksBankAg => Self::BksBankAg,
common_enums::enums::BankNames::BrullKallmusBankAg => Self::BrullKallmusBankAg,
common_enums::enums::BankNames::BtvVierLanderBank => Self::BtvVierLanderBank,
common_enums::enums::BankNames::Bunq => Self::Bunq,
common_enums::enums::BankNames::CapitalBankGraweGruppeAg => {
Self::CapitalBankGraweGruppeAg
}
common_enums::enums::BankNames::Citi => Self::CitiHandlowy,
common_enums::enums::BankNames::Dolomitenbank => Self::Dolomitenbank,
common_enums::enums::BankNames::EasybankAg => Self::EasybankAg,
common_enums::enums::BankNames::ErsteBankUndSparkassen => Self::ErsteBankUndSparkassen,
common_enums::enums::BankNames::Handelsbanken => Self::Handelsbanken,
common_enums::enums::BankNames::HypoAlpeadriabankInternationalAg => {
Self::HypoAlpeadriabankInternationalAg
}
common_enums::enums::BankNames::HypoNoeLbFurNiederosterreichUWien => {
Self::HypoNoeLbFurNiederosterreichUWien
}
common_enums::enums::BankNames::HypoOberosterreichSalzburgSteiermark => {
Self::HypoOberosterreichSalzburgSteiermark
}
common_enums::enums::BankNames::HypoTirolBankAg => Self::HypoTirolBankAg,
common_enums::enums::BankNames::HypoVorarlbergBankAg => Self::HypoVorarlbergBankAg,
common_enums::enums::BankNames::HypoBankBurgenlandAktiengesellschaft => {
Self::HypoBankBurgenlandAktiengesellschaft
}
common_enums::enums::BankNames::Ing => Self::Ing,
common_enums::enums::BankNames::Knab => Self::Knab,
common_enums::enums::BankNames::MarchfelderBank => Self::MarchfelderBank,
common_enums::enums::BankNames::OberbankAg => Self::OberbankAg,
common_enums::enums::BankNames::RaiffeisenBankengruppeOsterreich => {
Self::RaiffeisenBankengruppeOsterreich
}
common_enums::enums::BankNames::Rabobank => Self::Rabobank,
common_enums::enums::BankNames::Regiobank => Self::Regiobank,
common_enums::enums::BankNames::Revolut => Self::Revolut,
common_enums::enums::BankNames::SnsBank => Self::SnsBank,
common_enums::enums::BankNames::TriodosBank => Self::TriodosBank,
common_enums::enums::BankNames::VanLanschot => Self::VanLanschot,
common_enums::enums::BankNames::Moneyou => Self::Moneyou,
common_enums::enums::BankNames::SchoellerbankAg => Self::SchoellerbankAg,
common_enums::enums::BankNames::SpardaBankWien => Self::SpardaBankWien,
common_enums::enums::BankNames::VolksbankGruppe => Self::VolksbankGruppe,
common_enums::enums::BankNames::VolkskreditbankAg => Self::VolkskreditbankAg,
common_enums::enums::BankNames::VrBankBraunau => Self::VrBankBraunau,
common_enums::enums::BankNames::PlusBank => Self::PlusBank,
common_enums::enums::BankNames::EtransferPocztowy24 => Self::EtransferPocztowy24,
common_enums::enums::BankNames::BankiSpbdzielcze => Self::BankiSpbdzielcze,
common_enums::enums::BankNames::BankNowyBfgSa => Self::BankNowyBfgSa,
common_enums::enums::BankNames::GetinBank => Self::GetinBank,
common_enums::enums::BankNames::Blik => Self::Blik,
common_enums::enums::BankNames::NoblePay => Self::NoblePay,
common_enums::enums::BankNames::IdeaBank => Self::IdeaBank,
common_enums::enums::BankNames::EnveloBank => Self::EnveloBank,
common_enums::enums::BankNames::NestPrzelew => Self::NestPrzelew,
common_enums::enums::BankNames::MbankMtransfer => Self::MbankMtransfer,
common_enums::enums::BankNames::Inteligo => Self::Inteligo,
common_enums::enums::BankNames::PbacZIpko => Self::PbacZIpko,
common_enums::enums::BankNames::BnpParibas => Self::BnpParibas,
common_enums::enums::BankNames::BankPekaoSa => Self::BankPekaoSa,
common_enums::enums::BankNames::VolkswagenBank => Self::VolkswagenBank,
common_enums::enums::BankNames::AliorBank => Self::AliorBank,
common_enums::enums::BankNames::Boz => Self::Boz,
_ => Err(errors::ConnectorError::NotImplemented(
connector_util::get_unimplemented_payment_method_error_message("stripe"),
))?,
})
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="881" end="902">
fn from(value: WebhookEventStatus) -> Self {
match value {
WebhookEventStatus::WarningNeedsResponse => Self::DisputeOpened,
WebhookEventStatus::WarningClosed => Self::DisputeCancelled,
WebhookEventStatus::WarningUnderReview => Self::DisputeChallenged,
WebhookEventStatus::Won => Self::DisputeWon,
WebhookEventStatus::Lost => Self::DisputeLost,
WebhookEventStatus::NeedsResponse
| WebhookEventStatus::UnderReview
| WebhookEventStatus::ChargeRefunded
| WebhookEventStatus::Succeeded
| WebhookEventStatus::RequiresPaymentMethod
| WebhookEventStatus::RequiresConfirmation
| WebhookEventStatus::RequiresAction
| WebhookEventStatus::Processing
| WebhookEventStatus::RequiresCapture
| WebhookEventStatus::Canceled
| WebhookEventStatus::Chargeable
| WebhookEventStatus::Failed
| WebhookEventStatus::Unknown => Self::EventNotSupported,
}
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="1674" end="2036">
fn try_from(
data: (&types::PaymentsAuthorizeRouterData, MinorUnit),
) -> Result<Self, Self::Error> {
let item = data.0;
let amount = data.1;
let order_id = item.connector_request_reference_id.clone();
let shipping_address = match item.get_optional_shipping() {
Some(shipping_details) => {
let shipping_address = shipping_details.address.as_ref();
shipping_address.and_then(|shipping_detail| {
shipping_detail
.first_name
.as_ref()
.map(|first_name| StripeShippingAddress {
city: shipping_address.and_then(|a| a.city.clone()),
country: shipping_address.and_then(|a| a.country),
line1: shipping_address.and_then(|a| a.line1.clone()),
line2: shipping_address.and_then(|a| a.line2.clone()),
zip: shipping_address.and_then(|a| a.zip.clone()),
state: shipping_address.and_then(|a| a.state.clone()),
name: format!(
"{} {}",
first_name.clone().expose(),
shipping_detail
.last_name
.clone()
.expose_option()
.unwrap_or_default()
)
.into(),
phone: shipping_details.phone.as_ref().map(|p| {
format!(
"{}{}",
p.country_code.clone().unwrap_or_default(),
p.number.clone().expose_option().unwrap_or_default()
)
.into()
}),
})
})
}
None => None,
};
let billing_address = match item.get_optional_billing() {
Some(billing_details) => {
let billing_address = billing_details.address.as_ref();
StripeBillingAddress {
city: billing_address.and_then(|a| a.city.clone()),
country: billing_address.and_then(|a| a.country),
address_line1: billing_address.and_then(|a| a.line1.clone()),
address_line2: billing_address.and_then(|a| a.line2.clone()),
zip_code: billing_address.and_then(|a| a.zip.clone()),
state: billing_address.and_then(|a| a.state.clone()),
name: billing_address.and_then(|a| {
a.first_name.as_ref().map(|first_name| {
format!(
"{} {}",
first_name.clone().expose(),
a.last_name.clone().expose_option().unwrap_or_default()
)
.into()
})
}),
email: billing_details.email.clone(),
phone: billing_details.phone.as_ref().map(|p| {
format!(
"{}{}",
p.country_code.clone().unwrap_or_default(),
p.number.clone().expose_option().unwrap_or_default()
)
.into()
}),
}
}
None => StripeBillingAddress::default(),
};
let mut payment_method_options = None;
let (
mut payment_data,
payment_method,
billing_address,
payment_method_types,
setup_future_usage,
) = {
match item
.request
.mandate_id
.clone()
.and_then(|mandate_ids| mandate_ids.mandate_reference_id)
{
Some(payments::MandateReferenceId::ConnectorMandateId(connector_mandate_ids)) => (
None,
connector_mandate_ids.get_connector_mandate_id(),
StripeBillingAddress::default(),
get_payment_method_type_for_saved_payment_method_payment(item)?,
None,
),
Some(payments::MandateReferenceId::NetworkMandateId(network_transaction_id)) => {
payment_method_options = Some(StripePaymentMethodOptions::Card {
mandate_options: None,
network_transaction_id: None,
mit_exemption: Some(MitExemption {
network_transaction_id: Secret::new(network_transaction_id),
}),
});
let payment_data = match item.request.payment_method_data {
domain::payments::PaymentMethodData::CardDetailsForNetworkTransactionId(
ref card_details_for_network_transaction_id,
) => StripePaymentMethodData::Card(StripeCardData {
payment_method_data_type: StripePaymentMethodType::Card,
payment_method_data_card_number:
card_details_for_network_transaction_id.card_number.clone(),
payment_method_data_card_exp_month:
card_details_for_network_transaction_id
.card_exp_month
.clone(),
payment_method_data_card_exp_year:
card_details_for_network_transaction_id
.card_exp_year
.clone(),
payment_method_data_card_cvc: None,
payment_method_auth_type: None,
payment_method_data_card_preferred_network:
card_details_for_network_transaction_id
.card_network
.clone()
.and_then(get_stripe_card_network),
}),
domain::payments::PaymentMethodData::CardRedirect(_)
| domain::payments::PaymentMethodData::Wallet(_)
| domain::payments::PaymentMethodData::PayLater(_)
| domain::payments::PaymentMethodData::BankRedirect(_)
| domain::payments::PaymentMethodData::BankDebit(_)
| domain::payments::PaymentMethodData::BankTransfer(_)
| domain::payments::PaymentMethodData::Crypto(_)
| domain::payments::PaymentMethodData::MandatePayment
| domain::payments::PaymentMethodData::Reward
| domain::payments::PaymentMethodData::RealTimePayment(_)
| domain::payments::PaymentMethodData::MobilePayment(_)
| domain::payments::PaymentMethodData::Upi(_)
| domain::payments::PaymentMethodData::Voucher(_)
| domain::payments::PaymentMethodData::GiftCard(_)
| domain::payments::PaymentMethodData::OpenBanking(_)
| domain::payments::PaymentMethodData::CardToken(_)
| domain::PaymentMethodData::NetworkToken(_)
| domain::PaymentMethodData::Card(_) => {
Err(errors::ConnectorError::NotSupported {
message: "Network tokenization for payment method".to_string(),
connector: "Stripe",
})?
}
};
(
Some(payment_data),
None,
StripeBillingAddress::default(),
None,
None,
)
}
Some(payments::MandateReferenceId::NetworkTokenWithNTI(_)) | None => {
let (payment_method_data, payment_method_type, billing_address) =
create_stripe_payment_method(
&item.request.payment_method_data,
item.auth_type,
item.payment_method_token.clone(),
Some(connector_util::PaymentsAuthorizeRequestData::is_customer_initiated_mandate_payment(
&item.request,
)),
billing_address
)?;
validate_shipping_address_against_payment_method(
&shipping_address,
payment_method_type.as_ref(),
)?;
(
Some(payment_method_data),
None,
billing_address,
payment_method_type,
item.request.setup_future_usage,
)
}
}
};
payment_data = match item.request.payment_method_data {
domain::PaymentMethodData::Wallet(domain::WalletData::ApplePay(_)) => {
let payment_method_token = item
.payment_method_token
.to_owned()
.get_required_value("payment_token")
.change_context(errors::ConnectorError::InvalidWalletToken {
wallet_name: "Apple Pay".to_string(),
})?;
let payment_method_token = match payment_method_token {
types::PaymentMethodToken::Token(payment_method_token) => payment_method_token,
types::PaymentMethodToken::ApplePayDecrypt(_) => {
Err(errors::ConnectorError::InvalidWalletToken {
wallet_name: "Apple Pay".to_string(),
})?
}
types::PaymentMethodToken::PazeDecrypt(_) => {
Err(crate::unimplemented_payment_method!("Paze", "Stripe"))?
}
types::PaymentMethodToken::GooglePayDecrypt(_) => {
Err(crate::unimplemented_payment_method!("Google Pay", "Stripe"))?
}
};
Some(StripePaymentMethodData::Wallet(
StripeWallet::ApplepayPayment(ApplepayPayment {
token: payment_method_token,
payment_method_types: StripePaymentMethodType::Card,
}),
))
}
_ => payment_data,
};
let setup_mandate_details = item
.request
.setup_mandate_details
.as_ref()
.and_then(|mandate_details| {
mandate_details
.customer_acceptance
.as_ref()
.map(|customer_acceptance| {
Ok::<_, error_stack::Report<errors::ConnectorError>>(
match customer_acceptance.acceptance_type {
AcceptanceType::Online => {
let online_mandate = customer_acceptance
.online
.clone()
.get_required_value("online")
.change_context(
errors::ConnectorError::MissingRequiredField {
field_name: "online",
},
)?;
StripeMandateRequest {
mandate_type: StripeMandateType::Online {
ip_address: online_mandate
.ip_address
.get_required_value("ip_address")
.change_context(
errors::ConnectorError::MissingRequiredField {
field_name: "ip_address",
},
)?,
user_agent: online_mandate.user_agent,
},
}
}
AcceptanceType::Offline => StripeMandateRequest {
mandate_type: StripeMandateType::Offline,
},
},
)
})
})
.transpose()?
.or_else(|| {
//stripe requires us to send mandate_data while making recurring payment through saved bank debit
if payment_method.is_some() {
//check if payment is done through saved payment method
match &payment_method_types {
//check if payment method is bank debit
Some(
StripePaymentMethodType::Ach
| StripePaymentMethodType::Sepa
| StripePaymentMethodType::Becs
| StripePaymentMethodType::Bacs,
) => Some(StripeMandateRequest {
mandate_type: StripeMandateType::Offline,
}),
_ => None,
}
} else {
None
}
});
let meta_data =
get_transaction_metadata(item.request.metadata.clone().map(Into::into), order_id);
// We pass browser_info only when payment_data exists.
// Hence, we're pass Null during recurring payments as payment_method_data[type] is not passed
let browser_info = if payment_data.is_some() {
item.request
.browser_info
.clone()
.map(StripeBrowserInformation::from)
} else {
None
};
let (charges, customer) = match &item.request.split_payments {
Some(common_types::payments::SplitPaymentsRequest::StripeSplitPayment(
stripe_split_payment,
)) => {
let charges = match &stripe_split_payment.charge_type {
api_models::enums::PaymentChargeType::Stripe(charge_type) => {
match charge_type {
api_models::enums::StripeChargeType::Direct => Some(IntentCharges {
application_fee_amount: stripe_split_payment.application_fees,
destination_account_id: None,
}),
api_models::enums::StripeChargeType::Destination => {
Some(IntentCharges {
application_fee_amount: stripe_split_payment.application_fees,
destination_account_id: Some(
stripe_split_payment.transfer_account_id.clone(),
),
})
}
}
}
};
(charges, None)
}
Some(common_types::payments::SplitPaymentsRequest::AdyenSplitPayment(_))
| Some(common_types::payments::SplitPaymentsRequest::XenditSplitPayment(_))
| None => (None, item.connector_customer.to_owned().map(Secret::new)),
};
Ok(Self {
amount, //hopefully we don't loose some cents here
currency: item.request.currency.to_string(), //we need to copy the value and not transfer ownership
statement_descriptor_suffix: item.request.statement_descriptor_suffix.clone(),
statement_descriptor: item.request.statement_descriptor.clone(),
meta_data,
return_url: item
.request
.router_return_url
.clone()
.unwrap_or_else(|| "https://juspay.in/".to_string()),
confirm: true, // Stripe requires confirm to be true if return URL is present
description: item.description.clone(),
shipping: shipping_address,
billing: billing_address,
capture_method: StripeCaptureMethod::from(item.request.capture_method),
payment_data,
payment_method_options,
payment_method,
customer,
setup_mandate_details,
off_session: item.request.off_session,
setup_future_usage,
payment_method_types,
expand: Some(ExpandableObjects::LatestCharge),
browser_info,
charges,
})
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="4320" end="4342">
fn should_return_err_for_empty_line1() {
// Arrange
let stripe_shipping_address = create_stripe_shipping_address(
"name".to_string(),
None,
Some(CountryAlpha2::AD),
Some("zip".to_string()),
);
let payment_method = &StripePaymentMethodType::AfterpayClearpay;
//Act
let result = validate_shipping_address_against_payment_method(
&Some(stripe_shipping_address),
Some(payment_method),
);
// Assert
assert!(result.is_err());
let missing_fields = get_missing_fields(result.unwrap_err().current_context()).to_owned();
assert_eq!(missing_fields.len(), 1);
assert_eq!(*missing_fields.first().unwrap(), "shipping.address.line1");
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="3373" end="3390">
pub struct StripeShippingAddress {
#[serde(rename = "shipping[address][city]")]
pub city: Option<String>,
#[serde(rename = "shipping[address][country]")]
pub country: Option<api_enums::CountryAlpha2>,
#[serde(rename = "shipping[address][line1]")]
pub line1: Option<Secret<String>>,
#[serde(rename = "shipping[address][line2]")]
pub line2: Option<Secret<String>>,
#[serde(rename = "shipping[address][postal_code]")]
pub zip: Option<Secret<String>>,
#[serde(rename = "shipping[address][state]")]
pub state: Option<Secret<String>>,
#[serde(rename = "shipping[name]")]
pub name: Secret<String>,
#[serde(rename = "shipping[phone]")]
pub phone: Option<Secret<String>>,
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="647" end="676">
pub enum StripePaymentMethodType {
Affirm,
AfterpayClearpay,
Alipay,
#[serde(rename = "amazon_pay")]
AmazonPay,
#[serde(rename = "au_becs_debit")]
Becs,
#[serde(rename = "bacs_debit")]
Bacs,
Bancontact,
Blik,
Card,
CustomerBalance,
Eps,
Giropay,
Ideal,
Klarna,
#[serde(rename = "p24")]
Przelewy24,
#[serde(rename = "sepa_debit")]
Sepa,
Sofort,
#[serde(rename = "us_bank_account")]
Ach,
#[serde(rename = "wechat_pay")]
Wechatpay,
#[serde(rename = "cashapp")]
Cashapp,
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payment_methods.rs<|crate|> router anchor=payment_methods_session_confirm kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/payment_methods.rs" role="context" start="2546" end="2659">
pub async fn payment_methods_session_confirm(
state: SessionState,
req_state: routes::app::ReqState,
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
profile: domain::Profile,
payment_method_session_id: id_type::GlobalPaymentMethodSessionId,
request: payment_methods::PaymentMethodSessionConfirmRequest,
) -> RouterResponse<payment_methods::PaymentMethodSessionResponse> {
let db: &dyn StorageInterface = state.store.as_ref();
let key_manager_state = &(&state).into();
// Validate if the session still exists
let payment_method_session = db
.get_payment_methods_session(key_manager_state, &key_store, &payment_method_session_id)
.await
.to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError {
message: "payment methods session does not exist or has expired".to_string(),
})
.attach_printable("Failed to retrieve payment methods session from db")?;
let payment_method_session_billing = payment_method_session
.billing
.clone()
.map(|billing| billing.into_inner())
.map(From::from);
// Unify the billing address that we receive from the session and from the confirm request
let unified_billing_address = request
.payment_method_data
.billing
.clone()
.map(|payment_method_billing| {
payment_method_billing.unify_address(payment_method_session_billing.as_ref())
})
.or_else(|| payment_method_session_billing.clone());
let create_payment_method_request = get_payment_method_create_request(
request
.payment_method_data
.payment_method_data
.as_ref()
.get_required_value("payment_method_data")?,
request.payment_method_type,
request.payment_method_subtype,
payment_method_session.customer_id.clone(),
unified_billing_address.as_ref(),
Some(&payment_method_session),
)
.attach_printable("Failed to create payment method request")?;
let payment_method = create_payment_method_core(
&state,
&req_state,
create_payment_method_request.clone(),
&merchant_account,
&key_store,
&profile,
)
.await?;
let payments_response = match &payment_method_session.psp_tokenization {
Some(common_types::payment_methods::PspTokenization {
tokenization_type: common_enums::TokenizationType::MultiUse,
..
}) => {
let zero_auth_request = construct_zero_auth_payments_request(
&request,
&payment_method_session,
&payment_method,
)?;
let payments_response = Box::pin(create_zero_auth_payment(
state.clone(),
req_state,
merchant_account.clone(),
profile.clone(),
key_store.clone(),
zero_auth_request,
))
.await?;
Some(payments_response)
}
Some(common_types::payment_methods::PspTokenization {
tokenization_type: common_enums::TokenizationType::SingleUse,
..
}) => {
Box::pin(create_single_use_tokenization_flow(
state.clone(),
req_state.clone(),
merchant_account.clone(),
profile.clone(),
key_store.clone(),
&create_payment_method_request.clone(),
&payment_method,
&payment_method_session,
))
.await?;
None
}
None => None,
};
//TODO: update the payment method session with the payment id and payment method id
let payment_method_session_response = transformers::generate_payment_method_session_response(
payment_method_session,
Secret::new("CLIENT_SECRET_REDACTED".to_string()),
payments_response,
);
Ok(services::ApplicationResponse::Json(
payment_method_session_response,
))
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods.rs" role="context" start="2545" end="2545">
))
.await?;
logger::info!(associated_payments_response=?response);
response
.get_json_body()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unexpected response from payments core")
}
#[cfg(feature = "v2")]
pub async fn payment_methods_session_confirm(
state: SessionState,
req_state: routes::app::ReqState,
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
profile: domain::Profile,
payment_method_session_id: id_type::GlobalPaymentMethodSessionId,
request: payment_methods::PaymentMethodSessionConfirmRequest,
) -> RouterResponse<payment_methods::PaymentMethodSessionResponse> {
let db: &dyn StorageInterface = state.store.as_ref();
let key_manager_state = &(&state).into();
// Validate if the session still exists
<file_sep path="hyperswitch/crates/router/src/core/payment_methods.rs" role="context" start="2690" end="2714">
pub async fn perform_payment_ops(
&self,
state: &SessionState,
parent_payment_method_token: Option<String>,
pma: &api::CustomerPaymentMethod,
pm_list_context: PaymentMethodListContext,
) -> RouterResult<()> {
let token = parent_payment_method_token
.as_ref()
.get_required_value("parent_payment_method_token")?;
let token_data = pm_list_context
.get_token_data()
.get_required_value("PaymentTokenData")?;
let intent_fulfillment_time = self
.profile
.get_order_fulfillment_time()
.unwrap_or(common_utils::consts::DEFAULT_INTENT_FULFILLMENT_TIME);
pm_routes::ParentPaymentMethodToken::create_key_for_token((token, pma.payment_method_type))
.insert(intent_fulfillment_time, token_data, state)
.await?;
Ok(())
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods.rs" role="context" start="2663" end="2688">
pub async fn form_payments_info(
payment_intent: PaymentIntent,
merchant_account: &domain::MerchantAccount,
profile: domain::Profile,
db: &dyn StorageInterface,
key_manager_state: &util_types::keymanager::KeyManagerState,
key_store: &domain::MerchantKeyStore,
) -> RouterResult<Self> {
let collect_cvv_during_payment = profile.should_collect_cvv_during_payment;
let off_session_payment_flag = matches!(
payment_intent.setup_future_usage,
common_enums::FutureUsage::OffSession
);
let is_connector_agnostic_mit_enabled =
profile.is_connector_agnostic_mit_enabled.unwrap_or(false);
Ok(Self {
payment_intent,
profile,
collect_cvv_during_payment,
off_session_payment_flag,
is_connector_agnostic_mit_enabled,
})
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods.rs" role="context" start="2517" end="2543">
async fn create_zero_auth_payment(
state: SessionState,
req_state: routes::app::ReqState,
merchant_account: domain::MerchantAccount,
profile: domain::Profile,
key_store: domain::MerchantKeyStore,
request: api_models::payments::PaymentsRequest,
) -> RouterResult<api_models::payments::PaymentsResponse> {
let response = Box::pin(payments_core::payments_create_and_confirm_intent(
state,
req_state,
merchant_account,
profile,
key_store,
request,
hyperswitch_domain_models::payments::HeaderPayload::default(),
None,
))
.await?;
logger::info!(associated_payments_response=?response);
response
.get_json_body()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unexpected response from payments core")
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods.rs" role="context" start="2470" end="2514">
fn construct_zero_auth_payments_request(
confirm_request: &payment_methods::PaymentMethodSessionConfirmRequest,
payment_method_session: &hyperswitch_domain_models::payment_methods::PaymentMethodSession,
payment_method: &payment_methods::PaymentMethodResponse,
) -> RouterResult<api_models::payments::PaymentsRequest> {
use api_models::payments;
Ok(payments::PaymentsRequest {
amount_details: payments::AmountDetails::new_for_zero_auth_payment(
common_enums::Currency::USD,
),
payment_method_data: confirm_request.payment_method_data.clone(),
payment_method_type: confirm_request.payment_method_type,
payment_method_subtype: confirm_request.payment_method_subtype,
customer_id: Some(payment_method_session.customer_id.clone()),
customer_present: Some(enums::PresenceOfCustomerDuringPayment::Present),
setup_future_usage: Some(common_enums::FutureUsage::OffSession),
payment_method_id: Some(payment_method.id.clone()),
merchant_reference_id: None,
routing_algorithm_id: None,
capture_method: None,
authentication_type: None,
// We have already passed payment method billing address
billing: None,
shipping: None,
description: None,
return_url: payment_method_session.return_url.clone(),
apply_mit_exemption: None,
statement_descriptor: None,
order_details: None,
allowed_payment_method_types: None,
metadata: None,
connector_metadata: None,
feature_metadata: None,
payment_link_enabled: None,
payment_link_config: None,
request_incremental_authorization: None,
session_expiry: None,
frm_metadata: None,
request_external_three_ds_authentication: None,
customer_acceptance: None,
browser_info: None,
force_3ds_challenge: None,
})
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods.rs" role="context" start="2719" end="2863">
async fn create_single_use_tokenization_flow(
state: SessionState,
req_state: routes::app::ReqState,
merchant_account: domain::MerchantAccount,
profile: domain::Profile,
key_store: domain::MerchantKeyStore,
payment_method_create_request: &payment_methods::PaymentMethodCreate,
payment_method: &api::PaymentMethodResponse,
payment_method_session: &domain::payment_methods::PaymentMethodSession,
) -> RouterResult<()> {
let customer_id = payment_method_create_request.customer_id.to_owned();
let connector_id = payment_method_create_request
.get_tokenize_connector_id()
.change_context(errors::ApiErrorResponse::MissingRequiredField {
field_name: "psp_tokenization.connector_id",
})
.attach_printable("Failed to get tokenize connector id")?;
let db = &state.store;
let merchant_connector_account_details = db
.find_merchant_connector_account_by_id(&(&state).into(), &connector_id, &key_store)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: connector_id.get_string_repr().to_owned(),
})
.attach_printable("error while fetching merchant_connector_account from connector_id")?;
let auth_type = merchant_connector_account_details
.get_connector_account_details()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while parsing value for ConnectorAuthType")?;
let payment_method_data_request = types::PaymentMethodTokenizationData {
payment_method_data: payment_method_data::PaymentMethodData::try_from(
payment_method_create_request.payment_method_data.clone(),
)
.change_context(errors::ApiErrorResponse::MissingRequiredField {
field_name: "card_cvc",
})
.attach_printable(
"Failed to convert type from Payment Method Create Data to Payment Method Data",
)?,
browser_info: None,
currency: api_models::enums::Currency::default(),
amount: None,
};
let payment_method_session_address = types::PaymentAddress::new(
None,
payment_method_session
.billing
.clone()
.map(|address| address.into_inner()),
None,
None,
);
let mut router_data =
types::RouterData::<api::PaymentMethodToken, _, types::PaymentsResponseData> {
flow: std::marker::PhantomData,
merchant_id: merchant_account.get_id().clone(),
customer_id: None,
connector_customer: None,
connector: merchant_connector_account_details
.connector_name
.to_string(),
payment_id: consts::IRRELEVANT_PAYMENT_INTENT_ID.to_string(), //Static
attempt_id: consts::IRRELEVANT_PAYMENT_ATTEMPT_ID.to_string(), //Static
tenant_id: state.tenant.tenant_id.clone(),
status: common_enums::enums::AttemptStatus::default(),
payment_method: common_enums::enums::PaymentMethod::Card,
connector_auth_type: auth_type,
description: None,
address: payment_method_session_address,
auth_type: common_enums::enums::AuthenticationType::default(),
connector_meta_data: None,
connector_wallets_details: None,
amount_captured: None,
access_token: None,
session_token: None,
reference_id: None,
payment_method_token: None,
recurring_mandate_payment_data: None,
preprocessing_id: None,
payment_method_balance: None,
connector_api_version: None,
request: payment_method_data_request.clone(),
response: Err(hyperswitch_domain_models::router_data::ErrorResponse::default()),
connector_request_reference_id: payment_method_session.id.get_string_repr().to_string(),
#[cfg(feature = "payouts")]
payout_method_data: None,
#[cfg(feature = "payouts")]
quote_id: None,
test_mode: None,
connector_http_status_code: None,
external_latency: None,
apple_pay_flow: None,
frm_metadata: None,
dispute_id: None,
refund_id: None,
connector_response: None,
payment_method_status: None,
minor_amount_captured: None,
integrity_check: Ok(()),
additional_merchant_data: None,
header_payload: None,
connector_mandate_request_reference_id: None,
authentication_id: None,
psd2_sca_exemption_type: None,
};
let payment_method_token_response = tokenization::add_token_for_payment_method(
&mut router_data,
payment_method_data_request.clone(),
state.clone(),
&merchant_connector_account_details.clone(),
)
.await?;
let token_response = payment_method_token_response.token.map_err(|err| {
errors::ApiErrorResponse::ExternalConnectorError {
code: err.code,
message: err.message,
connector: (merchant_connector_account_details.clone())
.connector_name
.to_string(),
status_code: err.status_code,
reason: err.reason,
}
})?;
let value = payment_method_data::SingleUsePaymentMethodToken::get_single_use_token_from_payment_method_token(
token_response.clone().into(),
connector_id.clone()
);
let key = payment_method_data::SingleUseTokenKey::store_key(&payment_method.id);
add_single_use_token_to_store(&state, key, value)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to store single use token")?;
Ok(())
}
<file_sep path="hyperswitch/crates/router/src/routes/app.rs" role="context" start="1906" end="1906">
pub struct Profile;
<file_sep path="hyperswitch/v2_compatible_migrations/2024-08-28-081757_drop_not_null_constraints_on_v1_columns/up.sql" role="context" start="5" end="21">
ALTER COLUMN org_id DROP NOT NULL;
-- Create index on org_id in organization table
-- This is done to mullify the effects of droping primary key for v1
CREATE INDEX idx_organization_org_id ON organization (org_id);
------------------------ Merchant Account -------------------
-- Drop not null in merchant_account table for v1 columns that are dropped in v2
ALTER TABLE merchant_account
DROP CONSTRAINT merchant_account_pkey,
ALTER COLUMN merchant_id DROP NOT NULL,
ALTER COLUMN primary_business_details DROP NOT NULL,
ALTER COLUMN is_recon_enabled DROP NOT NULL;
-- This is done to mullify the effects of droping primary key for v1
CREATE INDEX idx_merchant_account_merchant_id ON merchant_account (merchant_id);
<file_sep path="hyperswitch/crates/api_models/src/errors/types.rs" role="context" start="86" end="100">
pub enum ApiErrorResponse {
Unauthorized(ApiError),
ForbiddenCommonResource(ApiError),
ForbiddenPrivateResource(ApiError),
Conflict(ApiError),
Gone(ApiError),
Unprocessable(ApiError),
InternalServerError(ApiError),
NotImplemented(ApiError),
ConnectorError(ApiError, #[serde(skip_serializing)] StatusCode),
NotFound(ApiError),
MethodNotAllowed(ApiError),
BadRequest(ApiError),
DomainError(ApiError),
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/utils.rs<|crate|> router anchor=get_mca_from_object_reference_id kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/utils.rs" role="context" start="560" end="674">
pub async fn get_mca_from_object_reference_id(
state: &SessionState,
object_reference_id: webhooks::ObjectReferenceId,
merchant_account: &domain::MerchantAccount,
connector_name: &str,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::MerchantConnectorAccount, errors::ApiErrorResponse> {
let db = &*state.store;
#[cfg(feature = "v1")]
let default_profile_id = merchant_account.default_profile.as_ref();
#[cfg(feature = "v2")]
let default_profile_id = Option::<&String>::None;
match default_profile_id {
Some(profile_id) => {
#[cfg(feature = "v1")]
{
db.find_merchant_connector_account_by_profile_id_connector_name(
&state.into(),
profile_id,
connector_name,
key_store,
)
.await
.to_not_found_response(
errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: format!(
"profile_id {} and connector_name {connector_name}",
profile_id.get_string_repr()
),
},
)
}
#[cfg(feature = "v2")]
{
let _db = db;
let _profile_id = profile_id;
todo!()
}
}
_ => match object_reference_id {
webhooks::ObjectReferenceId::PaymentId(payment_id_type) => {
get_mca_from_payment_intent(
state,
merchant_account,
find_payment_intent_from_payment_id_type(
state,
payment_id_type,
merchant_account,
key_store,
)
.await?,
key_store,
connector_name,
)
.await
}
webhooks::ObjectReferenceId::RefundId(refund_id_type) => {
get_mca_from_payment_intent(
state,
merchant_account,
find_payment_intent_from_refund_id_type(
state,
refund_id_type,
merchant_account,
key_store,
connector_name,
)
.await?,
key_store,
connector_name,
)
.await
}
webhooks::ObjectReferenceId::MandateId(mandate_id_type) => {
get_mca_from_payment_intent(
state,
merchant_account,
find_payment_intent_from_mandate_id_type(
state,
mandate_id_type,
merchant_account,
key_store,
)
.await?,
key_store,
connector_name,
)
.await
}
webhooks::ObjectReferenceId::ExternalAuthenticationID(authentication_id_type) => {
find_mca_from_authentication_id_type(
state,
authentication_id_type,
merchant_account,
key_store,
)
.await
}
#[cfg(feature = "payouts")]
webhooks::ObjectReferenceId::PayoutId(payout_id_type) => {
get_mca_from_payout_attempt(
state,
merchant_account,
payout_id_type,
connector_name,
key_store,
)
.await
}
},
}
}
<file_sep path="hyperswitch/crates/router/src/utils.rs" role="context" start="559" end="559">
use api_models::{
enums,
payments::{self},
webhooks,
};
pub use common_utils::{
crypto::{self, Encryptable},
ext_traits::{ByteSliceExt, BytesExt, Encode, StringExt, ValueExt},
fp_utils::when,
id_type, pii,
validation::validate_email,
};
pub use hyperswitch_connectors::utils::QrImage;
pub use self::ext_traits::{OptionExt, ValidateCall};
use crate::core::webhooks as webhooks_core;
use crate::{
consts,
core::{
authentication::types::ExternalThreeDSConnectorMetadata,
errors::{self, CustomResult, RouterResult, StorageErrorExt},
payments as payments_core,
},
headers::ACCEPT_LANGUAGE,
logger,
routes::{metrics, SessionState},
services::{self, authentication::get_header_value_by_key},
types::{
self, domain,
transformers::{ForeignFrom, ForeignInto},
},
};
<file_sep path="hyperswitch/crates/router/src/utils.rs" role="context" start="710" end="723">
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())
}
<file_sep path="hyperswitch/crates/router/src/utils.rs" role="context" start="677" end="708">
pub fn handle_json_response_deserialization_failure(
res: types::Response,
connector: &'static str,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
metrics::RESPONSE_DESERIALIZATION_FAILURE
.add(1, router_env::metric_attributes!(("connector", connector)));
let response_data = String::from_utf8(res.response.to_vec())
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
// check for whether the response is in json format
match serde_json::from_str::<Value>(&response_data) {
// in case of unexpected response but in json format
Ok(_) => Err(errors::ConnectorError::ResponseDeserializationFailed)?,
// in case of unexpected response but in html or string format
Err(error_msg) => {
logger::error!(deserialization_error=?error_msg);
logger::error!("UNEXPECTED RESPONSE FROM CONNECTOR: {}", response_data);
Ok(types::ErrorResponse {
status_code: res.status_code,
code: consts::NO_ERROR_CODE.to_string(),
message: consts::UNSUPPORTED_ERROR_MESSAGE.to_string(),
reason: Some(response_data),
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
})
}
}
}
<file_sep path="hyperswitch/crates/router/src/utils.rs" role="context" start="477" end="557">
pub async fn get_mca_from_payout_attempt(
state: &SessionState,
merchant_account: &domain::MerchantAccount,
payout_id_type: webhooks::PayoutIdType,
connector_name: &str,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::MerchantConnectorAccount, errors::ApiErrorResponse> {
let db = &*state.store;
let payout = match payout_id_type {
webhooks::PayoutIdType::PayoutAttemptId(payout_attempt_id) => db
.find_payout_attempt_by_merchant_id_payout_attempt_id(
merchant_account.get_id(),
&payout_attempt_id,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PayoutNotFound)?,
webhooks::PayoutIdType::ConnectorPayoutId(connector_payout_id) => db
.find_payout_attempt_by_merchant_id_connector_payout_id(
merchant_account.get_id(),
&connector_payout_id,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PayoutNotFound)?,
};
let key_manager_state: &KeyManagerState = &state.into();
match payout.merchant_connector_id {
Some(merchant_connector_id) => {
#[cfg(feature = "v1")]
{
db.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
key_manager_state,
merchant_account.get_id(),
&merchant_connector_id,
key_store,
)
.await
.to_not_found_response(
errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: merchant_connector_id.get_string_repr().to_string(),
},
)
}
#[cfg(feature = "v2")]
{
//get mca using id
let _id = merchant_connector_id;
let _ = key_store;
let _ = connector_name;
let _ = key_manager_state;
todo!()
}
}
None => {
#[cfg(feature = "v1")]
{
db.find_merchant_connector_account_by_profile_id_connector_name(
key_manager_state,
&payout.profile_id,
connector_name,
key_store,
)
.await
.to_not_found_response(
errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: format!(
"profile_id {} and connector_name {}",
payout.profile_id.get_string_repr(),
connector_name
),
},
)
}
#[cfg(feature = "v2")]
{
todo!()
}
}
}
}
<file_sep path="hyperswitch/crates/router/src/utils.rs" role="context" start="380" end="474">
pub async fn get_mca_from_payment_intent(
state: &SessionState,
merchant_account: &domain::MerchantAccount,
payment_intent: PaymentIntent,
key_store: &domain::MerchantKeyStore,
connector_name: &str,
) -> CustomResult<domain::MerchantConnectorAccount, errors::ApiErrorResponse> {
let db = &*state.store;
let key_manager_state: &KeyManagerState = &state.into();
#[cfg(feature = "v1")]
let payment_attempt = db
.find_payment_attempt_by_attempt_id_merchant_id(
&payment_intent.active_attempt.get_id(),
merchant_account.get_id(),
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
#[cfg(feature = "v2")]
let payment_attempt = db
.find_payment_attempt_by_attempt_id_merchant_id(
key_manager_state,
key_store,
&payment_intent.active_attempt.get_id(),
merchant_account.get_id(),
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
match payment_attempt.merchant_connector_id {
Some(merchant_connector_id) => {
#[cfg(feature = "v1")]
{
db.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
key_manager_state,
merchant_account.get_id(),
&merchant_connector_id,
key_store,
)
.await
.to_not_found_response(
errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: merchant_connector_id.get_string_repr().to_string(),
},
)
}
#[cfg(feature = "v2")]
{
//get mca using id
let _id = merchant_connector_id;
let _ = key_store;
let _ = key_manager_state;
let _ = connector_name;
todo!()
}
}
None => {
let profile_id = payment_intent
.profile_id
.as_ref()
.get_required_value("profile_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("profile_id is not set in payment_intent")?
.clone();
#[cfg(feature = "v1")]
{
db.find_merchant_connector_account_by_profile_id_connector_name(
key_manager_state,
&profile_id,
connector_name,
key_store,
)
.await
.to_not_found_response(
errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: format!(
"profile_id {} and connector_name {connector_name}",
profile_id.get_string_repr()
),
},
)
}
#[cfg(feature = "v2")]
{
//get mca using id
let _ = profile_id;
todo!()
}
}
}
}
<file_sep path="hyperswitch/crates/router/tests/utils.rs" role="context" start="409" end="411">
pub struct PaymentId {
payment_id: common_utils::id_type::PaymentId,
}
<file_sep path="hyperswitch/v2_compatible_migrations/2024-08-28-081757_drop_not_null_constraints_on_v1_columns/up.sql" role="context" start="5" end="21">
ALTER COLUMN org_id DROP NOT NULL;
-- Create index on org_id in organization table
-- This is done to mullify the effects of droping primary key for v1
CREATE INDEX idx_organization_org_id ON organization (org_id);
------------------------ Merchant Account -------------------
-- Drop not null in merchant_account table for v1 columns that are dropped in v2
ALTER TABLE merchant_account
DROP CONSTRAINT merchant_account_pkey,
ALTER COLUMN merchant_id DROP NOT NULL,
ALTER COLUMN primary_business_details DROP NOT NULL,
ALTER COLUMN is_recon_enabled DROP NOT NULL;
-- This is done to mullify the effects of droping primary key for v1
CREATE INDEX idx_merchant_account_merchant_id ON merchant_account (merchant_id);
<file_sep path="hyperswitch/crates/api_models/src/errors/types.rs" role="context" start="86" end="100">
pub enum ApiErrorResponse {
Unauthorized(ApiError),
ForbiddenCommonResource(ApiError),
ForbiddenPrivateResource(ApiError),
Conflict(ApiError),
Gone(ApiError),
Unprocessable(ApiError),
InternalServerError(ApiError),
NotImplemented(ApiError),
ConnectorError(ApiError, #[serde(skip_serializing)] StatusCode),
NotFound(ApiError),
MethodNotAllowed(ApiError),
BadRequest(ApiError),
DomainError(ApiError),
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/plaid.rs<|crate|> router anchor=new kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/connector/plaid.rs" role="context" start="32" end="36">
pub fn new() -> &'static Self {
&Self {
amount_converter: &FloatMajorUnitForConnector,
}
}
<file_sep path="hyperswitch/crates/router/src/connector/plaid.rs" role="context" start="31" end="31">
use common_utils::types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector};
<file_sep path="hyperswitch/crates/router/src/connector/plaid.rs" role="context" start="83" end="85">
fn id(&self) -> &'static str {
"plaid"
}
<file_sep path="hyperswitch/crates/router/src/connector/plaid.rs" role="context" start="67" end="79">
fn build_headers(
&self,
req: &types::RouterData<Flow, Request, Response>,
_connectors: &settings::Connectors,
) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
)];
let mut auth = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut auth);
Ok(header)
}
<file_sep path="hyperswitch/crates/router/src/connector/plaid.rs" role="context" start="375" end="395">
fn build_request(
&self,
req: &types::PaymentsPostProcessingRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Post)
.url(&types::PaymentsPostProcessingType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::PaymentsPostProcessingType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsPostProcessingType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
<file_sep path="hyperswitch/crates/router/src/connector/plaid.rs" role="context" start="366" end="373">
fn get_request_body(
&self,
req: &types::PaymentsPostProcessingRouterData,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = plaid::PlaidLinkTokenRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/utils.rs<|crate|> router anchor=get_card_issuer kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/connector/utils.rs" role="context" start="3183" end="3185">
fn get_card_issuer(&self) -> Result<CardIssuer, Error> {
get_card_issuer(self.network_token.peek())
}
<file_sep path="hyperswitch/crates/router/src/connector/utils.rs" role="context" start="3182" end="3182">
use api_models::payouts::{self, PayoutVendorAccountDetails};
use common_utils::{
date_time,
errors::{ParsingError, ReportSwitchExt},
ext_traits::StringExt,
id_type,
pii::{self, Email, IpAddress},
types::{AmountConvertor, MinorUnit},
};
use crate::{
consts,
core::{
errors::{self, ApiErrorResponse, CustomResult},
payments::{types::AuthenticationData, PaymentData},
},
pii::PeekInterface,
types::{
self, api, domain,
storage::enums as storage_enums,
transformers::{ForeignFrom, ForeignTryFrom},
ApplePayPredecryptData, BrowserInformation, PaymentsCancelData, ResponseId,
},
utils::{OptionExt, ValueExt},
};
type Error = error_stack::Report<errors::ConnectorError>;
<file_sep path="hyperswitch/crates/router/src/connector/utils.rs" role="context" start="3200" end="3206">
fn get_expiry_year_4_digit(&self) -> Secret<String> {
let mut year = self.network_token_exp_year.peek().clone();
if year.len() == 2 {
year = format!("20{}", year);
}
Secret::new(year)
}
<file_sep path="hyperswitch/crates/router/src/connector/utils.rs" role="context" start="3191" end="3197">
fn get_expiry_year_4_digit(&self) -> Secret<String> {
let mut year = self.token_exp_year.peek().clone();
if year.len() == 2 {
year = format!("20{}", year);
}
Secret::new(year)
}
<file_sep path="hyperswitch/crates/router/src/connector/utils.rs" role="context" start="3178" end="3180">
fn get_card_issuer(&self) -> Result<CardIssuer, Error> {
get_card_issuer(self.token_number.peek())
}
<file_sep path="hyperswitch/crates/router/src/connector/utils.rs" role="context" start="3148" end="3163">
pub fn get_refund_integrity_object<T>(
amount_convertor: &dyn AmountConvertor<Output = T>,
refund_amount: T,
currency: String,
) -> Result<RefundIntegrityObject, error_stack::Report<errors::ConnectorError>> {
let currency_enum = enums::Currency::from_str(currency.to_uppercase().as_str())
.change_context(errors::ConnectorError::ParsingFailed)?;
let refund_amount_in_minor_unit =
convert_back_amount_to_minor_units(amount_convertor, refund_amount, currency_enum)?;
Ok(RefundIntegrityObject {
currency: currency_enum,
refund_amount: refund_amount_in_minor_unit,
})
}
<file_sep path="hyperswitch/crates/router/src/connector/utils.rs" role="context" start="1480" end="1482">
fn get_card_issuer(&self) -> Result<CardIssuer, Error> {
get_card_issuer(self.card_number.peek())
}
<file_sep path="hyperswitch/crates/router/src/connector/utils.rs" role="context" start="67" end="67">
type Error = error_stack::Report<errors::ConnectorError>;
<file_sep path="hyperswitch/crates/router/src/connector/utils.rs" role="context" start="1443" end="1452">
pub enum CardIssuer {
AmericanExpress,
Master,
Maestro,
Visa,
Discover,
DinersClub,
JCB,
CarteBlanche,
}
<file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="2478" end="2478">
type Error = error_stack::Report<errors::ValidationError>;
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/utils/currency.rs<|crate|> router anchor=new kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/utils/currency.rs" role="context" start="104" end="109">
fn new(exchange_rate: ExchangeRates) -> Self {
Self {
data: Arc::new(exchange_rate),
timestamp: date_time::now_unix_timestamp(),
}
}
<file_sep path="hyperswitch/crates/router/src/utils/currency.rs" role="context" start="103" end="103">
use std::{collections::HashMap, ops::Deref, str::FromStr, sync::Arc};
use common_utils::{date_time, errors::CustomResult, events::ApiEventMetric, ext_traits::AsyncExt};
use currency_conversion::types::{CurrencyFactors, ExchangeRates};
<file_sep path="hyperswitch/crates/router/src/utils/currency.rs" role="context" start="115" end="117">
async fn retrieve_forex_from_local_cache() -> Option<FxExchangeRatesCacheEntry> {
FX_EXCHANGE_RATES_CACHE.read().await.clone()
}
<file_sep path="hyperswitch/crates/router/src/utils/currency.rs" role="context" start="110" end="112">
fn is_expired(&self, data_expiration_delay: u32) -> bool {
self.timestamp + i64::from(data_expiration_delay) < date_time::now_unix_timestamp()
}
<file_sep path="hyperswitch/crates/router/src/utils/currency.rs" role="context" start="98" end="100">
fn deref(&self) -> &Self::Target {
&self.0
}
<file_sep path="hyperswitch/crates/router/src/utils/currency.rs" role="context" start="284" end="348">
async fn fetch_forex_rates_from_primary_api(
state: &SessionState,
) -> Result<FxExchangeRatesCacheEntry, error_stack::Report<ForexError>> {
let forex_api_key = state.conf.forex_api.get_inner().api_key.peek();
logger::debug!("forex_log: Primary api call for forex fetch");
let forex_url: String = format!("{}{}{}", FOREX_BASE_URL, forex_api_key, FOREX_BASE_CURRENCY);
let forex_request = services::RequestBuilder::new()
.method(services::Method::Get)
.url(&forex_url)
.build();
logger::info!(primary_forex_request=?forex_request,"forex_log: Primary api call for forex fetch");
let response = state
.api_client
.send_request(
&state.clone(),
forex_request,
Some(FOREX_API_TIMEOUT),
false,
)
.await
.change_context(ForexError::ApiUnresponsive)
.attach_printable("Primary forex fetch api unresponsive")?;
let forex_response = response
.json::<ForexResponse>()
.await
.change_context(ForexError::ParsingError)
.attach_printable(
"Unable to parse response received from primary api into ForexResponse",
)?;
logger::info!(primary_forex_response=?forex_response,"forex_log");
let mut conversions: HashMap<enums::Currency, CurrencyFactors> = HashMap::new();
for enum_curr in enums::Currency::iter() {
match forex_response.rates.get(&enum_curr.to_string()) {
Some(rate) => {
let from_factor = match Decimal::new(1, 0).checked_div(**rate) {
Some(rate) => rate,
None => {
logger::error!(
"forex_error: Rates for {} not received from API",
&enum_curr
);
continue;
}
};
let currency_factors = CurrencyFactors::new(**rate, from_factor);
conversions.insert(enum_curr, currency_factors);
}
None => {
logger::error!(
"forex_error: Rates for {} not received from API",
&enum_curr
);
}
};
}
Ok(FxExchangeRatesCacheEntry::new(ExchangeRates::new(
enums::Currency::USD,
conversions,
)))
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/types/domain/user.rs<|crate|> router anchor=foreign_from kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/types/domain/user.rs" role="context" start="1244" end="1249">
fn foreign_from(value: UserStatus) -> Self {
match value {
UserStatus::Active => Self::Active,
UserStatus::InvitationSent => Self::InvitationSent,
}
}
<file_sep path="hyperswitch/crates/router/src/types/domain/user.rs" role="context" start="1243" end="1243">
use diesel_models::{
enums::{TotpStatus, UserRoleVersion, UserStatus},
organization::{self as diesel_org, Organization, OrganizationBridge},
user as storage_user,
user_role::{UserRole, UserRoleNew},
};
<file_sep path="hyperswitch/crates/router/src/types/domain/user.rs" role="context" start="1267" end="1269">
pub fn get_role_name(self) -> String {
self.0
}
<file_sep path="hyperswitch/crates/router/src/types/domain/user.rs" role="context" start="1256" end="1265">
pub fn new(name: String) -> UserResult<Self> {
let is_empty_or_whitespace = name.trim().is_empty();
let is_too_long = name.graphemes(true).count() > consts::user_role::MAX_ROLE_NAME_LENGTH;
if is_empty_or_whitespace || is_too_long || name.contains(' ') {
Err(UserErrors::RoleNameParsingError.into())
} else {
Ok(Self(name.to_lowercase()))
}
}
<file_sep path="hyperswitch/crates/router/src/types/domain/user.rs" role="context" start="1211" end="1240">
pub async fn decrypt_and_get_totp_secret(
&self,
state: &SessionState,
) -> UserResult<Option<Secret<String>>> {
if self.0.totp_secret.is_none() {
return Ok(None);
}
let key_manager_state = &state.into();
let user_key_store = state
.global_store
.get_user_key_store_by_user_id(
key_manager_state,
self.get_user_id(),
&state.store.get_master_key().to_vec().into(),
)
.await
.change_context(UserErrors::InternalServerError)?;
Ok(domain_types::crypto_operation::<String, masking::WithType>(
key_manager_state,
type_name!(storage_user::User),
domain_types::CryptoOperation::DecryptOptional(self.0.totp_secret.clone()),
Identifier::User(user_key_store.user_id.clone()),
user_key_store.key.peek(),
)
.await
.and_then(|val| val.try_into_optionaloperation())
.change_context(UserErrors::InternalServerError)?
.map(Encryptable::into_inner))
}
<file_sep path="hyperswitch/crates/router/src/types/domain/user.rs" role="context" start="1207" end="1209">
pub fn get_recovery_codes(&self) -> Option<Vec<Secret<String>>> {
self.0.totp_recovery_codes.clone()
}
<file_sep path="hyperswitch/crates/router/src/types/domain/user.rs" role="context" start="287" end="291">
fn from(_value: user_api::ConnectAccountRequest) -> Self {
let new_organization = api_org::OrganizationNew::new(None);
let db_organization = ForeignFrom::foreign_from(new_organization);
Self(db_organization)
}
<file_sep path="hyperswitch/crates/router/src/types/domain/user.rs" role="context" start="295" end="304">
fn from(
(_value, org_id): (user_api::CreateInternalUserRequest, id_type::OrganizationId),
) -> Self {
let new_organization = api_org::OrganizationNew {
org_id,
org_name: None,
};
let db_organization = ForeignFrom::foreign_from(new_organization);
Self(db_organization)
}
<file_sep path="hyperswitch/crates/api_models/src/user_role.rs" role="context" start="38" end="41">
pub enum UserStatus {
Active,
InvitationSent,
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/types.rs<|crate|> router anchor=foreign_from kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/types.rs" role="context" start="1056" end="1072">
fn foreign_from(item: &domain::MerchantConnectorAccountFeatureMetadata) -> Self {
let revenue_recovery = item
.revenue_recovery
.as_ref()
.map(
|revenue_recovery_metadata| api_models::admin::RevenueRecoveryMetadata {
max_retry_count: revenue_recovery_metadata.max_retry_count,
billing_connector_retry_threshold: revenue_recovery_metadata
.billing_connector_retry_threshold,
billing_account_reference: revenue_recovery_metadata
.mca_reference
.recovery_to_billing
.clone(),
},
);
Self { revenue_recovery }
}
<file_sep path="hyperswitch/crates/router/src/types.rs" role="context" start="1055" end="1055">
authentication_id: None,
psd2_sca_exemption_type: None,
additional_merchant_data: data.additional_merchant_data.clone(),
connector_mandate_request_reference_id: None,
}
}
}
#[cfg(feature = "v2")]
impl ForeignFrom<&domain::MerchantConnectorAccountFeatureMetadata>
for api_models::admin::MerchantConnectorAccountFeatureMetadata
{
fn foreign_from(item: &domain::MerchantConnectorAccountFeatureMetadata) -> Self {
let revenue_recovery = item
.revenue_recovery
.as_ref()
.map(
|revenue_recovery_metadata| api_models::admin::RevenueRecoveryMetadata {
max_retry_count: revenue_recovery_metadata.max_retry_count,
billing_connector_retry_threshold: revenue_recovery_metadata
.billing_connector_retry_threshold,
billing_account_reference: revenue_recovery_metadata
.mca_reference
.recovery_to_billing
.clone(),
<file_sep path="hyperswitch/crates/router/src/types.rs" role="context" start="1080" end="1100">
fn foreign_try_from(
feature_metadata: &api_models::admin::MerchantConnectorAccountFeatureMetadata,
) -> Result<Self, Self::Error> {
let revenue_recovery = feature_metadata
.revenue_recovery
.as_ref()
.map(|revenue_recovery_metadata| {
domain::AccountReferenceMap::new(
revenue_recovery_metadata.billing_account_reference.clone(),
)
.map(|mca_reference| domain::RevenueRecoveryMetadata {
max_retry_count: revenue_recovery_metadata.max_retry_count,
billing_connector_retry_threshold: revenue_recovery_metadata
.billing_connector_retry_threshold,
mca_reference,
})
})
.transpose()?;
Ok(Self { revenue_recovery })
}
<file_sep path="hyperswitch/crates/router/src/types.rs" role="context" start="992" end="1049">
fn foreign_from(
item: (
&RouterData<F1, PayoutsData, PayoutsResponseData>,
PayoutsData,
),
) -> Self {
let data = item.0;
let request = item.1;
Self {
flow: PhantomData,
request,
merchant_id: data.merchant_id.clone(),
connector: data.connector.clone(),
attempt_id: data.attempt_id.clone(),
tenant_id: data.tenant_id.clone(),
status: data.status,
payment_method: data.payment_method,
connector_auth_type: data.connector_auth_type.clone(),
description: data.description.clone(),
address: data.address.clone(),
auth_type: data.auth_type,
connector_meta_data: data.connector_meta_data.clone(),
connector_wallets_details: data.connector_wallets_details.clone(),
amount_captured: data.amount_captured,
minor_amount_captured: data.minor_amount_captured,
access_token: data.access_token.clone(),
response: data.response.clone(),
payment_id: data.payment_id.clone(),
session_token: data.session_token.clone(),
reference_id: data.reference_id.clone(),
customer_id: data.customer_id.clone(),
payment_method_token: None,
recurring_mandate_payment_data: None,
preprocessing_id: None,
connector_customer: data.connector_customer.clone(),
connector_request_reference_id:
IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_PAYOUTS_FLOW.to_string(),
payout_method_data: data.payout_method_data.clone(),
quote_id: data.quote_id.clone(),
test_mode: data.test_mode,
payment_method_balance: None,
payment_method_status: None,
connector_api_version: None,
connector_http_status_code: data.connector_http_status_code,
external_latency: data.external_latency,
apple_pay_flow: None,
frm_metadata: None,
refund_id: None,
dispute_id: None,
connector_response: data.connector_response.clone(),
integrity_check: Ok(()),
header_payload: data.header_payload.clone(),
authentication_id: None,
psd2_sca_exemption_type: None,
additional_merchant_data: data.additional_merchant_data.clone(),
connector_mandate_request_reference_id: None,
}
}
<file_sep path="hyperswitch/crates/router/src/types.rs" role="context" start="927" end="982">
fn foreign_from(item: (&RouterData<F1, T1, PaymentsResponseData>, T2)) -> Self {
let data = item.0;
let request = item.1;
Self {
flow: PhantomData,
request,
merchant_id: data.merchant_id.clone(),
connector: data.connector.clone(),
attempt_id: data.attempt_id.clone(),
tenant_id: data.tenant_id.clone(),
status: data.status,
payment_method: data.payment_method,
connector_auth_type: data.connector_auth_type.clone(),
description: data.description.clone(),
address: data.address.clone(),
auth_type: data.auth_type,
connector_meta_data: data.connector_meta_data.clone(),
connector_wallets_details: data.connector_wallets_details.clone(),
amount_captured: data.amount_captured,
minor_amount_captured: data.minor_amount_captured,
access_token: data.access_token.clone(),
response: data.response.clone(),
payment_id: data.payment_id.clone(),
session_token: data.session_token.clone(),
reference_id: data.reference_id.clone(),
customer_id: data.customer_id.clone(),
payment_method_token: None,
preprocessing_id: None,
connector_customer: data.connector_customer.clone(),
recurring_mandate_payment_data: data.recurring_mandate_payment_data.clone(),
connector_request_reference_id: data.connector_request_reference_id.clone(),
#[cfg(feature = "payouts")]
payout_method_data: data.payout_method_data.clone(),
#[cfg(feature = "payouts")]
quote_id: data.quote_id.clone(),
test_mode: data.test_mode,
payment_method_status: None,
payment_method_balance: data.payment_method_balance.clone(),
connector_api_version: data.connector_api_version.clone(),
connector_http_status_code: data.connector_http_status_code,
external_latency: data.external_latency,
apple_pay_flow: data.apple_pay_flow.clone(),
frm_metadata: data.frm_metadata.clone(),
dispute_id: data.dispute_id.clone(),
refund_id: data.refund_id.clone(),
connector_response: data.connector_response.clone(),
integrity_check: Ok(()),
additional_merchant_data: data.additional_merchant_data.clone(),
header_payload: data.header_payload.clone(),
connector_mandate_request_reference_id: data
.connector_mandate_request_reference_id
.clone(),
authentication_id: data.authentication_id.clone(),
psd2_sca_exemption_type: data.psd2_sca_exemption_type,
}
}
<file_sep path="hyperswitch/crates/router/src/types.rs" role="context" start="332" end="354">
fn get_amount_capturable<F>(
&self,
_payment_data: &PaymentData<F>,
attempt_status: common_enums::AttemptStatus,
) -> Option<i64>
where
F: Clone,
{
let intent_status = common_enums::IntentStatus::foreign_from(attempt_status);
match intent_status {
common_enums::IntentStatus::Succeeded
| common_enums::IntentStatus::PartiallyCaptured => Some(0),
common_enums::IntentStatus::Processing
| common_enums::IntentStatus::Cancelled
| common_enums::IntentStatus::Failed
| common_enums::IntentStatus::RequiresCustomerAction
| common_enums::IntentStatus::RequiresMerchantAction
| common_enums::IntentStatus::RequiresPaymentMethod
| common_enums::IntentStatus::RequiresConfirmation
| common_enums::IntentStatus::RequiresCapture
| common_enums::IntentStatus::PartiallyCapturedAndCapturable => None,
}
}
<file_sep path="hyperswitch/crates/router/src/types.rs" role="context" start="718" end="726">
fn foreign_from(value: AdditionalMerchantData) -> Self {
match value {
AdditionalMerchantData::OpenBankingRecipientData(data) => {
Self::OpenBankingRecipientData(
api_models::admin::MerchantRecipientData::foreign_from(data),
)
}
}
}
<file_sep path="hyperswitch/crates/api_models/src/admin.rs" role="context" start="968" end="979">
pub struct RevenueRecoveryMetadata {
/// The maximum number of retries allowed for an invoice. This limit is set by the merchant for each `billing connector`. Once this limit is reached, no further retries will be attempted.
#[schema(value_type = u16, example = "15")]
pub max_retry_count: u16,
/// Maximum number of `billing connector` retries before revenue recovery can start executing retries.
#[schema(value_type = u16, example = "10")]
pub billing_connector_retry_threshold: u16,
/// Billing account reference id is payment gateway id at billing connector end.
/// Merchants need to provide a mapping between these merchant connector account and the corresponding account reference IDs for each `billing connector`.
#[schema(value_type = u16, example = r#"{ "mca_vDSg5z6AxnisHq5dbJ6g": "stripe_123", "mca_vDSg5z6AumisHqh4x5m1": "adyen_123" }"#)]
pub billing_account_reference: HashMap<id_type::MerchantConnectorAccountId, String>,
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/services/authentication.rs<|crate|> router anchor=get_platform_merchant_account kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="3991" end="4014">
async fn get_platform_merchant_account<A>(
state: &A,
request_headers: &HeaderMap,
merchant_account: domain::MerchantAccount,
) -> RouterResult<(domain::MerchantAccount, Option<domain::MerchantAccount>)>
where
A: SessionStateInfo + Sync,
{
let connected_merchant_id =
get_and_validate_connected_merchant_id(request_headers, &merchant_account)?;
match connected_merchant_id {
Some(merchant_id) => {
let connected_merchant_account = get_connected_merchant_account(
state,
merchant_id,
merchant_account.organization_id.clone(),
)
.await?;
Ok((connected_merchant_account, Some(merchant_account)))
}
None => Ok((merchant_account, None)),
}
}
<file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="3990" end="3990">
use actix_web::http::header::HeaderMap;
use crate::{
core::{
api_keys,
errors::{self, utils::StorageErrorExt, RouterResult},
},
headers,
routes::app::SessionStateInfo,
services::api,
types::{domain, storage},
utils::OptionExt,
};
<file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="4034" end="4044">
fn throw_error_if_platform_merchant_authentication_required(
request_headers: &HeaderMap,
) -> RouterResult<()> {
HeaderMapStruct::new(request_headers)
.get_id_type_from_header_if_present::<id_type::MerchantId>(
headers::X_CONNECTED_MERCHANT_ID,
)?
.map_or(Ok(()), |_| {
Err(errors::ApiErrorResponse::PlatformAccountAuthNotSupported.into())
})
}
<file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="4016" end="4032">
fn get_and_validate_connected_merchant_id(
request_headers: &HeaderMap,
merchant_account: &domain::MerchantAccount,
) -> RouterResult<Option<id_type::MerchantId>> {
HeaderMapStruct::new(request_headers)
.get_id_type_from_header_if_present::<id_type::MerchantId>(
headers::X_CONNECTED_MERCHANT_ID,
)?
.map(|merchant_id| {
merchant_account
.is_platform_account
.then_some(merchant_id)
.ok_or(errors::ApiErrorResponse::InvalidPlatformOperation)
})
.transpose()
.attach_printable("Non platform_merchant_account using X_CONNECTED_MERCHANT_ID header")
}
<file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="3956" end="3989">
async fn get_connected_merchant_account<A>(
state: &A,
connected_merchant_id: id_type::MerchantId,
platform_org_id: id_type::OrganizationId,
) -> RouterResult<domain::MerchantAccount>
where
A: SessionStateInfo + Sync,
{
let key_manager_state = &(&state.session_state()).into();
let key_store = state
.store()
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&connected_merchant_id,
&state.store().get_master_key().to_vec().into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::InvalidPlatformOperation)
.attach_printable("Failed to fetch merchant key store for the merchant id")?;
let connected_merchant_account = state
.store()
.find_merchant_account_by_merchant_id(key_manager_state, &connected_merchant_id, &key_store)
.await
.to_not_found_response(errors::ApiErrorResponse::InvalidPlatformOperation)
.attach_printable("Failed to fetch merchant account for the merchant id")?;
if platform_org_id != connected_merchant_account.organization_id {
return Err(errors::ApiErrorResponse::InvalidPlatformOperation)
.attach_printable("Access for merchant id Unauthorized");
}
Ok(connected_merchant_account)
}
<file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="3891" end="3953">
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(AuthenticationDataWithUser, AuthenticationType)> {
let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?;
if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
authorization::check_tenant(
payload.tenant_id.clone(),
&state.session_state().tenant.tenant_id,
)?;
let role_info = authorization::get_role_info(state, &payload).await?;
authorization::check_permission(self.permission, &role_info)?;
let key_manager_state = &(&state.session_state()).into();
let key_store = state
.store()
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&payload.merchant_id,
&state.store().get_master_key().to_vec().into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken)
.attach_printable("Failed to fetch merchant key store for the merchant id")?;
let merchant = state
.store()
.find_merchant_account_by_merchant_id(
key_manager_state,
&payload.merchant_id,
&key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken)
.attach_printable("Failed to fetch merchant account for the merchant id")?;
let user_id = payload.user_id;
let user = state
.session_state()
.global_store
.find_user_by_id(&user_id)
.await
.to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken)
.attach_printable("Failed to fetch user for the user id")?;
let auth = AuthenticationDataWithUser {
merchant_account: merchant,
key_store,
profile_id: payload.profile_id.clone(),
user,
};
let auth_type = AuthenticationType::MerchantJwt {
merchant_id: auth.merchant_account.get_id().clone(),
user_id: Some(user_id),
};
Ok((auth, auth_type))
}
<file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="2040" end="2152">
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(AuthenticationData, AuthenticationType)> {
let header_map_struct = HeaderMapStruct::new(request_headers);
let auth_string = header_map_struct.get_auth_string_from_header()?;
let api_key = auth_string
.split(',')
.find_map(|part| part.trim().strip_prefix("api-key="))
.ok_or_else(|| {
report!(errors::ApiErrorResponse::Unauthorized)
.attach_printable("Unable to parse api_key")
})?;
if api_key.is_empty() {
return Err(errors::ApiErrorResponse::Unauthorized)
.attach_printable("API key is empty");
}
let profile_id = HeaderMapStruct::new(request_headers)
.get_id_type_from_header::<id_type::ProfileId>(headers::X_PROFILE_ID)?;
let api_key = api_keys::PlaintextApiKey::from(api_key);
let hash_key = {
let config = state.conf();
config.api_keys.get_inner().get_hash_key()?
};
let hashed_api_key = api_key.keyed_hash(hash_key.peek());
let stored_api_key = state
.store()
.find_api_key_by_hash_optional(hashed_api_key.into())
.await
.change_context(errors::ApiErrorResponse::InternalServerError) // If retrieve failed
.attach_printable("Failed to retrieve API key")?
.ok_or(report!(errors::ApiErrorResponse::Unauthorized)) // If retrieve returned `None`
.attach_printable("Merchant not authenticated")?;
if stored_api_key
.expires_at
.map(|expires_at| expires_at < date_time::now())
.unwrap_or(false)
{
return Err(report!(errors::ApiErrorResponse::Unauthorized))
.attach_printable("API key has expired");
}
let key_manager_state = &(&state.session_state()).into();
let key_store = state
.store()
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&stored_api_key.merchant_id,
&state.store().get_master_key().to_vec().into(),
)
.await
.change_context(errors::ApiErrorResponse::Unauthorized)
.attach_printable("Failed to fetch merchant key store for the merchant id")?;
let merchant = state
.store()
.find_merchant_account_by_merchant_id(
key_manager_state,
&stored_api_key.merchant_id,
&key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
// Get connected merchant account if API call is done by Platform merchant account on behalf of connected merchant account
let (merchant, platform_merchant_account) = if state.conf().platform.enabled {
get_platform_merchant_account(state, request_headers, merchant).await?
} else {
(merchant, None)
};
let key_store = if platform_merchant_account.is_some() {
state
.store()
.get_merchant_key_store_by_merchant_id(
key_manager_state,
merchant.get_id(),
&state.store().get_master_key().to_vec().into(),
)
.await
.change_context(errors::ApiErrorResponse::Unauthorized)
.attach_printable("Failed to fetch merchant key store for the merchant id")?
} else {
key_store
};
let profile = state
.store()
.find_business_profile_by_profile_id(key_manager_state, &key_store, &profile_id)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
let auth = AuthenticationData {
merchant_account: merchant,
platform_merchant_account,
key_store,
profile,
};
Ok((
auth.clone(),
AuthenticationType::ApiKey {
merchant_id: auth.merchant_account.get_id().clone(),
key_id: stored_api_key.key_id,
},
))
}
<file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="528" end="633">
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(AuthenticationData, AuthenticationType)> {
let api_key = get_api_key(request_headers)
.change_context(errors::ApiErrorResponse::Unauthorized)?
.trim();
if api_key.is_empty() {
return Err(errors::ApiErrorResponse::Unauthorized)
.attach_printable("API key is empty");
}
let api_key = api_keys::PlaintextApiKey::from(api_key);
let hash_key = {
let config = state.conf();
config.api_keys.get_inner().get_hash_key()?
};
let hashed_api_key = api_key.keyed_hash(hash_key.peek());
let stored_api_key = state
.store()
.find_api_key_by_hash_optional(hashed_api_key.into())
.await
.change_context(errors::ApiErrorResponse::InternalServerError) // If retrieve failed
.attach_printable("Failed to retrieve API key")?
.ok_or(report!(errors::ApiErrorResponse::Unauthorized)) // If retrieve returned `None`
.attach_printable("Merchant not authenticated")?;
if stored_api_key
.expires_at
.map(|expires_at| expires_at < date_time::now())
.unwrap_or(false)
{
return Err(report!(errors::ApiErrorResponse::Unauthorized))
.attach_printable("API key has expired");
}
let key_manager_state = &(&state.session_state()).into();
let key_store = state
.store()
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&stored_api_key.merchant_id,
&state.store().get_master_key().to_vec().into(),
)
.await
.change_context(errors::ApiErrorResponse::Unauthorized)
.attach_printable("Failed to fetch merchant key store for the merchant id")?;
let profile_id =
get_header_value_by_key(headers::X_PROFILE_ID.to_string(), request_headers)?
.map(id_type::ProfileId::from_str)
.transpose()
.change_context(errors::ValidationError::IncorrectValueProvided {
field_name: "X-Profile-Id",
})
.change_context(errors::ApiErrorResponse::Unauthorized)?;
let merchant = state
.store()
.find_merchant_account_by_merchant_id(
key_manager_state,
&stored_api_key.merchant_id,
&key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
// Get connected merchant account if API call is done by Platform merchant account on behalf of connected merchant account
let (merchant, platform_merchant_account) = if state.conf().platform.enabled {
get_platform_merchant_account(state, request_headers, merchant).await?
} else {
(merchant, None)
};
let key_store = if platform_merchant_account.is_some() {
state
.store()
.get_merchant_key_store_by_merchant_id(
key_manager_state,
merchant.get_id(),
&state.store().get_master_key().to_vec().into(),
)
.await
.change_context(errors::ApiErrorResponse::Unauthorized)
.attach_printable("Failed to fetch merchant key store for the merchant id")?
} else {
key_store
};
let auth = AuthenticationData {
merchant_account: merchant,
platform_merchant_account,
key_store,
profile_id,
};
Ok((
auth.clone(),
AuthenticationType::ApiKey {
merchant_id: auth.merchant_account.get_id().clone(),
key_id: stored_api_key.key_id,
},
))
}
<file_sep path="hyperswitch/crates/router/src/core/errors.rs" role="context" start="31" end="31">
pub type RouterResult<T> = CustomResult<T, ApiErrorResponse>;
<file_sep path="hyperswitch/v2_compatible_migrations/2024-08-28-081757_drop_not_null_constraints_on_v1_columns/up.sql" role="context" start="5" end="21">
ALTER COLUMN org_id DROP NOT NULL;
-- Create index on org_id in organization table
-- This is done to mullify the effects of droping primary key for v1
CREATE INDEX idx_organization_org_id ON organization (org_id);
------------------------ Merchant Account -------------------
-- Drop not null in merchant_account table for v1 columns that are dropped in v2
ALTER TABLE merchant_account
DROP CONSTRAINT merchant_account_pkey,
ALTER COLUMN merchant_id DROP NOT NULL,
ALTER COLUMN primary_business_details DROP NOT NULL,
ALTER COLUMN is_recon_enabled DROP NOT NULL;
-- This is done to mullify the effects of droping primary key for v1
CREATE INDEX idx_merchant_account_merchant_id ON merchant_account (merchant_id);
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/trustpay.rs<|crate|> router<|connector|> trustpay anchor=get_default_payment_info kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/tests/connectors/trustpay.rs" role="context" start="73" end="96">
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::IN),
..Default::default()
}),
phone: None,
email: None,
}),
None,
None,
)),
..Default::default()
})
}
<file_sep path="hyperswitch/crates/router/tests/connectors/trustpay.rs" role="context" start="72" end="72">
use hyperswitch_domain_models::address::{Address, AddressDetails};
use masking::Secret;
use router::types::{self, api, domain, storage::enums, BrowserInformation};
<file_sep path="hyperswitch/crates/router/tests/connectors/trustpay.rs" role="context" start="116" end="141">
async fn should_sync_auto_captured_payment() {
let authorize_response = CONNECTOR
.make_payment(
get_default_payment_authorize_data(),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
assert_ne!(txn_id, None, "Empty connector transaction id");
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
}),
None,
)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Charged,);
}
<file_sep path="hyperswitch/crates/router/tests/connectors/trustpay.rs" role="context" start="103" end="112">
async fn should_make_payment() {
let authorize_response = CONNECTOR
.make_payment(
get_default_payment_authorize_data(),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
}
<file_sep path="hyperswitch/crates/router/tests/connectors/trustpay.rs" role="context" start="59" end="71">
fn get_default_payment_authorize_data() -> Option<types::PaymentsAuthorizeData> {
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_number: cards::CardNumber::from_str("4200000000000000").unwrap(),
card_exp_year: Secret::new("25".to_string()),
card_cvc: Secret::new("123".to_string()),
..utils::CCardType::default().0
}),
browser_info: Some(get_default_browser_info()),
router_return_url: Some(String::from("http://localhost:8080")),
..utils::PaymentAuthorizeType::default().0
})
}
<file_sep path="hyperswitch/crates/router/tests/connectors/trustpay.rs" role="context" start="40" end="57">
fn get_default_browser_info() -> BrowserInformation {
BrowserInformation {
color_depth: Some(24),
java_enabled: Some(false),
java_script_enabled: Some(true),
language: Some("en-US".to_string()),
screen_height: Some(1080),
screen_width: Some(1920),
time_zone: Some(3600),
accept_header: Some("*".to_string()),
user_agent: Some("none".to_string()),
ip_address: None,
os_type: None,
os_version: None,
device_model: None,
accept_language: Some("en".to_string()),
}
}
<file_sep path="hyperswitch/crates/router/tests/connectors/trustpay.rs" role="context" start="189" end="208">
async fn should_fail_payment_for_incorrect_card_number() {
let payment_authorize_data = types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_number: cards::CardNumber::from_str("1234567891011").unwrap(),
card_exp_year: Secret::new("25".to_string()),
card_cvc: Secret::new("123".to_string()),
..utils::CCardType::default().0
}),
browser_info: Some(get_default_browser_info()),
..utils::PaymentAuthorizeType::default().0
};
let response = CONNECTOR
.make_payment(Some(payment_authorize_data), get_default_payment_info())
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Errors { code: 61, description: \"invalid payment data (country or brand)\" }".to_string(),
);
}
<file_sep path="hyperswitch/crates/router/tests/macros.rs" role="context" start="17" end="21">
struct Address {
line1: String,
zip: String,
city: String,
}
<file_sep path="hyperswitch/migrations/2025-02-06-111828_drop_int_id_column_accross_database/up.sql" role="context" start="20" end="36">
------------------------ Payment Attempt -----------------------
ALTER TABLE payment_attempt DROP COLUMN id;
------------------------ Payment Methods -----------------------
ALTER TABLE payment_methods DROP COLUMN IF EXISTS id;
------------------------ Address -----------------------
ALTER TABLE address DROP COLUMN IF EXISTS id;
------------------------ Dispute -----------------------
ALTER TABLE dispute DROP COLUMN IF EXISTS id;
------------------------ Mandate -----------------------
ALTER TABLE mandate DROP COLUMN IF EXISTS id;
------------------------ Refund -----------------------
<file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="4244" end="4252">
pub struct Address {
/// Provide the address details
pub address: Option<AddressDetails>,
pub phone: Option<PhoneDetails>,
#[schema(value_type = Option<String>)]
pub email: Option<Email>,
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/iatapay.rs<|crate|> router<|connector|> iatapay anchor=get_default_payment_info kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/tests/connectors/iatapay.rs" role="context" start="57" end="84">
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()
})
}
<file_sep path="hyperswitch/crates/router/tests/connectors/iatapay.rs" role="context" start="56" end="56">
use hyperswitch_domain_models::address::{Address, AddressDetails, PhoneDetails};
use masking::Secret;
use router::types::{self, api, storage::enums, AccessToken};
<file_sep path="hyperswitch/crates/router/tests/connectors/iatapay.rs" role="context" start="99" end="105">
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);
}
<file_sep path="hyperswitch/crates/router/tests/connectors/iatapay.rs" role="context" start="86" end="93">
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
})
}
<file_sep path="hyperswitch/crates/router/tests/connectors/iatapay.rs" role="context" start="40" end="53">
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,
}
}
<file_sep path="hyperswitch/crates/router/tests/connectors/iatapay.rs" role="context" start="35" end="37">
fn get_name(&self) -> String {
"iatapay".to_string()
}
<file_sep path="hyperswitch/crates/router/tests/connectors/iatapay.rs" role="context" start="134" end="151">
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",
);
}
<file_sep path="hyperswitch/crates/router/tests/connectors/iatapay.rs" role="context" start="109" end="130">
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(),
);
}
<file_sep path="hyperswitch/crates/router/tests/macros.rs" role="context" start="17" end="21">
struct Address {
line1: String,
zip: String,
city: String,
}
<file_sep path="hyperswitch/migrations/2025-02-06-111828_drop_int_id_column_accross_database/up.sql" role="context" start="20" end="36">
------------------------ Payment Attempt -----------------------
ALTER TABLE payment_attempt DROP COLUMN id;
------------------------ Payment Methods -----------------------
ALTER TABLE payment_methods DROP COLUMN IF EXISTS id;
------------------------ Address -----------------------
ALTER TABLE address DROP COLUMN IF EXISTS id;
------------------------ Dispute -----------------------
ALTER TABLE dispute DROP COLUMN IF EXISTS id;
------------------------ Mandate -----------------------
ALTER TABLE mandate DROP COLUMN IF EXISTS id;
------------------------ Refund -----------------------
<file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="4244" end="4252">
pub struct Address {
/// Provide the address details
pub address: Option<AddressDetails>,
pub phone: Option<PhoneDetails>,
#[schema(value_type = Option<String>)]
pub email: Option<Email>,
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/compatibility/stripe/setup_intents/types.rs<|crate|> router anchor=from kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/compatibility/stripe/setup_intents/types.rs" role="context" start="511" end="549">
fn from(resp: payments::PaymentsResponse) -> Self {
Self {
object: "setup_intent".to_owned(),
status: StripeSetupStatus::from(resp.status),
client_secret: resp.client_secret,
charges: payment_intent::Charges::new(),
created: resp.created,
customer: resp.customer_id,
metadata: resp.metadata,
id: resp.payment_id,
refunds: resp
.refunds
.map(|a| a.into_iter().map(Into::into).collect()),
mandate_id: resp.mandate_id,
next_action: into_stripe_next_action(resp.next_action, resp.return_url),
last_payment_error: resp.error_code.map(|code| -> LastPaymentError {
LastPaymentError {
charge: None,
code: Some(code.to_owned()),
decline_code: None,
message: resp
.error_message
.unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()),
param: None,
payment_method: StripePaymentMethod {
payment_method_id: "place_holder_id".to_string(),
object: "payment_method",
card: None,
created: u64::try_from(date_time::now().assume_utc().unix_timestamp())
.unwrap_or_default(),
method_type: "card".to_string(),
livemode: false,
},
error_type: code,
}
}),
connector_transaction_id: resp.connector_transaction_id,
}
}
<file_sep path="hyperswitch/crates/router/src/compatibility/stripe/setup_intents/types.rs" role="context" start="510" end="510">
use api_models::payments;
use common_utils::{date_time, ext_traits::StringExt, id_type, pii as secret};
use crate::{
compatibility::stripe::{
payment_intents::types as payment_intent, refunds::types as stripe_refunds,
},
consts,
core::errors,
pii::{self, PeekInterface},
types::{
api::{self as api_types, admin, enums as api_enums},
transformers::{ForeignFrom, ForeignTryFrom},
},
utils::OptionExt,
};
<file_sep path="hyperswitch/crates/router/src/compatibility/stripe/setup_intents/types.rs" role="context" start="576" end="588">
fn try_from(item: StripePaymentListConstraints) -> Result<Self, Self::Error> {
Ok(Self {
customer_id: item.customer,
starting_after: item.starting_after,
ending_before: item.ending_before,
limit: item.limit,
created: from_timestamp_to_datetime(item.created)?,
created_lt: from_timestamp_to_datetime(item.created_lt)?,
created_gt: from_timestamp_to_datetime(item.created_gt)?,
created_lte: from_timestamp_to_datetime(item.created_lte)?,
created_gte: from_timestamp_to_datetime(item.created_gte)?,
})
}
<file_sep path="hyperswitch/crates/router/src/compatibility/stripe/setup_intents/types.rs" role="context" start="570" end="572">
fn default_limit() -> u32 {
10
}
<file_sep path="hyperswitch/crates/router/src/compatibility/stripe/setup_intents/types.rs" role="context" start="400" end="466">
pub(crate) fn into_stripe_next_action(
next_action: Option<payments::NextActionData>,
return_url: Option<String>,
) -> Option<StripeNextAction> {
next_action.map(|next_action_data| match next_action_data {
payments::NextActionData::RedirectToUrl { redirect_to_url } => {
StripeNextAction::RedirectToUrl {
redirect_to_url: RedirectUrl {
return_url,
url: Some(redirect_to_url),
},
}
}
payments::NextActionData::DisplayBankTransferInformation {
bank_transfer_steps_and_charges_details,
} => StripeNextAction::DisplayBankTransferInformation {
bank_transfer_steps_and_charges_details,
},
payments::NextActionData::ThirdPartySdkSessionToken { session_token } => {
StripeNextAction::ThirdPartySdkSessionToken { session_token }
}
payments::NextActionData::QrCodeInformation {
image_data_url,
display_to_timestamp,
qr_code_url,
display_text,
border_color,
} => StripeNextAction::QrCodeInformation {
image_data_url,
display_to_timestamp,
qr_code_url,
display_text,
border_color,
},
payments::NextActionData::FetchQrCodeInformation { qr_code_fetch_url } => {
StripeNextAction::FetchQrCodeInformation { qr_code_fetch_url }
}
payments::NextActionData::DisplayVoucherInformation { voucher_details } => {
StripeNextAction::DisplayVoucherInformation { voucher_details }
}
payments::NextActionData::WaitScreenInformation {
display_from_timestamp,
display_to_timestamp,
} => StripeNextAction::WaitScreenInformation {
display_from_timestamp,
display_to_timestamp,
},
payments::NextActionData::ThreeDsInvoke { .. } => StripeNextAction::RedirectToUrl {
redirect_to_url: RedirectUrl {
return_url: None,
url: None,
},
},
payments::NextActionData::InvokeSdkClient { next_action_data } => {
StripeNextAction::InvokeSdkClient { next_action_data }
}
payments::NextActionData::CollectOtp {
consent_data_required,
} => StripeNextAction::CollectOtp {
consent_data_required,
},
payments::NextActionData::InvokeHiddenIframe { iframe_data } => {
StripeNextAction::InvokeHiddenIframe { iframe_data }
}
})
}
<file_sep path="hyperswitch/crates/router/src/compatibility/stripe/setup_intents/types.rs" role="context" start="347" end="352">
fn from(item: StripePaymentCancelRequest) -> Self {
Self {
cancellation_reason: item.cancellation_reason.map(|c| c.to_string()),
..Self::default()
}
}
<file_sep path="hyperswitch/crates/router/src/compatibility/stripe/setup_intents/types.rs" role="context" start="120" end="127">
fn from(item: StripePaymentMethodDetails) -> Self {
match item {
StripePaymentMethodDetails::Card(card) => Self::Card(payments::Card::from(card)),
StripePaymentMethodDetails::Wallet(wallet) => {
Self::Wallet(payments::WalletData::from(wallet))
}
}
}
<file_sep path="hyperswitch/crates/router/src/compatibility/stripe/setup_intents/types.rs" role="context" start="180" end="294">
fn try_from(item: StripeSetupIntentRequest) -> errors::RouterResult<Self> {
let routable_connector: Option<api_enums::RoutableConnectors> =
item.connector.and_then(|v| v.into_iter().next());
let routing = routable_connector
.map(|connector| {
api_models::routing::RoutingAlgorithm::Single(Box::new(
api_models::routing::RoutableConnectorChoice {
choice_kind: api_models::routing::RoutableChoiceKind::FullStruct,
connector,
merchant_connector_id: None,
},
))
})
.map(|r| {
serde_json::to_value(r)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("converting to routing failed")
})
.transpose()?;
let ip_address = item
.receipt_ipaddress
.map(|ip| std::net::IpAddr::from_str(ip.as_str()))
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "receipt_ipaddress".to_string(),
expected_format: "127.0.0.1".to_string(),
})?;
let metadata_object = item
.metadata
.clone()
.parse_value("metadata")
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "metadata mapping failed",
})?;
let request = Ok(Self {
amount: Some(api_types::Amount::Zero),
capture_method: None,
amount_to_capture: None,
confirm: item.confirm,
customer_id: item.customer,
currency: item
.currency
.as_ref()
.map(|c| c.to_uppercase().parse_enum("currency"))
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "currency",
})?,
email: item.receipt_email,
name: item
.billing_details
.as_ref()
.and_then(|b| b.name.as_ref().map(|x| masking::Secret::new(x.to_owned()))),
phone: item.shipping.as_ref().and_then(|s| s.phone.clone()),
description: item.description,
return_url: item.return_url,
payment_method_data: item.payment_method_data.as_ref().and_then(|pmd| {
pmd.payment_method_details
.as_ref()
.map(|spmd| payments::PaymentMethodDataRequest {
payment_method_data: Some(payments::PaymentMethodData::from(
spmd.to_owned(),
)),
billing: pmd.billing_details.clone().map(payments::Address::from),
})
}),
payment_method: item
.payment_method_data
.as_ref()
.map(|pmd| api_enums::PaymentMethod::from(pmd.stype.to_owned())),
shipping: item
.shipping
.as_ref()
.map(|s| payments::Address::from(s.to_owned())),
billing: item
.billing_details
.as_ref()
.map(|b| payments::Address::from(b.to_owned())),
statement_descriptor_name: item.statement_descriptor,
statement_descriptor_suffix: item.statement_descriptor_suffix,
metadata: metadata_object,
client_secret: item.client_secret.map(|s| s.peek().clone()),
setup_future_usage: item.setup_future_usage,
merchant_connector_details: item.merchant_connector_details,
routing,
authentication_type: match item.payment_method_options {
Some(pmo) => {
let payment_intent::StripePaymentMethodOptions::Card {
request_three_d_secure,
}: payment_intent::StripePaymentMethodOptions = pmo;
Some(api_enums::AuthenticationType::foreign_from(
request_three_d_secure,
))
}
None => None,
},
mandate_data: ForeignTryFrom::foreign_try_from((
item.mandate_data,
item.currency.to_owned(),
))?,
browser_info: Some(
serde_json::to_value(crate::types::BrowserInformation {
ip_address,
user_agent: item.user_agent,
..Default::default()
})
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("convert to browser info failed")?,
),
connector_metadata: item.connector_metadata,
..Default::default()
});
request
}
<file_sep path="hyperswitch/crates/router/src/compatibility/stripe/setup_intents/types.rs" role="context" start="499" end="508">
pub struct StripePaymentMethod {
#[serde(rename = "id")]
payment_method_id: String,
object: &'static str,
card: Option<StripeCard>,
created: u64,
#[serde(rename = "type")]
method_type: String,
livemode: bool,
}
<file_sep path="hyperswitch/crates/router/src/compatibility/stripe/setup_intents/types.rs" role="context" start="487" end="496">
pub struct LastPaymentError {
charge: Option<String>,
code: Option<String>,
decline_code: Option<String>,
message: String,
param: Option<String>,
payment_method: StripePaymentMethod,
#[serde(rename = "type")]
error_type: String,
}
<file_sep path="hyperswitch/crates/router/src/compatibility/stripe/payment_intents/types.rs" role="context" start="591" end="597">
pub struct Charges {
object: &'static str,
data: Vec<String>,
has_more: bool,
total_count: i32,
url: String,
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/relay.rs<|crate|> router anchor=relay kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/relay.rs" role="context" start="222" end="295">
pub async fn relay<T: RelayInterface>(
state: SessionState,
merchant_account: domain::MerchantAccount,
profile_id_optional: Option<id_type::ProfileId>,
key_store: domain::MerchantKeyStore,
req: RelayRequestInner<T>,
) -> RouterResponse<relay_api_models::RelayResponse> {
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
let merchant_id = merchant_account.get_id();
let connector_id = &req.connector_id;
let profile_id_from_auth_layer = profile_id_optional.get_required_value("ProfileId")?;
let profile = db
.find_business_profile_by_merchant_id_profile_id(
key_manager_state,
&key_store,
merchant_id,
&profile_id_from_auth_layer,
)
.await
.change_context(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id_from_auth_layer.get_string_repr().to_owned(),
})?;
#[cfg(feature = "v1")]
let connector_account = db
.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
key_manager_state,
merchant_id,
connector_id,
&key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: connector_id.get_string_repr().to_string(),
})?;
#[cfg(feature = "v2")]
let connector_account = db
.find_merchant_connector_account_by_id(key_manager_state, connector_id, &key_store)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: connector_id.get_string_repr().to_string(),
})?;
T::validate_relay_request(&req.data)?;
let relay_domain = T::get_domain_models(req, merchant_id, profile.get_id());
let relay_record = db
.insert_relay(key_manager_state, &key_store, relay_domain)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to insert a relay record in db")?;
let relay_response =
T::process_relay(&state, merchant_account, connector_account, &relay_record)
.await
.attach_printable("Failed to process relay")?;
let relay_update_record = db
.update_relay(key_manager_state, &key_store, relay_record, relay_response)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let response = T::generate_response(relay_update_record)
.attach_printable("Failed to generate relay response")?;
Ok(hyperswitch_domain_models::api::ApplicationResponse::Json(
response,
))
}
<file_sep path="hyperswitch/crates/router/src/core/relay.rs" role="context" start="221" end="221">
use api_models::relay as relay_api_models;
use common_utils::{
self, fp_utils,
id_type::{self, GenerateId},
};
use hyperswitch_domain_models::relay;
use super::errors::{self, ConnectorErrorExt, RouterResponse, RouterResult, StorageErrorExt};
use crate::{
core::payments,
routes::SessionState,
services,
types::{
api::{self},
domain,
},
utils::OptionExt,
};
<file_sep path="hyperswitch/crates/router/src/core/relay.rs" role="context" start="394" end="398">
fn should_call_connector_for_relay_refund_status(relay: &relay::Relay, force_sync: bool) -> bool {
// This allows refund sync at connector level if force_sync is enabled, or
// check if the refund is in terminal state
!matches!(relay.status, RelayStatus::Failure | RelayStatus::Success) && force_sync
}
<file_sep path="hyperswitch/crates/router/src/core/relay.rs" role="context" start="297" end="392">
pub async fn relay_retrieve(
state: SessionState,
merchant_account: domain::MerchantAccount,
profile_id_optional: Option<id_type::ProfileId>,
key_store: domain::MerchantKeyStore,
req: relay_api_models::RelayRetrieveRequest,
) -> RouterResponse<relay_api_models::RelayResponse> {
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
let merchant_id = merchant_account.get_id();
let relay_id = &req.id;
let profile_id_from_auth_layer = profile_id_optional.get_required_value("ProfileId")?;
db.find_business_profile_by_merchant_id_profile_id(
key_manager_state,
&key_store,
merchant_id,
&profile_id_from_auth_layer,
)
.await
.change_context(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id_from_auth_layer.get_string_repr().to_owned(),
})?;
let relay_record_result = db
.find_relay_by_id(key_manager_state, &key_store, relay_id)
.await;
let relay_record = match relay_record_result {
Err(error) => {
if error.current_context().is_db_not_found() {
Err(error).change_context(errors::ApiErrorResponse::GenericNotFoundError {
message: "relay not found".to_string(),
})?
} else {
Err(error)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("error while fetch relay record")?
}
}
Ok(relay) => relay,
};
#[cfg(feature = "v1")]
let connector_account = db
.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
key_manager_state,
merchant_id,
&relay_record.connector_id,
&key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: relay_record.connector_id.get_string_repr().to_string(),
})?;
#[cfg(feature = "v2")]
let connector_account = db
.find_merchant_connector_account_by_id(
key_manager_state,
&relay_record.connector_id,
&key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: relay_record.connector_id.get_string_repr().to_string(),
})?;
let relay_response = match relay_record.relay_type {
common_enums::RelayType::Refund => {
if should_call_connector_for_relay_refund_status(&relay_record, req.force_sync) {
let relay_response = sync_relay_refund_with_gateway(
&state,
&merchant_account,
&relay_record,
connector_account,
)
.await?;
db.update_relay(key_manager_state, &key_store, relay_record, relay_response)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update the relay record")?
} else {
relay_record
}
}
};
let response = relay_api_models::RelayResponse::from(relay_response);
Ok(hyperswitch_domain_models::api::ApplicationResponse::Json(
response,
))
}
<file_sep path="hyperswitch/crates/router/src/core/relay.rs" role="context" start="200" end="220">
pub async fn relay_flow_decider(
state: SessionState,
merchant_account: domain::MerchantAccount,
profile_id_optional: Option<id_type::ProfileId>,
key_store: domain::MerchantKeyStore,
request: relay_api_models::RelayRequest,
) -> RouterResponse<relay_api_models::RelayResponse> {
let relay_flow_request = match request.relay_type {
common_enums::RelayType::Refund => {
RelayRequestInner::<RelayRefund>::from_relay_request(request)?
}
};
relay(
state,
merchant_account,
profile_id_optional,
key_store,
relay_flow_request,
)
.await
}
<file_sep path="hyperswitch/crates/router/src/core/relay.rs" role="context" start="172" end="197">
fn generate_response(value: relay::Relay) -> RouterResult<api_models::relay::RelayResponse> {
let error = value
.error_code
.zip(value.error_message)
.map(
|(error_code, error_message)| api_models::relay::RelayError {
code: error_code,
message: error_message,
},
);
let data =
api_models::relay::RelayData::from(value.request_data.get_required_value("RelayData")?);
Ok(api_models::relay::RelayResponse {
id: value.id,
status: value.status,
error,
connector_resource_id: value.connector_resource_id,
connector_id: value.connector_id,
profile_id: value.profile_id,
relay_type: value.relay_type,
data: Some(data),
connector_reference_id: value.connector_reference_id,
})
}
<file_sep path="hyperswitch/crates/router/src/core/relay.rs" role="context" start="99" end="122">
fn get_domain_models(
relay_request: RelayRequestInner<Self>,
merchant_id: &id_type::MerchantId,
profile_id: &id_type::ProfileId,
) -> relay::Relay {
let relay_id = id_type::RelayId::generate();
let relay_refund: relay::RelayRefundData = relay_request.data.into();
relay::Relay {
id: relay_id.clone(),
connector_resource_id: relay_request.connector_resource_id.clone(),
connector_id: relay_request.connector_id.clone(),
profile_id: profile_id.clone(),
merchant_id: merchant_id.clone(),
relay_type: common_enums::RelayType::Refund,
request_data: Some(relay::RelayData::Refund(relay_refund)),
status: RelayStatus::Created,
connector_reference_id: None,
error_code: None,
error_message: None,
created_at: common_utils::date_time::now(),
modified_at: common_utils::date_time::now(),
response_data: None,
}
}
<file_sep path="hyperswitch/crates/router/src/core/relay.rs" role="context" start="47" end="52">
fn validate_relay_request(req: &Self::Request) -> RouterResult<()> {
req.validate()
.change_context(errors::ApiErrorResponse::PreconditionFailed {
message: "Invalid relay request".to_string(),
})
}
<file_sep path="hyperswitch/crates/router/src/core/relay.rs" role="context" start="70" end="75">
pub struct RelayRequestInner<T: RelayInterface + ?Sized> {
pub connector_resource_id: String,
pub connector_id: id_type::MerchantConnectorAccountId,
pub relay_type: PhantomData<T>,
pub data: T::Request,
}
<file_sep path="hyperswitch/crates/router/src/core/relay.rs" role="context" start="45" end="68">
pub trait RelayInterface {
type Request: Validate;
fn validate_relay_request(req: &Self::Request) -> RouterResult<()> {
req.validate()
.change_context(errors::ApiErrorResponse::PreconditionFailed {
message: "Invalid relay request".to_string(),
})
}
fn get_domain_models(
relay_request: RelayRequestInner<Self>,
merchant_id: &id_type::MerchantId,
profile_id: &id_type::ProfileId,
) -> relay::Relay;
async fn process_relay(
state: &SessionState,
merchant_account: domain::MerchantAccount,
connector_account: domain::MerchantConnectorAccount,
relay_record: &relay::Relay,
) -> RouterResult<relay::RelayUpdate>;
fn generate_response(value: relay::Relay) -> RouterResult<api_models::relay::RelayResponse>;
}
<file_sep path="hyperswitch/v2_compatible_migrations/2024-08-28-081757_drop_not_null_constraints_on_v1_columns/up.sql" role="context" start="5" end="21">
ALTER COLUMN org_id DROP NOT NULL;
-- Create index on org_id in organization table
-- This is done to mullify the effects of droping primary key for v1
CREATE INDEX idx_organization_org_id ON organization (org_id);
------------------------ Merchant Account -------------------
-- Drop not null in merchant_account table for v1 columns that are dropped in v2
ALTER TABLE merchant_account
DROP CONSTRAINT merchant_account_pkey,
ALTER COLUMN merchant_id DROP NOT NULL,
ALTER COLUMN primary_business_details DROP NOT NULL,
ALTER COLUMN is_recon_enabled DROP NOT NULL;
-- This is done to mullify the effects of droping primary key for v1
CREATE INDEX idx_merchant_account_merchant_id ON merchant_account (merchant_id);
<file_sep path="hyperswitch/crates/api_models/src/errors/types.rs" role="context" start="86" end="100">
pub enum ApiErrorResponse {
Unauthorized(ApiError),
ForbiddenCommonResource(ApiError),
ForbiddenPrivateResource(ApiError),
Conflict(ApiError),
Gone(ApiError),
Unprocessable(ApiError),
InternalServerError(ApiError),
NotImplemented(ApiError),
ConnectorError(ApiError, #[serde(skip_serializing)] StatusCode),
NotFound(ApiError),
MethodNotAllowed(ApiError),
BadRequest(ApiError),
DomainError(ApiError),
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payments/routing.rs<|crate|> router anchor=default kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/payments/routing.rs" role="context" start="122" end="124">
fn default() -> Self {
Self::V1(routing_types::RoutingAlgorithmRef::default())
}
<file_sep path="hyperswitch/crates/router/src/core/payments/routing.rs" role="context" start="121" end="121">
use crate::{
core::{
errors, errors as oss_errors,
routing::{self},
},
logger,
types::{
api::{self, routing as routing_types},
domain, storage as oss_storage,
transformers::{ForeignFrom, ForeignInto, ForeignTryFrom},
},
utils::{OptionExt, ValueExt},
SessionState,
};
<file_sep path="hyperswitch/crates/router/src/core/payments/routing.rs" role="context" start="190" end="299">
pub fn make_dsl_input(
payments_dsl_input: &routing::PaymentsDslInput<'_>,
) -> RoutingResult<dsl_inputs::BackendInput> {
let mandate_data = dsl_inputs::MandateData {
mandate_acceptance_type: payments_dsl_input.setup_mandate.as_ref().and_then(
|mandate_data| {
mandate_data
.customer_acceptance
.as_ref()
.map(|customer_accept| match customer_accept.acceptance_type {
hyperswitch_domain_models::mandates::AcceptanceType::Online => {
euclid_enums::MandateAcceptanceType::Online
}
hyperswitch_domain_models::mandates::AcceptanceType::Offline => {
euclid_enums::MandateAcceptanceType::Offline
}
})
},
),
mandate_type: payments_dsl_input
.setup_mandate
.as_ref()
.and_then(|mandate_data| {
mandate_data
.mandate_type
.clone()
.map(|mandate_type| match mandate_type {
hyperswitch_domain_models::mandates::MandateDataType::SingleUse(_) => {
euclid_enums::MandateType::SingleUse
}
hyperswitch_domain_models::mandates::MandateDataType::MultiUse(_) => {
euclid_enums::MandateType::MultiUse
}
})
}),
payment_type: Some(
if payments_dsl_input
.recurring_details
.as_ref()
.is_some_and(|data| {
matches!(
data,
api_models::mandates::RecurringDetails::ProcessorPaymentToken(_)
)
})
{
euclid_enums::PaymentType::PptMandate
} else {
payments_dsl_input.setup_mandate.map_or_else(
|| euclid_enums::PaymentType::NonMandate,
|_| euclid_enums::PaymentType::SetupMandate,
)
},
),
};
let payment_method_input = dsl_inputs::PaymentMethodInput {
payment_method: Some(payments_dsl_input.payment_attempt.payment_method_type),
payment_method_type: Some(payments_dsl_input.payment_attempt.payment_method_subtype),
card_network: payments_dsl_input
.payment_method_data
.as_ref()
.and_then(|pm_data| match pm_data {
domain::PaymentMethodData::Card(card) => card.card_network.clone(),
_ => None,
}),
};
let payment_input = dsl_inputs::PaymentInput {
amount: payments_dsl_input
.payment_attempt
.amount_details
.get_net_amount(),
card_bin: payments_dsl_input.payment_method_data.as_ref().and_then(
|pm_data| match pm_data {
domain::PaymentMethodData::Card(card) => Some(card.card_number.get_card_isin()),
_ => None,
},
),
currency: payments_dsl_input.currency,
authentication_type: Some(payments_dsl_input.payment_attempt.authentication_type),
capture_method: Some(payments_dsl_input.payment_intent.capture_method),
business_country: None,
billing_country: payments_dsl_input
.address
.get_payment_method_billing()
.and_then(|billing_address| billing_address.address.as_ref())
.and_then(|address_details| address_details.country)
.map(api_enums::Country::from_alpha2),
business_label: None,
setup_future_usage: Some(payments_dsl_input.payment_intent.setup_future_usage),
};
let metadata = payments_dsl_input
.payment_intent
.metadata
.clone()
.map(|value| value.parse_value("routing_parameters"))
.transpose()
.change_context(errors::RoutingError::MetadataParsingError)
.attach_printable("Unable to parse routing_parameters from metadata of payment_intent")
.unwrap_or(None);
Ok(dsl_inputs::BackendInput {
metadata,
payment: payment_input,
payment_method: payment_method_input,
mandate: mandate_data,
})
}
<file_sep path="hyperswitch/crates/router/src/core/payments/routing.rs" role="context" start="135" end="187">
pub fn make_dsl_input_for_payouts(
payout_data: &payouts::PayoutData,
) -> RoutingResult<dsl_inputs::BackendInput> {
let mandate = dsl_inputs::MandateData {
mandate_acceptance_type: None,
mandate_type: None,
payment_type: None,
};
let metadata = payout_data
.payouts
.metadata
.clone()
.map(|val| val.parse_value("routing_parameters"))
.transpose()
.change_context(errors::RoutingError::MetadataParsingError)
.attach_printable("Unable to parse routing_parameters from metadata of payouts")
.unwrap_or(None);
let payment = dsl_inputs::PaymentInput {
amount: payout_data.payouts.amount,
card_bin: None,
currency: payout_data.payouts.destination_currency,
authentication_type: None,
capture_method: None,
business_country: payout_data
.payout_attempt
.business_country
.map(api_enums::Country::from_alpha2),
billing_country: payout_data
.billing_address
.as_ref()
.and_then(|bic| bic.country)
.map(api_enums::Country::from_alpha2),
business_label: payout_data.payout_attempt.business_label.clone(),
setup_future_usage: None,
};
let payment_method = dsl_inputs::PaymentMethodInput {
payment_method: payout_data
.payouts
.payout_type
.map(api_enums::PaymentMethod::foreign_from),
payment_method_type: payout_data
.payout_method_data
.as_ref()
.map(api_enums::PaymentMethodType::foreign_from),
card_network: None,
};
Ok(dsl_inputs::BackendInput {
mandate,
metadata,
payment,
payment_method,
})
}
<file_sep path="hyperswitch/crates/router/src/core/payments/routing.rs" role="context" start="1658" end="1805">
pub async fn perform_contract_based_routing(
state: &SessionState,
routable_connectors: Vec<api_routing::RoutableConnectorChoice>,
profile_id: &common_utils::id_type::ProfileId,
_dynamic_routing_config_params_interpolator: routing::helpers::DynamicRoutingConfigParamsInterpolator,
contract_based_algo_ref: api_routing::ContractRoutingAlgorithm,
) -> RoutingResult<Vec<api_routing::RoutableConnectorChoice>> {
if contract_based_algo_ref.enabled_feature
== api_routing::DynamicRoutingFeatures::DynamicConnectorSelection
{
logger::debug!(
"performing contract_based_routing for profile {}",
profile_id.get_string_repr()
);
let client = state
.grpc_client
.dynamic_routing
.contract_based_client
.as_ref()
.ok_or(errors::RoutingError::ContractRoutingClientInitializationError)
.attach_printable("contract routing gRPC client not found")?;
let contract_based_routing_configs = routing::helpers::fetch_dynamic_routing_configs::<
api_routing::ContractBasedRoutingConfig,
>(
state,
profile_id,
contract_based_algo_ref
.algorithm_id_with_timestamp
.algorithm_id
.ok_or(errors::RoutingError::GenericNotFoundError {
field: "contract_based_routing_algorithm_id".to_string(),
})
.attach_printable("contract_based_routing_algorithm_id not found in profile_id")?,
)
.await
.change_context(errors::RoutingError::ContractBasedRoutingConfigError)
.attach_printable("unable to fetch contract based dynamic routing configs")?;
let label_info = contract_based_routing_configs
.label_info
.clone()
.ok_or(errors::RoutingError::ContractBasedRoutingConfigError)
.attach_printable("Label information not found in contract routing configs")?;
let contract_based_connectors = routable_connectors
.clone()
.into_iter()
.filter(|conn| {
label_info
.iter()
.any(|info| Some(info.mca_id.clone()) == conn.merchant_connector_id.clone())
})
.collect::<Vec<_>>();
let mut other_connectors = routable_connectors
.into_iter()
.filter(|conn| {
label_info
.iter()
.all(|info| Some(info.mca_id.clone()) != conn.merchant_connector_id.clone())
})
.collect::<Vec<_>>();
let contract_based_connectors_result = client
.calculate_contract_score(
profile_id.get_string_repr().into(),
contract_based_routing_configs.clone(),
"".to_string(),
contract_based_connectors,
state.get_grpc_headers(),
)
.await
.attach_printable(
"unable to calculate/fetch contract score from dynamic routing service",
);
let contract_based_connectors = match contract_based_connectors_result {
Ok(resp) => resp,
Err(err) => match err.current_context() {
DynamicRoutingError::ContractNotFound => {
client
.update_contracts(
profile_id.get_string_repr().into(),
label_info,
"".to_string(),
vec![],
u64::default(),
state.get_grpc_headers(),
)
.await
.change_context(errors::RoutingError::ContractScoreUpdationError)
.attach_printable(
"unable to update contract based routing window in dynamic routing service",
)?;
return Err((errors::RoutingError::ContractScoreCalculationError {
err: err.to_string(),
})
.into());
}
_ => {
return Err((errors::RoutingError::ContractScoreCalculationError {
err: err.to_string(),
})
.into())
}
},
};
let mut connectors = Vec::with_capacity(contract_based_connectors.labels_with_score.len());
for label_with_score in contract_based_connectors.labels_with_score {
let (connector, merchant_connector_id) = label_with_score.label
.split_once(':')
.ok_or(errors::RoutingError::InvalidContractBasedConnectorLabel(label_with_score.label.to_string()))
.attach_printable(
"unable to split connector_name and mca_id from the label obtained by the dynamic routing service",
)?;
connectors.push(api_routing::RoutableConnectorChoice {
choice_kind: api_routing::RoutableChoiceKind::FullStruct,
connector: common_enums::RoutableConnectors::from_str(connector)
.change_context(errors::RoutingError::GenericConversionError {
from: "String".to_string(),
to: "RoutableConnectors".to_string(),
})
.attach_printable("unable to convert String to RoutableConnectors")?,
merchant_connector_id: Some(
common_utils::id_type::MerchantConnectorAccountId::wrap(
merchant_connector_id.to_string(),
)
.change_context(errors::RoutingError::GenericConversionError {
from: "String".to_string(),
to: "MerchantConnectorAccountId".to_string(),
})
.attach_printable("unable to convert MerchantConnectorAccountId from string")?,
),
});
}
connectors.append(&mut other_connectors);
logger::debug!(contract_based_routing_connectors=?connectors);
Ok(connectors)
} else {
Ok(routable_connectors)
}
}
<file_sep path="hyperswitch/crates/router/src/core/payments/routing.rs" role="context" start="978" end="1104">
pub async fn perform_session_flow_routing<'a>(
state: &'a SessionState,
key_store: &'a domain::MerchantKeyStore,
session_input: SessionFlowRoutingInput<'_>,
business_profile: &domain::Profile,
transaction_type: &api_enums::TransactionType,
) -> RoutingResult<FxHashMap<api_enums::PaymentMethodType, Vec<routing_types::SessionRoutingChoice>>>
{
let mut pm_type_map: FxHashMap<api_enums::PaymentMethodType, FxHashMap<String, api::GetToken>> =
FxHashMap::default();
let profile_id = business_profile.get_id().clone();
let routing_algorithm =
MerchantAccountRoutingAlgorithm::V1(business_profile.routing_algorithm_id.clone());
let payment_method_input = dsl_inputs::PaymentMethodInput {
payment_method: None,
payment_method_type: None,
card_network: None,
};
let payment_input = dsl_inputs::PaymentInput {
amount: session_input
.payment_intent
.amount_details
.calculate_net_amount(),
currency: session_input.payment_intent.amount_details.currency,
authentication_type: session_input.payment_intent.authentication_type,
card_bin: None,
capture_method: Option::<euclid_enums::CaptureMethod>::foreign_from(
session_input.payment_intent.capture_method,
),
// business_country not available in payment_intent anymore
business_country: None,
billing_country: session_input
.country
.map(storage_enums::Country::from_alpha2),
// business_label not available in payment_intent anymore
business_label: None,
setup_future_usage: Some(session_input.payment_intent.setup_future_usage),
};
let metadata = session_input
.payment_intent
.parse_and_get_metadata("routing_parameters")
.change_context(errors::RoutingError::MetadataParsingError)
.attach_printable("Unable to parse routing_parameters from metadata of payment_intent")
.unwrap_or(None);
let mut backend_input = dsl_inputs::BackendInput {
metadata,
payment: payment_input,
payment_method: payment_method_input,
mandate: dsl_inputs::MandateData {
mandate_acceptance_type: None,
mandate_type: None,
payment_type: None,
},
};
for connector_data in session_input.chosen.iter() {
pm_type_map
.entry(connector_data.payment_method_sub_type)
.or_default()
.insert(
connector_data.connector.connector_name.to_string(),
connector_data.connector.get_token.clone(),
);
}
let mut result: FxHashMap<
api_enums::PaymentMethodType,
Vec<routing_types::SessionRoutingChoice>,
> = FxHashMap::default();
for (pm_type, allowed_connectors) in pm_type_map {
let euclid_pmt: euclid_enums::PaymentMethodType = pm_type;
let euclid_pm: euclid_enums::PaymentMethod = euclid_pmt.into();
backend_input.payment_method.payment_method = Some(euclid_pm);
backend_input.payment_method.payment_method_type = Some(euclid_pmt);
let session_pm_input = SessionRoutingPmTypeInput {
routing_algorithm: &routing_algorithm,
backend_input: backend_input.clone(),
allowed_connectors,
profile_id: &profile_id,
};
let routable_connector_choice_option = perform_session_routing_for_pm_type(
state,
key_store,
&session_pm_input,
transaction_type,
business_profile,
)
.await?;
if let Some(routable_connector_choice) = routable_connector_choice_option {
let mut session_routing_choice: Vec<routing_types::SessionRoutingChoice> = Vec::new();
for selection in routable_connector_choice {
let connector_name = selection.connector.to_string();
if let Some(get_token) = session_pm_input.allowed_connectors.get(&connector_name) {
let connector_data = api::ConnectorData::get_connector_by_name(
&state.clone().conf.connectors,
&connector_name,
get_token.clone(),
selection.merchant_connector_id,
)
.change_context(errors::RoutingError::InvalidConnectorName(connector_name))?;
session_routing_choice.push(routing_types::SessionRoutingChoice {
connector: connector_data,
payment_method_type: pm_type,
});
}
}
if !session_routing_choice.is_empty() {
result.insert(pm_type, session_routing_choice);
}
}
}
Ok(result)
}
<file_sep path="hyperswitch/crates/api_models/src/routing.rs" role="context" start="443" end="448">
pub struct RoutingAlgorithmRef {
pub algorithm_id: Option<common_utils::id_type::RoutingId>,
pub timestamp: i64,
pub config_algo_id: Option<String>,
pub surcharge_config_algo_id: Option<String>,
}
<file_sep path="hyperswitch/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/event.test.js" role="context" start="61" end="78">
"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.",
);
}
// Response body should have value "succeeded" for "status"
if (jsonData?.status) {
pm.test(
"[POST]::/payments - Content check if value for 'status' matches 'succeeded'",
function () {
pm.expect(jsonData.status).to.eql("succeeded");
},
);
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payments/types.rs<|crate|> router anchor=new kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/payments/types.rs" role="context" start="248" end="253">
pub fn new(payment_attempt_id: String) -> Self {
Self {
surcharge_results: HashMap::new(),
payment_attempt_id,
}
}
<file_sep path="hyperswitch/crates/router/src/core/payments/types.rs" role="context" start="247" end="247">
use std::{collections::HashMap, num::TryFromIntError};
pub use hyperswitch_domain_models::router_request_types::{
AuthenticationData, SplitRefundsRequest, StripeSplitRefund, SurchargeDetails,
};
<file_sep path="hyperswitch/crates/router/src/core/payments/types.rs" role="context" start="257" end="259">
pub fn get_surcharge_results_size(&self) -> usize {
self.surcharge_results.len()
}
<file_sep path="hyperswitch/crates/router/src/core/payments/types.rs" role="context" start="254" end="256">
pub fn is_empty_result(&self) -> bool {
self.surcharge_results.is_empty()
}
<file_sep path="hyperswitch/crates/router/src/core/payments/types.rs" role="context" start="206" end="228">
fn foreign_try_from(
(surcharge_details, payment_attempt): (&SurchargeDetails, &PaymentAttempt),
) -> Result<Self, Self::Error> {
let currency = payment_attempt.currency.unwrap_or_default();
let display_surcharge_amount = currency
.to_currency_base_unit_asf64(surcharge_details.surcharge_amount.get_amount_as_i64())?;
let display_tax_on_surcharge_amount = currency.to_currency_base_unit_asf64(
surcharge_details
.tax_on_surcharge_amount
.get_amount_as_i64(),
)?;
let display_total_surcharge_amount = currency.to_currency_base_unit_asf64(
(surcharge_details.surcharge_amount + surcharge_details.tax_on_surcharge_amount)
.get_amount_as_i64(),
)?;
Ok(Self {
surcharge: surcharge_details.surcharge.clone().into(),
tax_on_surcharge: surcharge_details.tax_on_surcharge.clone().map(Into::into),
display_surcharge_amount,
display_tax_on_surcharge_amount,
display_total_surcharge_amount,
})
}
<file_sep path="hyperswitch/crates/router/src/core/payments/types.rs" role="context" start="196" end="200">
fn foreign_try_from(
(surcharge_details, payment_attempt): (&SurchargeDetails, &PaymentAttempt),
) -> Result<Self, Self::Error> {
todo!()
}
<file_sep path="hyperswitch/crates/router/src/core/payments/types.rs" role="context" start="116" end="131">
pub fn get_status_count(&self) -> HashMap<storage_enums::CaptureStatus, i16> {
let mut hash_map: HashMap<storage_enums::CaptureStatus, i16> = HashMap::new();
hash_map.insert(storage_enums::CaptureStatus::Charged, 0);
hash_map.insert(storage_enums::CaptureStatus::Pending, 0);
hash_map.insert(storage_enums::CaptureStatus::Started, 0);
hash_map.insert(storage_enums::CaptureStatus::Failed, 0);
self.all_captures
.iter()
.fold(hash_map, |mut accumulator, capture| {
let current_capture_status = capture.1.status;
accumulator
.entry(current_capture_status)
.and_modify(|count| *count += 1);
accumulator
})
}
<file_sep path="hyperswitch/crates/router/src/core/payments/types.rs" role="context" start="85" end="97">
pub fn get_total_blocked_amount(&self) -> common_types::MinorUnit {
self.all_captures
.iter()
.fold(common_types::MinorUnit::new(0), |accumulator, capture| {
accumulator
+ match capture.1.status {
storage_enums::CaptureStatus::Charged
| storage_enums::CaptureStatus::Pending => capture.1.amount,
storage_enums::CaptureStatus::Started
| storage_enums::CaptureStatus::Failed => common_types::MinorUnit::new(0),
}
})
}
<file_sep path="hyperswitch/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/event.test.js" role="context" start="61" end="78">
"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.",
);
}
// Response body should have value "succeeded" for "status"
if (jsonData?.status) {
pm.test(
"[POST]::/payments - Content check if value for 'status' matches 'succeeded'",
function () {
pm.expect(jsonData.status).to.eql("succeeded");
},
);
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/utils.rs<|crate|> router anchor=get_connector_request_reference_id kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/utils.rs" role="context" start="1430" end="1436">
pub fn get_connector_request_reference_id(
conf: &Settings,
merchant_id: &common_utils::id_type::MerchantId,
payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt,
) -> String {
todo!()
}
<file_sep path="hyperswitch/crates/router/src/core/utils.rs" role="context" start="1429" end="1429">
use common_utils::{crypto::Encryptable, pii::Email};
use common_utils::{
errors::CustomResult,
ext_traits::AsyncExt,
types::{keymanager::KeyManagerState, ConnectorTransactionIdTrait, MinorUnit},
};
use hyperswitch_domain_models::{
merchant_connector_account::MerchantConnectorAccount, payment_address::PaymentAddress,
router_data::ErrorResponse, router_request_types, types::OrderDetailsWithAmount,
};
use super::payments::helpers;
use crate::core::payments;
use crate::{
configs::Settings,
consts,
core::{
errors::{self, RouterResult, StorageErrorExt},
payments::PaymentData,
},
db::StorageInterface,
routes::SessionState,
types::{
self, api, domain,
storage::{self, enums},
PollConfig,
},
utils::{generate_id, generate_uuid, OptionExt, ValueExt},
};
<file_sep path="hyperswitch/crates/router/src/core/utils.rs" role="context" start="1474" end="1479">
fn connector_needs_business_sub_label(connector_name: &str) -> bool {
let connectors_list = [api_models::enums::Connector::Cybersource];
connectors_list
.map(|connector| connector.to_string())
.contains(&connector_name.to_string())
}
<file_sep path="hyperswitch/crates/router/src/core/utils.rs" role="context" start="1439" end="1472">
pub async fn validate_and_get_business_profile(
db: &dyn StorageInterface,
key_manager_state: &KeyManagerState,
merchant_key_store: &domain::MerchantKeyStore,
profile_id: Option<&common_utils::id_type::ProfileId>,
merchant_id: &common_utils::id_type::MerchantId,
) -> RouterResult<Option<domain::Profile>> {
profile_id
.async_map(|profile_id| async {
db.find_business_profile_by_profile_id(
key_manager_state,
merchant_key_store,
profile_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})
})
.await
.transpose()?
.map(|business_profile| {
// Check if the merchant_id of business profile is same as the current merchant_id
if business_profile.merchant_id.ne(merchant_id) {
Err(errors::ApiErrorResponse::AccessForbidden {
resource: business_profile.get_id().get_string_repr().to_owned(),
}
.into())
} else {
Ok(business_profile)
}
})
.transpose()
}
<file_sep path="hyperswitch/crates/router/src/core/utils.rs" role="context" start="1413" end="1426">
pub fn get_connector_request_reference_id(
conf: &Settings,
merchant_id: &common_utils::id_type::MerchantId,
payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt,
) -> String {
let is_config_enabled_for_merchant =
is_merchant_enabled_for_payment_id_as_connector_request_id(conf, merchant_id);
// Send payment_id if config is enabled for a merchant, else send attempt_id
if is_config_enabled_for_merchant {
payment_attempt.payment_id.get_string_repr().to_owned()
} else {
payment_attempt.attempt_id.to_owned()
}
}
<file_sep path="hyperswitch/crates/router/src/core/utils.rs" role="context" start="1402" end="1410">
pub fn is_merchant_enabled_for_payment_id_as_connector_request_id(
conf: &Settings,
merchant_id: &common_utils::id_type::MerchantId,
) -> bool {
let config_map = &conf
.connector_request_reference_id_config
.merchant_ids_send_payment_id_as_connector_request_id;
config_map.contains(merchant_id)
}
<file_sep path="hyperswitch/crates/router/src/core/utils.rs" role="context" start="1208" end="1305">
pub async fn construct_defend_dispute_router_data<'a>(
state: &'a SessionState,
payment_intent: &'a storage::PaymentIntent,
payment_attempt: &storage::PaymentAttempt,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
dispute: &storage::Dispute,
) -> RouterResult<types::DefendDisputeRouterData> {
let _db = &*state.store;
let connector_id = &dispute.connector;
let profile_id = payment_intent
.profile_id
.as_ref()
.get_required_value("profile_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("profile_id is not set in payment_intent")?
.clone();
let merchant_connector_account = helpers::get_merchant_connector_account(
state,
merchant_account.get_id(),
None,
key_store,
&profile_id,
connector_id,
payment_attempt.merchant_connector_id.as_ref(),
)
.await?;
let test_mode: Option<bool> = merchant_connector_account.is_test_mode_on();
let auth_type: types::ConnectorAuthType = merchant_connector_account
.get_connector_account_details()
.parse_value("ConnectorAuthType")
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let payment_method = payment_attempt
.payment_method
.get_required_value("payment_method_type")?;
let router_data = types::RouterData {
flow: PhantomData,
merchant_id: merchant_account.get_id().clone(),
connector: connector_id.to_string(),
payment_id: payment_attempt.payment_id.get_string_repr().to_owned(),
tenant_id: state.tenant.tenant_id.clone(),
attempt_id: payment_attempt.attempt_id.clone(),
status: payment_attempt.status,
payment_method,
connector_auth_type: auth_type,
description: None,
address: PaymentAddress::default(),
auth_type: payment_attempt.authentication_type.unwrap_or_default(),
connector_meta_data: merchant_connector_account.get_metadata(),
connector_wallets_details: merchant_connector_account.get_connector_wallets_details(),
amount_captured: payment_intent
.amount_captured
.map(|amt| amt.get_amount_as_i64()),
minor_amount_captured: payment_intent.amount_captured,
payment_method_status: None,
request: types::DefendDisputeRequestData {
dispute_id: dispute.dispute_id.clone(),
connector_dispute_id: dispute.connector_dispute_id.clone(),
},
response: Err(ErrorResponse::get_not_implemented()),
access_token: None,
session_token: None,
reference_id: None,
payment_method_token: None,
customer_id: None,
connector_customer: None,
recurring_mandate_payment_data: None,
preprocessing_id: None,
payment_method_balance: None,
connector_request_reference_id: get_connector_request_reference_id(
&state.conf,
merchant_account.get_id(),
payment_attempt,
),
#[cfg(feature = "payouts")]
payout_method_data: None,
#[cfg(feature = "payouts")]
quote_id: None,
test_mode,
connector_api_version: None,
connector_http_status_code: None,
external_latency: None,
apple_pay_flow: None,
frm_metadata: None,
refund_id: None,
dispute_id: Some(dispute.dispute_id.clone()),
connector_response: None,
integrity_check: Ok(()),
additional_merchant_data: None,
header_payload: None,
connector_mandate_request_reference_id: None,
authentication_id: None,
psd2_sca_exemption_type: None,
};
Ok(router_data)
}
<file_sep path="hyperswitch/crates/router/src/core/utils.rs" role="context" start="981" end="1080">
pub async fn construct_upload_file_router_data<'a>(
state: &'a SessionState,
payment_intent: &'a storage::PaymentIntent,
payment_attempt: &storage::PaymentAttempt,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
create_file_request: &api::CreateFileRequest,
connector_id: &str,
file_key: String,
) -> RouterResult<types::UploadFileRouterData> {
let profile_id = payment_intent
.profile_id
.as_ref()
.get_required_value("profile_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("profile_id is not set in payment_intent")?
.clone();
let merchant_connector_account = helpers::get_merchant_connector_account(
state,
merchant_account.get_id(),
None,
key_store,
&profile_id,
connector_id,
payment_attempt.merchant_connector_id.as_ref(),
)
.await?;
let test_mode: Option<bool> = merchant_connector_account.is_test_mode_on();
let auth_type: types::ConnectorAuthType = merchant_connector_account
.get_connector_account_details()
.parse_value("ConnectorAuthType")
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let payment_method = payment_attempt
.payment_method
.get_required_value("payment_method_type")?;
let router_data = types::RouterData {
flow: PhantomData,
merchant_id: merchant_account.get_id().clone(),
connector: connector_id.to_string(),
payment_id: payment_attempt.payment_id.get_string_repr().to_owned(),
tenant_id: state.tenant.tenant_id.clone(),
attempt_id: payment_attempt.attempt_id.clone(),
status: payment_attempt.status,
payment_method,
connector_auth_type: auth_type,
description: None,
address: PaymentAddress::default(),
auth_type: payment_attempt.authentication_type.unwrap_or_default(),
connector_meta_data: merchant_connector_account.get_metadata(),
connector_wallets_details: merchant_connector_account.get_connector_wallets_details(),
amount_captured: payment_intent
.amount_captured
.map(|amt| amt.get_amount_as_i64()),
minor_amount_captured: payment_intent.amount_captured,
payment_method_status: None,
request: types::UploadFileRequestData {
file_key,
file: create_file_request.file.clone(),
file_type: create_file_request.file_type.clone(),
file_size: create_file_request.file_size,
},
response: Err(ErrorResponse::default()),
access_token: None,
session_token: None,
reference_id: None,
payment_method_token: None,
connector_customer: None,
customer_id: None,
recurring_mandate_payment_data: None,
preprocessing_id: None,
payment_method_balance: None,
connector_request_reference_id: get_connector_request_reference_id(
&state.conf,
merchant_account.get_id(),
payment_attempt,
),
#[cfg(feature = "payouts")]
payout_method_data: None,
#[cfg(feature = "payouts")]
quote_id: None,
test_mode,
connector_api_version: None,
connector_http_status_code: None,
external_latency: None,
apple_pay_flow: None,
frm_metadata: None,
refund_id: None,
dispute_id: None,
connector_response: None,
integrity_check: Ok(()),
additional_merchant_data: None,
header_payload: None,
connector_mandate_request_reference_id: None,
authentication_id: None,
psd2_sca_exemption_type: None,
};
Ok(router_data)
}
<file_sep path="hyperswitch/crates/router/src/configs.rs" role="context" start="8" end="8">
pub type Settings = settings::Settings<RawSecret>;
<file_sep path="hyperswitch/v2_compatible_migrations/2024-08-28-081721_add_v2_columns/up.sql" role="context" start="37" end="53">
ADD COLUMN frm_merchant_decision VARCHAR(64),
ADD COLUMN statement_descriptor VARCHAR(255),
ADD COLUMN enable_payment_link BOOLEAN,
ADD COLUMN apply_mit_exemption BOOLEAN,
ADD COLUMN customer_present BOOLEAN,
ADD COLUMN routing_algorithm_id VARCHAR(64),
ADD COLUMN payment_link_config JSONB;
ALTER TABLE payment_attempt
ADD COLUMN payment_method_type_v2 VARCHAR,
ADD COLUMN connector_payment_id VARCHAR(128),
ADD COLUMN payment_method_subtype VARCHAR(64),
ADD COLUMN routing_result JSONB,
ADD COLUMN authentication_applied "AuthenticationType",
ADD COLUMN external_reference_id VARCHAR(128),
ADD COLUMN tax_on_surcharge BIGINT,
ADD COLUMN payment_method_billing_address BYTEA,
<file_sep path="hyperswitch/crates/api_models/src/user/theme.rs" role="context" start="63" end="70">
struct Settings {
colors: Colors,
sidebar: Option<Sidebar>,
typography: Option<Typography>,
buttons: Buttons,
borders: Option<Borders>,
spacing: Option<Spacing>,
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/api_keys.rs<|crate|> router anchor=generate_task_id_for_api_key_expiry_workflow kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/api_keys.rs" role="context" start="534" end="541">
fn generate_task_id_for_api_key_expiry_workflow(
key_id: &common_utils::id_type::ApiKeyId,
) -> String {
format!(
"{API_KEY_EXPIRY_RUNNER}_{API_KEY_EXPIRY_NAME}_{}",
key_id.get_string_repr()
)
}
<file_sep path="hyperswitch/crates/router/src/core/api_keys.rs" role="context" start="533" end="533">
use common_utils::date_time;
<file_sep path="hyperswitch/crates/router/src/core/api_keys.rs" role="context" start="550" end="552">
fn from(s: String) -> Self {
Self(s.into())
}
<file_sep path="hyperswitch/crates/router/src/core/api_keys.rs" role="context" start="544" end="546">
fn from(s: &str) -> Self {
Self(s.to_owned().into())
}
<file_sep path="hyperswitch/crates/router/src/core/api_keys.rs" role="context" start="513" end="531">
pub async fn list_api_keys(
state: SessionState,
merchant_id: common_utils::id_type::MerchantId,
limit: Option<i64>,
offset: Option<i64>,
) -> RouterResponse<Vec<api::RetrieveApiKeyResponse>> {
let store = state.store.as_ref();
let api_keys = store
.list_api_keys_by_merchant_id(&merchant_id, limit, offset)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to list merchant API keys")?;
let api_keys = api_keys
.into_iter()
.map(ForeignInto::foreign_into)
.collect();
Ok(ApplicationResponse::Json(api_keys))
}
<file_sep path="hyperswitch/crates/router/src/core/api_keys.rs" role="context" start="493" end="510">
pub async fn revoke_api_key_expiry_task(
store: &dyn crate::db::StorageInterface,
key_id: &common_utils::id_type::ApiKeyId,
) -> Result<(), errors::ProcessTrackerError> {
let task_id = generate_task_id_for_api_key_expiry_workflow(key_id);
let task_ids = vec![task_id];
let updated_process_tracker_data = storage::ProcessTrackerUpdate::StatusUpdate {
status: storage_enums::ProcessTrackerStatus::Finish,
business_status: Some(String::from(diesel_models::business_status::REVOKED)),
};
store
.process_tracker_update_process_status_by_ids(task_ids, updated_process_tracker_data)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?;
Ok(())
}
<file_sep path="hyperswitch/crates/router/src/core/api_keys.rs" role="context" start="366" end="423">
pub async fn update_api_key_expiry_task(
store: &dyn crate::db::StorageInterface,
api_key: &ApiKey,
expiry_reminder_days: Vec<u8>,
) -> Result<(), errors::ProcessTrackerError> {
let current_time = date_time::now();
let schedule_time = expiry_reminder_days
.first()
.and_then(|expiry_reminder_day| {
api_key.expires_at.map(|expires_at| {
expires_at.saturating_sub(time::Duration::days(i64::from(*expiry_reminder_day)))
})
});
if let Some(schedule_time) = schedule_time {
if schedule_time <= current_time {
return Ok(());
}
}
let task_id = generate_task_id_for_api_key_expiry_workflow(&api_key.key_id);
let task_ids = vec![task_id.clone()];
let updated_tracking_data = &storage::ApiKeyExpiryTrackingData {
key_id: api_key.key_id.clone(),
merchant_id: api_key.merchant_id.clone(),
api_key_name: api_key.name.clone(),
prefix: api_key.prefix.clone(),
api_key_expiry: api_key.expires_at,
expiry_reminder_days,
};
let updated_api_key_expiry_workflow_model = serde_json::to_value(updated_tracking_data)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| {
format!("unable to serialize API key expiry tracker: {updated_tracking_data:?}")
})?;
let updated_process_tracker_data = storage::ProcessTrackerUpdate::Update {
name: None,
retry_count: Some(0),
schedule_time,
tracking_data: Some(updated_api_key_expiry_workflow_model),
business_status: Some(String::from(
diesel_models::process_tracker::business_status::PENDING,
)),
status: Some(storage_enums::ProcessTrackerStatus::New),
updated_at: Some(current_time),
};
store
.process_tracker_update_process_status_by_ids(task_ids, updated_process_tracker_data)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?;
Ok(())
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payment_methods/cards.rs<|crate|> router anchor=delete_card_from_locker kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="2513" end="2538">
pub async fn delete_card_from_locker(
state: &routes::SessionState,
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(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")
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="2512" end="2512">
);
})
},
&metrics::CARD_GET_TIME,
router_env::metric_attributes!(("locker", "rust")),
)
.await?;
logger::debug!("card retrieved from rust locker");
Ok(get_card_from_rs_locker_resp)
}
pub async fn delete_card_from_locker(
state: &routes::SessionState,
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(state, customer_id, merchant_id, card_reference)
.await
.inspect_err(|_| {
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="2550" end="2591">
pub async fn add_card_hs(
state: &routes::SessionState,
req: api::PaymentMethodCreate,
card: &api::CardDetail,
customer_id: &id_type::CustomerId,
merchant_account: &domain::MerchantAccount,
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: 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: state.conf.locker.ttl_for_storage_in_secs,
});
let store_card_payload =
add_card_to_hs_locker(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,
merchant_account.get_id(),
);
Ok((payment_method_resp, store_card_payload.duplication_check))
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="2541" end="2547">
pub async fn delete_card_by_locker_id(
state: &routes::SessionState,
id: &id_type::GlobalCustomerId,
merchant_id: &id_type::MerchantId,
) -> errors::RouterResult<payment_methods::DeleteCardResp> {
todo!()
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="2477" end="2511">
pub async fn get_card_from_locker(
state: &routes::SessionState,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
card_reference: &str,
) -> errors::RouterResult<Card> {
metrics::GET_FROM_LOCKER.add(1, &[]);
let get_card_from_rs_locker_resp = common_utils::metrics::utils::record_operation_time(
async {
get_card_from_hs_locker(
state,
customer_id,
merchant_id,
card_reference,
api_enums::LockerChoice::HyperswitchCardVault,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while getting card from hyperswitch card vault")
.inspect_err(|_| {
metrics::CARD_LOCKER_FAILURES.add(
1,
router_env::metric_attributes!(("locker", "rust"), ("operation", "get")),
);
})
},
&metrics::CARD_GET_TIME,
router_env::metric_attributes!(("locker", "rust")),
)
.await?;
logger::debug!("card retrieved from rust locker");
Ok(get_card_from_rs_locker_resp)
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="2434" end="2475">
pub async fn add_card_to_locker(
state: &routes::SessionState,
req: api::PaymentMethodCreate,
card: &api::CardDetail,
customer_id: &id_type::CustomerId,
merchant_account: &domain::MerchantAccount,
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 {
add_card_hs(
state,
req.clone(),
card,
customer_id,
merchant_account,
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)
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="1454" end="1705">
pub async fn add_payment_method(
state: &routes::SessionState,
req: api::PaymentMethodCreate,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
) -> errors::RouterResponse<api::PaymentMethodResponse> {
req.validate()?;
let db = &*state.store;
let merchant_id = merchant_account.get_id();
let customer_id = req.customer_id.clone().get_required_value("customer_id")?;
let payment_method = req.payment_method.get_required_value("payment_method")?;
let key_manager_state = state.into();
let payment_method_billing_address: Option<Encryptable<Secret<serde_json::Value>>> = req
.billing
.clone()
.async_map(|billing| create_encrypted_data(&key_manager_state, key_store, billing))
.await
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt Payment method billing address")?;
let connector_mandate_details = req
.connector_mandate_details
.clone()
.map(serde_json::to_value)
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let response = match payment_method {
#[cfg(feature = "payouts")]
api_enums::PaymentMethod::BankTransfer => match req.bank_transfer.clone() {
Some(bank) => add_bank_to_locker(
state,
req.clone(),
merchant_account,
key_store,
&bank,
&customer_id,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Add PaymentMethod Failed"),
_ => Ok(store_default_payment_method(
&req,
&customer_id,
merchant_id,
)),
},
api_enums::PaymentMethod::Card => match req.card.clone() {
Some(card) => {
let mut card_details = card;
card_details = helpers::populate_bin_details_for_payment_method_create(
card_details.clone(),
db,
)
.await;
helpers::validate_card_expiry(
&card_details.card_exp_month,
&card_details.card_exp_year,
)?;
Box::pin(add_card_to_locker(
state,
req.clone(),
&card_details,
&customer_id,
merchant_account,
None,
))
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Add Card Failed")
}
_ => Ok(store_default_payment_method(
&req,
&customer_id,
merchant_id,
)),
},
_ => Ok(store_default_payment_method(
&req,
&customer_id,
merchant_id,
)),
};
let (mut resp, duplication_check) = response?;
match duplication_check {
Some(duplication_check) => match duplication_check {
payment_methods::DataDuplicationCheck::Duplicated => {
let existing_pm = get_or_insert_payment_method(
state,
req.clone(),
&mut resp,
merchant_account,
&customer_id,
key_store,
)
.await?;
resp.client_secret = existing_pm.client_secret;
}
payment_methods::DataDuplicationCheck::MetaDataChanged => {
if let Some(card) = req.card.clone() {
let existing_pm = get_or_insert_payment_method(
state,
req.clone(),
&mut resp,
merchant_account,
&customer_id,
key_store,
)
.await?;
let client_secret = existing_pm.client_secret.clone();
delete_card_from_locker(
state,
&customer_id,
merchant_id,
existing_pm
.locker_id
.as_ref()
.unwrap_or(&existing_pm.payment_method_id),
)
.await?;
let add_card_resp = add_card_hs(
state,
req.clone(),
&card,
&customer_id,
merchant_account,
api::enums::LockerChoice::HyperswitchCardVault,
Some(
existing_pm
.locker_id
.as_ref()
.unwrap_or(&existing_pm.payment_method_id),
),
)
.await;
if let Err(err) = add_card_resp {
logger::error!(vault_err=?err);
db.delete_payment_method_by_merchant_id_payment_method_id(
&(state.into()),
key_store,
merchant_id,
&resp.payment_method_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
Err(report!(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while updating card metadata changes"))?
};
let existing_pm_data =
get_card_details_without_locker_fallback(&existing_pm, state).await?;
let updated_card = Some(api::CardDetailFromLocker {
scheme: existing_pm.scheme.clone(),
last4_digits: Some(card.card_number.get_last4()),
issuer_country: card
.card_issuing_country
.or(existing_pm_data.issuer_country),
card_isin: Some(card.card_number.get_card_isin()),
card_number: Some(card.card_number),
expiry_month: Some(card.card_exp_month),
expiry_year: Some(card.card_exp_year),
card_token: None,
card_fingerprint: None,
card_holder_name: card
.card_holder_name
.or(existing_pm_data.card_holder_name),
nick_name: card.nick_name.or(existing_pm_data.nick_name),
card_network: card.card_network.or(existing_pm_data.card_network),
card_issuer: card.card_issuer.or(existing_pm_data.card_issuer),
card_type: card.card_type.or(existing_pm_data.card_type),
saved_to_locker: true,
});
let updated_pmd = updated_card.as_ref().map(|card| {
PaymentMethodsData::Card(CardDetailsPaymentMethod::from(card.clone()))
});
let pm_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>> =
updated_pmd
.async_map(|updated_pmd| {
create_encrypted_data(&key_manager_state, key_store, updated_pmd)
})
.await
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt payment method data")?;
let pm_update = storage::PaymentMethodUpdate::PaymentMethodDataUpdate {
payment_method_data: pm_data_encrypted.map(Into::into),
};
db.update_payment_method(
&(state.into()),
key_store,
existing_pm,
pm_update,
merchant_account.storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to add payment method in db")?;
resp.client_secret = client_secret;
}
}
},
None => {
let pm_metadata = resp.metadata.as_ref().map(|data| data.peek());
let locker_id = if resp.payment_method == Some(api_enums::PaymentMethod::Card)
|| resp.payment_method == Some(api_enums::PaymentMethod::BankTransfer)
{
Some(resp.payment_method_id)
} else {
None
};
resp.payment_method_id = generate_id(consts::ID_LENGTH, "pm");
let pm = insert_payment_method(
state,
&resp,
&req,
key_store,
merchant_id,
&customer_id,
pm_metadata.cloned(),
None,
locker_id,
connector_mandate_details,
req.network_transaction_id.clone(),
merchant_account.storage_scheme,
payment_method_billing_address,
None,
None,
None,
)
.await?;
resp.client_secret = pm.client_secret;
}
}
Ok(services::ApplicationResponse::Json(resp))
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="2071" end="2293">
pub async fn update_customer_payment_method(
state: routes::SessionState,
merchant_account: domain::MerchantAccount,
req: api::PaymentMethodUpdate,
payment_method_id: &str,
key_store: domain::MerchantKeyStore,
) -> errors::RouterResponse<api::PaymentMethodResponse> {
// Currently update is supported only for cards
if let Some(card_update) = req.card.clone() {
let db = state.store.as_ref();
let pm = db
.find_payment_method(
&((&state).into()),
&key_store,
payment_method_id,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
if let Some(cs) = &req.client_secret {
let is_client_secret_expired = authenticate_pm_client_secret_and_check_expiry(cs, &pm)?;
if is_client_secret_expired {
return Err((errors::ApiErrorResponse::ClientSecretExpired).into());
};
};
if pm.status == enums::PaymentMethodStatus::AwaitingData {
return Err(report!(errors::ApiErrorResponse::NotSupported {
message: "Payment method is awaiting data so it cannot be updated".into()
}));
}
if pm.payment_method_data.is_none() {
return Err(report!(errors::ApiErrorResponse::GenericNotFoundError {
message: "payment_method_data not found".to_string()
}));
}
// Fetch the existing payment method data from db
let existing_card_data =
pm.payment_method_data
.clone()
.map(|x| x.into_inner().expose())
.map(
|value| -> Result<
PaymentMethodsData,
error_stack::Report<errors::ApiErrorResponse>,
> {
value
.parse_value::<PaymentMethodsData>("PaymentMethodsData")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to deserialize payment methods data")
},
)
.transpose()?
.and_then(|pmd| match pmd {
PaymentMethodsData::Card(crd) => Some(api::CardDetailFromLocker::from(crd)),
_ => None,
})
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to obtain decrypted card object from db")?;
let is_card_updation_required =
validate_payment_method_update(card_update.clone(), existing_card_data.clone());
let response = if is_card_updation_required {
// Fetch the existing card data from locker for getting card number
let card_data_from_locker = get_card_from_locker(
&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 locker")?;
if card_update.card_exp_month.is_some() || card_update.card_exp_year.is_some() {
helpers::validate_card_expiry(
card_update
.card_exp_month
.as_ref()
.unwrap_or(&card_data_from_locker.card_exp_month),
card_update
.card_exp_year
.as_ref()
.unwrap_or(&card_data_from_locker.card_exp_year),
)?;
}
let updated_card_details = card_update.apply(card_data_from_locker.clone());
// Construct new payment method object from request
let new_pm = api::PaymentMethodCreate {
payment_method: pm.get_payment_method_type(),
payment_method_type: pm.get_payment_method_subtype(),
payment_method_issuer: pm.payment_method_issuer.clone(),
payment_method_issuer_code: pm.payment_method_issuer_code,
#[cfg(feature = "payouts")]
bank_transfer: None,
card: Some(updated_card_details.clone()),
#[cfg(feature = "payouts")]
wallet: None,
metadata: None,
customer_id: Some(pm.customer_id.clone()),
client_secret: pm.client_secret.clone(),
payment_method_data: None,
card_network: None,
billing: None,
connector_mandate_details: None,
network_transaction_id: None,
};
new_pm.validate()?;
// Delete old payment method from locker
delete_card_from_locker(
&state,
&pm.customer_id,
&pm.merchant_id,
pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id),
)
.await?;
// Add the updated payment method data to locker
let (mut add_card_resp, _) = Box::pin(add_card_to_locker(
&state,
new_pm.clone(),
&updated_card_details,
&pm.customer_id,
&merchant_account,
Some(pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id)),
))
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to add updated payment method to locker")?;
// Construct new updated card object. Consider a field if passed in request or else populate it with the existing value from existing_card_data
let updated_card = Some(api::CardDetailFromLocker {
scheme: existing_card_data.scheme,
last4_digits: Some(card_data_from_locker.card_number.get_last4()),
issuer_country: existing_card_data.issuer_country,
card_number: existing_card_data.card_number,
expiry_month: card_update
.card_exp_month
.or(existing_card_data.expiry_month),
expiry_year: card_update.card_exp_year.or(existing_card_data.expiry_year),
card_token: existing_card_data.card_token,
card_fingerprint: existing_card_data.card_fingerprint,
card_holder_name: card_update
.card_holder_name
.or(existing_card_data.card_holder_name),
nick_name: card_update.nick_name.or(existing_card_data.nick_name),
card_network: existing_card_data.card_network,
card_isin: existing_card_data.card_isin,
card_issuer: existing_card_data.card_issuer,
card_type: existing_card_data.card_type,
saved_to_locker: true,
});
let updated_pmd = updated_card
.as_ref()
.map(|card| PaymentMethodsData::Card(CardDetailsPaymentMethod::from(card.clone())));
let key_manager_state = (&state).into();
let pm_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>> = updated_pmd
.async_map(|updated_pmd| {
create_encrypted_data(&key_manager_state, &key_store, updated_pmd)
})
.await
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt payment method data")?;
let pm_update = storage::PaymentMethodUpdate::PaymentMethodDataUpdate {
payment_method_data: pm_data_encrypted.map(Into::into),
};
add_card_resp
.payment_method_id
.clone_from(&pm.payment_method_id);
db.update_payment_method(
&((&state).into()),
&key_store,
pm,
pm_update,
merchant_account.storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update payment method in db")?;
add_card_resp
} else {
// Return existing payment method data as response without any changes
api::PaymentMethodResponse {
merchant_id: pm.merchant_id.to_owned(),
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: Some(existing_card_data),
metadata: pm.metadata,
created: Some(pm.created_at),
recurring_enabled: false,
installment_payment_enabled: false,
payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]),
last_used_at: Some(common_utils::date_time::now()),
client_secret: pm.client_secret.clone(),
}
};
Ok(services::ApplicationResponse::Json(response))
} else {
Err(report!(errors::ApiErrorResponse::NotSupported {
message: "Payment method update for the given payment method is not supported".into()
}))
}
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="2918" end="2954">
pub async fn delete_card_from_hs_locker<'a>(
state: &routes::SessionState,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
card_reference: &'a str,
) -> errors::CustomResult<payment_methods::DeleteCardResp, errors::VaultError> {
let locker = &state.conf.locker;
let jwekey = &state.conf.jwekey.get_inner();
let request = payment_methods::mk_delete_card_request_hs(
jwekey,
locker,
customer_id,
merchant_id,
card_reference,
state.tenant.tenant_id.clone(),
state.request_id,
)
.await
.change_context(errors::VaultError::DeleteCardFailed)
.attach_printable("Making delete card request failed")?;
if !locker.mock_locker {
call_locker_api::<payment_methods::DeleteCardResp>(
state,
request,
"delete_card_from_locker",
Some(api_enums::LockerChoice::HyperswitchCardVault),
)
.await
.change_context(errors::VaultError::DeleteCardFailed)
} else {
Ok(mock_delete_card_hs(&*state.store, card_reference)
.await
.change_context(errors::VaultError::DeleteCardFailed)?)
}
}
<file_sep path="hyperswitch/crates/router/tests/utils.rs" role="context" start="389" end="391">
pub struct MerchantId {
merchant_id: common_utils::id_type::MerchantId,
}
<file_sep path="hyperswitch/crates/api_models/src/errors/types.rs" role="context" start="86" end="100">
pub enum ApiErrorResponse {
Unauthorized(ApiError),
ForbiddenCommonResource(ApiError),
ForbiddenPrivateResource(ApiError),
Conflict(ApiError),
Gone(ApiError),
Unprocessable(ApiError),
InternalServerError(ApiError),
NotImplemented(ApiError),
ConnectorError(ApiError, #[serde(skip_serializing)] StatusCode),
NotFound(ApiError),
MethodNotAllowed(ApiError),
BadRequest(ApiError),
DomainError(ApiError),
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payments/routing.rs<|crate|> router anchor=perform_volume_split kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/payments/routing.rs" role="context" start="646" end="668">
pub fn perform_volume_split(
mut splits: Vec<routing_types::ConnectorVolumeSplit>,
) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> {
let weights: Vec<u8> = splits.iter().map(|sp| sp.split).collect();
let weighted_index = distributions::WeightedIndex::new(weights)
.change_context(errors::RoutingError::VolumeSplitFailed)
.attach_printable("Error creating weighted distribution for volume split")?;
let mut rng = rand::thread_rng();
let idx = weighted_index.sample(&mut rng);
splits
.get(idx)
.ok_or(errors::RoutingError::VolumeSplitFailed)
.attach_printable("Volume split index lookup failed")?;
// Panic Safety: We have performed a `get(idx)` operation just above which will
// ensure that the index is always present, else throw an error.
let removed = splits.remove(idx);
splits.insert(0, removed);
Ok(splits.into_iter().map(|sp| sp.connector).collect())
}
<file_sep path="hyperswitch/crates/router/src/core/payments/routing.rs" role="context" start="645" end="645">
use rand::distributions::{self, Distribution};
use rand::SeedableRng;
use crate::{
core::{
errors, errors as oss_errors,
routing::{self},
},
logger,
types::{
api::{self, routing as routing_types},
domain, storage as oss_storage,
transformers::{ForeignFrom, ForeignInto, ForeignTryFrom},
},
utils::{OptionExt, ValueExt},
SessionState,
};
type RoutingResult<O> = oss_errors::CustomResult<O, errors::RoutingError>;
<file_sep path="hyperswitch/crates/router/src/core/payments/routing.rs" role="context" start="718" end="808">
pub async fn refresh_cgraph_cache(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
key: String,
profile_id: &common_utils::id_type::ProfileId,
transaction_type: &api_enums::TransactionType,
) -> RoutingResult<Arc<hyperswitch_constraint_graph::ConstraintGraph<euclid_dir::DirValue>>> {
let mut merchant_connector_accounts = state
.store
.find_merchant_connector_account_by_merchant_id_and_disabled_list(
&state.into(),
&key_store.merchant_id,
false,
key_store,
)
.await
.change_context(errors::RoutingError::KgraphCacheRefreshFailed)?;
match transaction_type {
api_enums::TransactionType::Payment => {
merchant_connector_accounts.retain(|mca| {
mca.connector_type != storage_enums::ConnectorType::PaymentVas
&& mca.connector_type != storage_enums::ConnectorType::PaymentMethodAuth
&& mca.connector_type != storage_enums::ConnectorType::PayoutProcessor
&& mca.connector_type != storage_enums::ConnectorType::AuthenticationProcessor
});
}
#[cfg(feature = "payouts")]
api_enums::TransactionType::Payout => {
merchant_connector_accounts
.retain(|mca| mca.connector_type == storage_enums::ConnectorType::PayoutProcessor);
}
};
let connector_type = match transaction_type {
api_enums::TransactionType::Payment => common_enums::ConnectorType::PaymentProcessor,
#[cfg(feature = "payouts")]
api_enums::TransactionType::Payout => common_enums::ConnectorType::PayoutProcessor,
};
let merchant_connector_accounts = merchant_connector_accounts
.filter_based_on_profile_and_connector_type(profile_id, connector_type);
let api_mcas = merchant_connector_accounts
.into_iter()
.map(admin_api::MerchantConnectorResponse::foreign_try_from)
.collect::<Result<Vec<_>, _>>()
.change_context(errors::RoutingError::KgraphCacheRefreshFailed)?;
let connector_configs = state
.conf
.pm_filters
.0
.clone()
.into_iter()
.filter(|(key, _)| key != "default")
.map(|(key, value)| {
let key = api_enums::RoutableConnectors::from_str(&key)
.map_err(|_| errors::RoutingError::InvalidConnectorName(key))?;
Ok((key, value.foreign_into()))
})
.collect::<Result<HashMap<_, _>, errors::RoutingError>>()?;
let default_configs = state
.conf
.pm_filters
.0
.get("default")
.cloned()
.map(ForeignFrom::foreign_from);
let config_pm_filters = CountryCurrencyFilter {
connector_configs,
default_configs,
};
let cgraph = Arc::new(
mca_graph::make_mca_graph(api_mcas, &config_pm_filters)
.change_context(errors::RoutingError::KgraphCacheRefreshFailed)
.attach_printable("when construction cgraph")?,
);
CGRAPH_CACHE
.push(
CacheKey {
key,
prefix: state.tenant.redis_key_prefix.clone(),
},
Arc::clone(&cgraph),
)
.await;
Ok(cgraph)
}
<file_sep path="hyperswitch/crates/router/src/core/payments/routing.rs" role="context" start="671" end="715">
pub async fn get_merchant_cgraph(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
profile_id: &common_utils::id_type::ProfileId,
transaction_type: &api_enums::TransactionType,
) -> RoutingResult<Arc<hyperswitch_constraint_graph::ConstraintGraph<euclid_dir::DirValue>>> {
let merchant_id = &key_store.merchant_id;
let key = {
match transaction_type {
api_enums::TransactionType::Payment => {
format!(
"cgraph_{}_{}",
merchant_id.get_string_repr(),
profile_id.get_string_repr()
)
}
#[cfg(feature = "payouts")]
api_enums::TransactionType::Payout => {
format!(
"cgraph_po_{}_{}",
merchant_id.get_string_repr(),
profile_id.get_string_repr()
)
}
}
};
let cached_cgraph = CGRAPH_CACHE
.get_val::<Arc<hyperswitch_constraint_graph::ConstraintGraph<euclid_dir::DirValue>>>(
CacheKey {
key: key.clone(),
prefix: state.tenant.redis_key_prefix.clone(),
},
)
.await;
let cgraph = if let Some(graph) = cached_cgraph {
graph
} else {
refresh_cgraph_cache(state, key_store, key.clone(), profile_id, transaction_type).await?
};
Ok(cgraph)
}
<file_sep path="hyperswitch/crates/router/src/core/payments/routing.rs" role="context" start="617" end="644">
pub fn perform_dynamic_routing_volume_split(
splits: Vec<api_models::routing::RoutingVolumeSplit>,
rng_seed: Option<&str>,
) -> RoutingResult<api_models::routing::RoutingVolumeSplit> {
let weights: Vec<u8> = splits.iter().map(|sp| sp.split).collect();
let weighted_index = distributions::WeightedIndex::new(weights)
.change_context(errors::RoutingError::VolumeSplitFailed)
.attach_printable("Error creating weighted distribution for volume split")?;
let idx = if let Some(seed) = rng_seed {
let mut hasher = hash_map::DefaultHasher::new();
seed.hash(&mut hasher);
let hash = hasher.finish();
let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(hash);
weighted_index.sample(&mut rng)
} else {
let mut rng = rand::thread_rng();
weighted_index.sample(&mut rng)
};
let routing_choice = *splits
.get(idx)
.ok_or(errors::RoutingError::VolumeSplitFailed)
.attach_printable("Volume split index lookup failed")?;
Ok(routing_choice)
}
<file_sep path="hyperswitch/crates/router/src/core/payments/routing.rs" role="context" start="567" end="614">
pub async fn refresh_routing_cache_v1(
state: &SessionState,
key: String,
algorithm_id: &common_utils::id_type::RoutingId,
profile_id: &common_utils::id_type::ProfileId,
) -> RoutingResult<Arc<CachedAlgorithm>> {
let algorithm = {
let algorithm = state
.store
.find_routing_algorithm_by_profile_id_algorithm_id(profile_id, algorithm_id)
.await
.change_context(errors::RoutingError::DslMissingInDb)?;
let algorithm: routing_types::RoutingAlgorithm = algorithm
.algorithm_data
.parse_value("RoutingAlgorithm")
.change_context(errors::RoutingError::DslParsingError)?;
algorithm
};
let cached_algorithm = match algorithm {
routing_types::RoutingAlgorithm::Single(conn) => CachedAlgorithm::Single(conn),
routing_types::RoutingAlgorithm::Priority(plist) => CachedAlgorithm::Priority(plist),
routing_types::RoutingAlgorithm::VolumeSplit(splits) => {
CachedAlgorithm::VolumeSplit(splits)
}
routing_types::RoutingAlgorithm::Advanced(program) => {
let interpreter = backend::VirInterpreterBackend::with_program(program)
.change_context(errors::RoutingError::DslBackendInitError)
.attach_printable("Error initializing DSL interpreter backend")?;
CachedAlgorithm::Advanced(interpreter)
}
};
let arc_cached_algorithm = Arc::new(cached_algorithm);
ROUTING_CACHE
.push(
CacheKey {
key,
prefix: state.tenant.redis_key_prefix.clone(),
},
arc_cached_algorithm.clone(),
)
.await;
Ok(arc_cached_algorithm)
}
<file_sep path="hyperswitch/crates/router/src/core/payments/routing.rs" role="context" start="412" end="466">
pub async fn perform_static_routing_v1(
state: &SessionState,
merchant_id: &common_utils::id_type::MerchantId,
algorithm_id: Option<&common_utils::id_type::RoutingId>,
business_profile: &domain::Profile,
transaction_data: &routing::TransactionData<'_>,
) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> {
let algorithm_id = if let Some(id) = algorithm_id {
id
} else {
#[cfg(feature = "v1")]
let fallback_config = routing::helpers::get_merchant_default_config(
&*state.clone().store,
business_profile.get_id().get_string_repr(),
&api_enums::TransactionType::from(transaction_data),
)
.await
.change_context(errors::RoutingError::FallbackConfigFetchFailed)?;
#[cfg(feature = "v2")]
let fallback_config = admin::ProfileWrapper::new(business_profile.clone())
.get_default_fallback_list_of_connector_under_profile()
.change_context(errors::RoutingError::FallbackConfigFetchFailed)?;
return Ok(fallback_config);
};
let cached_algorithm = ensure_algorithm_cached_v1(
state,
merchant_id,
algorithm_id,
business_profile.get_id(),
&api_enums::TransactionType::from(transaction_data),
)
.await?;
Ok(match cached_algorithm.as_ref() {
CachedAlgorithm::Single(conn) => vec![(**conn).clone()],
CachedAlgorithm::Priority(plist) => plist.clone(),
CachedAlgorithm::VolumeSplit(splits) => perform_volume_split(splits.to_vec())
.change_context(errors::RoutingError::ConnectorSelectionFailed)?,
CachedAlgorithm::Advanced(interpreter) => {
let backend_input = match transaction_data {
routing::TransactionData::Payment(payment_data) => make_dsl_input(payment_data)?,
#[cfg(feature = "payouts")]
routing::TransactionData::Payout(payout_data) => {
make_dsl_input_for_payouts(payout_data)?
}
};
execute_dsl_and_get_connector_v1(backend_input, interpreter)?
}
})
}
<file_sep path="hyperswitch/crates/router/src/core/payments/routing.rs" role="context" start="511" end="531">
pub fn perform_straight_through_routing(
algorithm: &routing_types::StraightThroughAlgorithm,
creds_identifier: Option<&str>,
) -> RoutingResult<(Vec<routing_types::RoutableConnectorChoice>, bool)> {
Ok(match algorithm {
routing_types::StraightThroughAlgorithm::Single(conn) => {
(vec![(**conn).clone()], creds_identifier.is_none())
}
routing_types::StraightThroughAlgorithm::Priority(conns) => (conns.clone(), true),
routing_types::StraightThroughAlgorithm::VolumeSplit(splits) => (
perform_volume_split(splits.to_vec())
.change_context(errors::RoutingError::ConnectorSelectionFailed)
.attach_printable(
"Volume Split connector selection error in straight through routing",
)?,
true,
),
})
}
<file_sep path="hyperswitch/crates/router/src/core/payments/routing.rs" role="context" start="111" end="111">
type RoutingResult<O> = oss_errors::CustomResult<O, errors::RoutingError>;
<file_sep path="hyperswitch/crates/router/tests/utils.rs" role="context" start="399" end="401">
pub struct Error {
pub message: Message,
}
<file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="2478" end="2478">
type Error = error_stack::Report<errors::ValidationError>;
<file_sep path="hyperswitch/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/event.test.js" role="context" start="61" end="78">
"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.",
);
}
// Response body should have value "succeeded" for "status"
if (jsonData?.status) {
pm.test(
"[POST]::/payments - Content check if value for 'status' matches 'succeeded'",
function () {
pm.expect(jsonData.status).to.eql("succeeded");
},
);
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payments.rs<|crate|> router anchor=generate_response kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="2937" end="2965">
fn generate_response(
&self,
payment_flow_response: &Self::PaymentFlowResponse,
payment_id: id_type::PaymentId,
connector: String,
) -> RouterResult<services::ApplicationResponse<api::RedirectionResponse>> {
let payments_response = &payment_flow_response.payments_response;
let redirect_response = helpers::get_handle_response_url(
payment_id.clone(),
&payment_flow_response.business_profile,
payments_response,
connector.clone(),
)?;
// html script to check if inside iframe, then send post message to parent for redirection else redirect self to return_url
let html = core_utils::get_html_redirect_response_for_external_authentication(
redirect_response.return_url_with_query_params,
payments_response,
payment_id,
&payment_flow_response.poll_config,
)?;
Ok(services::ApplicationResponse::Form(Box::new(
services::RedirectionFormData {
redirect_form: services::RedirectForm::Html { html_data: html },
payment_method_data: None,
amount: payments_response.amount.to_string(),
currency: payments_response.currency.clone(),
},
)))
}
<file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="2936" end="2936">
.store
.find_business_profile_by_profile_id(key_manager_state, &merchant_key_store, profile_id)
.await
.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
Ok(router_types::AuthenticatePaymentFlowResponse {
payments_response,
poll_config,
business_profile,
})
}
fn generate_response(
&self,
payment_flow_response: &Self::PaymentFlowResponse,
payment_id: id_type::PaymentId,
connector: String,
) -> RouterResult<services::ApplicationResponse<api::RedirectionResponse>> {
let payments_response = &payment_flow_response.payments_response;
let redirect_response = helpers::get_handle_response_url(
payment_id.clone(),
&payment_flow_response.business_profile,
payments_response,
connector.clone(),
)?;
<file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="2975" end="3231">
pub async fn call_connector_service<F, RouterDReq, ApiRequest, D>(
state: &SessionState,
req_state: ReqState,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
connector: api::ConnectorData,
operation: &BoxedOperation<'_, F, ApiRequest, D>,
payment_data: &mut D,
customer: &Option<domain::Customer>,
call_connector_action: CallConnectorAction,
validate_result: &operations::ValidateResult,
schedule_time: Option<time::PrimitiveDateTime>,
header_payload: HeaderPayload,
frm_suggestion: Option<storage_enums::FrmSuggestion>,
business_profile: &domain::Profile,
is_retry_payment: bool,
should_retry_with_pan: bool,
) -> RouterResult<(
RouterData<F, RouterDReq, router_types::PaymentsResponseData>,
helpers::MerchantConnectorAccountType,
)>
where
F: Send + Clone + Sync,
RouterDReq: Send + Sync,
// To create connector flow specific interface data
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
D: ConstructFlowSpecificData<F, RouterDReq, router_types::PaymentsResponseData>,
RouterData<F, RouterDReq, router_types::PaymentsResponseData>: Feature<F, RouterDReq> + Send,
// To construct connector flow specific api
dyn api::Connector:
services::api::ConnectorIntegration<F, RouterDReq, router_types::PaymentsResponseData>,
{
let stime_connector = Instant::now();
let merchant_connector_account = construct_profile_id_and_get_mca(
state,
merchant_account,
payment_data,
&connector.connector_name.to_string(),
connector.merchant_connector_id.as_ref(),
key_store,
false,
)
.await?;
#[cfg(feature = "v1")]
if payment_data
.get_payment_attempt()
.merchant_connector_id
.is_none()
{
payment_data.set_merchant_connector_id_in_attempt(merchant_connector_account.get_mca_id());
}
operation
.to_domain()?
.populate_payment_data(
state,
payment_data,
merchant_account,
business_profile,
&connector,
)
.await?;
let (pd, tokenization_action) = get_connector_tokenization_action_when_confirm_true(
state,
operation,
payment_data,
validate_result,
&merchant_connector_account,
key_store,
customer,
business_profile,
should_retry_with_pan,
)
.await?;
*payment_data = pd;
// Validating the blocklist guard and generate the fingerprint
blocklist_guard(state, merchant_account, key_store, operation, payment_data).await?;
let updated_customer = call_create_connector_customer_if_required(
state,
customer,
merchant_account,
key_store,
&merchant_connector_account,
payment_data,
)
.await?;
#[cfg(feature = "v1")]
let merchant_recipient_data = if let Some(true) = payment_data
.get_payment_intent()
.is_payment_processor_token_flow
{
None
} else {
payment_data
.get_merchant_recipient_data(
state,
merchant_account,
key_store,
&merchant_connector_account,
&connector,
)
.await?
};
// TODO: handle how we read `is_processor_token_flow` in v2 and then call `get_merchant_recipient_data`
#[cfg(feature = "v2")]
let merchant_recipient_data = None;
let mut router_data = payment_data
.construct_router_data(
state,
connector.connector.id(),
merchant_account,
key_store,
customer,
&merchant_connector_account,
merchant_recipient_data,
None,
)
.await?;
let add_access_token_result = router_data
.add_access_token(
state,
&connector,
merchant_account,
payment_data.get_creds_identifier(),
)
.await?;
router_data = router_data.add_session_token(state, &connector).await?;
let should_continue_further = access_token::update_router_data_with_access_token_result(
&add_access_token_result,
&mut router_data,
&call_connector_action,
);
router_data.payment_method_token = if let Some(decrypted_token) =
add_decrypted_payment_method_token(tokenization_action.clone(), payment_data).await?
{
Some(decrypted_token)
} else {
router_data.payment_method_token
};
let payment_method_token_response = router_data
.add_payment_method_token(
state,
&connector,
&tokenization_action,
should_continue_further,
)
.await?;
let mut should_continue_further =
tokenization::update_router_data_with_payment_method_token_result(
payment_method_token_response,
&mut router_data,
is_retry_payment,
should_continue_further,
);
(router_data, should_continue_further) = complete_preprocessing_steps_if_required(
state,
&connector,
payment_data,
router_data,
operation,
should_continue_further,
)
.await?;
if let Ok(router_types::PaymentsResponseData::PreProcessingResponse {
session_token: Some(session_token),
..
}) = router_data.response.to_owned()
{
payment_data.push_sessions_token(session_token);
};
// In case of authorize flow, pre-task and post-tasks are being called in build request
// if we do not want to proceed further, then the function will return Ok(None, false)
let (connector_request, should_continue_further) = if should_continue_further {
// Check if the actual flow specific request can be built with available data
router_data
.build_flow_specific_connector_request(state, &connector, call_connector_action.clone())
.await?
} else {
(None, false)
};
if should_add_task_to_process_tracker(payment_data) {
operation
.to_domain()?
.add_task_to_process_tracker(
state,
payment_data.get_payment_attempt(),
validate_result.requeue,
schedule_time,
)
.await
.map_err(|error| logger::error!(process_tracker_error=?error))
.ok();
}
// Update the payment trackers just before calling the connector
// Since the request is already built in the previous step,
// there should be no error in request construction from hyperswitch end
(_, *payment_data) = operation
.to_update_tracker()?
.update_trackers(
state,
req_state,
payment_data.clone(),
customer.clone(),
merchant_account.storage_scheme,
updated_customer,
key_store,
frm_suggestion,
header_payload.clone(),
)
.await?;
let router_data = if should_continue_further {
// The status of payment_attempt and intent will be updated in the previous step
// update this in router_data.
// This is added because few connector integrations do not update the status,
// and rely on previous status set in router_data
router_data.status = payment_data.get_payment_attempt().status;
router_data
.decide_flows(
state,
&connector,
call_connector_action,
connector_request,
business_profile,
header_payload.clone(),
)
.await
} else {
Ok(router_data)
}?;
let etime_connector = Instant::now();
let duration_connector = etime_connector.saturating_duration_since(stime_connector);
tracing::info!(duration = format!("Duration taken: {}", duration_connector.as_millis()));
Ok((router_data, merchant_connector_account))
}
<file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="2967" end="2969">
fn get_payment_action(&self) -> services::PaymentAction {
services::PaymentAction::PaymentAuthenticateCompleteAuthorize
}
<file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="2727" end="2936">
async fn call_payment_flow(
&self,
state: &SessionState,
req_state: ReqState,
merchant_account: domain::MerchantAccount,
merchant_key_store: domain::MerchantKeyStore,
req: PaymentsRedirectResponseData,
connector_action: CallConnectorAction,
connector: String,
payment_id: id_type::PaymentId,
platform_merchant_account: Option<domain::MerchantAccount>,
) -> RouterResult<Self::PaymentFlowResponse> {
let merchant_id = merchant_account.get_id().clone();
let key_manager_state = &state.into();
let payment_intent = state
.store
.find_payment_intent_by_payment_id_merchant_id(
key_manager_state,
&payment_id,
&merchant_id,
&merchant_key_store,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
let payment_attempt = state
.store
.find_payment_attempt_by_attempt_id_merchant_id(
&payment_intent.active_attempt.get_id(),
&merchant_id,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
let authentication_id = payment_attempt
.authentication_id
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("missing authentication_id in payment_attempt")?;
let authentication = state
.store
.find_authentication_by_merchant_id_authentication_id(
&merchant_id,
authentication_id.clone(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::AuthenticationNotFound {
id: authentication_id,
})?;
// Fetching merchant_connector_account to check if pull_mechanism is enabled for 3ds connector
let authentication_merchant_connector_account = helpers::get_merchant_connector_account(
state,
&merchant_id,
None,
&merchant_key_store,
&payment_intent
.profile_id
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("missing profile_id in payment_intent")?,
&payment_attempt
.authentication_connector
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("missing authentication connector in payment_intent")?,
None,
)
.await?;
let is_pull_mechanism_enabled =
utils::check_if_pull_mechanism_for_external_3ds_enabled_from_connector_metadata(
authentication_merchant_connector_account
.get_metadata()
.map(|metadata| metadata.expose()),
);
let response = if is_pull_mechanism_enabled
|| authentication.authentication_type
!= Some(common_enums::DecoupledAuthenticationType::Challenge)
{
let payment_confirm_req = api::PaymentsRequest {
payment_id: Some(req.resource_id.clone()),
merchant_id: req.merchant_id.clone(),
feature_metadata: Some(api_models::payments::FeatureMetadata {
redirect_response: Some(api_models::payments::RedirectResponse {
param: req.param.map(Secret::new),
json_payload: Some(
req.json_payload.unwrap_or(serde_json::json!({})).into(),
),
}),
search_tags: None,
apple_pay_recurring_details: None,
}),
..Default::default()
};
Box::pin(payments_core::<
api::Authorize,
api::PaymentsResponse,
_,
_,
_,
_,
>(
state.clone(),
req_state,
merchant_account,
None,
merchant_key_store.clone(),
PaymentConfirm,
payment_confirm_req,
services::api::AuthFlow::Merchant,
connector_action,
None,
HeaderPayload::with_source(enums::PaymentSource::ExternalAuthenticator),
platform_merchant_account,
))
.await?
} else {
let payment_sync_req = api::PaymentsRetrieveRequest {
resource_id: req.resource_id,
merchant_id: req.merchant_id,
param: req.param,
force_sync: req.force_sync,
connector: req.connector,
merchant_connector_details: req.creds_identifier.map(|creds_id| {
api::MerchantConnectorDetailsWrap {
creds_identifier: creds_id,
encoded_data: None,
}
}),
client_secret: None,
expand_attempts: None,
expand_captures: None,
};
Box::pin(
payments_core::<api::PSync, api::PaymentsResponse, _, _, _, _>(
state.clone(),
req_state,
merchant_account.clone(),
None,
merchant_key_store.clone(),
PaymentStatus,
payment_sync_req,
services::api::AuthFlow::Merchant,
connector_action,
None,
HeaderPayload::default(),
platform_merchant_account,
),
)
.await?
};
let payments_response = match response {
services::ApplicationResponse::Json(response) => Ok(response),
services::ApplicationResponse::JsonWithHeaders((response, _)) => Ok(response),
_ => Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get the response in json"),
}?;
// When intent status is RequiresCustomerAction, Set poll_id in redis to allow the fetch status of poll through retrieve_poll_status api from client
if payments_response.status == common_enums::IntentStatus::RequiresCustomerAction {
let req_poll_id = core_utils::get_external_authentication_request_poll_id(&payment_id);
let poll_id = core_utils::get_poll_id(&merchant_id, req_poll_id.clone());
let redis_conn = state
.store
.get_redis_conn()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get redis connection")?;
redis_conn
.set_key_with_expiry(
&poll_id.into(),
api_models::poll::PollStatus::Pending.to_string(),
consts::POLL_ID_TTL,
)
.await
.change_context(errors::StorageError::KVError)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to add poll_id in redis")?;
};
let default_poll_config = router_types::PollConfig::default();
let default_config_str = default_poll_config
.encode_to_string_of_json()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error while stringifying default poll config")?;
let poll_config = state
.store
.find_config_by_key_unwrap_or(
&router_types::PollConfig::get_poll_config_key(connector),
Some(default_config_str),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("The poll config was not found in the DB")?;
let poll_config: router_types::PollConfig = poll_config
.config
.parse_struct("PollConfig")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error while parsing PollConfig")?;
let profile_id = payments_response
.profile_id
.as_ref()
.get_required_value("profile_id")?;
let business_profile = state
.store
.find_business_profile_by_profile_id(key_manager_state, &merchant_key_store, profile_id)
.await
.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
Ok(router_types::AuthenticatePaymentFlowResponse {
payments_response,
poll_config,
business_profile,
})
}
<file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="2713" end="2715">
fn get_payment_action(&self) -> services::PaymentAction {
services::PaymentAction::PSync
}
<file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="1731" end="1797">
pub async fn record_attempt_core(
state: SessionState,
req_state: ReqState,
merchant_account: domain::MerchantAccount,
profile: domain::Profile,
key_store: domain::MerchantKeyStore,
req: api_models::payments::PaymentsAttemptRecordRequest,
payment_id: id_type::GlobalPaymentId,
header_payload: HeaderPayload,
platform_merchant_account: Option<domain::MerchantAccount>,
) -> RouterResponse<api_models::payments::PaymentAttemptResponse> {
tracing::Span::current().record("merchant_id", merchant_account.get_id().get_string_repr());
let operation: &operations::payment_attempt_record::PaymentAttemptRecord =
&operations::payment_attempt_record::PaymentAttemptRecord;
let boxed_operation: BoxedOperation<
'_,
api::RecordAttempt,
api_models::payments::PaymentsAttemptRecordRequest,
domain_payments::PaymentAttemptRecordData<api::RecordAttempt>,
> = Box::new(operation);
let _validate_result = boxed_operation
.to_validate_request()?
.validate_request(&req, &merchant_account)?;
tracing::Span::current().record("global_payment_id", payment_id.get_string_repr());
let operations::GetTrackerResponse { payment_data } = boxed_operation
.to_get_tracker()?
.get_trackers(
&state,
&payment_id,
&req,
&merchant_account,
&profile,
&key_store,
&header_payload,
platform_merchant_account.as_ref(),
)
.await?;
let (_operation, payment_data) = boxed_operation
.to_update_tracker()?
.update_trackers(
&state,
req_state,
payment_data,
None,
merchant_account.storage_scheme,
None,
&key_store,
None,
header_payload.clone(),
)
.await?;
transformers::GenerateResponse::generate_response(
payment_data,
&state,
None,
None,
header_payload.x_hs_latency,
&merchant_account,
&profile,
)
}
<file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="1519" end="1585">
pub async fn payments_core<F, Res, Req, Op, FData, D>(
state: SessionState,
req_state: ReqState,
merchant_account: domain::MerchantAccount,
profile_id: Option<id_type::ProfileId>,
key_store: domain::MerchantKeyStore,
operation: Op,
req: Req,
auth_flow: services::AuthFlow,
call_connector_action: CallConnectorAction,
eligible_connectors: Option<Vec<enums::Connector>>,
header_payload: HeaderPayload,
platform_merchant_account: Option<domain::MerchantAccount>,
) -> RouterResponse<Res>
where
F: Send + Clone + Sync,
FData: Send + Sync + Clone,
Op: Operation<F, Req, Data = D> + Send + Sync + Clone,
Req: Debug + Authenticate + Clone,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
Res: transformers::ToResponse<F, D, Op>,
// To create connector flow specific interface data
D: ConstructFlowSpecificData<F, FData, router_types::PaymentsResponseData>,
RouterData<F, FData, router_types::PaymentsResponseData>: Feature<F, FData>,
// To construct connector flow specific api
dyn api::Connector:
services::api::ConnectorIntegration<F, FData, router_types::PaymentsResponseData>,
// To perform router related operation for PaymentResponse
PaymentResponse: Operation<F, FData, Data = D>,
{
let eligible_routable_connectors = eligible_connectors.map(|connectors| {
connectors
.into_iter()
.flat_map(|c| c.foreign_try_into())
.collect()
});
let (payment_data, _req, customer, connector_http_status_code, external_latency) =
payments_operation_core::<_, _, _, _, _>(
&state,
req_state,
merchant_account,
profile_id,
key_store,
operation.clone(),
req,
call_connector_action,
auth_flow,
eligible_routable_connectors,
header_payload.clone(),
platform_merchant_account,
)
.await?;
Res::generate_response(
payment_data,
customer,
auth_flow,
&state.base_url,
operation,
&state.conf.connector_request_reference_id_config,
connector_http_status_code,
external_latency,
header_payload.x_hs_latency,
)
}
<file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="2312" end="2312">
type PaymentFlowResponse = router_types::RedirectPaymentFlowResponse;
<file_sep path="hyperswitch/crates/router/tests/utils.rs" role="context" start="409" end="411">
pub struct PaymentId {
payment_id: common_utils::id_type::PaymentId,
}
<file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="6322" end="6328">
pub struct RedirectionResponse {
pub return_url: String,
pub params: Vec<(String, String)>,
pub return_url_with_query_params: String,
pub http_method: String,
pub headers: Vec<(String, String)>,
}
<file_sep path="hyperswitch/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/event.test.js" role="context" start="61" end="78">
"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.",
);
}
// Response body should have value "succeeded" for "status"
if (jsonData?.status) {
pm.test(
"[POST]::/payments - Content check if value for 'status' matches 'succeeded'",
function () {
pm.expect(jsonData.status).to.eql("succeeded");
},
);
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payment_methods/cards.rs<|crate|> router anchor=get_card_from_locker kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="2477" end="2511">
pub async fn get_card_from_locker(
state: &routes::SessionState,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
card_reference: &str,
) -> errors::RouterResult<Card> {
metrics::GET_FROM_LOCKER.add(1, &[]);
let get_card_from_rs_locker_resp = common_utils::metrics::utils::record_operation_time(
async {
get_card_from_hs_locker(
state,
customer_id,
merchant_id,
card_reference,
api_enums::LockerChoice::HyperswitchCardVault,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while getting card from hyperswitch card vault")
.inspect_err(|_| {
metrics::CARD_LOCKER_FAILURES.add(
1,
router_env::metric_attributes!(("locker", "rust"), ("operation", "get")),
);
})
},
&metrics::CARD_GET_TIME,
router_env::metric_attributes!(("locker", "rust")),
)
.await?;
logger::debug!("card retrieved from rust locker");
Ok(get_card_from_rs_locker_resp)
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="2476" end="2476">
);
})
},
&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)
}
pub async fn get_card_from_locker(
state: &routes::SessionState,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
card_reference: &str,
) -> errors::RouterResult<Card> {
metrics::GET_FROM_LOCKER.add(1, &[]);
let get_card_from_rs_locker_resp = common_utils::metrics::utils::record_operation_time(
async {
get_card_from_hs_locker(
state,
customer_id,
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="2541" end="2547">
pub async fn delete_card_by_locker_id(
state: &routes::SessionState,
id: &id_type::GlobalCustomerId,
merchant_id: &id_type::MerchantId,
) -> errors::RouterResult<payment_methods::DeleteCardResp> {
todo!()
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="2513" end="2538">
pub async fn delete_card_from_locker(
state: &routes::SessionState,
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(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")
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="2434" end="2475">
pub async fn add_card_to_locker(
state: &routes::SessionState,
req: api::PaymentMethodCreate,
card: &api::CardDetail,
customer_id: &id_type::CustomerId,
merchant_account: &domain::MerchantAccount,
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 {
add_card_hs(
state,
req.clone(),
card,
customer_id,
merchant_account,
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)
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="2358" end="2431">
pub async fn add_bank_to_locker(
state: &routes::SessionState,
req: api::PaymentMethodCreate,
merchant_account: &domain::MerchantAccount,
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 = 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: merchant_account.get_id().to_owned(),
merchant_customer_id: customer_id.to_owned(),
enc_data,
ttl: state.conf.locker.ttl_for_storage_in_secs,
});
let store_resp = add_card_to_hs_locker(
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,
merchant_account.get_id(),
);
Ok((payment_method_resp, store_resp.duplication_check))
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="5344" end="5361">
pub async fn get_card_details_from_locker(
state: &routes::SessionState,
pm: &domain::PaymentMethod,
) -> errors::RouterResult<api::CardDetailFromLocker> {
let card = get_card_from_locker(
state,
&pm.customer_id,
&pm.merchant_id,
pm.locker_id.as_ref().unwrap_or(pm.get_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("Get Card Details Failed")
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="5746" end="5803">
pub async fn retrieve_payment_method(
state: routes::SessionState,
pm: api::PaymentMethodId,
key_store: domain::MerchantKeyStore,
merchant_account: domain::MerchantAccount,
) -> errors::RouterResponse<api::PaymentMethodResponse> {
let db = state.store.as_ref();
let pm = db
.find_payment_method(
&((&state).into()),
&key_store,
&pm.payment_method_id,
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 state.conf.locker.locker_enabled {
let card = get_card_from_locker(
&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 {
get_card_details_without_locker_fallback(&pm, &state).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: false,
installment_payment_enabled: false,
payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]),
last_used_at: Some(pm.last_used_at),
client_secret: pm.client_secret,
},
))
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="2869" end="2915">
pub async fn get_card_from_hs_locker<'a>(
state: &'a routes::SessionState,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
card_reference: &'a str,
locker_choice: api_enums::LockerChoice,
) -> errors::CustomResult<Card, errors::VaultError> {
let locker = &state.conf.locker;
let jwekey = &state.conf.jwekey.get_inner();
if !locker.mock_locker {
let request = payment_methods::mk_get_card_request_hs(
jwekey,
locker,
customer_id,
merchant_id,
card_reference,
Some(locker_choice),
state.tenant.tenant_id.clone(),
state.request_id,
)
.await
.change_context(errors::VaultError::FetchCardFailed)
.attach_printable("Making get card request failed")?;
let get_card_resp = call_locker_api::<payment_methods::RetrieveCardResp>(
state,
request,
"get_card_from_locker",
Some(locker_choice),
)
.await
.change_context(errors::VaultError::FetchCardFailed)?;
let retrieve_card_resp = get_card_resp
.payload
.get_required_value("RetrieveCardRespPayload")
.change_context(errors::VaultError::FetchCardFailed)?;
retrieve_card_resp
.card
.get_required_value("Card")
.change_context(errors::VaultError::FetchCardFailed)
} else {
let (get_card_resp, _) = mock_get_card(&*state.store, card_reference).await?;
payment_methods::mk_get_card_response(get_card_resp)
.change_context(errors::VaultError::ResponseDeserializationFailed)
}
}
<file_sep path="hyperswitch/crates/router/src/connector/payone/transformers.rs" role="context" start="117" end="121">
pub struct Card {
card_holder_name: Secret<String>,
card_number: CardNumber,
expiry_date: Secret<String>,
}
<file_sep path="hyperswitch/crates/api_models/src/errors/types.rs" role="context" start="86" end="100">
pub enum ApiErrorResponse {
Unauthorized(ApiError),
ForbiddenCommonResource(ApiError),
ForbiddenPrivateResource(ApiError),
Conflict(ApiError),
Gone(ApiError),
Unprocessable(ApiError),
InternalServerError(ApiError),
NotImplemented(ApiError),
ConnectorError(ApiError, #[serde(skip_serializing)] StatusCode),
NotFound(ApiError),
MethodNotAllowed(ApiError),
BadRequest(ApiError),
DomainError(ApiError),
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payments/flows/session_flow.rs<|crate|> router anchor=decide_flow kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/payments/flows/session_flow.rs" role="context" start="1261" end="1314">
async fn decide_flow<'a, 'b>(
&'b self,
state: &'a routes::SessionState,
connector: &api::ConnectorData,
_confirm: Option<bool>,
call_connector_action: payments::CallConnectorAction,
business_profile: &domain::Profile,
header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<Self> {
match connector.get_token {
api::GetToken::GpayMetadata => {
create_gpay_session_token(state, self, connector, business_profile)
}
api::GetToken::SamsungPayMetadata => create_samsung_pay_session_token(
state,
self,
header_payload,
connector,
business_profile,
),
api::GetToken::ApplePayMetadata => {
create_applepay_session_token(
state,
self,
connector,
business_profile,
header_payload,
)
.await
}
api::GetToken::PaypalSdkMetadata => {
create_paypal_sdk_session_token(state, self, connector, business_profile)
}
api::GetToken::PazeMetadata => create_paze_session_token(self, header_payload),
api::GetToken::Connector => {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::Session,
types::PaymentsSessionData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
let resp = services::execute_connector_processing_step(
state,
connector_integration,
self,
call_connector_action,
None,
)
.await
.to_payment_failed_response()?;
Ok(resp)
}
}
}
<file_sep path="hyperswitch/crates/router/src/core/payments/flows/session_flow.rs" role="context" start="1260" end="1260">
use api_models::{admin as admin_types, payments as payment_types};
use common_utils::{
ext_traits::ByteSliceExt,
request::RequestContent,
types::{AmountConvertor, StringMajorUnitForConnector},
};
use hyperswitch_domain_models::payments::PaymentIntentData;
use crate::{
consts::PROTOCOL,
core::{
errors::{self, ConnectorErrorExt, RouterResult},
payments::{self, access_token, helpers, transformers, PaymentData},
},
headers, logger,
routes::{self, app::settings, metrics},
services,
types::{
self,
api::{self, enums},
domain,
},
utils::OptionExt,
};
<file_sep path="hyperswitch/crates/router/src/core/payments/flows/session_flow.rs" role="context" start="1223" end="1257">
fn create_paypal_sdk_session_token(
_state: &routes::SessionState,
router_data: &types::PaymentsSessionRouterData,
connector: &api::ConnectorData,
_business_profile: &domain::Profile,
) -> RouterResult<types::PaymentsSessionRouterData> {
let connector_metadata = router_data.connector_meta_data.clone();
let paypal_sdk_data = connector_metadata
.clone()
.parse_value::<payment_types::PaypalSdkSessionTokenData>("PaypalSdkSessionTokenData")
.change_context(errors::ConnectorError::NoConnectorMetaData)
.attach_printable(format!(
"cannot parse paypal_sdk metadata from the given value {connector_metadata:?}"
))
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "connector_metadata".to_string(),
expected_format: "paypal_sdk_metadata_format".to_string(),
})?;
Ok(types::PaymentsSessionRouterData {
response: Ok(types::PaymentsResponseData::SessionResponse {
session_token: payment_types::SessionToken::Paypal(Box::new(
payment_types::PaypalSessionTokenResponse {
connector: connector.connector_name.to_string(),
session_token: paypal_sdk_data.data.client_id,
sdk_next_action: payment_types::SdkNextAction {
next_action: payment_types::NextActionCall::PostSessionTokens,
},
},
)),
}),
..router_data.clone()
})
}
<file_sep path="hyperswitch/crates/router/src/core/payments/flows/session_flow.rs" role="context" start="1195" end="1205">
fn log_session_response_if_error(
response: &Result<Result<types::Response, types::Response>, Report<errors::ApiClientError>>,
) {
if let Err(error) = response.as_ref() {
logger::error!(?error);
};
response
.as_ref()
.ok()
.map(|res| res.as_ref().map_err(|error| logger::error!(?error)));
}
<file_sep path="hyperswitch/crates/router/src/core/payments/flows/session_flow.rs" role="context" start="925" end="1128">
fn create_gpay_session_token(
state: &routes::SessionState,
router_data: &types::PaymentsSessionRouterData,
connector: &api::ConnectorData,
business_profile: &domain::Profile,
) -> RouterResult<types::PaymentsSessionRouterData> {
// connector_wallet_details is being parse into admin types to check specifically if google_pay field is present
// this is being done because apple_pay details from metadata is also being filled into connector_wallets_details
let google_pay_wallets_details = router_data
.connector_wallets_details
.clone()
.parse_value::<admin_types::ConnectorWalletDetails>("ConnectorWalletDetails")
.change_context(errors::ConnectorError::NoConnectorWalletDetails)
.attach_printable(format!(
"cannot parse connector_wallets_details from the given value {:?}",
router_data.connector_wallets_details
))
.map_err(|err| {
logger::debug!(
"Failed to parse connector_wallets_details for google_pay flow: {:?}",
err
);
})
.ok()
.and_then(|connector_wallets_details| connector_wallets_details.google_pay);
let connector_metadata = router_data.connector_meta_data.clone();
let delayed_response = is_session_response_delayed(state, connector);
if delayed_response {
Ok(types::PaymentsSessionRouterData {
response: Ok(types::PaymentsResponseData::SessionResponse {
session_token: payment_types::SessionToken::GooglePay(Box::new(
payment_types::GpaySessionTokenResponse::ThirdPartyResponse(
payment_types::GooglePayThirdPartySdk {
delayed_session_token: true,
connector: connector.connector_name.to_string(),
sdk_next_action: payment_types::SdkNextAction {
next_action: payment_types::NextActionCall::Confirm,
},
},
),
)),
}),
..router_data.clone()
})
} else {
let is_billing_details_required = is_billing_address_required_to_be_collected_from_wallet(
state,
connector,
business_profile,
enums::PaymentMethodType::GooglePay,
);
let required_amount_type = StringMajorUnitForConnector;
let google_pay_amount = required_amount_type
.convert(
router_data.request.minor_amount,
router_data.request.currency,
)
.change_context(errors::ApiErrorResponse::PreconditionFailed {
message: "Failed to convert amount to string major unit for googlePay".to_string(),
})?;
let session_data = router_data.request.clone();
let transaction_info = payment_types::GpayTransactionInfo {
country_code: session_data.country.unwrap_or_default(),
currency_code: router_data.request.currency,
total_price_status: "Final".to_string(),
total_price: google_pay_amount,
};
let required_shipping_contact_fields =
is_shipping_address_required_to_be_collected_form_wallet(
state,
connector,
business_profile,
enums::PaymentMethodType::GooglePay,
);
if google_pay_wallets_details.is_some() {
let gpay_data = router_data
.connector_wallets_details
.clone()
.parse_value::<payment_types::GooglePayWalletDetails>("GooglePayWalletDetails")
.change_context(errors::ConnectorError::NoConnectorWalletDetails)
.attach_printable(format!(
"cannot parse gpay connector_wallets_details from the given value {:?}",
router_data.connector_wallets_details
))
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "connector_wallets_details".to_string(),
expected_format: "gpay_connector_wallets_details_format".to_string(),
})?;
let payment_types::GooglePayProviderDetails::GooglePayMerchantDetails(gpay_info) =
gpay_data.google_pay.provider_details.clone();
let gpay_allowed_payment_methods = get_allowed_payment_methods_from_cards(
gpay_data,
&gpay_info.merchant_info.tokenization_specification,
is_billing_details_required,
)?;
Ok(types::PaymentsSessionRouterData {
response: Ok(types::PaymentsResponseData::SessionResponse {
session_token: payment_types::SessionToken::GooglePay(Box::new(
payment_types::GpaySessionTokenResponse::GooglePaySession(
payment_types::GooglePaySessionResponse {
merchant_info: payment_types::GpayMerchantInfo {
merchant_name: gpay_info.merchant_info.merchant_name,
merchant_id: gpay_info.merchant_info.merchant_id,
},
allowed_payment_methods: vec![gpay_allowed_payment_methods],
transaction_info,
connector: connector.connector_name.to_string(),
sdk_next_action: payment_types::SdkNextAction {
next_action: payment_types::NextActionCall::Confirm,
},
delayed_session_token: false,
secrets: None,
shipping_address_required: required_shipping_contact_fields,
// We pass Email as a required field irrespective of
// collect_billing_details_from_wallet_connector or
// collect_shipping_details_from_wallet_connector as it is common to both.
email_required: required_shipping_contact_fields
|| is_billing_details_required,
shipping_address_parameters:
api_models::payments::GpayShippingAddressParameters {
phone_number_required: required_shipping_contact_fields,
},
},
),
)),
}),
..router_data.clone()
})
} else {
let billing_address_parameters = is_billing_details_required.then_some(
payment_types::GpayBillingAddressParameters {
phone_number_required: is_billing_details_required,
format: payment_types::GpayBillingAddressFormat::FULL,
},
);
let gpay_data = connector_metadata
.clone()
.parse_value::<payment_types::GpaySessionTokenData>("GpaySessionTokenData")
.change_context(errors::ConnectorError::NoConnectorMetaData)
.attach_printable(format!(
"cannot parse gpay metadata from the given value {connector_metadata:?}"
))
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "connector_metadata".to_string(),
expected_format: "gpay_metadata_format".to_string(),
})?;
let gpay_allowed_payment_methods = gpay_data
.data
.allowed_payment_methods
.into_iter()
.map(
|allowed_payment_methods| payment_types::GpayAllowedPaymentMethods {
parameters: payment_types::GpayAllowedMethodsParameters {
billing_address_required: Some(is_billing_details_required),
billing_address_parameters: billing_address_parameters.clone(),
..allowed_payment_methods.parameters
},
..allowed_payment_methods
},
)
.collect();
Ok(types::PaymentsSessionRouterData {
response: Ok(types::PaymentsResponseData::SessionResponse {
session_token: payment_types::SessionToken::GooglePay(Box::new(
payment_types::GpaySessionTokenResponse::GooglePaySession(
payment_types::GooglePaySessionResponse {
merchant_info: gpay_data.data.merchant_info,
allowed_payment_methods: gpay_allowed_payment_methods,
transaction_info,
connector: connector.connector_name.to_string(),
sdk_next_action: payment_types::SdkNextAction {
next_action: payment_types::NextActionCall::Confirm,
},
delayed_session_token: false,
secrets: None,
shipping_address_required: required_shipping_contact_fields,
// We pass Email as a required field irrespective of
// collect_billing_details_from_wallet_connector or
// collect_shipping_details_from_wallet_connector as it is common to both.
email_required: required_shipping_contact_fields
|| is_billing_details_required,
shipping_address_parameters:
api_models::payments::GpayShippingAddressParameters {
phone_number_required: required_shipping_contact_fields,
},
},
),
)),
}),
..router_data.clone()
})
}
}
}
<file_sep path="hyperswitch/crates/router/src/core/payments/flows/session_flow.rs" role="context" start="575" end="610">
fn create_paze_session_token(
router_data: &types::PaymentsSessionRouterData,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<types::PaymentsSessionRouterData> {
let paze_wallet_details = router_data
.connector_wallets_details
.clone()
.parse_value::<payment_types::PazeSessionTokenData>("PazeSessionTokenData")
.change_context(errors::ConnectorError::NoConnectorWalletDetails)
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "connector_wallets_details".to_string(),
expected_format: "paze_metadata_format".to_string(),
})?;
let required_amount_type = StringMajorUnitForConnector;
let transaction_currency_code = router_data.request.currency;
let transaction_amount = required_amount_type
.convert(router_data.request.minor_amount, transaction_currency_code)
.change_context(errors::ApiErrorResponse::PreconditionFailed {
message: "Failed to convert amount to string major unit for paze".to_string(),
})?;
Ok(types::PaymentsSessionRouterData {
response: Ok(types::PaymentsResponseData::SessionResponse {
session_token: payment_types::SessionToken::Paze(Box::new(
payment_types::PazeSessionTokenResponse {
client_id: paze_wallet_details.data.client_id,
client_name: paze_wallet_details.data.client_name,
client_profile_id: paze_wallet_details.data.client_profile_id,
transaction_currency_code,
transaction_amount,
email_address: router_data.request.email.clone(),
},
)),
}),
..router_data.clone()
})
}
<file_sep path="hyperswitch/crates/router/src/routes/app.rs" role="context" start="1906" end="1906">
pub struct Profile;
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payment_methods/vault.rs<|crate|> router anchor=from_values kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/vault.rs" role="context" start="844" end="874">
fn from_values(
value1: String,
value2: String,
) -> CustomResult<(Self, SupplementaryVaultData), errors::VaultError> {
let value1: VaultPayoutMethod = value1
.parse_struct("VaultMethodValue1")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Could not deserialize into vault method value 1")?;
let value2: VaultPayoutMethod = value2
.parse_struct("VaultMethodValue2")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Could not deserialize into vault method value 2")?;
match (value1, value2) {
(VaultPayoutMethod::Card(mvalue1), VaultPayoutMethod::Card(mvalue2)) => {
let (card, supp_data) = api::CardPayout::from_values(mvalue1, mvalue2)?;
Ok((Self::Card(card), supp_data))
}
(VaultPayoutMethod::Bank(mvalue1), VaultPayoutMethod::Bank(mvalue2)) => {
let (bank, supp_data) = api::BankPayout::from_values(mvalue1, mvalue2)?;
Ok((Self::Bank(bank), supp_data))
}
(VaultPayoutMethod::Wallet(mvalue1), VaultPayoutMethod::Wallet(mvalue2)) => {
let (wallet, supp_data) = api::WalletPayout::from_values(mvalue1, mvalue2)?;
Ok((Self::Wallet(wallet), supp_data))
}
_ => Err(errors::VaultError::PayoutMethodNotSupported)
.attach_printable("Payout method not supported"),
}
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/vault.rs" role="context" start="843" end="843">
use crate::types::api::payouts;
use crate::{
consts,
core::errors::{self, CustomResult, RouterResult},
db, logger, routes,
routes::metrics,
types::{
api, domain,
storage::{self, enums},
},
utils::StringExt,
};
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/vault.rs" role="context" start="903" end="934">
pub async fn store_payment_method_data_in_locker(
state: &routes::SessionState,
token_id: Option<String>,
payment_method: &domain::PaymentMethodData,
customer_id: Option<id_type::CustomerId>,
pm: enums::PaymentMethod,
merchant_key_store: &domain::MerchantKeyStore,
) -> RouterResult<String> {
let value1 = payment_method
.get_value1(customer_id.clone())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error getting Value1 for locker")?;
let value2 = payment_method
.get_value2(customer_id)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error getting Value12 for locker")?;
let lookup_key = token_id.unwrap_or_else(|| generate_id_with_default_len("token"));
let lookup_key = create_tokenize(
state,
value1,
Some(value2),
lookup_key,
merchant_key_store.key.get_inner(),
)
.await?;
add_delete_tokenized_data_task(&*state.store, &lookup_key, pm).await?;
metrics::TOKENIZED_DATA_COUNT.add(1, &[]);
Ok(lookup_key)
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/vault.rs" role="context" start="887" end="900">
pub async fn get_payment_method_data_from_locker(
state: &routes::SessionState,
lookup_key: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> RouterResult<(Option<domain::PaymentMethodData>, SupplementaryVaultData)> {
let de_tokenize =
get_tokenized_data(state, lookup_key, true, merchant_key_store.key.get_inner()).await?;
let (payment_method, customer_id) =
domain::PaymentMethodData::from_values(de_tokenize.value1, de_tokenize.value2)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error parsing Payment Method from Values")?;
Ok((Some(payment_method), customer_id))
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/vault.rs" role="context" start="828" end="842">
fn get_value2(
&self,
customer_id: Option<id_type::CustomerId>,
) -> CustomResult<String, errors::VaultError> {
let value2 = match self {
Self::Card(card) => VaultPayoutMethod::Card(card.get_value2(customer_id)?),
Self::Bank(bank) => VaultPayoutMethod::Bank(bank.get_value2(customer_id)?),
Self::Wallet(wallet) => VaultPayoutMethod::Wallet(wallet.get_value2(customer_id)?),
};
value2
.encode_to_string_of_json()
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode payout method value2")
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/vault.rs" role="context" start="812" end="826">
fn get_value1(
&self,
customer_id: Option<id_type::CustomerId>,
) -> CustomResult<String, errors::VaultError> {
let value1 = match self {
Self::Card(card) => VaultPayoutMethod::Card(card.get_value1(customer_id)?),
Self::Bank(bank) => VaultPayoutMethod::Bank(bank.get_value1(customer_id)?),
Self::Wallet(wallet) => VaultPayoutMethod::Wallet(wallet.get_value1(customer_id)?),
};
value1
.encode_to_string_of_json()
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode payout method value1")
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/vault.rs" role="context" start="938" end="951">
pub async fn get_payout_method_data_from_temporary_locker(
state: &routes::SessionState,
lookup_key: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> RouterResult<(Option<api::PayoutMethodData>, SupplementaryVaultData)> {
let de_tokenize =
get_tokenized_data(state, lookup_key, true, merchant_key_store.key.get_inner()).await?;
let (payout_method, supp_data) =
api::PayoutMethodData::from_values(de_tokenize.value1, de_tokenize.value2)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error parsing Payout Method from Values")?;
Ok((Some(payout_method), supp_data))
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/vault.rs" role="context" start="804" end="808">
pub enum VaultPayoutMethod {
Card(String),
Bank(String),
Wallet(String),
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/vault.rs" role="context" start="35" end="38">
pub struct SupplementaryVaultData {
pub customer_id: Option<id_type::CustomerId>,
pub payment_method_id: Option<String>,
}
<file_sep path="hyperswitch/crates/router/src/connector/payone/transformers.rs" role="context" start="117" end="121">
pub struct Card {
card_holder_name: Secret<String>,
card_number: CardNumber,
expiry_date: Secret<String>,
}
<file_sep path="hyperswitch/migrations/2024-07-31-063531_alter_customer_id_in_payouts/up.sql" role="context" start="1" end="9">
ALTER TABLE payouts
ALTER COLUMN customer_id
DROP NOT NULL,
ALTER COLUMN address_id
DROP NOT NULL;
ALTER TABLE payout_attempt
ALTER COLUMN customer_id
DROP NOT NULL,
<file_sep path="hyperswitch/crates/api_models/src/payouts.rs" role="context" start="262" end="267">
pub enum Bank {
Ach(AchBankTransfer),
Bacs(BacsBankTransfer),
Sepa(SepaBankTransfer),
Pix(PixBankTransfer),
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payments/routing.rs<|crate|> router anchor=perform_cgraph_filtering kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/payments/routing.rs" role="context" start="811" end="853">
pub async fn perform_cgraph_filtering(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
chosen: Vec<routing_types::RoutableConnectorChoice>,
backend_input: dsl_inputs::BackendInput,
eligible_connectors: Option<&Vec<api_enums::RoutableConnectors>>,
profile_id: &common_utils::id_type::ProfileId,
transaction_type: &api_enums::TransactionType,
) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> {
let context = euclid_graph::AnalysisContext::from_dir_values(
backend_input
.into_context()
.change_context(errors::RoutingError::KgraphAnalysisError)?,
);
let cached_cgraph = get_merchant_cgraph(state, key_store, profile_id, transaction_type).await?;
let mut final_selection = Vec::<routing_types::RoutableConnectorChoice>::new();
for choice in chosen {
let routable_connector = choice.connector;
let euclid_choice: ast::ConnectorChoice = choice.clone().foreign_into();
let dir_val = euclid_choice
.into_dir_value()
.change_context(errors::RoutingError::KgraphAnalysisError)?;
let cgraph_eligible = cached_cgraph
.check_value_validity(
dir_val,
&context,
&mut hyperswitch_constraint_graph::Memoization::new(),
&mut hyperswitch_constraint_graph::CycleCheck::new(),
None,
)
.change_context(errors::RoutingError::KgraphAnalysisError)?;
let filter_eligible =
eligible_connectors.map_or(true, |list| list.contains(&routable_connector));
if cgraph_eligible && filter_eligible {
final_selection.push(choice);
}
}
Ok(final_selection)
}
<file_sep path="hyperswitch/crates/router/src/core/payments/routing.rs" role="context" start="810" end="810">
use api_models::{
admin as admin_api,
enums::{self as api_enums, CountryAlpha2},
routing::ConnectorSelection,
};
use common_utils::ext_traits::AsyncExt;
use euclid::{
backend::{self, inputs as dsl_inputs, EuclidBackend},
dssa::graph::{self as euclid_graph, CgraphExt},
enums as euclid_enums,
frontend::{ast, dir as euclid_dir},
};
use crate::{
core::{
errors, errors as oss_errors,
routing::{self},
},
logger,
types::{
api::{self, routing as routing_types},
domain, storage as oss_storage,
transformers::{ForeignFrom, ForeignInto, ForeignTryFrom},
},
utils::{OptionExt, ValueExt},
SessionState,
};
type RoutingResult<O> = oss_errors::CustomResult<O, errors::RoutingError>;
<file_sep path="hyperswitch/crates/router/src/core/payments/routing.rs" role="context" start="881" end="928">
pub async fn perform_fallback_routing(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
transaction_data: &routing::TransactionData<'_>,
eligible_connectors: Option<&Vec<api_enums::RoutableConnectors>>,
business_profile: &domain::Profile,
) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> {
#[cfg(feature = "v1")]
let fallback_config = routing::helpers::get_merchant_default_config(
&*state.store,
match transaction_data {
routing::TransactionData::Payment(payment_data) => payment_data
.payment_intent
.profile_id
.as_ref()
.get_required_value("profile_id")
.change_context(errors::RoutingError::ProfileIdMissing)?
.get_string_repr(),
#[cfg(feature = "payouts")]
routing::TransactionData::Payout(payout_data) => {
payout_data.payout_attempt.profile_id.get_string_repr()
}
},
&api_enums::TransactionType::from(transaction_data),
)
.await
.change_context(errors::RoutingError::FallbackConfigFetchFailed)?;
#[cfg(feature = "v2")]
let fallback_config = admin::ProfileWrapper::new(business_profile.clone())
.get_default_fallback_list_of_connector_under_profile()
.change_context(errors::RoutingError::FallbackConfigFetchFailed)?;
let backend_input = match transaction_data {
routing::TransactionData::Payment(payment_data) => make_dsl_input(payment_data)?,
#[cfg(feature = "payouts")]
routing::TransactionData::Payout(payout_data) => make_dsl_input_for_payouts(payout_data)?,
};
perform_cgraph_filtering(
state,
key_store,
fallback_config,
backend_input,
eligible_connectors,
business_profile.get_id(),
&api_enums::TransactionType::from(transaction_data),
)
.await
}
<file_sep path="hyperswitch/crates/router/src/core/payments/routing.rs" role="context" start="855" end="879">
pub async fn perform_eligibility_analysis(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
chosen: Vec<routing_types::RoutableConnectorChoice>,
transaction_data: &routing::TransactionData<'_>,
eligible_connectors: Option<&Vec<api_enums::RoutableConnectors>>,
profile_id: &common_utils::id_type::ProfileId,
) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> {
let backend_input = match transaction_data {
routing::TransactionData::Payment(payment_data) => make_dsl_input(payment_data)?,
#[cfg(feature = "payouts")]
routing::TransactionData::Payout(payout_data) => make_dsl_input_for_payouts(payout_data)?,
};
perform_cgraph_filtering(
state,
key_store,
chosen,
backend_input,
eligible_connectors,
profile_id,
&api_enums::TransactionType::from(transaction_data),
)
.await
}
<file_sep path="hyperswitch/crates/router/src/core/payments/routing.rs" role="context" start="718" end="808">
pub async fn refresh_cgraph_cache(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
key: String,
profile_id: &common_utils::id_type::ProfileId,
transaction_type: &api_enums::TransactionType,
) -> RoutingResult<Arc<hyperswitch_constraint_graph::ConstraintGraph<euclid_dir::DirValue>>> {
let mut merchant_connector_accounts = state
.store
.find_merchant_connector_account_by_merchant_id_and_disabled_list(
&state.into(),
&key_store.merchant_id,
false,
key_store,
)
.await
.change_context(errors::RoutingError::KgraphCacheRefreshFailed)?;
match transaction_type {
api_enums::TransactionType::Payment => {
merchant_connector_accounts.retain(|mca| {
mca.connector_type != storage_enums::ConnectorType::PaymentVas
&& mca.connector_type != storage_enums::ConnectorType::PaymentMethodAuth
&& mca.connector_type != storage_enums::ConnectorType::PayoutProcessor
&& mca.connector_type != storage_enums::ConnectorType::AuthenticationProcessor
});
}
#[cfg(feature = "payouts")]
api_enums::TransactionType::Payout => {
merchant_connector_accounts
.retain(|mca| mca.connector_type == storage_enums::ConnectorType::PayoutProcessor);
}
};
let connector_type = match transaction_type {
api_enums::TransactionType::Payment => common_enums::ConnectorType::PaymentProcessor,
#[cfg(feature = "payouts")]
api_enums::TransactionType::Payout => common_enums::ConnectorType::PayoutProcessor,
};
let merchant_connector_accounts = merchant_connector_accounts
.filter_based_on_profile_and_connector_type(profile_id, connector_type);
let api_mcas = merchant_connector_accounts
.into_iter()
.map(admin_api::MerchantConnectorResponse::foreign_try_from)
.collect::<Result<Vec<_>, _>>()
.change_context(errors::RoutingError::KgraphCacheRefreshFailed)?;
let connector_configs = state
.conf
.pm_filters
.0
.clone()
.into_iter()
.filter(|(key, _)| key != "default")
.map(|(key, value)| {
let key = api_enums::RoutableConnectors::from_str(&key)
.map_err(|_| errors::RoutingError::InvalidConnectorName(key))?;
Ok((key, value.foreign_into()))
})
.collect::<Result<HashMap<_, _>, errors::RoutingError>>()?;
let default_configs = state
.conf
.pm_filters
.0
.get("default")
.cloned()
.map(ForeignFrom::foreign_from);
let config_pm_filters = CountryCurrencyFilter {
connector_configs,
default_configs,
};
let cgraph = Arc::new(
mca_graph::make_mca_graph(api_mcas, &config_pm_filters)
.change_context(errors::RoutingError::KgraphCacheRefreshFailed)
.attach_printable("when construction cgraph")?,
);
CGRAPH_CACHE
.push(
CacheKey {
key,
prefix: state.tenant.redis_key_prefix.clone(),
},
Arc::clone(&cgraph),
)
.await;
Ok(cgraph)
}
<file_sep path="hyperswitch/crates/router/src/core/payments/routing.rs" role="context" start="671" end="715">
pub async fn get_merchant_cgraph(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
profile_id: &common_utils::id_type::ProfileId,
transaction_type: &api_enums::TransactionType,
) -> RoutingResult<Arc<hyperswitch_constraint_graph::ConstraintGraph<euclid_dir::DirValue>>> {
let merchant_id = &key_store.merchant_id;
let key = {
match transaction_type {
api_enums::TransactionType::Payment => {
format!(
"cgraph_{}_{}",
merchant_id.get_string_repr(),
profile_id.get_string_repr()
)
}
#[cfg(feature = "payouts")]
api_enums::TransactionType::Payout => {
format!(
"cgraph_po_{}_{}",
merchant_id.get_string_repr(),
profile_id.get_string_repr()
)
}
}
};
let cached_cgraph = CGRAPH_CACHE
.get_val::<Arc<hyperswitch_constraint_graph::ConstraintGraph<euclid_dir::DirValue>>>(
CacheKey {
key: key.clone(),
prefix: state.tenant.redis_key_prefix.clone(),
},
)
.await;
let cgraph = if let Some(graph) = cached_cgraph {
graph
} else {
refresh_cgraph_cache(state, key_store, key.clone(), profile_id, transaction_type).await?
};
Ok(cgraph)
}
<file_sep path="hyperswitch/crates/router/src/core/payments/routing.rs" role="context" start="1373" end="1423">
async fn perform_session_routing_for_pm_type<'a>(
state: &'a SessionState,
key_store: &'a domain::MerchantKeyStore,
session_pm_input: &SessionRoutingPmTypeInput<'_>,
transaction_type: &api_enums::TransactionType,
business_profile: &domain::Profile,
) -> RoutingResult<Option<Vec<api_models::routing::RoutableConnectorChoice>>> {
let profile_wrapper = admin::ProfileWrapper::new(business_profile.clone());
let chosen_connectors = get_chosen_connectors(
state,
key_store,
session_pm_input,
transaction_type,
&profile_wrapper,
)
.await?;
let mut final_selection = perform_cgraph_filtering(
state,
key_store,
chosen_connectors,
session_pm_input.backend_input.clone(),
None,
session_pm_input.profile_id,
transaction_type,
)
.await?;
if final_selection.is_empty() {
let fallback = profile_wrapper
.get_default_fallback_list_of_connector_under_profile()
.change_context(errors::RoutingError::FallbackConfigFetchFailed)?;
final_selection = perform_cgraph_filtering(
state,
key_store,
fallback,
session_pm_input.backend_input.clone(),
None,
session_pm_input.profile_id,
transaction_type,
)
.await?;
}
if final_selection.is_empty() {
Ok(None)
} else {
Ok(Some(final_selection))
}
}
<file_sep path="hyperswitch/crates/router/src/core/payments/routing.rs" role="context" start="111" end="111">
type RoutingResult<O> = oss_errors::CustomResult<O, errors::RoutingError>;
<file_sep path="hyperswitch/crates/router/src/core/errors.rs" role="context" start="339" end="410">
pub enum RoutingError {
#[error("Merchant routing algorithm not found in cache")]
CacheMiss,
#[error("Final connector selection failed")]
ConnectorSelectionFailed,
#[error("[DSL] Missing required field in payment data: '{field_name}'")]
DslMissingRequiredField { field_name: String },
#[error("The lock on the DSL cache is most probably poisoned")]
DslCachePoisoned,
#[error("Expected DSL to be saved in DB but did not find")]
DslMissingInDb,
#[error("Unable to parse DSL from JSON")]
DslParsingError,
#[error("Failed to initialize DSL backend")]
DslBackendInitError,
#[error("Error updating merchant with latest dsl cache contents")]
DslMerchantUpdateError,
#[error("Error executing the DSL")]
DslExecutionError,
#[error("Final connector selection failed")]
DslFinalConnectorSelectionFailed,
#[error("[DSL] Received incorrect selection algorithm as DSL output")]
DslIncorrectSelectionAlgorithm,
#[error("there was an error saving/retrieving values from the kgraph cache")]
KgraphCacheFailure,
#[error("failed to refresh the kgraph cache")]
KgraphCacheRefreshFailed,
#[error("there was an error during the kgraph analysis phase")]
KgraphAnalysisError,
#[error("'profile_id' was not provided")]
ProfileIdMissing,
#[error("the profile was not found in the database")]
ProfileNotFound,
#[error("failed to fetch the fallback config for the merchant")]
FallbackConfigFetchFailed,
#[error("Invalid connector name received: '{0}'")]
InvalidConnectorName(String),
#[error("The routing algorithm in merchant account had invalid structure")]
InvalidRoutingAlgorithmStructure,
#[error("Volume split failed")]
VolumeSplitFailed,
#[error("Unable to parse metadata")]
MetadataParsingError,
#[error("Unable to retrieve success based routing config")]
SuccessBasedRoutingConfigError,
#[error("Params not found in success based routing config")]
SuccessBasedRoutingParamsNotFoundError,
#[error("Unable to calculate success based routing config from dynamic routing service")]
SuccessRateCalculationError,
#[error("Success rate client from dynamic routing gRPC service not initialized")]
SuccessRateClientInitializationError,
#[error("Unable to convert from '{from}' to '{to}'")]
GenericConversionError { from: String, to: String },
#[error("Invalid success based connector label received from dynamic routing service: '{0}'")]
InvalidSuccessBasedConnectorLabel(String),
#[error("unable to find '{field}'")]
GenericNotFoundError { field: String },
#[error("Unable to deserialize from '{from}' to '{to}'")]
DeserializationError { from: String, to: String },
#[error("Unable to retrieve contract based routing config")]
ContractBasedRoutingConfigError,
#[error("Params not found in contract based routing config")]
ContractBasedRoutingParamsNotFoundError,
#[error("Unable to calculate contract score from dynamic routing service: '{err}'")]
ContractScoreCalculationError { err: String },
#[error("Unable to update contract score on dynamic routing service")]
ContractScoreUpdationError,
#[error("contract routing client from dynamic routing gRPC service not initialized")]
ContractRoutingClientInitializationError,
#[error("Invalid contract based connector label received from dynamic routing service: '{0}'")]
InvalidContractBasedConnectorLabel(String),
}
<file_sep path="hyperswitch/migrations/2023-04-06-092008_create_merchant_ek/up.sql" role="context" start="1" end="6">
CREATE TABLE merchant_key_store(
merchant_id VARCHAR(255) NOT NULL PRIMARY KEY,
key bytea NOT NULL,
created_at TIMESTAMP NOT NULL
);
<file_sep path="hyperswitch/crates/api_models/src/routing.rs" role="context" start="173" end="179">
pub struct RoutableConnectorChoice {
#[serde(skip)]
pub choice_kind: RoutableChoiceKind,
pub connector: RoutableConnectors,
#[schema(value_type = Option<String>)]
pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/adyenplatform.rs<|crate|> router anchor=new kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/connector/adyenplatform.rs" role="context" start="52" end="57">
pub const fn new() -> &'static Self {
&Self {
#[cfg(feature = "payouts")]
amount_converter: &MinorUnitForConnector,
}
}
<file_sep path="hyperswitch/crates/router/src/connector/adyenplatform.rs" role="context" start="51" end="51">
use common_utils::types::MinorUnitForConnector;
<file_sep path="hyperswitch/crates/router/src/connector/adyenplatform.rs" role="context" start="65" end="75">
fn get_auth_header(
&self,
auth_type: &types::ConnectorAuthType,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
let auth = adyenplatform::AdyenplatformAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(vec![(
headers::AUTHORIZATION.to_string(),
auth.api_key.into_masked(),
)])
}
<file_sep path="hyperswitch/crates/router/src/connector/adyenplatform.rs" role="context" start="61" end="63">
fn id(&self) -> &'static str {
"adyenplatform"
}
<file_sep path="hyperswitch/crates/router/src/connector/adyenplatform.rs" role="context" start="345" end="381">
async fn verify_webhook_source(
&self,
request: &api::IncomingWebhookRequestDetails<'_>,
merchant_id: &common_utils::id_type::MerchantId,
connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>,
_connector_account_details: crypto::Encryptable<Secret<serde_json::Value>>,
connector_label: &str,
) -> CustomResult<bool, errors::ConnectorError> {
let connector_webhook_secrets = self
.get_webhook_source_verification_merchant_secret(
merchant_id,
connector_label,
connector_webhook_details,
)
.await
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;
let signature = self
.get_webhook_source_verification_signature(request, &connector_webhook_secrets)
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;
let message = self
.get_webhook_source_verification_message(
request,
merchant_id,
&connector_webhook_secrets,
)
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;
let raw_key = hex::decode(connector_webhook_secrets.secret)
.change_context(errors::ConnectorError::WebhookVerificationSecretInvalid)?;
let signing_key = hmac::Key::new(hmac::HMAC_SHA256, &raw_key);
let signed_messaged = hmac::sign(&signing_key, &message);
let payload_sign = consts::BASE64_ENGINE.encode(signed_messaged.as_ref());
Ok(payload_sign.as_bytes().eq(&signature))
}
<file_sep path="hyperswitch/crates/router/src/connector/adyenplatform.rs" role="context" start="448" end="465">
fn get_webhook_resource_object(
&self,
#[cfg(feature = "payouts")] request: &api::IncomingWebhookRequestDetails<'_>,
#[cfg(not(feature = "payouts"))] _request: &api::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
#[cfg(feature = "payouts")]
{
let webhook_body: adyenplatform::AdyenplatformIncomingWebhook = request
.body
.parse_struct("AdyenplatformIncomingWebhook")
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;
Ok(Box::new(webhook_body))
}
#[cfg(not(feature = "payouts"))]
{
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/nmi/transformers.rs<|crate|> router anchor=foreign_from kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/connector/nmi/transformers.rs" role="context" start="1314" end="1332">
fn foreign_from(status: NmiWebhookEventType) -> Self {
match status {
NmiWebhookEventType::SaleSuccess => Self::PaymentIntentSuccess,
NmiWebhookEventType::SaleFailure => Self::PaymentIntentFailure,
NmiWebhookEventType::RefundSuccess => Self::RefundSuccess,
NmiWebhookEventType::RefundFailure => Self::RefundFailure,
NmiWebhookEventType::VoidSuccess => Self::PaymentIntentCancelled,
NmiWebhookEventType::AuthSuccess => Self::PaymentIntentAuthorizationSuccess,
NmiWebhookEventType::CaptureSuccess => Self::PaymentIntentCaptureSuccess,
NmiWebhookEventType::AuthFailure => Self::PaymentIntentAuthorizationFailure,
NmiWebhookEventType::CaptureFailure => Self::PaymentIntentCaptureFailure,
NmiWebhookEventType::VoidFailure => Self::PaymentIntentCancelFailure,
NmiWebhookEventType::SaleUnknown
| NmiWebhookEventType::RefundUnknown
| NmiWebhookEventType::AuthUnknown
| NmiWebhookEventType::VoidUnknown
| NmiWebhookEventType::CaptureUnknown => Self::EventNotSupported,
}
}
<file_sep path="hyperswitch/crates/router/src/connector/nmi/transformers.rs" role="context" start="1350" end="1357">
fn try_from(item: &NmiWebhookBody) -> Result<Self, Self::Error> {
let transaction = Some(SyncTransactionResponse {
transaction_id: item.event_body.transaction_id.to_owned(),
condition: item.event_body.condition.to_owned(),
});
Ok(Self { transaction })
}
<file_sep path="hyperswitch/crates/router/src/connector/nmi/transformers.rs" role="context" start="1210" end="1222">
fn from(value: String) -> Self {
match value.as_str() {
"abandoned" => Self::Abandoned,
"canceled" => Self::Cancelled,
"in_progress" => Self::InProgress,
"pendingsettlement" => Self::Pendingsettlement,
"complete" => Self::Complete,
"failed" => Self::Failed,
"unknown" => Self::Unknown,
// Other than above values only pending is possible, since value is a string handling this as default
_ => Self::Pending,
}
}
<file_sep path="hyperswitch/crates/router/src/connector/nmi/transformers.rs" role="context" start="1197" end="1206">
fn from(item: NmiStatus) -> Self {
match item {
NmiStatus::Abandoned
| NmiStatus::Cancelled
| NmiStatus::Failed
| NmiStatus::Unknown => Self::Failure,
NmiStatus::Pending | NmiStatus::InProgress => Self::Pending,
NmiStatus::Pendingsettlement | NmiStatus::Complete => Self::Success,
}
}
<file_sep path="hyperswitch/crates/router/src/connector/nmi/transformers.rs" role="context" start="865" end="902">
fn try_from(
item: types::ResponseRouterData<
api::SetupMandate,
StandardResponse,
T,
types::PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let (response, status) = match item.response.response {
Response::Approved => (
Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::ConnectorTransactionId(
item.response.transactionid.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.orderid),
incremental_authorization_allowed: None,
charges: None,
}),
enums::AttemptStatus::Charged,
),
Response::Declined | Response::Error => (
Err(types::ErrorResponse::foreign_from((
item.response,
item.http_code,
))),
enums::AttemptStatus::Failure,
),
};
Ok(Self {
status,
response,
..item.data
})
}
<file_sep path="hyperswitch/crates/router/src/connector/nmi/transformers.rs" role="context" start="352" end="395">
fn try_from(
item: types::ResponseRouterData<
api::CompleteAuthorize,
NmiCompleteResponse,
types::CompleteAuthorizeData,
types::PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let (response, status) = match item.response.response {
Response::Approved => (
Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::ConnectorTransactionId(
item.response.transactionid,
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.orderid),
incremental_authorization_allowed: None,
charges: None,
}),
if let Some(diesel_models::enums::CaptureMethod::Automatic) =
item.data.request.capture_method
{
enums::AttemptStatus::CaptureInitiated
} else {
enums::AttemptStatus::Authorizing
},
),
Response::Declined | Response::Error => (
Err(types::ErrorResponse::foreign_from((
item.response,
item.http_code,
))),
enums::AttemptStatus::Failure,
),
};
Ok(Self {
status,
response,
..item.data
})
}
<file_sep path="hyperswitch/crates/router/src/connector/nmi/transformers.rs" role="context" start="1280" end="1311">
pub enum NmiWebhookEventType {
#[serde(rename = "transaction.sale.success")]
SaleSuccess,
#[serde(rename = "transaction.sale.failure")]
SaleFailure,
#[serde(rename = "transaction.sale.unknown")]
SaleUnknown,
#[serde(rename = "transaction.auth.success")]
AuthSuccess,
#[serde(rename = "transaction.auth.failure")]
AuthFailure,
#[serde(rename = "transaction.auth.unknown")]
AuthUnknown,
#[serde(rename = "transaction.refund.success")]
RefundSuccess,
#[serde(rename = "transaction.refund.failure")]
RefundFailure,
#[serde(rename = "transaction.refund.unknown")]
RefundUnknown,
#[serde(rename = "transaction.void.success")]
VoidSuccess,
#[serde(rename = "transaction.void.failure")]
VoidFailure,
#[serde(rename = "transaction.void.unknown")]
VoidUnknown,
#[serde(rename = "transaction.capture.success")]
CaptureSuccess,
#[serde(rename = "transaction.capture.failure")]
CaptureFailure,
#[serde(rename = "transaction.capture.unknown")]
CaptureUnknown,
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payments.rs<|crate|> router anchor=get_connector_choice kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="6040" end="6119">
pub async fn get_connector_choice<F, Req, D>(
operation: &BoxedOperation<'_, F, Req, D>,
state: &SessionState,
req: &Req,
merchant_account: &domain::MerchantAccount,
business_profile: &domain::Profile,
key_store: &domain::MerchantKeyStore,
payment_data: &mut D,
eligible_connectors: Option<Vec<enums::RoutableConnectors>>,
mandate_type: Option<api::MandateTransactionType>,
) -> RouterResult<Option<ConnectorCallType>>
where
F: Send + Clone,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
{
let connector_choice = operation
.to_domain()?
.get_connector(
merchant_account,
&state.clone(),
req,
payment_data.get_payment_intent(),
key_store,
)
.await?;
let connector = if should_call_connector(operation, payment_data) {
Some(match connector_choice {
api::ConnectorChoice::SessionMultiple(connectors) => {
let routing_output = perform_session_token_routing(
state.clone(),
merchant_account,
business_profile,
key_store,
payment_data,
connectors,
)
.await?;
ConnectorCallType::SessionMultiple(routing_output)
}
api::ConnectorChoice::StraightThrough(straight_through) => {
connector_selection(
state,
merchant_account,
business_profile,
key_store,
payment_data,
Some(straight_through),
eligible_connectors,
mandate_type,
)
.await?
}
api::ConnectorChoice::Decide => {
connector_selection(
state,
merchant_account,
business_profile,
key_store,
payment_data,
None,
eligible_connectors,
mandate_type,
)
.await?
}
})
} else if let api::ConnectorChoice::StraightThrough(algorithm) = connector_choice {
update_straight_through_routing(payment_data, algorithm)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update straight through routing algorithm")?;
None
} else {
None
};
Ok(connector)
}
<file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="6039" end="6039">
let _: api_models::routing::RoutingAlgorithm = request_straight_through
.clone()
.parse_value("RoutingAlgorithm")
.attach_printable("Invalid straight through routing rules format")?;
payment_data.set_straight_through_algorithm_in_payment_attempt(request_straight_through);
Ok(())
}
#[cfg(feature = "v1")]
#[allow(clippy::too_many_arguments)]
pub async fn get_connector_choice<F, Req, D>(
operation: &BoxedOperation<'_, F, Req, D>,
state: &SessionState,
req: &Req,
merchant_account: &domain::MerchantAccount,
business_profile: &domain::Profile,
key_store: &domain::MerchantKeyStore,
payment_data: &mut D,
eligible_connectors: Option<Vec<enums::RoutableConnectors>>,
mandate_type: Option<api::MandateTransactionType>,
) -> RouterResult<Option<ConnectorCallType>>
where
F: Send + Clone,
<file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="6186" end="6242">
pub async fn set_eligible_connector_for_nti_in_payment_data<F, D>(
state: &SessionState,
business_profile: &domain::Profile,
key_store: &domain::MerchantKeyStore,
payment_data: &mut D,
connector_choice: api::ConnectorChoice,
) -> RouterResult<api::ConnectorData>
where
F: Send + Clone,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
{
let (mandate_reference_id, card_details_for_network_transaction_id, eligible_connector_data) =
match connector_choice {
api::ConnectorChoice::StraightThrough(straight_through) => {
get_eligible_connector_for_nti(
state,
key_store,
payment_data,
core_routing::StraightThroughAlgorithmTypeSingle(straight_through),
business_profile,
)
.await?
}
api::ConnectorChoice::Decide => {
get_eligible_connector_for_nti(
state,
key_store,
payment_data,
core_routing::DecideConnector,
business_profile,
)
.await?
}
api::ConnectorChoice::SessionMultiple(_) => {
Err(errors::ApiErrorResponse::InternalServerError).attach_printable(
"Invalid routing rule configured for nti and card details based mit flow",
)?
}
};
// Set the eligible connector in the attempt
payment_data
.set_connector_in_payment_attempt(Some(eligible_connector_data.connector_name.to_string()));
// Set `NetworkMandateId` as the MandateId
payment_data.set_mandate_id(payments_api::MandateIds {
mandate_id: None,
mandate_reference_id: Some(mandate_reference_id),
});
// Set the card details received in the recurring details within the payment method data.
payment_data.set_payment_method_data(Some(
hyperswitch_domain_models::payment_method_data::PaymentMethodData::CardDetailsForNetworkTransactionId(card_details_for_network_transaction_id),
));
Ok(eligible_connector_data)
}
<file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="6121" end="6184">
async fn get_eligible_connector_for_nti<T: core_routing::GetRoutableConnectorsForChoice, F, D>(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
payment_data: &D,
connector_choice: T,
business_profile: &domain::Profile,
) -> RouterResult<(
api_models::payments::MandateReferenceId,
hyperswitch_domain_models::payment_method_data::CardDetailsForNetworkTransactionId,
api::ConnectorData,
)>
where
F: Send + Clone,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
{
// Since this flow will only be used in the MIT flow, recurring details are mandatory.
let recurring_payment_details = payment_data
.get_recurring_details()
.ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)
.attach_printable("Failed to fetch recurring details for mit")?;
let (mandate_reference_id, card_details_for_network_transaction_id)= hyperswitch_domain_models::payment_method_data::CardDetailsForNetworkTransactionId::get_nti_and_card_details_for_mit_flow(recurring_payment_details.clone()).get_required_value("network transaction id and card details").attach_printable("Failed to fetch network transaction id and card details for mit")?;
helpers::validate_card_expiry(
&card_details_for_network_transaction_id.card_exp_month,
&card_details_for_network_transaction_id.card_exp_year,
)?;
let network_transaction_id_supported_connectors = &state
.conf
.network_transaction_id_supported_connectors
.connector_list
.iter()
.map(|value| value.to_string())
.collect::<HashSet<_>>();
let eligible_connector_data_list = connector_choice
.get_routable_connectors(&*state.store, business_profile)
.await?
.filter_network_transaction_id_flow_supported_connectors(
network_transaction_id_supported_connectors.to_owned(),
)
.construct_dsl_and_perform_eligibility_analysis(
state,
key_store,
payment_data,
business_profile.get_id(),
)
.await
.attach_printable("Failed to fetch eligible connector data")?;
let eligible_connector_data = eligible_connector_data_list
.first()
.ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)
.attach_printable(
"No eligible connector found for the network transaction id based mit flow",
)?;
Ok((
mandate_reference_id,
card_details_for_network_transaction_id,
eligible_connector_data.clone(),
))
}
<file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="6020" end="6036">
pub fn update_straight_through_routing<F, D>(
payment_data: &mut D,
request_straight_through: serde_json::Value,
) -> CustomResult<(), errors::ParsingError>
where
F: Send + Clone,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
{
let _: api_models::routing::RoutingAlgorithm = request_straight_through
.clone()
.parse_value("RoutingAlgorithm")
.attach_printable("Invalid straight through routing rules format")?;
payment_data.set_straight_through_algorithm_in_payment_attempt(request_straight_through);
Ok(())
}
<file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="5996" end="6017">
pub async fn reset_process_sync_task(
db: &dyn StorageInterface,
payment_attempt: &storage::PaymentAttempt,
schedule_time: time::PrimitiveDateTime,
) -> Result<(), errors::ProcessTrackerError> {
let runner = storage::ProcessTrackerRunner::PaymentsSyncWorkflow;
let task = "PAYMENTS_SYNC";
let process_tracker_id = pt_utils::get_process_tracker_id(
runner,
task,
payment_attempt.get_id(),
&payment_attempt.merchant_id,
);
let psync_process = db
.find_process_by_id(&process_tracker_id)
.await?
.ok_or(errors::ProcessTrackerError::ProcessFetchingFailed)?;
db.as_scheduler()
.reset_process(psync_process, schedule_time)
.await?;
Ok(())
}
<file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="258" end="893">
pub async fn payments_operation_core<F, Req, Op, FData, D>(
state: &SessionState,
req_state: ReqState,
merchant_account: domain::MerchantAccount,
profile_id_from_auth_layer: Option<id_type::ProfileId>,
key_store: domain::MerchantKeyStore,
operation: Op,
req: Req,
call_connector_action: CallConnectorAction,
auth_flow: services::AuthFlow,
eligible_connectors: Option<Vec<common_enums::RoutableConnectors>>,
header_payload: HeaderPayload,
platform_merchant_account: Option<domain::MerchantAccount>,
) -> RouterResult<(D, Req, Option<domain::Customer>, Option<u16>, Option<u128>)>
where
F: Send + Clone + Sync,
Req: Authenticate + Clone,
Op: Operation<F, Req, Data = D> + Send + Sync,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
// To create connector flow specific interface data
D: ConstructFlowSpecificData<F, FData, router_types::PaymentsResponseData>,
RouterData<F, FData, router_types::PaymentsResponseData>: Feature<F, FData>,
// To construct connector flow specific api
dyn api::Connector:
services::api::ConnectorIntegration<F, FData, router_types::PaymentsResponseData>,
// To perform router related operation for PaymentResponse
PaymentResponse: Operation<F, FData, Data = D>,
FData: Send + Sync + Clone,
{
let operation: BoxedOperation<'_, F, Req, D> = Box::new(operation);
tracing::Span::current().record("merchant_id", merchant_account.get_id().get_string_repr());
let (operation, validate_result) = operation
.to_validate_request()?
.validate_request(&req, &merchant_account)?;
tracing::Span::current().record("payment_id", format!("{}", validate_result.payment_id));
// get profile from headers
let operations::GetTrackerResponse {
operation,
customer_details,
mut payment_data,
business_profile,
mandate_type,
} = operation
.to_get_tracker()?
.get_trackers(
state,
&validate_result.payment_id,
&req,
&merchant_account,
&key_store,
auth_flow,
&header_payload,
platform_merchant_account.as_ref(),
)
.await?;
operation
.to_get_tracker()?
.validate_request_with_state(state, &req, &mut payment_data, &business_profile)
.await?;
core_utils::validate_profile_id_from_auth_layer(
profile_id_from_auth_layer,
&payment_data.get_payment_intent().clone(),
)?;
let (operation, customer) = operation
.to_domain()?
// get_customer_details
.get_or_create_customer_details(
state,
&mut payment_data,
customer_details,
&key_store,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)
.attach_printable("Failed while fetching/creating customer")?;
let authentication_type =
call_decision_manager(state, &merchant_account, &business_profile, &payment_data).await?;
payment_data.set_authentication_type_in_attempt(authentication_type);
let connector = get_connector_choice(
&operation,
state,
&req,
&merchant_account,
&business_profile,
&key_store,
&mut payment_data,
eligible_connectors,
mandate_type,
)
.await?;
let should_add_task_to_process_tracker = should_add_task_to_process_tracker(&payment_data);
let locale = header_payload.locale.clone();
payment_data = tokenize_in_router_when_confirm_false_or_external_authentication(
state,
&operation,
&mut payment_data,
&validate_result,
&key_store,
&customer,
&business_profile,
)
.await?;
let mut connector_http_status_code = None;
let mut external_latency = None;
if let Some(connector_details) = connector {
// Fetch and check FRM configs
#[cfg(feature = "frm")]
let mut frm_info = None;
#[allow(unused_variables, unused_mut)]
let mut should_continue_transaction: bool = true;
#[cfg(feature = "frm")]
let mut should_continue_capture: bool = true;
#[cfg(feature = "frm")]
let frm_configs = if state.conf.frm.enabled {
Box::pin(frm_core::call_frm_before_connector_call(
&operation,
&merchant_account,
&mut payment_data,
state,
&mut frm_info,
&customer,
&mut should_continue_transaction,
&mut should_continue_capture,
key_store.clone(),
))
.await?
} else {
None
};
#[cfg(feature = "frm")]
logger::debug!(
"frm_configs: {:?}\nshould_continue_transaction: {:?}\nshould_continue_capture: {:?}",
frm_configs,
should_continue_transaction,
should_continue_capture,
);
let is_eligible_for_uas =
helpers::is_merchant_eligible_authentication_service(merchant_account.get_id(), state)
.await?;
if is_eligible_for_uas {
let should_do_uas_confirmation_call = false;
operation
.to_domain()?
.call_unified_authentication_service_if_eligible(
state,
&mut payment_data,
&mut should_continue_transaction,
&connector_details,
&business_profile,
&key_store,
mandate_type,
&should_do_uas_confirmation_call,
)
.await?;
} else {
logger::info!(
"skipping authentication service call since the merchant is not eligible."
);
operation
.to_domain()?
.call_external_three_ds_authentication_if_eligible(
state,
&mut payment_data,
&mut should_continue_transaction,
&connector_details,
&business_profile,
&key_store,
mandate_type,
)
.await?;
};
operation
.to_domain()?
.payments_dynamic_tax_calculation(
state,
&mut payment_data,
&connector_details,
&business_profile,
&key_store,
&merchant_account,
)
.await?;
if should_continue_transaction {
#[cfg(feature = "frm")]
match (
should_continue_capture,
payment_data.get_payment_attempt().capture_method,
) {
(
false,
Some(storage_enums::CaptureMethod::Automatic)
| Some(storage_enums::CaptureMethod::SequentialAutomatic),
)
| (false, Some(storage_enums::CaptureMethod::Scheduled)) => {
if let Some(info) = &mut frm_info {
if let Some(frm_data) = &mut info.frm_data {
frm_data.fraud_check.payment_capture_method =
payment_data.get_payment_attempt().capture_method;
}
}
payment_data
.set_capture_method_in_attempt(storage_enums::CaptureMethod::Manual);
logger::debug!("payment_id : {:?} capture method has been changed to manual, since it has configured Post FRM flow",payment_data.get_payment_attempt().payment_id);
}
_ => (),
};
payment_data = match connector_details {
ConnectorCallType::PreDetermined(ref connector) => {
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
let routable_connectors =
convert_connector_data_to_routable_connectors(&[connector.clone()])
.map_err(|e| logger::error!(routable_connector_error=?e))
.unwrap_or_default();
let schedule_time = if should_add_task_to_process_tracker {
payment_sync::get_sync_process_schedule_time(
&*state.store,
connector.connector.id(),
merchant_account.get_id(),
0,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while getting process schedule time")?
} else {
None
};
let (router_data, mca) = call_connector_service(
state,
req_state.clone(),
&merchant_account,
&key_store,
connector.clone(),
&operation,
&mut payment_data,
&customer,
call_connector_action.clone(),
&validate_result,
schedule_time,
header_payload.clone(),
#[cfg(feature = "frm")]
frm_info.as_ref().and_then(|fi| fi.suggested_action),
#[cfg(not(feature = "frm"))]
None,
&business_profile,
false,
false,
)
.await?;
if is_eligible_for_uas {
let should_do_uas_confirmation_call = true;
operation
.to_domain()?
.call_unified_authentication_service_if_eligible(
state,
&mut payment_data,
&mut should_continue_transaction,
&connector_details,
&business_profile,
&key_store,
mandate_type,
&should_do_uas_confirmation_call,
)
.await?;
}
let op_ref = &operation;
let should_trigger_post_processing_flows = is_operation_confirm(&operation);
let operation = Box::new(PaymentResponse);
connector_http_status_code = router_data.connector_http_status_code;
external_latency = router_data.external_latency;
//add connector http status code metrics
add_connector_http_status_code_metrics(connector_http_status_code);
operation
.to_post_update_tracker()?
.save_pm_and_mandate(
state,
&router_data,
&merchant_account,
&key_store,
&mut payment_data,
&business_profile,
)
.await?;
let mut payment_data = operation
.to_post_update_tracker()?
.update_tracker(
state,
payment_data,
router_data,
&key_store,
merchant_account.storage_scheme,
&locale,
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
routable_connectors,
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
&business_profile,
)
.await?;
if should_trigger_post_processing_flows {
complete_postprocessing_steps_if_required(
state,
&merchant_account,
&key_store,
&customer,
&mca,
connector,
&mut payment_data,
op_ref,
Some(header_payload.clone()),
)
.await?;
}
payment_data
}
ConnectorCallType::Retryable(ref connectors) => {
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
let routable_connectors =
convert_connector_data_to_routable_connectors(connectors)
.map_err(|e| logger::error!(routable_connector_error=?e))
.unwrap_or_default();
let mut connectors = connectors.clone().into_iter();
let connector_data = get_connector_data(&mut connectors)?;
let schedule_time = if should_add_task_to_process_tracker {
payment_sync::get_sync_process_schedule_time(
&*state.store,
connector_data.connector.id(),
merchant_account.get_id(),
0,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while getting process schedule time")?
} else {
None
};
let (router_data, mca) = call_connector_service(
state,
req_state.clone(),
&merchant_account,
&key_store,
connector_data.clone(),
&operation,
&mut payment_data,
&customer,
call_connector_action.clone(),
&validate_result,
schedule_time,
header_payload.clone(),
#[cfg(feature = "frm")]
frm_info.as_ref().and_then(|fi| fi.suggested_action),
#[cfg(not(feature = "frm"))]
None,
&business_profile,
false,
false,
)
.await?;
#[cfg(all(feature = "retry", feature = "v1"))]
let mut router_data = router_data;
#[cfg(all(feature = "retry", feature = "v1"))]
{
use crate::core::payments::retry::{self, GsmValidation};
let config_bool = retry::config_should_call_gsm(
&*state.store,
merchant_account.get_id(),
&business_profile,
)
.await;
if config_bool && router_data.should_call_gsm() {
router_data = retry::do_gsm_actions(
state,
req_state.clone(),
&mut payment_data,
connectors,
&connector_data,
router_data,
&merchant_account,
&key_store,
&operation,
&customer,
&validate_result,
schedule_time,
#[cfg(feature = "frm")]
frm_info.as_ref().and_then(|fi| fi.suggested_action),
#[cfg(not(feature = "frm"))]
None,
&business_profile,
)
.await?;
};
}
let op_ref = &operation;
let should_trigger_post_processing_flows = is_operation_confirm(&operation);
if is_eligible_for_uas {
let should_do_uas_confirmation_call = true;
operation
.to_domain()?
.call_unified_authentication_service_if_eligible(
state,
&mut payment_data,
&mut should_continue_transaction,
&connector_details,
&business_profile,
&key_store,
mandate_type,
&should_do_uas_confirmation_call,
)
.await?;
}
let operation = Box::new(PaymentResponse);
connector_http_status_code = router_data.connector_http_status_code;
external_latency = router_data.external_latency;
//add connector http status code metrics
add_connector_http_status_code_metrics(connector_http_status_code);
operation
.to_post_update_tracker()?
.save_pm_and_mandate(
state,
&router_data,
&merchant_account,
&key_store,
&mut payment_data,
&business_profile,
)
.await?;
let mut payment_data = operation
.to_post_update_tracker()?
.update_tracker(
state,
payment_data,
router_data,
&key_store,
merchant_account.storage_scheme,
&locale,
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
routable_connectors,
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
&business_profile,
)
.await?;
if should_trigger_post_processing_flows {
complete_postprocessing_steps_if_required(
state,
&merchant_account,
&key_store,
&customer,
&mca,
&connector_data,
&mut payment_data,
op_ref,
Some(header_payload.clone()),
)
.await?;
}
payment_data
}
ConnectorCallType::SessionMultiple(connectors) => {
let session_surcharge_details =
call_surcharge_decision_management_for_session_flow(
state,
&merchant_account,
&business_profile,
payment_data.get_payment_attempt(),
payment_data.get_payment_intent(),
payment_data.get_billing_address(),
&connectors,
)
.await?;
Box::pin(call_multiple_connectors_service(
state,
&merchant_account,
&key_store,
connectors,
&operation,
payment_data,
&customer,
session_surcharge_details,
&business_profile,
header_payload.clone(),
))
.await?
}
};
#[cfg(feature = "frm")]
if let Some(fraud_info) = &mut frm_info {
#[cfg(feature = "v1")]
Box::pin(frm_core::post_payment_frm_core(
state,
req_state,
&merchant_account,
&mut payment_data,
fraud_info,
frm_configs
.clone()
.ok_or(errors::ApiErrorResponse::MissingRequiredField {
field_name: "frm_configs",
})
.attach_printable("Frm configs label not found")?,
&customer,
key_store.clone(),
&mut should_continue_capture,
platform_merchant_account.as_ref(),
))
.await?;
}
} else {
(_, payment_data) = operation
.to_update_tracker()?
.update_trackers(
state,
req_state,
payment_data.clone(),
customer.clone(),
validate_result.storage_scheme,
None,
&key_store,
#[cfg(feature = "frm")]
frm_info.and_then(|info| info.suggested_action),
#[cfg(not(feature = "frm"))]
None,
header_payload.clone(),
)
.await?;
}
let payment_intent_status = payment_data.get_payment_intent().status;
payment_data
.get_payment_attempt()
.payment_token
.as_ref()
.zip(payment_data.get_payment_attempt().payment_method)
.map(ParentPaymentMethodToken::create_key_for_token)
.async_map(|key_for_hyperswitch_token| async move {
if key_for_hyperswitch_token
.should_delete_payment_method_token(payment_intent_status)
{
let _ = key_for_hyperswitch_token.delete(state).await;
}
})
.await;
} else {
(_, payment_data) = operation
.to_update_tracker()?
.update_trackers(
state,
req_state,
payment_data.clone(),
customer.clone(),
validate_result.storage_scheme,
None,
&key_store,
None,
header_payload.clone(),
)
.await?;
}
let cloned_payment_data = payment_data.clone();
let cloned_customer = customer.clone();
#[cfg(feature = "v1")]
operation
.to_domain()?
.store_extended_card_info_temporarily(
state,
payment_data.get_payment_intent().get_id(),
&business_profile,
payment_data.get_payment_method_data(),
)
.await?;
utils::trigger_payments_webhook(
merchant_account,
business_profile,
&key_store,
cloned_payment_data,
cloned_customer,
state,
operation,
)
.await
.map_err(|error| logger::warn!(payments_outgoing_webhook_error=?error))
.ok();
Ok((
payment_data,
req,
customer,
connector_http_status_code,
external_latency,
))
}
<file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="7191" end="7230">
pub async fn perform_session_token_routing<F, D>(
state: SessionState,
business_profile: &domain::Profile,
key_store: &domain::MerchantKeyStore,
payment_data: &D,
connectors: api::SessionConnectorDatas,
) -> RouterResult<SessionTokenRoutingResult>
where
F: Clone,
D: OperationSessionGetters<F>,
{
let chosen = connectors.apply_filter_for_session_routing();
let sfr = SessionFlowRoutingInput {
country: payment_data
.get_payment_intent()
.billing_address
.as_ref()
.and_then(|address| address.get_inner().address.as_ref())
.and_then(|details| details.country),
payment_intent: payment_data.get_payment_intent(),
chosen,
};
let result = self_routing::perform_session_flow_routing(
&state,
key_store,
sfr,
business_profile,
&enums::TransactionType::Payment,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("error performing session flow routing")?;
let final_list = connectors.filter_and_validate_for_session_flow(&result)?;
Ok(SessionTokenRoutingResult {
final_result: final_list,
routing_result: result,
})
}
<file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="6246" end="6315">
pub async fn connector_selection<F, D>(
state: &SessionState,
merchant_account: &domain::MerchantAccount,
business_profile: &domain::Profile,
key_store: &domain::MerchantKeyStore,
payment_data: &mut D,
request_straight_through: Option<serde_json::Value>,
eligible_connectors: Option<Vec<enums::RoutableConnectors>>,
mandate_type: Option<api::MandateTransactionType>,
) -> RouterResult<ConnectorCallType>
where
F: Send + Clone,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
{
let request_straight_through: Option<api::routing::StraightThroughAlgorithm> =
request_straight_through
.map(|val| val.parse_value("RoutingAlgorithm"))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Invalid straight through routing rules format")?;
let mut routing_data = storage::RoutingData {
routed_through: payment_data.get_payment_attempt().connector.clone(),
merchant_connector_id: payment_data
.get_payment_attempt()
.merchant_connector_id
.clone(),
algorithm: request_straight_through.clone(),
routing_info: payment_data
.get_payment_attempt()
.straight_through_algorithm
.clone()
.map(|val| val.parse_value("PaymentRoutingInfo"))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Invalid straight through algorithm format found in payment attempt")?
.unwrap_or(storage::PaymentRoutingInfo {
algorithm: None,
pre_routing_results: None,
}),
};
let decided_connector = decide_connector(
state.clone(),
merchant_account,
business_profile,
key_store,
payment_data,
request_straight_through,
&mut routing_data,
eligible_connectors,
mandate_type,
)
.await?;
let encoded_info = routing_data
.routing_info
.encode_to_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("error serializing payment routing info to serde value")?;
payment_data.set_connector_in_payment_attempt(routing_data.routed_through);
payment_data.set_merchant_connector_id_in_attempt(routing_data.merchant_connector_id);
payment_data.set_straight_through_algorithm_in_payment_attempt(encoded_info);
Ok(decided_connector)
}
<file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="8054" end="8097">
pub trait OperationSessionSetters<F> {
// Setter functions for PaymentData
fn set_payment_intent(&mut self, payment_intent: storage::PaymentIntent);
fn set_payment_attempt(&mut self, payment_attempt: storage::PaymentAttempt);
fn set_payment_method_data(&mut self, payment_method_data: Option<domain::PaymentMethodData>);
fn set_email_if_not_present(&mut self, email: pii::Email);
fn set_payment_method_id_in_attempt(&mut self, payment_method_id: Option<String>);
fn set_pm_token(&mut self, token: String);
fn set_connector_customer_id(&mut self, customer_id: Option<String>);
fn push_sessions_token(&mut self, token: api::SessionToken);
fn set_surcharge_details(&mut self, surcharge_details: Option<types::SurchargeDetails>);
fn set_merchant_connector_id_in_attempt(
&mut self,
merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
);
#[cfg(feature = "v1")]
fn set_capture_method_in_attempt(&mut self, capture_method: enums::CaptureMethod);
fn set_frm_message(&mut self, frm_message: FraudCheck);
fn set_payment_intent_status(&mut self, status: storage_enums::IntentStatus);
fn set_authentication_type_in_attempt(
&mut self,
authentication_type: Option<enums::AuthenticationType>,
);
fn set_recurring_mandate_payment_data(
&mut self,
recurring_mandate_payment_data:
hyperswitch_domain_models::router_data::RecurringMandatePaymentData,
);
fn set_mandate_id(&mut self, mandate_id: api_models::payments::MandateIds);
fn set_setup_future_usage_in_payment_intent(
&mut self,
setup_future_usage: storage_enums::FutureUsage,
);
#[cfg(feature = "v1")]
fn set_straight_through_algorithm_in_payment_attempt(
&mut self,
straight_through_algorithm: serde_json::Value,
);
fn set_connector_in_payment_attempt(&mut self, connector: Option<String>);
#[cfg(feature = "v1")]
fn set_vault_operation(&mut self, vault_operation: domain_payments::VaultOperation);
}
<file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="8013" end="8052">
pub trait OperationSessionGetters<F> {
fn get_payment_attempt(&self) -> &storage::PaymentAttempt;
fn get_payment_intent(&self) -> &storage::PaymentIntent;
fn get_payment_method_info(&self) -> Option<&domain::PaymentMethod>;
fn get_mandate_id(&self) -> Option<&payments_api::MandateIds>;
fn get_address(&self) -> &PaymentAddress;
fn get_creds_identifier(&self) -> Option<&str>;
fn get_token(&self) -> Option<&str>;
fn get_multiple_capture_data(&self) -> Option<&types::MultipleCaptureData>;
fn get_payment_link_data(&self) -> Option<api_models::payments::PaymentLinkResponse>;
fn get_ephemeral_key(&self) -> Option<ephemeral_key::EphemeralKey>;
fn get_setup_mandate(&self) -> Option<&MandateData>;
fn get_poll_config(&self) -> Option<router_types::PollConfig>;
fn get_authentication(&self) -> Option<&storage::Authentication>;
fn get_frm_message(&self) -> Option<FraudCheck>;
fn get_refunds(&self) -> Vec<storage::Refund>;
fn get_disputes(&self) -> Vec<storage::Dispute>;
fn get_authorizations(&self) -> Vec<diesel_models::authorization::Authorization>;
fn get_attempts(&self) -> Option<Vec<storage::PaymentAttempt>>;
fn get_recurring_details(&self) -> Option<&RecurringDetails>;
// TODO: this should be a mandatory field, should we throw an error instead of returning an Option?
fn get_payment_intent_profile_id(&self) -> Option<&id_type::ProfileId>;
fn get_currency(&self) -> storage_enums::Currency;
fn get_amount(&self) -> api::Amount;
fn get_payment_attempt_connector(&self) -> Option<&str>;
fn get_billing_address(&self) -> Option<hyperswitch_domain_models::address::Address>;
fn get_payment_method_data(&self) -> Option<&domain::PaymentMethodData>;
fn get_sessions_token(&self) -> Vec<api::SessionToken>;
fn get_token_data(&self) -> Option<&storage::PaymentTokenData>;
fn get_mandate_connector(&self) -> Option<&MandateConnectorDetails>;
fn get_force_sync(&self) -> Option<bool>;
fn get_capture_method(&self) -> Option<enums::CaptureMethod>;
fn get_merchant_connector_id_in_attempt(&self) -> Option<id_type::MerchantConnectorAccountId>;
#[cfg(feature = "v1")]
fn get_vault_operation(&self) -> Option<&domain_payments::VaultOperation>;
#[cfg(feature = "v2")]
fn get_optional_payment_attempt(&self) -> Option<&storage::PaymentAttempt>;
}
<file_sep path="hyperswitch/crates/router/src/routes/app.rs" role="context" start="1906" end="1906">
pub struct Profile;
<file_sep path="hyperswitch/v2_compatible_migrations/2024-08-28-081757_drop_not_null_constraints_on_v1_columns/up.sql" role="context" start="5" end="21">
ALTER COLUMN org_id DROP NOT NULL;
-- Create index on org_id in organization table
-- This is done to mullify the effects of droping primary key for v1
CREATE INDEX idx_organization_org_id ON organization (org_id);
------------------------ Merchant Account -------------------
-- Drop not null in merchant_account table for v1 columns that are dropped in v2
ALTER TABLE merchant_account
DROP CONSTRAINT merchant_account_pkey,
ALTER COLUMN merchant_id DROP NOT NULL,
ALTER COLUMN primary_business_details DROP NOT NULL,
ALTER COLUMN is_recon_enabled DROP NOT NULL;
-- This is done to mullify the effects of droping primary key for v1
CREATE INDEX idx_merchant_account_merchant_id ON merchant_account (merchant_id);
<file_sep path="hyperswitch/crates/api_models/src/errors/types.rs" role="context" start="86" end="100">
pub enum ApiErrorResponse {
Unauthorized(ApiError),
ForbiddenCommonResource(ApiError),
ForbiddenPrivateResource(ApiError),
Conflict(ApiError),
Gone(ApiError),
Unprocessable(ApiError),
InternalServerError(ApiError),
NotImplemented(ApiError),
ConnectorError(ApiError, #[serde(skip_serializing)] StatusCode),
NotFound(ApiError),
MethodNotAllowed(ApiError),
BadRequest(ApiError),
DomainError(ApiError),
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/api_keys.rs<|crate|> router anchor=add_api_key_expiry_task kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/api_keys.rs" role="context" start="192" end="251">
pub async fn add_api_key_expiry_task(
store: &dyn crate::db::StorageInterface,
api_key: &ApiKey,
expiry_reminder_days: Vec<u8>,
) -> Result<(), errors::ProcessTrackerError> {
let current_time = date_time::now();
let schedule_time = expiry_reminder_days
.first()
.and_then(|expiry_reminder_day| {
api_key.expires_at.map(|expires_at| {
expires_at.saturating_sub(time::Duration::days(i64::from(*expiry_reminder_day)))
})
})
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to obtain initial process tracker schedule time")?;
if schedule_time <= current_time {
return Ok(());
}
let api_key_expiry_tracker = storage::ApiKeyExpiryTrackingData {
key_id: api_key.key_id.clone(),
merchant_id: api_key.merchant_id.clone(),
api_key_name: api_key.name.clone(),
prefix: api_key.prefix.clone(),
// We need API key expiry too, because we need to decide on the schedule_time in
// execute_workflow() where we won't be having access to the Api key object.
api_key_expiry: api_key.expires_at,
expiry_reminder_days: expiry_reminder_days.clone(),
};
let process_tracker_id = generate_task_id_for_api_key_expiry_workflow(&api_key.key_id);
let process_tracker_entry = storage::ProcessTrackerNew::new(
process_tracker_id,
API_KEY_EXPIRY_NAME,
API_KEY_EXPIRY_RUNNER,
[API_KEY_EXPIRY_TAG],
api_key_expiry_tracker,
None,
schedule_time,
common_types::consts::API_VERSION,
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to construct API key expiry process tracker task")?;
store
.insert_process(process_tracker_entry)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| {
format!(
"Failed while inserting API key expiry reminder to process_tracker: {:?}",
api_key.key_id
)
})?;
metrics::TASKS_ADDED_COUNT.add(1, router_env::metric_attributes!(("flow", "ApiKeyExpiry")));
Ok(())
}
<file_sep path="hyperswitch/crates/router/src/core/api_keys.rs" role="context" start="191" end="191">
use common_utils::date_time;
use diesel_models::{api_keys::ApiKey, enums as storage_enums};
use router_env::{instrument, tracing};
use crate::{
configs::settings,
consts,
core::errors::{self, RouterResponse, StorageErrorExt},
db::domain,
routes::{metrics, SessionState},
services::{authentication, ApplicationResponse},
types::{api, storage, transformers::ForeignInto},
};
<file_sep path="hyperswitch/crates/router/src/core/api_keys.rs" role="context" start="271" end="359">
pub async fn update_api_key(
state: SessionState,
api_key: api::UpdateApiKeyRequest,
) -> RouterResponse<api::RetrieveApiKeyResponse> {
let merchant_id = api_key.merchant_id.clone();
let key_id = api_key.key_id.clone();
let store = state.store.as_ref();
let api_key = store
.update_api_key(
merchant_id.to_owned(),
key_id.to_owned(),
api_key.foreign_into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::ApiKeyNotFound)?;
let state_inner = state.clone();
let hashed_api_key = api_key.hashed_api_key.clone();
let key_id_inner = api_key.key_id.clone();
let expires_at = api_key.expires_at;
authentication::decision::spawn_tracked_job(
async move {
authentication::decision::add_api_key(
&state_inner,
hashed_api_key.into_inner().into(),
merchant_id.clone(),
key_id_inner,
expires_at.map(authentication::decision::convert_expiry),
)
.await
},
authentication::decision::ADD,
);
#[cfg(feature = "email")]
{
let expiry_reminder_days = state.conf.api_keys.get_inner().expiry_reminder_days.clone();
let task_id = generate_task_id_for_api_key_expiry_workflow(&key_id);
// In order to determine how to update the existing process in the process_tracker table,
// we need access to the current entry in the table.
let existing_process_tracker_task = store
.find_process_by_id(task_id.as_str())
.await
.change_context(errors::ApiErrorResponse::InternalServerError) // If retrieve failed
.attach_printable(
"Failed to retrieve API key expiry reminder task from process tracker",
)?;
// If process exist
if existing_process_tracker_task.is_some() {
if api_key.expires_at.is_some() {
// Process exist in process, update the process with new schedule_time
update_api_key_expiry_task(store, &api_key, expiry_reminder_days)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Failed to update API key expiry reminder task in process tracker",
)?;
}
// If an expiry is set to 'never'
else {
// Process exist in process, revoke it
revoke_api_key_expiry_task(store, &key_id)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Failed to revoke API key expiry reminder task in process tracker",
)?;
}
}
// This case occurs if the expiry for an API key is set to 'never' during its creation. If so,
// process in tracker was not created.
else if api_key.expires_at.is_some() {
// Process doesn't exist in process_tracker table, so create new entry with
// schedule_time based on new expiry set.
add_api_key_expiry_task(store, &api_key, expiry_reminder_days)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Failed to insert API key expiry reminder task to process tracker",
)?;
}
}
Ok(ApplicationResponse::Json(api_key.foreign_into()))
}
<file_sep path="hyperswitch/crates/router/src/core/api_keys.rs" role="context" start="254" end="268">
pub async fn retrieve_api_key(
state: SessionState,
merchant_id: common_utils::id_type::MerchantId,
key_id: common_utils::id_type::ApiKeyId,
) -> RouterResponse<api::RetrieveApiKeyResponse> {
let store = state.store.as_ref();
let api_key = store
.find_api_key_by_merchant_id_key_id_optional(&merchant_id, &key_id)
.await
.change_context(errors::ApiErrorResponse::InternalServerError) // If retrieve failed
.attach_printable("Failed to retrieve API key")?
.ok_or(report!(errors::ApiErrorResponse::ApiKeyNotFound))?; // If retrieve returned `None`
Ok(ApplicationResponse::Json(api_key.foreign_into()))
}
<file_sep path="hyperswitch/crates/router/src/core/api_keys.rs" role="context" start="112" end="184">
pub async fn create_api_key(
state: SessionState,
api_key: api::CreateApiKeyRequest,
key_store: domain::MerchantKeyStore,
) -> RouterResponse<api::CreateApiKeyResponse> {
let api_key_config = state.conf.api_keys.get_inner();
let store = state.store.as_ref();
let merchant_id = key_store.merchant_id.clone();
let hash_key = api_key_config.get_hash_key()?;
let plaintext_api_key = PlaintextApiKey::new(consts::API_KEY_LENGTH);
let api_key = storage::ApiKeyNew {
key_id: PlaintextApiKey::new_key_id(),
merchant_id: merchant_id.to_owned(),
name: api_key.name,
description: api_key.description,
hashed_api_key: plaintext_api_key.keyed_hash(hash_key.peek()).into(),
prefix: plaintext_api_key.prefix(),
created_at: date_time::now(),
expires_at: api_key.expiration.into(),
last_used: None,
};
let api_key = store
.insert_api_key(api_key)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to insert new API key")?;
let state_inner = state.clone();
let hashed_api_key = api_key.hashed_api_key.clone();
let merchant_id_inner = merchant_id.clone();
let key_id = api_key.key_id.clone();
let expires_at = api_key.expires_at;
authentication::decision::spawn_tracked_job(
async move {
authentication::decision::add_api_key(
&state_inner,
hashed_api_key.into_inner().into(),
merchant_id_inner,
key_id,
expires_at.map(authentication::decision::convert_expiry),
)
.await
},
authentication::decision::ADD,
);
metrics::API_KEY_CREATED.add(
1,
router_env::metric_attributes!(("merchant", merchant_id.clone())),
);
// Add process to process_tracker for email reminder, only if expiry is set to future date
// If the `api_key` is set to expire in less than 7 days, the merchant is not notified about it's expiry
#[cfg(feature = "email")]
{
if api_key.expires_at.is_some() {
let expiry_reminder_days = state.conf.api_keys.get_inner().expiry_reminder_days.clone();
add_api_key_expiry_task(store, &api_key, expiry_reminder_days)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to insert API key expiry reminder to process tracker")?;
}
}
Ok(ApplicationResponse::Json(
(api_key, plaintext_api_key).foreign_into(),
))
}
<file_sep path="hyperswitch/crates/router/src/core/api_keys.rs" role="context" start="78" end="108">
pub fn keyed_hash(&self, key: &[u8; Self::HASH_KEY_LEN]) -> HashedApiKey {
/*
Decisions regarding API key hashing algorithm chosen:
- Since API key hash verification would be done for each request, there is a requirement
for the hashing to be quick.
- Password hashing algorithms would not be suitable for this purpose as they're designed to
prevent brute force attacks, considering that the same password could be shared across
multiple sites by the user.
- Moreover, password hash verification happens once per user session, so the delay involved
is negligible, considering the security benefits it provides.
While with API keys (assuming uniqueness of keys across the application), the delay
involved in hashing (with the use of a password hashing algorithm) becomes significant,
considering that it must be done per request.
- Since we are the only ones generating API keys and are able to guarantee their uniqueness,
a simple hash algorithm is sufficient for this purpose.
Hash algorithms considered:
- Password hashing algorithms: Argon2id and PBKDF2
- Simple hashing algorithms: HMAC-SHA256, HMAC-SHA512, BLAKE3
After benchmarking the simple hashing algorithms, we decided to go with the BLAKE3 keyed
hashing algorithm, with a randomly generated key for the hash key.
*/
HashedApiKey(
blake3::keyed_hash(key, self.0.peek().as_bytes())
.to_hex()
.to_string(),
)
}
<file_sep path="hyperswitch/crates/router/src/core/api_keys.rs" role="context" start="59" end="63">
pub fn new(length: usize) -> Self {
let env = router_env::env::prefix_for_env();
let key = common_utils::crypto::generate_cryptographically_secure_random_string(length);
Self(format!("{env}_{key}").into())
}
<file_sep path="hyperswitch/crates/router/src/core/api_keys.rs" role="context" start="534" end="541">
fn generate_task_id_for_api_key_expiry_workflow(
key_id: &common_utils::id_type::ApiKeyId,
) -> String {
format!(
"{API_KEY_EXPIRY_RUNNER}_{API_KEY_EXPIRY_NAME}_{}",
key_id.get_string_repr()
)
}
<file_sep path="hyperswitch/crates/router/tests/utils.rs" role="context" start="394" end="396">
pub struct ApiKey {
api_key: String,
}
<file_sep path="hyperswitch/migrations/2023-02-01-135102_create_api_keys_table/up.sql" role="context" start="1" end="9">
CREATE TABLE api_keys (
key_id VARCHAR(64) NOT NULL PRIMARY KEY,
merchant_id VARCHAR(64) NOT NULL,
NAME VARCHAR(64) NOT NULL,
description VARCHAR(256) DEFAULT NULL,
hash_key VARCHAR(64) NOT NULL,
hashed_api_key VARCHAR(128) NOT NULL,
prefix VARCHAR(16) NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT now()::TIMESTAMP,
<file_sep path="hyperswitch/crates/api_models/src/errors/types.rs" role="context" start="86" end="100">
pub enum ApiErrorResponse {
Unauthorized(ApiError),
ForbiddenCommonResource(ApiError),
ForbiddenPrivateResource(ApiError),
Conflict(ApiError),
Gone(ApiError),
Unprocessable(ApiError),
InternalServerError(ApiError),
NotImplemented(ApiError),
ConnectorError(ApiError, #[serde(skip_serializing)] StatusCode),
NotFound(ApiError),
MethodNotAllowed(ApiError),
BadRequest(ApiError),
DomainError(ApiError),
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/configs/settings.rs<|crate|> router anchor=new kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/configs/settings.rs" role="context" start="907" end="909">
pub fn new() -> ApplicationResult<Self> {
Self::with_config_path(None)
}
<file_sep path="hyperswitch/crates/router/src/configs/settings.rs" role="context" start="906" end="906">
pub use hyperswitch_interfaces::configs::Connectors;
pub use router_env::config::{Log, LogConsole, LogFile, LogTelemetry};
use crate::{
configs,
core::errors::{ApplicationError, ApplicationResult},
env::{self, Env},
events::EventsConfig,
routes::app,
AppState,
};
<file_sep path="hyperswitch/crates/router/src/configs/settings.rs" role="context" start="960" end="1053">
pub fn validate(&self) -> ApplicationResult<()> {
self.server.validate()?;
self.master_database.get_inner().validate()?;
#[cfg(feature = "olap")]
self.replica_database.get_inner().validate()?;
// The logger may not yet be initialized when validating the application configuration
#[allow(clippy::print_stderr)]
self.redis.validate().map_err(|error| {
eprintln!("{error}");
ApplicationError::InvalidConfigurationValueError("Redis configuration".into())
})?;
if self.log.file.enabled {
if self.log.file.file_name.is_default_or_empty() {
return Err(error_stack::Report::from(
ApplicationError::InvalidConfigurationValueError(
"log file name must not be empty".into(),
),
));
}
if self.log.file.path.is_default_or_empty() {
return Err(error_stack::Report::from(
ApplicationError::InvalidConfigurationValueError(
"log directory path must not be empty".into(),
),
));
}
}
self.secrets.get_inner().validate()?;
self.locker.validate()?;
self.connectors.validate("connectors")?;
self.cors.validate()?;
self.scheduler
.as_ref()
.map(|scheduler_settings| scheduler_settings.validate())
.transpose()?;
#[cfg(feature = "kv_store")]
self.drainer.validate()?;
self.api_keys.get_inner().validate()?;
self.file_storage
.validate()
.map_err(|err| ApplicationError::InvalidConfigurationValueError(err.to_string()))?;
self.lock_settings.validate()?;
self.events.validate()?;
#[cfg(feature = "olap")]
self.opensearch.validate()?;
self.encryption_management
.validate()
.map_err(|err| ApplicationError::InvalidConfigurationValueError(err.into()))?;
self.secrets_management
.validate()
.map_err(|err| ApplicationError::InvalidConfigurationValueError(err.into()))?;
self.generic_link.payment_method_collect.validate()?;
self.generic_link.payout_link.validate()?;
#[cfg(feature = "v2")]
self.cell_information.validate()?;
self.network_tokenization_service
.as_ref()
.map(|x| x.get_inner().validate())
.transpose()?;
self.paze_decrypt_keys
.as_ref()
.map(|x| x.get_inner().validate())
.transpose()?;
self.google_pay_decrypt_keys
.as_ref()
.map(|x| x.validate())
.transpose()?;
self.key_manager.get_inner().validate()?;
#[cfg(feature = "email")]
self.email
.validate()
.map_err(|err| ApplicationError::InvalidConfigurationValueError(err.into()))?;
self.theme
.storage
.validate()
.map_err(|err| ApplicationError::InvalidConfigurationValueError(err.to_string()))?;
Ok(())
}
<file_sep path="hyperswitch/crates/router/src/configs/settings.rs" role="context" start="911" end="958">
pub fn with_config_path(config_path: Option<PathBuf>) -> ApplicationResult<Self> {
// Configuration values are picked up in the following priority order (1 being least
// priority):
// 1. Defaults from the implementation of the `Default` trait.
// 2. Values from config file. The config file accessed depends on the environment
// specified by the `RUN_ENV` environment variable. `RUN_ENV` can be one of
// `development`, `sandbox` or `production`. If nothing is specified for `RUN_ENV`,
// `/config/development.toml` file is read.
// 3. Environment variables prefixed with `ROUTER` and each level separated by double
// underscores.
//
// Values in config file override the defaults in `Default` trait, and the values set using
// environment variables override both the defaults and the config file values.
let environment = env::which();
let config_path = router_env::Config::config_path(&environment.to_string(), config_path);
let config = router_env::Config::builder(&environment.to_string())
.change_context(ApplicationError::ConfigurationError)?
.add_source(File::from(config_path).required(false));
#[cfg(feature = "v2")]
let config = {
let required_fields_config_file =
router_env::Config::get_config_directory().join(REQUIRED_FIELDS_CONFIG_FILE);
config.add_source(File::from(required_fields_config_file).required(false))
};
let config = config
.add_source(
Environment::with_prefix("ROUTER")
.try_parsing(true)
.separator("__")
.list_separator(",")
.with_list_parse_key("log.telemetry.route_to_trace")
.with_list_parse_key("redis.cluster_urls")
.with_list_parse_key("events.kafka.brokers")
.with_list_parse_key("connectors.supported.wallets")
.with_list_parse_key("connector_request_reference_id_config.merchant_ids_send_payment_id_as_connector_request_id"),
)
.build()
.change_context(ApplicationError::ConfigurationError)?;
serde_path_to_error::deserialize(config)
.attach_printable("Unable to deserialize application configuration")
.change_context(ApplicationError::ConfigurationError)
}
<file_sep path="hyperswitch/crates/router/src/configs/settings.rs" role="context" start="778" end="791">
fn from(val: Database) -> Self {
Self {
username: val.username,
password: val.password,
host: val.host,
port: val.port,
dbname: val.dbname,
pool_size: val.pool_size,
connection_timeout: val.connection_timeout,
queue_strategy: val.queue_strategy,
min_idle: val.min_idle,
max_lifetime: val.max_lifetime,
}
}
<file_sep path="hyperswitch/crates/router/src/configs/settings.rs" role="context" start="392" end="400">
fn default() -> Self {
Self {
#[allow(clippy::expect_used)]
logo: url::Url::parse("https://hyperswitch.io/favicon.ico")
.expect("Failed to parse default logo URL"),
merchant_name: Secret::new("HyperSwitch".to_string()),
theme: "#4285F4".to_string(),
}
}
<file_sep path="hyperswitch/crates/router/src/configs/settings.rs" role="context" start="1214" end="1250">
fn deserialize_hashset_inner<T>(value: impl AsRef<str>) -> Result<HashSet<T>, String>
where
T: Eq + std::str::FromStr + std::hash::Hash,
<T as std::str::FromStr>::Err: std::fmt::Display,
{
let (values, errors) = value
.as_ref()
.trim()
.split(',')
.map(|s| {
T::from_str(s.trim()).map_err(|error| {
format!(
"Unable to deserialize `{}` as `{}`: {error}",
s.trim(),
std::any::type_name::<T>()
)
})
})
.fold(
(HashSet::new(), Vec::new()),
|(mut values, mut errors), result| match result {
Ok(t) => {
values.insert(t);
(values, errors)
}
Err(error) => {
errors.push(error);
(values, errors)
}
},
);
if !errors.is_empty() {
Err(format!("Some errors occurred:\n{}", errors.join("\n")))
} else {
Ok(values)
}
}
<file_sep path="hyperswitch/crates/router/src/core/errors.rs" role="context" start="34" end="34">
pub type ApplicationResult<T> = error_stack::Result<T, ApplicationError>;
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/utils/currency.rs<|crate|> router anchor=from kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/utils/currency.rs" role="context" start="149" end="154">
fn from(value: Conversion) -> Self {
Self {
to_factor: value.to_factor,
from_factor: value.from_factor,
}
}
<file_sep path="hyperswitch/crates/router/src/utils/currency.rs" role="context" start="148" end="148">
use crate::{
logger,
routes::app::settings::{Conversion, DefaultExchangeRates},
services, SessionState,
};
<file_sep path="hyperswitch/crates/router/src/utils/currency.rs" role="context" start="178" end="198">
async fn call_api_if_redis_forex_data_expired(
state: &SessionState,
data_expiration_delay: u32,
) -> CustomResult<FxExchangeRatesCacheEntry, ForexError> {
match retrieve_forex_data_from_redis(state).await {
Ok(Some(data)) => {
call_forex_api_if_redis_data_expired(state, data, data_expiration_delay).await
}
Ok(None) => {
// No data in local as well as redis
call_forex_api_and_save_data_to_cache_and_redis(state, None).await?;
Err(ForexError::ForexDataUnavailable.into())
}
Err(error) => {
// Error in deriving forex rates from redis
logger::error!("forex_error: {:?}", error);
call_forex_api_and_save_data_to_cache_and_redis(state, None).await?;
Err(ForexError::ForexDataUnavailable.into())
}
}
}
<file_sep path="hyperswitch/crates/router/src/utils/currency.rs" role="context" start="158" end="176">
pub async fn get_forex_rates(
state: &SessionState,
data_expiration_delay: u32,
) -> CustomResult<FxExchangeRatesCacheEntry, ForexError> {
if let Some(local_rates) = retrieve_forex_from_local_cache().await {
if local_rates.is_expired(data_expiration_delay) {
// expired local data
logger::debug!("forex_log: Forex stored in cache is expired");
call_forex_api_and_save_data_to_cache_and_redis(state, Some(local_rates)).await
} else {
// Valid data present in local
logger::debug!("forex_log: forex found in cache");
Ok(local_rates)
}
} else {
// No data in local
call_api_if_redis_forex_data_expired(state, data_expiration_delay).await
}
}
<file_sep path="hyperswitch/crates/router/src/utils/currency.rs" role="context" start="130" end="145">
fn try_from(value: DefaultExchangeRates) -> Result<Self, Self::Error> {
let mut conversion_usable: HashMap<enums::Currency, CurrencyFactors> = HashMap::new();
for (curr, conversion) in value.conversion {
let enum_curr = enums::Currency::from_str(curr.as_str())
.change_context(ForexError::ConversionError)
.attach_printable("Unable to Convert currency received")?;
conversion_usable.insert(enum_curr, CurrencyFactors::from(conversion));
}
let base_curr = enums::Currency::from_str(value.base_currency.as_str())
.change_context(ForexError::ConversionError)
.attach_printable("Unable to convert base currency")?;
Ok(Self {
base_currency: base_curr,
conversion: conversion_usable,
})
}
<file_sep path="hyperswitch/crates/router/src/utils/currency.rs" role="context" start="119" end="126">
async fn save_forex_data_to_local_cache(
exchange_rates_cache_entry: FxExchangeRatesCacheEntry,
) -> CustomResult<(), ForexError> {
let mut local = FX_EXCHANGE_RATES_CACHE.write().await;
*local = Some(exchange_rates_cache_entry);
logger::debug!("forex_log: forex saved in cache");
Ok(())
}
<file_sep path="hyperswitch/crates/router/src/utils/currency.rs" role="context" start="449" end="465">
async fn acquire_redis_lock(state: &SessionState) -> CustomResult<bool, ForexError> {
let forex_api = state.conf.forex_api.get_inner();
logger::debug!("forex_log: Acquiring redis lock");
state
.store
.get_redis_conn()
.change_context(ForexError::RedisConnectionError)?
.set_key_if_not_exists_with_expiry(
&REDIX_FOREX_CACHE_KEY.into(),
"",
Some(i64::from(forex_api.redis_lock_timeout_in_seconds)),
)
.await
.map(|val| matches!(val, redis_interface::SetnxReply::KeySet))
.change_context(ForexError::CouldNotAcquireLock)
.attach_printable("Unable to acquire redis lock")
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/compatibility/stripe/payment_intents/types.rs<|crate|> router anchor=new kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/compatibility/stripe/payment_intents/types.rs" role="context" start="600" end="608">
pub fn new() -> Self {
Self {
object: "list",
data: vec![],
has_more: false,
total_count: 0,
url: "http://placeholder".to_string(),
}
}
<file_sep path="hyperswitch/crates/router/src/compatibility/stripe/payment_intents/types.rs" role="context" start="636" end="648">
fn try_from(item: StripePaymentListConstraints) -> Result<Self, Self::Error> {
Ok(Self {
customer_id: item.customer,
starting_after: item.starting_after,
ending_before: item.ending_before,
limit: item.limit,
created: from_timestamp_to_datetime(item.created)?,
created_lt: from_timestamp_to_datetime(item.created_lt)?,
created_gt: from_timestamp_to_datetime(item.created_gt)?,
created_lte: from_timestamp_to_datetime(item.created_lte)?,
created_gte: from_timestamp_to_datetime(item.created_gte)?,
})
}
<file_sep path="hyperswitch/crates/router/src/compatibility/stripe/payment_intents/types.rs" role="context" start="630" end="632">
fn default_limit() -> u32 {
10
}
<file_sep path="hyperswitch/crates/router/src/compatibility/stripe/payment_intents/types.rs" role="context" start="514" end="575">
fn from(resp: payments::PaymentsResponse) -> Self {
Self {
object: "payment_intent",
id: resp.payment_id,
status: StripePaymentStatus::from(resp.status),
amount: resp.amount.get_amount_as_i64(),
amount_capturable: resp.amount_capturable.get_amount_as_i64(),
amount_received: resp.amount_received.map(|amt| amt.get_amount_as_i64()),
connector: resp.connector,
client_secret: resp.client_secret,
created: resp.created.map(|t| t.assume_utc().unix_timestamp()),
currency: resp.currency.to_lowercase(),
customer: resp.customer_id,
description: resp.description,
refunds: resp
.refunds
.map(|a| a.into_iter().map(Into::into).collect()),
mandate: resp.mandate_id,
mandate_data: resp.mandate_data,
setup_future_usage: resp.setup_future_usage,
off_session: resp.off_session,
capture_on: resp.capture_on,
capture_method: resp.capture_method,
payment_method: resp.payment_method,
payment_method_data: resp
.payment_method_data
.and_then(|pmd| pmd.payment_method_data),
payment_token: resp.payment_token,
shipping: resp.shipping,
billing: resp.billing,
email: resp.email.map(|inner| inner.into()),
name: resp.name.map(Encryptable::into_inner),
phone: resp.phone.map(Encryptable::into_inner),
authentication_type: resp.authentication_type,
statement_descriptor_name: resp.statement_descriptor_name,
statement_descriptor_suffix: resp.statement_descriptor_suffix,
next_action: into_stripe_next_action(resp.next_action, resp.return_url),
cancellation_reason: resp.cancellation_reason,
metadata: resp.metadata,
charges: Charges::new(),
last_payment_error: resp.error_code.map(|code| LastPaymentError {
charge: None,
code: Some(code.to_owned()),
decline_code: None,
message: resp
.error_message
.unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()),
param: None,
payment_method: StripePaymentMethod {
payment_method_id: "place_holder_id".to_string(),
object: "payment_method",
card: None,
created: u64::try_from(date_time::now().assume_utc().unix_timestamp())
.unwrap_or_default(),
method_type: "card".to_string(),
livemode: false,
},
error_type: code,
}),
connector_transaction_id: resp.connector_transaction_id,
}
}
<file_sep path="hyperswitch/crates/router/src/compatibility/stripe/payment_intents/types.rs" role="context" start="452" end="457">
fn from(item: StripePaymentCancelRequest) -> Self {
Self {
cancellation_reason: item.cancellation_reason.map(|c| c.to_string()),
..Self::default()
}
}
<file_sep path="hyperswitch/crates/router/src/compatibility/stripe/payment_intents/types.rs" role="context" start="652" end="666">
fn from_timestamp_to_datetime(
time: Option<i64>,
) -> Result<Option<PrimitiveDateTime>, errors::ApiErrorResponse> {
if let Some(time) = time {
let time = time::OffsetDateTime::from_unix_timestamp(time).map_err(|_| {
errors::ApiErrorResponse::InvalidRequestData {
message: "Error while converting timestamp".to_string(),
}
})?;
Ok(Some(PrimitiveDateTime::new(time.date(), time.time())))
} else {
Ok(None)
}
}
<file_sep path="hyperswitch/crates/router/src/compatibility/stripe/payment_intents/types.rs" role="context" start="921" end="970">
fn get_pmd_based_on_payment_method_type(
payment_method_type: Option<api_enums::PaymentMethodType>,
billing_details: Option<hyperswitch_domain_models::address::Address>,
) -> Option<payments::PaymentMethodData> {
match payment_method_type {
Some(api_enums::PaymentMethodType::UpiIntent) => Some(payments::PaymentMethodData::Upi(
payments::UpiData::UpiIntent(payments::UpiIntentData {}),
)),
Some(api_enums::PaymentMethodType::Fps) => {
Some(payments::PaymentMethodData::RealTimePayment(Box::new(
payments::RealTimePaymentData::Fps {},
)))
}
Some(api_enums::PaymentMethodType::DuitNow) => {
Some(payments::PaymentMethodData::RealTimePayment(Box::new(
payments::RealTimePaymentData::DuitNow {},
)))
}
Some(api_enums::PaymentMethodType::PromptPay) => {
Some(payments::PaymentMethodData::RealTimePayment(Box::new(
payments::RealTimePaymentData::PromptPay {},
)))
}
Some(api_enums::PaymentMethodType::VietQr) => {
Some(payments::PaymentMethodData::RealTimePayment(Box::new(
payments::RealTimePaymentData::VietQr {},
)))
}
Some(api_enums::PaymentMethodType::Ideal) => Some(
payments::PaymentMethodData::BankRedirect(payments::BankRedirectData::Ideal {
billing_details: billing_details.as_ref().map(|billing_data| {
payments::BankRedirectBilling {
billing_name: billing_data.get_optional_full_name(),
email: billing_data.email.clone(),
}
}),
bank_name: None,
country: billing_details
.as_ref()
.and_then(|billing_data| billing_data.get_optional_country()),
}),
),
Some(api_enums::PaymentMethodType::LocalBankRedirect) => {
Some(payments::PaymentMethodData::BankRedirect(
payments::BankRedirectData::LocalBankRedirect {},
))
}
_ => None,
}
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/wellsfargopayout.rs<|crate|> router anchor=get_headers kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/connector/wellsfargopayout.rs" role="context" start="498" end="504">
fn get_headers(
&self,
req: &types::RefundSyncRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
<file_sep path="hyperswitch/crates/router/src/connector/wellsfargopayout.rs" role="context" start="497" end="497">
use common_utils::types::{AmountConvertor, StringMinorUnit, StringMinorUnitForConnector};
use self::transformers as wellsfargopayout;
use crate::{
configs::settings,
core::errors::{self, CustomResult},
events::connector_api_logs::ConnectorEvent,
headers,
services::{
self,
request::{self, Mask},
ConnectorIntegration, ConnectorSpecifications, ConnectorValidation,
},
types::{
self,
api::{self, ConnectorCommon, ConnectorCommonExt},
ErrorResponse, RequestContent, Response,
},
utils::BytesExt,
};
<file_sep path="hyperswitch/crates/router/src/connector/wellsfargopayout.rs" role="context" start="510" end="516">
fn get_url(
&self,
_req: &types::RefundSyncRouterData,
_connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
}
<file_sep path="hyperswitch/crates/router/src/connector/wellsfargopayout.rs" role="context" start="506" end="508">
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
<file_sep path="hyperswitch/crates/router/src/connector/wellsfargopayout.rs" role="context" start="486" end="492">
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
<file_sep path="hyperswitch/crates/router/src/connector/wellsfargopayout.rs" role="context" start="467" end="484">
fn handle_response(
&self,
data: &types::RefundsRouterData<api::Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
let response: wellsfargopayout::RefundResponse = res
.response
.parse_struct("wellsfargopayout RefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
<file_sep path="hyperswitch/crates/router/src/connector/wellsfargopayout.rs" role="context" start="448" end="465">
fn build_request(
&self,
req: &types::RefundsRouterData<api::Execute>,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
let request = services::RequestBuilder::new()
.method(services::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))
}
<file_sep path="hyperswitch/crates/router/src/connector/wellsfargopayout.rs" role="context" start="354" end="372">
fn build_request(
&self,
req: &types::PaymentsCaptureRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
Ok(Some(
services::RequestBuilder::new()
.method(services::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(),
))
}
<file_sep path="hyperswitch/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/event.test.js" role="context" start="61" end="78">
"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.",
);
}
// Response body should have value "succeeded" for "status"
if (jsonData?.status) {
pm.test(
"[POST]::/payments - Content check if value for 'status' matches 'succeeded'",
function () {
pm.expect(jsonData.status).to.eql("succeeded");
},
);
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/dummyconnector.rs<|crate|> router anchor=get_headers kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/connector/dummyconnector.rs" role="context" start="534" end="540">
fn get_headers(
&self,
req: &types::RefundSyncRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
<file_sep path="hyperswitch/crates/router/src/connector/dummyconnector.rs" role="context" start="533" end="533">
use common_utils::{consts as common_consts, request::RequestContent};
use crate::{
configs::settings,
connector::utils as connector_utils,
core::errors::{self, CustomResult},
events::connector_api_logs::ConnectorEvent,
headers,
services::{
self,
request::{self, Mask},
ConnectorIntegration, ConnectorSpecifications, ConnectorValidation,
},
types::{
self,
api::{self, ConnectorCommon, ConnectorCommonExt},
ErrorResponse, Response,
},
utils::BytesExt,
};
<file_sep path="hyperswitch/crates/router/src/connector/dummyconnector.rs" role="context" start="546" end="557">
fn get_url(
&self,
req: &types::RefundSyncRouterData,
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let refund_id = req.request.get_connector_refund_id()?;
Ok(format!(
"{}/refunds/{}",
self.base_url(connectors),
refund_id
))
}
<file_sep path="hyperswitch/crates/router/src/connector/dummyconnector.rs" role="context" start="542" end="544">
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
<file_sep path="hyperswitch/crates/router/src/connector/dummyconnector.rs" role="context" start="522" end="528">
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
<file_sep path="hyperswitch/crates/router/src/connector/dummyconnector.rs" role="context" start="502" end="520">
fn handle_response(
&self,
data: &types::RefundsRouterData<api::Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
let response: transformers::RefundResponse = res
.response
.parse_struct("transformers RefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
<file_sep path="hyperswitch/crates/router/src/connector/dummyconnector.rs" role="context" start="559" end="572">
fn build_request(
&self,
req: &types::RefundSyncRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Get)
.url(&types::RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
<file_sep path="hyperswitch/crates/router/src/connector/dummyconnector.rs" role="context" start="483" end="500">
fn build_request(
&self,
req: &types::RefundsRouterData<api::Execute>,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
let request = services::RequestBuilder::new()
.method(services::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))
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/signifyd.rs<|crate|> router anchor=get_headers kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/connector/signifyd.rs" role="context" start="579" end="585">
fn get_headers(
&self,
req: &frm_types::FrmRecordReturnRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
<file_sep path="hyperswitch/crates/router/src/connector/signifyd.rs" role="context" start="578" end="578">
use common_utils::{crypto, ext_traits::ByteSliceExt, request::RequestContent};
use crate::{
configs::settings,
core::errors::{self, CustomResult},
headers,
services::{self, request, ConnectorIntegration, ConnectorSpecifications, ConnectorValidation},
types::{
self,
api::{self, ConnectorCommon, ConnectorCommonExt},
},
};
use crate::{
consts,
events::connector_api_logs::ConnectorEvent,
types::{api::fraud_check as frm_api, fraud_check as frm_types, ErrorResponse, Response},
utils::BytesExt,
};
<file_sep path="hyperswitch/crates/router/src/connector/signifyd.rs" role="context" start="591" end="601">
fn get_url(
&self,
_req: &frm_types::FrmRecordReturnRouterData,
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}{}",
self.base_url(connectors),
"v3/orders/events/returns/records"
))
}
<file_sep path="hyperswitch/crates/router/src/connector/signifyd.rs" role="context" start="587" end="589">
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
<file_sep path="hyperswitch/crates/router/src/connector/signifyd.rs" role="context" start="562" end="568">
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
<file_sep path="hyperswitch/crates/router/src/connector/signifyd.rs" role="context" start="544" end="561">
fn handle_response(
&self,
data: &frm_types::FrmFulfillmentRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<frm_types::FrmFulfillmentRouterData, errors::ConnectorError> {
let response: signifyd::FrmFulfillmentSignifydApiResponse = res
.response
.parse_struct("FrmFulfillmentSignifydApiResponse Sale")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
frm_types::FrmFulfillmentRouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
<file_sep path="hyperswitch/crates/router/src/connector/signifyd.rs" role="context" start="522" end="542">
fn build_request(
&self,
req: &frm_types::FrmFulfillmentRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Post)
.url(&frm_types::FrmFulfillmentType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(frm_types::FrmFulfillmentType::get_headers(
self, req, connectors,
)?)
.set_body(frm_types::FrmFulfillmentType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
<file_sep path="hyperswitch/crates/router/src/connector/signifyd.rs" role="context" start="256" end="272">
fn build_request(
&self,
req: &frm_types::FrmSaleRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Post)
.url(&frm_types::FrmSaleType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(frm_types::FrmSaleType::get_headers(self, req, connectors)?)
.set_body(frm_types::FrmSaleType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
<file_sep path="hyperswitch/crates/router/src/types/fraud_check.rs" role="context" start="72" end="73">
pub type FrmRecordReturnRouterData =
RouterData<api::RecordReturn, FraudCheckRecordReturnData, FraudCheckResponseData>;
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/wellsfargopayout.rs<|crate|> router anchor=get_url kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/connector/wellsfargopayout.rs" role="context" start="510" end="516">
fn get_url(
&self,
_req: &types::RefundSyncRouterData,
_connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
}
<file_sep path="hyperswitch/crates/router/src/connector/wellsfargopayout.rs" role="context" start="509" end="509">
use common_utils::types::{AmountConvertor, StringMinorUnit, StringMinorUnitForConnector};
use self::transformers as wellsfargopayout;
use crate::{
configs::settings,
core::errors::{self, CustomResult},
events::connector_api_logs::ConnectorEvent,
headers,
services::{
self,
request::{self, Mask},
ConnectorIntegration, ConnectorSpecifications, ConnectorValidation,
},
types::{
self,
api::{self, ConnectorCommon, ConnectorCommonExt},
ErrorResponse, RequestContent, Response,
},
utils::BytesExt,
};
<file_sep path="hyperswitch/crates/router/src/connector/wellsfargopayout.rs" role="context" start="536" end="553">
fn handle_response(
&self,
data: &types::RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> {
let response: wellsfargopayout::RefundResponse = res
.response
.parse_struct("wellsfargopayout RefundSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
<file_sep path="hyperswitch/crates/router/src/connector/wellsfargopayout.rs" role="context" start="518" end="534">
fn build_request(
&self,
req: &types::RefundSyncRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
Ok(Some(
services::RequestBuilder::new()
.method(services::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(),
))
}
<file_sep path="hyperswitch/crates/router/src/connector/wellsfargopayout.rs" role="context" start="506" end="508">
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
<file_sep path="hyperswitch/crates/router/src/connector/wellsfargopayout.rs" role="context" start="498" end="504">
fn get_headers(
&self,
req: &types::RefundSyncRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
<file_sep path="hyperswitch/crates/router/src/connector/wellsfargopayout.rs" role="context" start="448" end="465">
fn build_request(
&self,
req: &types::RefundsRouterData<api::Execute>,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
let request = services::RequestBuilder::new()
.method(services::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))
}
<file_sep path="hyperswitch/crates/router/src/connector/wellsfargopayout.rs" role="context" start="354" end="372">
fn build_request(
&self,
req: &types::PaymentsCaptureRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
Ok(Some(
services::RequestBuilder::new()
.method(services::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(),
))
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/wise.rs<|crate|> router anchor=get_headers kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/connector/wise.rs" role="context" start="658" end="664">
fn get_headers(
&self,
req: &types::PayoutsRouterData<api::PoFulfill>,
connectors: &settings::Connectors,
) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
<file_sep path="hyperswitch/crates/router/src/connector/wise.rs" role="context" start="657" end="657">
use common_utils::request::RequestContent;
use common_utils::types::{AmountConvertor, MinorUnit, MinorUnitForConnector};
use self::transformers as wise;
use crate::{
configs::settings,
core::errors::{self, CustomResult},
events::connector_api_logs::ConnectorEvent,
headers,
services::{
self,
request::{self, Mask},
ConnectorSpecifications, ConnectorValidation,
},
types::{
self,
api::{self, ConnectorCommon, ConnectorCommonExt},
},
utils::BytesExt,
};
<file_sep path="hyperswitch/crates/router/src/connector/wise.rs" role="context" start="675" end="693">
fn build_request(
&self,
req: &types::PayoutsRouterData<api::PoFulfill>,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
let request = services::RequestBuilder::new()
.method(services::Method::Post)
.url(&types::PayoutFulfillType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PayoutFulfillType::get_headers(
self, req, connectors,
)?)
.set_body(types::PayoutFulfillType::get_request_body(
self, req, connectors,
)?)
.build();
Ok(Some(request))
}
<file_sep path="hyperswitch/crates/router/src/connector/wise.rs" role="context" start="666" end="673">
fn get_request_body(
&self,
req: &types::PayoutsRouterData<api::PoFulfill>,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = wise::WisePayoutFulfillRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
<file_sep path="hyperswitch/crates/router/src/connector/wise.rs" role="context" start="638" end="656">
fn get_url(
&self,
req: &types::PayoutsRouterData<api::PoFulfill>,
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let auth = wise::WiseAuthType::try_from(&req.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let transfer_id = req.request.connector_payout_id.to_owned().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "transfer_id",
},
)?;
Ok(format!(
"{}v3/profiles/{}/transfers/{}/payments",
connectors.wise.base_url,
auth.profile_id.peek(),
transfer_id
))
}
<file_sep path="hyperswitch/crates/router/src/connector/wise.rs" role="context" start="621" end="631">
fn build_request(
&self,
_req: &types::PayoutsRouterData<api::PoEligibility>,
_connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
// Eligibility check for cards is not implemented
Err(
errors::ConnectorError::NotImplemented("Payout Eligibility for Wise".to_string())
.into(),
)
}
<file_sep path="hyperswitch/crates/router/src/connector/wise.rs" role="context" start="564" end="580">
fn build_request(
&self,
req: &types::PayoutsRouterData<api::PoCreate>,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
let request = services::RequestBuilder::new()
.method(services::Method::Post)
.url(&types::PayoutCreateType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PayoutCreateType::get_headers(self, req, connectors)?)
.set_body(types::PayoutCreateType::get_request_body(
self, req, connectors,
)?)
.build();
Ok(Some(request))
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/signifyd.rs<|crate|> router anchor=get_url kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/connector/signifyd.rs" role="context" start="591" end="601">
fn get_url(
&self,
_req: &frm_types::FrmRecordReturnRouterData,
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}{}",
self.base_url(connectors),
"v3/orders/events/returns/records"
))
}
<file_sep path="hyperswitch/crates/router/src/connector/signifyd.rs" role="context" start="590" end="590">
use crate::{
configs::settings,
core::errors::{self, CustomResult},
headers,
services::{self, request, ConnectorIntegration, ConnectorSpecifications, ConnectorValidation},
types::{
self,
api::{self, ConnectorCommon, ConnectorCommonExt},
},
};
use crate::{
consts,
events::connector_api_logs::ConnectorEvent,
types::{api::fraud_check as frm_api, fraud_check as frm_types, ErrorResponse, Response},
utils::BytesExt,
};
<file_sep path="hyperswitch/crates/router/src/connector/signifyd.rs" role="context" start="612" end="632">
fn build_request(
&self,
req: &frm_types::FrmRecordReturnRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Post)
.url(&frm_types::FrmRecordReturnType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(frm_types::FrmRecordReturnType::get_headers(
self, req, connectors,
)?)
.set_body(frm_types::FrmRecordReturnType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
<file_sep path="hyperswitch/crates/router/src/connector/signifyd.rs" role="context" start="603" end="610">
fn get_request_body(
&self,
req: &frm_types::FrmRecordReturnRouterData,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let req_obj = signifyd::SignifydPaymentsRecordReturnRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(req_obj)))
}
<file_sep path="hyperswitch/crates/router/src/connector/signifyd.rs" role="context" start="587" end="589">
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
<file_sep path="hyperswitch/crates/router/src/connector/signifyd.rs" role="context" start="579" end="585">
fn get_headers(
&self,
req: &frm_types::FrmRecordReturnRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
<file_sep path="hyperswitch/crates/router/src/connector/signifyd.rs" role="context" start="432" end="452">
fn build_request(
&self,
req: &frm_types::FrmTransactionRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Post)
.url(&frm_types::FrmTransactionType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(frm_types::FrmTransactionType::get_headers(
self, req, connectors,
)?)
.set_body(frm_types::FrmTransactionType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
<file_sep path="hyperswitch/crates/router/src/connector/signifyd.rs" role="context" start="256" end="272">
fn build_request(
&self,
req: &frm_types::FrmSaleRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Post)
.url(&frm_types::FrmSaleType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(frm_types::FrmSaleType::get_headers(self, req, connectors)?)
.set_body(frm_types::FrmSaleType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
<file_sep path="hyperswitch/crates/router/src/types/fraud_check.rs" role="context" start="72" end="73">
pub type FrmRecordReturnRouterData =
RouterData<api::RecordReturn, FraudCheckRecordReturnData, FraudCheckResponseData>;
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/dummyconnector.rs<|crate|> router anchor=get_url kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/connector/dummyconnector.rs" role="context" start="546" end="557">
fn get_url(
&self,
req: &types::RefundSyncRouterData,
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let refund_id = req.request.get_connector_refund_id()?;
Ok(format!(
"{}/refunds/{}",
self.base_url(connectors),
refund_id
))
}
<file_sep path="hyperswitch/crates/router/src/connector/dummyconnector.rs" role="context" start="545" end="545">
use common_utils::{consts as common_consts, request::RequestContent};
use crate::{
configs::settings,
connector::utils as connector_utils,
core::errors::{self, CustomResult},
events::connector_api_logs::ConnectorEvent,
headers,
services::{
self,
request::{self, Mask},
ConnectorIntegration, ConnectorSpecifications, ConnectorValidation,
},
types::{
self,
api::{self, ConnectorCommon, ConnectorCommonExt},
ErrorResponse, Response,
},
utils::BytesExt,
};
<file_sep path="hyperswitch/crates/router/src/connector/dummyconnector.rs" role="context" start="574" end="592">
fn handle_response(
&self,
data: &types::RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> {
let response: transformers::RefundResponse = res
.response
.parse_struct("transformers RefundSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
<file_sep path="hyperswitch/crates/router/src/connector/dummyconnector.rs" role="context" start="559" end="572">
fn build_request(
&self,
req: &types::RefundSyncRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Get)
.url(&types::RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
<file_sep path="hyperswitch/crates/router/src/connector/dummyconnector.rs" role="context" start="542" end="544">
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
<file_sep path="hyperswitch/crates/router/src/connector/dummyconnector.rs" role="context" start="534" end="540">
fn get_headers(
&self,
req: &types::RefundSyncRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
<file_sep path="hyperswitch/crates/router/src/connector/dummyconnector.rs" role="context" start="319" end="332">
fn build_request(
&self,
req: &types::PaymentsSyncRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Get)
.url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
<file_sep path="hyperswitch/crates/router/src/connector/dummyconnector.rs" role="context" start="395" end="410">
fn build_request(
&self,
req: &types::PaymentsCaptureRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Post)
.url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsCaptureType::get_headers(
self, req, connectors,
)?)
.build(),
))
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/gpayments.rs<|crate|> router anchor=get_url kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/connector/gpayments.rs" role="context" start="540" end="547">
fn get_url(
&self,
req: &types::authentication::PreAuthNVersionCallRouterData,
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let base_url = build_endpoint(self.base_url(connectors), &req.connector_meta_data)?;
Ok(format!("{}/api/v2/auth/enrol", base_url,))
}
<file_sep path="hyperswitch/crates/router/src/connector/gpayments.rs" role="context" start="539" end="539">
use common_utils::{
request::RequestContent,
types::{AmountConvertor, MinorUnit, MinorUnitForConnector},
};
use crate::{
configs::settings,
connector::{gpayments::gpayments_types::GpaymentsConnectorMetaData, utils::to_connector_meta},
core::errors::{self, CustomResult},
events::connector_api_logs::ConnectorEvent,
headers, services,
services::{request, ConnectorIntegration, ConnectorSpecifications, ConnectorValidation},
types::{
self,
api::{self, ConnectorCommon, ConnectorCommonExt},
ErrorResponse, Response,
},
utils::BytesExt,
};
<file_sep path="hyperswitch/crates/router/src/connector/gpayments.rs" role="context" start="560" end="589">
fn build_request(
&self,
req: &types::authentication::PreAuthNVersionCallRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
let gpayments_auth_type = gpayments::GpaymentsAuthType::try_from(&req.connector_auth_type)?;
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Post)
.url(
&types::authentication::ConnectorPreAuthenticationVersionCallType::get_url(
self, req, connectors,
)?,
)
.attach_default_headers()
.headers(
types::authentication::ConnectorPreAuthenticationVersionCallType::get_headers(
self, req, connectors,
)?,
)
.set_body(
types::authentication::ConnectorPreAuthenticationVersionCallType::get_request_body(
self, req, connectors,
)?,
)
.add_certificate(Some(gpayments_auth_type.certificate))
.add_certificate_key(Some(gpayments_auth_type.private_key))
.build(),
))
}
<file_sep path="hyperswitch/crates/router/src/connector/gpayments.rs" role="context" start="549" end="558">
fn get_request_body(
&self,
req: &types::authentication::PreAuthNVersionCallRouterData,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_router_data = gpayments::GpaymentsRouterData::from((MinorUnit::zero(), req));
let req_obj =
gpayments_types::GpaymentsPreAuthVersionCallRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(req_obj)))
}
<file_sep path="hyperswitch/crates/router/src/connector/gpayments.rs" role="context" start="536" end="538">
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
<file_sep path="hyperswitch/crates/router/src/connector/gpayments.rs" role="context" start="528" end="534">
fn get_headers(
&self,
req: &types::authentication::PreAuthNVersionCallRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
<file_sep path="hyperswitch/crates/router/src/connector/gpayments.rs" role="context" start="463" end="492">
fn build_request(
&self,
req: &types::authentication::PreAuthNRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
let gpayments_auth_type = gpayments::GpaymentsAuthType::try_from(&req.connector_auth_type)?;
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Post)
.url(
&types::authentication::ConnectorPreAuthenticationType::get_url(
self, req, connectors,
)?,
)
.attach_default_headers()
.headers(
types::authentication::ConnectorPreAuthenticationType::get_headers(
self, req, connectors,
)?,
)
.set_body(
types::authentication::ConnectorPreAuthenticationType::get_request_body(
self, req, connectors,
)?,
)
.add_certificate(Some(gpayments_auth_type.certificate))
.add_certificate_key(Some(gpayments_auth_type.private_key))
.build(),
))
}
<file_sep path="hyperswitch/crates/router/src/connector/gpayments.rs" role="context" start="360" end="384">
fn build_request(
&self,
req: &types::authentication::ConnectorPostAuthenticationRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
let gpayments_auth_type = gpayments::GpaymentsAuthType::try_from(&req.connector_auth_type)?;
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Get)
.url(
&types::authentication::ConnectorPostAuthenticationType::get_url(
self, req, connectors,
)?,
)
.attach_default_headers()
.headers(
types::authentication::ConnectorPostAuthenticationType::get_headers(
self, req, connectors,
)?,
)
.add_certificate(Some(gpayments_auth_type.certificate))
.add_certificate_key(Some(gpayments_auth_type.private_key))
.build(),
))
}
<file_sep path="hyperswitch/crates/router/src/connector/gpayments.rs" role="context" start="216" end="223">
fn build_endpoint(
base_url: &str,
connector_metadata: &Option<common_utils::pii::SecretSerdeValue>,
) -> CustomResult<String, errors::ConnectorError> {
let metadata = gpayments::GpaymentsMetaData::try_from(connector_metadata)?;
let endpoint_prefix = metadata.endpoint_prefix;
Ok(base_url.replace("{{merchant_endpoint_prefix}}", &endpoint_prefix))
}
<file_sep path="hyperswitch/crates/router/src/types/authentication.rs" role="context" start="15" end="16">
pub type PreAuthNVersionCallRouterData =
RouterData<api::PreAuthenticationVersionCall, PreAuthNRequestData, AuthenticationResponseData>;
<file_sep path="hyperswitch/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/event.test.js" role="context" start="61" end="78">
"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.",
);
}
// Response body should have value "succeeded" for "status"
if (jsonData?.status) {
pm.test(
"[POST]::/payments - Content check if value for 'status' matches 'succeeded'",
function () {
pm.expect(jsonData.status).to.eql("succeeded");
},
);
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/gpayments.rs<|crate|> router anchor=get_url kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/connector/gpayments.rs" role="context" start="540" end="547">
fn get_url(
&self,
req: &types::authentication::PreAuthNVersionCallRouterData,
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let base_url = build_endpoint(self.base_url(connectors), &req.connector_meta_data)?;
Ok(format!("{}/api/v2/auth/enrol", base_url,))
}
<file_sep path="hyperswitch/crates/router/src/connector/gpayments.rs" role="context" start="539" end="539">
use common_utils::{
request::RequestContent,
types::{AmountConvertor, MinorUnit, MinorUnitForConnector},
};
use crate::{
configs::settings,
connector::{gpayments::gpayments_types::GpaymentsConnectorMetaData, utils::to_connector_meta},
core::errors::{self, CustomResult},
events::connector_api_logs::ConnectorEvent,
headers, services,
services::{request, ConnectorIntegration, ConnectorSpecifications, ConnectorValidation},
types::{
self,
api::{self, ConnectorCommon, ConnectorCommonExt},
ErrorResponse, Response,
},
utils::BytesExt,
};
<file_sep path="hyperswitch/crates/router/src/connector/gpayments.rs" role="context" start="560" end="589">
fn build_request(
&self,
req: &types::authentication::PreAuthNVersionCallRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
let gpayments_auth_type = gpayments::GpaymentsAuthType::try_from(&req.connector_auth_type)?;
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Post)
.url(
&types::authentication::ConnectorPreAuthenticationVersionCallType::get_url(
self, req, connectors,
)?,
)
.attach_default_headers()
.headers(
types::authentication::ConnectorPreAuthenticationVersionCallType::get_headers(
self, req, connectors,
)?,
)
.set_body(
types::authentication::ConnectorPreAuthenticationVersionCallType::get_request_body(
self, req, connectors,
)?,
)
.add_certificate(Some(gpayments_auth_type.certificate))
.add_certificate_key(Some(gpayments_auth_type.private_key))
.build(),
))
}
<file_sep path="hyperswitch/crates/router/src/connector/gpayments.rs" role="context" start="549" end="558">
fn get_request_body(
&self,
req: &types::authentication::PreAuthNVersionCallRouterData,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_router_data = gpayments::GpaymentsRouterData::from((MinorUnit::zero(), req));
let req_obj =
gpayments_types::GpaymentsPreAuthVersionCallRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(req_obj)))
}
<file_sep path="hyperswitch/crates/router/src/connector/gpayments.rs" role="context" start="536" end="538">
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
<file_sep path="hyperswitch/crates/router/src/connector/gpayments.rs" role="context" start="528" end="534">
fn get_headers(
&self,
req: &types::authentication::PreAuthNVersionCallRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
<file_sep path="hyperswitch/crates/router/src/connector/gpayments.rs" role="context" start="463" end="492">
fn build_request(
&self,
req: &types::authentication::PreAuthNRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
let gpayments_auth_type = gpayments::GpaymentsAuthType::try_from(&req.connector_auth_type)?;
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Post)
.url(
&types::authentication::ConnectorPreAuthenticationType::get_url(
self, req, connectors,
)?,
)
.attach_default_headers()
.headers(
types::authentication::ConnectorPreAuthenticationType::get_headers(
self, req, connectors,
)?,
)
.set_body(
types::authentication::ConnectorPreAuthenticationType::get_request_body(
self, req, connectors,
)?,
)
.add_certificate(Some(gpayments_auth_type.certificate))
.add_certificate_key(Some(gpayments_auth_type.private_key))
.build(),
))
}
<file_sep path="hyperswitch/crates/router/src/connector/gpayments.rs" role="context" start="360" end="384">
fn build_request(
&self,
req: &types::authentication::ConnectorPostAuthenticationRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
let gpayments_auth_type = gpayments::GpaymentsAuthType::try_from(&req.connector_auth_type)?;
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Get)
.url(
&types::authentication::ConnectorPostAuthenticationType::get_url(
self, req, connectors,
)?,
)
.attach_default_headers()
.headers(
types::authentication::ConnectorPostAuthenticationType::get_headers(
self, req, connectors,
)?,
)
.add_certificate(Some(gpayments_auth_type.certificate))
.add_certificate_key(Some(gpayments_auth_type.private_key))
.build(),
))
}
<file_sep path="hyperswitch/crates/router/src/connector/gpayments.rs" role="context" start="216" end="223">
fn build_endpoint(
base_url: &str,
connector_metadata: &Option<common_utils::pii::SecretSerdeValue>,
) -> CustomResult<String, errors::ConnectorError> {
let metadata = gpayments::GpaymentsMetaData::try_from(connector_metadata)?;
let endpoint_prefix = metadata.endpoint_prefix;
Ok(base_url.replace("{{merchant_endpoint_prefix}}", &endpoint_prefix))
}
<file_sep path="hyperswitch/crates/router/src/types/authentication.rs" role="context" start="15" end="16">
pub type PreAuthNVersionCallRouterData =
RouterData<api::PreAuthenticationVersionCall, PreAuthNRequestData, AuthenticationResponseData>;
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/signifyd.rs<|crate|> router anchor=get_request_body kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/connector/signifyd.rs" role="context" start="603" end="610">
fn get_request_body(
&self,
req: &frm_types::FrmRecordReturnRouterData,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let req_obj = signifyd::SignifydPaymentsRecordReturnRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(req_obj)))
}
<file_sep path="hyperswitch/crates/router/src/connector/signifyd.rs" role="context" start="602" end="602">
use common_utils::{crypto, ext_traits::ByteSliceExt, request::RequestContent};
use transformers as signifyd;
use crate::{
configs::settings,
core::errors::{self, CustomResult},
headers,
services::{self, request, ConnectorIntegration, ConnectorSpecifications, ConnectorValidation},
types::{
self,
api::{self, ConnectorCommon, ConnectorCommonExt},
},
};
use crate::{
consts,
events::connector_api_logs::ConnectorEvent,
types::{api::fraud_check as frm_api, fraud_check as frm_types, ErrorResponse, Response},
utils::BytesExt,
};
<file_sep path="hyperswitch/crates/router/src/connector/signifyd.rs" role="context" start="634" end="651">
fn handle_response(
&self,
data: &frm_types::FrmRecordReturnRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<frm_types::FrmRecordReturnRouterData, errors::ConnectorError> {
let response: signifyd::SignifydPaymentsRecordReturnResponse = res
.response
.parse_struct("SignifydPaymentsResponse Transaction")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
<frm_types::FrmRecordReturnRouterData>::try_from(types::ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
<file_sep path="hyperswitch/crates/router/src/connector/signifyd.rs" role="context" start="612" end="632">
fn build_request(
&self,
req: &frm_types::FrmRecordReturnRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Post)
.url(&frm_types::FrmRecordReturnType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(frm_types::FrmRecordReturnType::get_headers(
self, req, connectors,
)?)
.set_body(frm_types::FrmRecordReturnType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
<file_sep path="hyperswitch/crates/router/src/connector/signifyd.rs" role="context" start="591" end="601">
fn get_url(
&self,
_req: &frm_types::FrmRecordReturnRouterData,
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}{}",
self.base_url(connectors),
"v3/orders/events/returns/records"
))
}
<file_sep path="hyperswitch/crates/router/src/connector/signifyd.rs" role="context" start="587" end="589">
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
<file_sep path="hyperswitch/crates/router/src/connector/signifyd.rs" role="context" start="522" end="542">
fn build_request(
&self,
req: &frm_types::FrmFulfillmentRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Post)
.url(&frm_types::FrmFulfillmentType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(frm_types::FrmFulfillmentType::get_headers(
self, req, connectors,
)?)
.set_body(frm_types::FrmFulfillmentType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
<file_sep path="hyperswitch/crates/router/src/types/fraud_check.rs" role="context" start="72" end="73">
pub type FrmRecordReturnRouterData =
RouterData<api::RecordReturn, FraudCheckRecordReturnData, FraudCheckResponseData>;
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/wise.rs<|crate|> router anchor=get_request_body kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/connector/wise.rs" role="context" start="666" end="673">
fn get_request_body(
&self,
req: &types::PayoutsRouterData<api::PoFulfill>,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = wise::WisePayoutFulfillRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
<file_sep path="hyperswitch/crates/router/src/connector/wise.rs" role="context" start="665" end="665">
use common_utils::request::RequestContent;
use common_utils::types::{AmountConvertor, MinorUnit, MinorUnitForConnector};
use self::transformers as wise;
use crate::{
configs::settings,
core::errors::{self, CustomResult},
events::connector_api_logs::ConnectorEvent,
headers,
services::{
self,
request::{self, Mask},
ConnectorSpecifications, ConnectorValidation,
},
types::{
self,
api::{self, ConnectorCommon, ConnectorCommonExt},
},
utils::BytesExt,
};
<file_sep path="hyperswitch/crates/router/src/connector/wise.rs" role="context" start="696" end="715">
fn handle_response(
&self,
data: &types::PayoutsRouterData<api::PoFulfill>,
event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PayoutsRouterData<api::PoFulfill>, errors::ConnectorError> {
let response: wise::WiseFulfillResponse = res
.response
.parse_struct("WiseFulfillResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
<file_sep path="hyperswitch/crates/router/src/connector/wise.rs" role="context" start="675" end="693">
fn build_request(
&self,
req: &types::PayoutsRouterData<api::PoFulfill>,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
let request = services::RequestBuilder::new()
.method(services::Method::Post)
.url(&types::PayoutFulfillType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PayoutFulfillType::get_headers(
self, req, connectors,
)?)
.set_body(types::PayoutFulfillType::get_request_body(
self, req, connectors,
)?)
.build();
Ok(Some(request))
}
<file_sep path="hyperswitch/crates/router/src/connector/wise.rs" role="context" start="658" end="664">
fn get_headers(
&self,
req: &types::PayoutsRouterData<api::PoFulfill>,
connectors: &settings::Connectors,
) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
<file_sep path="hyperswitch/crates/router/src/connector/wise.rs" role="context" start="638" end="656">
fn get_url(
&self,
req: &types::PayoutsRouterData<api::PoFulfill>,
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let auth = wise::WiseAuthType::try_from(&req.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let transfer_id = req.request.connector_payout_id.to_owned().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "transfer_id",
},
)?;
Ok(format!(
"{}v3/profiles/{}/transfers/{}/payments",
connectors.wise.base_url,
auth.profile_id.peek(),
transfer_id
))
}
<file_sep path="hyperswitch/crates/router/src/connector/wise.rs" role="context" start="483" end="501">
fn build_request(
&self,
req: &types::PayoutsRouterData<api::PoRecipient>,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
let request = services::RequestBuilder::new()
.method(services::Method::Post)
.url(&types::PayoutRecipientType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PayoutRecipientType::get_headers(
self, req, connectors,
)?)
.set_body(types::PayoutRecipientType::get_request_body(
self, req, connectors,
)?)
.build();
Ok(Some(request))
}
<file_sep path="hyperswitch/crates/router/src/connector/wise.rs" role="context" start="37" end="41">
pub fn new() -> &'static Self {
&Self {
amount_converter: &MinorUnitForConnector,
}
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/services/authentication/blacklist.rs<|crate|> router anchor=check_user_in_blacklist kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/services/authentication/blacklist.rs" role="context" start="70" end="83">
pub async fn check_user_in_blacklist<A: SessionStateInfo>(
state: &A,
user_id: &str,
token_expiry: u64,
) -> RouterResult<bool> {
let token = format!("{}{}", USER_BLACKLIST_PREFIX, user_id);
let token_issued_at = expiry_to_i64(token_expiry - JWT_TOKEN_TIME_IN_SECS)?;
let redis_conn = get_redis_connection(state)?;
redis_conn
.get_key::<Option<i64>>(&token.as_str().into())
.await
.change_context(ApiErrorResponse::InternalServerError)
.map(|timestamp| timestamp > Some(token_issued_at))
}
<file_sep path="hyperswitch/crates/router/src/services/authentication/blacklist.rs" role="context" start="69" end="69">
use crate::{
consts::{JWT_TOKEN_TIME_IN_SECS, ROLE_BLACKLIST_PREFIX, USER_BLACKLIST_PREFIX},
core::errors::{ApiErrorResponse, RouterResult},
routes::app::SessionStateInfo,
};
<file_sep path="hyperswitch/crates/router/src/services/authentication/blacklist.rs" role="context" start="101" end="110">
pub async fn insert_email_token_in_blacklist(state: &SessionState, token: &str) -> UserResult<()> {
let redis_conn = get_redis_connection(state).change_context(UserErrors::InternalServerError)?;
let blacklist_key = format!("{}{token}", EMAIL_TOKEN_BLACKLIST_PREFIX);
let expiry =
expiry_to_i64(EMAIL_TOKEN_TIME_IN_SECS).change_context(UserErrors::InternalServerError)?;
redis_conn
.set_key_with_expiry(&blacklist_key.as_str().into(), true, expiry)
.await
.change_context(UserErrors::InternalServerError)
}
<file_sep path="hyperswitch/crates/router/src/services/authentication/blacklist.rs" role="context" start="85" end="98">
pub async fn check_role_in_blacklist<A: SessionStateInfo>(
state: &A,
role_id: &str,
token_expiry: u64,
) -> RouterResult<bool> {
let token = format!("{}{}", ROLE_BLACKLIST_PREFIX, role_id);
let token_issued_at = expiry_to_i64(token_expiry - JWT_TOKEN_TIME_IN_SECS)?;
let redis_conn = get_redis_connection(state)?;
redis_conn
.get_key::<Option<i64>>(&token.as_str().into())
.await
.change_context(ApiErrorResponse::InternalServerError)
.map(|timestamp| timestamp > Some(token_issued_at))
}
<file_sep path="hyperswitch/crates/router/src/services/authentication/blacklist.rs" role="context" start="61" end="68">
async fn invalidate_role_cache(state: &SessionState, role_id: &str) -> RouterResult<()> {
let redis_conn = get_redis_connection(state)?;
redis_conn
.delete_key(&authz::get_cache_key_from_role_id(role_id).as_str().into())
.await
.map(|_| ())
.change_context(ApiErrorResponse::InternalServerError)
}
<file_sep path="hyperswitch/crates/router/src/services/authentication/blacklist.rs" role="context" start="42" end="58">
pub async fn insert_role_in_blacklist(state: &SessionState, role_id: &str) -> UserResult<()> {
let role_blacklist_key = format!("{}{}", ROLE_BLACKLIST_PREFIX, role_id);
let expiry =
expiry_to_i64(JWT_TOKEN_TIME_IN_SECS).change_context(UserErrors::InternalServerError)?;
let redis_conn = get_redis_connection(state).change_context(UserErrors::InternalServerError)?;
redis_conn
.set_key_with_expiry(
&role_blacklist_key.as_str().into(),
date_time::now_unix_timestamp(),
expiry,
)
.await
.change_context(UserErrors::InternalServerError)?;
invalidate_role_cache(state, role_id)
.await
.change_context(UserErrors::InternalServerError)
}
<file_sep path="hyperswitch/crates/router/src/services/authentication/blacklist.rs" role="context" start="162" end="167">
async fn check_in_blacklist<A>(&self, state: &A) -> RouterResult<bool>
where
A: SessionStateInfo + Sync,
{
check_user_in_blacklist(state, &self.user_id, self.exp).await
}
<file_sep path="hyperswitch/crates/router/src/services/authentication/blacklist.rs" role="context" start="173" end="178">
async fn check_in_blacklist<A>(&self, state: &A) -> RouterResult<bool>
where
A: SessionStateInfo + Sync,
{
check_user_in_blacklist(state, &self.user_id, self.exp).await
}
<file_sep path="hyperswitch/crates/router/src/services/authentication/blacklist.rs" role="context" start="135" end="137">
fn expiry_to_i64(expiry: u64) -> RouterResult<i64> {
i64::try_from(expiry).change_context(ApiErrorResponse::InternalServerError)
}
<file_sep path="hyperswitch/crates/router/src/services/authentication/blacklist.rs" role="context" start="127" end="133">
fn get_redis_connection<A: SessionStateInfo>(state: &A) -> RouterResult<Arc<RedisConnectionPool>> {
state
.store()
.get_redis_conn()
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get redis connection")
}
<file_sep path="hyperswitch/crates/router/src/core/errors.rs" role="context" start="31" end="31">
pub type RouterResult<T> = CustomResult<T, ApiErrorResponse>;
<file_sep path="hyperswitch/crates/api_models/src/errors/types.rs" role="context" start="86" end="100">
pub enum ApiErrorResponse {
Unauthorized(ApiError),
ForbiddenCommonResource(ApiError),
ForbiddenPrivateResource(ApiError),
Conflict(ApiError),
Gone(ApiError),
Unprocessable(ApiError),
InternalServerError(ApiError),
NotImplemented(ApiError),
ConnectorError(ApiError, #[serde(skip_serializing)] StatusCode),
NotFound(ApiError),
MethodNotAllowed(ApiError),
BadRequest(ApiError),
DomainError(ApiError),
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/wellsfargopayout.rs<|crate|> router anchor=get_request_body kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/connector/wellsfargopayout.rs" role="context" start="430" end="446">
fn get_request_body(
&self,
req: &types::RefundsRouterData<api::Execute>,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let refund_amount = connector_utils::convert_amount(
self.amount_converter,
req.request.minor_refund_amount,
req.request.currency,
)?;
let connector_router_data =
wellsfargopayout::WellsfargopayoutRouterData::from((refund_amount, req));
let connector_req =
wellsfargopayout::WellsfargopayoutRefundRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
<file_sep path="hyperswitch/crates/router/src/connector/wellsfargopayout.rs" role="context" start="429" end="429">
use common_utils::types::{AmountConvertor, StringMinorUnit, StringMinorUnitForConnector};
use self::transformers as wellsfargopayout;
use super::utils as connector_utils;
use crate::{
configs::settings,
core::errors::{self, CustomResult},
events::connector_api_logs::ConnectorEvent,
headers,
services::{
self,
request::{self, Mask},
ConnectorIntegration, ConnectorSpecifications, ConnectorValidation,
},
types::{
self,
api::{self, ConnectorCommon, ConnectorCommonExt},
ErrorResponse, RequestContent, Response,
},
utils::BytesExt,
};
<file_sep path="hyperswitch/crates/router/src/connector/wellsfargopayout.rs" role="context" start="467" end="484">
fn handle_response(
&self,
data: &types::RefundsRouterData<api::Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
let response: wellsfargopayout::RefundResponse = res
.response
.parse_struct("wellsfargopayout RefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
<file_sep path="hyperswitch/crates/router/src/connector/wellsfargopayout.rs" role="context" start="448" end="465">
fn build_request(
&self,
req: &types::RefundsRouterData<api::Execute>,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
let request = services::RequestBuilder::new()
.method(services::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))
}
<file_sep path="hyperswitch/crates/router/src/connector/wellsfargopayout.rs" role="context" start="422" end="428">
fn get_url(
&self,
_req: &types::RefundsRouterData<api::Execute>,
_connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
}
<file_sep path="hyperswitch/crates/router/src/connector/wellsfargopayout.rs" role="context" start="418" end="420">
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
<file_sep path="hyperswitch/crates/router/src/connector/wellsfargopayout.rs" role="context" start="354" end="372">
fn build_request(
&self,
req: &types::PaymentsCaptureRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
Ok(Some(
services::RequestBuilder::new()
.method(services::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(),
))
}
<file_sep path="hyperswitch/crates/router/src/connector/wellsfargopayout.rs" role="context" start="33" end="37">
pub fn new() -> &'static Self {
&Self {
amount_converter: &StringMinorUnitForConnector,
}
}
<file_sep path="hyperswitch/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/event.test.js" role="context" start="61" end="78">
"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.",
);
}
// Response body should have value "succeeded" for "status"
if (jsonData?.status) {
pm.test(
"[POST]::/payments - Content check if value for 'status' matches 'succeeded'",
function () {
pm.expect(jsonData.status).to.eql("succeeded");
},
);
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/wellsfargopayout.rs<|crate|> router anchor=get_request_body kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/connector/wellsfargopayout.rs" role="context" start="430" end="446">
fn get_request_body(
&self,
req: &types::RefundsRouterData<api::Execute>,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let refund_amount = connector_utils::convert_amount(
self.amount_converter,
req.request.minor_refund_amount,
req.request.currency,
)?;
let connector_router_data =
wellsfargopayout::WellsfargopayoutRouterData::from((refund_amount, req));
let connector_req =
wellsfargopayout::WellsfargopayoutRefundRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
<file_sep path="hyperswitch/crates/router/src/connector/wellsfargopayout.rs" role="context" start="429" end="429">
use common_utils::types::{AmountConvertor, StringMinorUnit, StringMinorUnitForConnector};
use self::transformers as wellsfargopayout;
use super::utils as connector_utils;
use crate::{
configs::settings,
core::errors::{self, CustomResult},
events::connector_api_logs::ConnectorEvent,
headers,
services::{
self,
request::{self, Mask},
ConnectorIntegration, ConnectorSpecifications, ConnectorValidation,
},
types::{
self,
api::{self, ConnectorCommon, ConnectorCommonExt},
ErrorResponse, RequestContent, Response,
},
utils::BytesExt,
};
<file_sep path="hyperswitch/crates/router/src/connector/wellsfargopayout.rs" role="context" start="467" end="484">
fn handle_response(
&self,
data: &types::RefundsRouterData<api::Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
let response: wellsfargopayout::RefundResponse = res
.response
.parse_struct("wellsfargopayout RefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
<file_sep path="hyperswitch/crates/router/src/connector/wellsfargopayout.rs" role="context" start="448" end="465">
fn build_request(
&self,
req: &types::RefundsRouterData<api::Execute>,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
let request = services::RequestBuilder::new()
.method(services::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))
}
<file_sep path="hyperswitch/crates/router/src/connector/wellsfargopayout.rs" role="context" start="422" end="428">
fn get_url(
&self,
_req: &types::RefundsRouterData<api::Execute>,
_connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
}
<file_sep path="hyperswitch/crates/router/src/connector/wellsfargopayout.rs" role="context" start="418" end="420">
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
<file_sep path="hyperswitch/crates/router/src/connector/wellsfargopayout.rs" role="context" start="354" end="372">
fn build_request(
&self,
req: &types::PaymentsCaptureRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
Ok(Some(
services::RequestBuilder::new()
.method(services::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(),
))
}
<file_sep path="hyperswitch/crates/router/src/connector/wellsfargopayout.rs" role="context" start="33" end="37">
pub fn new() -> &'static Self {
&Self {
amount_converter: &StringMinorUnitForConnector,
}
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/wise.rs<|crate|> router anchor=get_url kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/connector/wise.rs" role="context" start="638" end="656">
fn get_url(
&self,
req: &types::PayoutsRouterData<api::PoFulfill>,
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let auth = wise::WiseAuthType::try_from(&req.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let transfer_id = req.request.connector_payout_id.to_owned().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "transfer_id",
},
)?;
Ok(format!(
"{}v3/profiles/{}/transfers/{}/payments",
connectors.wise.base_url,
auth.profile_id.peek(),
transfer_id
))
}
<file_sep path="hyperswitch/crates/router/src/connector/wise.rs" role="context" start="637" end="637">
use common_utils::request::RequestContent;
use common_utils::types::{AmountConvertor, MinorUnit, MinorUnitForConnector};
use self::transformers as wise;
use crate::{
configs::settings,
core::errors::{self, CustomResult},
events::connector_api_logs::ConnectorEvent,
headers,
services::{
self,
request::{self, Mask},
ConnectorSpecifications, ConnectorValidation,
},
types::{
self,
api::{self, ConnectorCommon, ConnectorCommonExt},
},
utils::BytesExt,
};
<file_sep path="hyperswitch/crates/router/src/connector/wise.rs" role="context" start="666" end="673">
fn get_request_body(
&self,
req: &types::PayoutsRouterData<api::PoFulfill>,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = wise::WisePayoutFulfillRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
<file_sep path="hyperswitch/crates/router/src/connector/wise.rs" role="context" start="658" end="664">
fn get_headers(
&self,
req: &types::PayoutsRouterData<api::PoFulfill>,
connectors: &settings::Connectors,
) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
<file_sep path="hyperswitch/crates/router/src/connector/wise.rs" role="context" start="621" end="631">
fn build_request(
&self,
_req: &types::PayoutsRouterData<api::PoEligibility>,
_connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
// Eligibility check for cards is not implemented
Err(
errors::ConnectorError::NotImplemented("Payout Eligibility for Wise".to_string())
.into(),
)
}
<file_sep path="hyperswitch/crates/router/src/connector/wise.rs" role="context" start="604" end="610">
fn get_error_response(
&self,
res: types::Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
<file_sep path="hyperswitch/crates/router/src/connector/wise.rs" role="context" start="675" end="693">
fn build_request(
&self,
req: &types::PayoutsRouterData<api::PoFulfill>,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
let request = services::RequestBuilder::new()
.method(services::Method::Post)
.url(&types::PayoutFulfillType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PayoutFulfillType::get_headers(
self, req, connectors,
)?)
.set_body(types::PayoutFulfillType::get_request_body(
self, req, connectors,
)?)
.build();
Ok(Some(request))
}
<file_sep path="hyperswitch/crates/router/src/connector/wise.rs" role="context" start="564" end="580">
fn build_request(
&self,
req: &types::PayoutsRouterData<api::PoCreate>,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
let request = services::RequestBuilder::new()
.method(services::Method::Post)
.url(&types::PayoutCreateType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PayoutCreateType::get_headers(self, req, connectors)?)
.set_body(types::PayoutCreateType::get_request_body(
self, req, connectors,
)?)
.build();
Ok(Some(request))
}
<file_sep path="hyperswitch/crates/router/src/connector/wise/transformers.rs" role="context" start="35" end="39">
pub struct WiseAuthType {
pub(super) api_key: Secret<String>,
#[allow(dead_code)]
pub(super) profile_id: Secret<String>,
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/trustpay.rs<|crate|> router<|connector|> trustpay anchor=get_default_payment_authorize_data kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/tests/connectors/trustpay.rs" role="context" start="59" end="71">
fn get_default_payment_authorize_data() -> Option<types::PaymentsAuthorizeData> {
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_number: cards::CardNumber::from_str("4200000000000000").unwrap(),
card_exp_year: Secret::new("25".to_string()),
card_cvc: Secret::new("123".to_string()),
..utils::CCardType::default().0
}),
browser_info: Some(get_default_browser_info()),
router_return_url: Some(String::from("http://localhost:8080")),
..utils::PaymentAuthorizeType::default().0
})
}
<file_sep path="hyperswitch/crates/router/tests/connectors/trustpay.rs" role="context" start="58" end="58">
use masking::Secret;
use router::types::{self, api, domain, storage::enums, BrowserInformation};
<file_sep path="hyperswitch/crates/router/tests/connectors/trustpay.rs" role="context" start="103" end="112">
async fn should_make_payment() {
let authorize_response = CONNECTOR
.make_payment(
get_default_payment_authorize_data(),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
}
<file_sep path="hyperswitch/crates/router/tests/connectors/trustpay.rs" role="context" start="73" end="96">
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::IN),
..Default::default()
}),
phone: None,
email: None,
}),
None,
None,
)),
..Default::default()
})
}
<file_sep path="hyperswitch/crates/router/tests/connectors/trustpay.rs" role="context" start="40" end="57">
fn get_default_browser_info() -> BrowserInformation {
BrowserInformation {
color_depth: Some(24),
java_enabled: Some(false),
java_script_enabled: Some(true),
language: Some("en-US".to_string()),
screen_height: Some(1080),
screen_width: Some(1920),
time_zone: Some(3600),
accept_header: Some("*".to_string()),
user_agent: Some("none".to_string()),
ip_address: None,
os_type: None,
os_version: None,
device_model: None,
accept_language: Some("en".to_string()),
}
}
<file_sep path="hyperswitch/crates/router/tests/connectors/trustpay.rs" role="context" start="35" end="37">
fn get_name(&self) -> String {
"trustpay".to_string()
}
<file_sep path="hyperswitch/crates/router/tests/connectors/trustpay.rs" role="context" start="145" end="158">
async fn should_refund_auto_captured_payment() {
let response = CONNECTOR
.make_payment_and_refund(
get_default_payment_authorize_data(),
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
<file_sep path="hyperswitch/crates/router/tests/connectors/trustpay.rs" role="context" start="116" end="141">
async fn should_sync_auto_captured_payment() {
let authorize_response = CONNECTOR
.make_payment(
get_default_payment_authorize_data(),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
assert_ne!(txn_id, None, "Empty connector transaction id");
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
}),
None,
)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Charged,);
}
<file_sep path="hyperswitch/crates/router/src/compatibility/stripe/customers/types.rs" role="context" start="202" end="207">
pub struct PaymentMethodData {
pub id: Option<String>,
pub object: &'static str,
pub card: Option<CardDetails>,
pub created: Option<time::PrimitiveDateTime>,
}
<file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="2504" end="2539">
pub enum PaymentMethodData {
#[schema(title = "Card")]
Card(Card),
#[schema(title = "CardRedirect")]
CardRedirect(CardRedirectData),
#[schema(title = "Wallet")]
Wallet(WalletData),
#[schema(title = "PayLater")]
PayLater(PayLaterData),
#[schema(title = "BankRedirect")]
BankRedirect(BankRedirectData),
#[schema(title = "BankDebit")]
BankDebit(BankDebitData),
#[schema(title = "BankTransfer")]
BankTransfer(Box<BankTransferData>),
#[schema(title = "RealTimePayment")]
RealTimePayment(Box<RealTimePaymentData>),
#[schema(title = "Crypto")]
Crypto(CryptoData),
#[schema(title = "MandatePayment")]
MandatePayment,
#[schema(title = "Reward")]
Reward,
#[schema(title = "Upi")]
Upi(UpiData),
#[schema(title = "Voucher")]
Voucher(VoucherData),
#[schema(title = "GiftCard")]
GiftCard(Box<GiftCardData>),
#[schema(title = "CardToken")]
CardToken(CardToken),
#[schema(title = "OpenBanking")]
OpenBanking(OpenBankingData),
#[schema(title = "MobilePayment")]
MobilePayment(MobilePaymentData),
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/trustpay.rs<|crate|> router<|connector|> trustpay anchor=get_default_payment_authorize_data kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/tests/connectors/trustpay.rs" role="context" start="59" end="71">
fn get_default_payment_authorize_data() -> Option<types::PaymentsAuthorizeData> {
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_number: cards::CardNumber::from_str("4200000000000000").unwrap(),
card_exp_year: Secret::new("25".to_string()),
card_cvc: Secret::new("123".to_string()),
..utils::CCardType::default().0
}),
browser_info: Some(get_default_browser_info()),
router_return_url: Some(String::from("http://localhost:8080")),
..utils::PaymentAuthorizeType::default().0
})
}
<file_sep path="hyperswitch/crates/router/tests/connectors/trustpay.rs" role="context" start="58" end="58">
use masking::Secret;
use router::types::{self, api, domain, storage::enums, BrowserInformation};
<file_sep path="hyperswitch/crates/router/tests/connectors/trustpay.rs" role="context" start="103" end="112">
async fn should_make_payment() {
let authorize_response = CONNECTOR
.make_payment(
get_default_payment_authorize_data(),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
}
<file_sep path="hyperswitch/crates/router/tests/connectors/trustpay.rs" role="context" start="73" end="96">
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::IN),
..Default::default()
}),
phone: None,
email: None,
}),
None,
None,
)),
..Default::default()
})
}
<file_sep path="hyperswitch/crates/router/tests/connectors/trustpay.rs" role="context" start="40" end="57">
fn get_default_browser_info() -> BrowserInformation {
BrowserInformation {
color_depth: Some(24),
java_enabled: Some(false),
java_script_enabled: Some(true),
language: Some("en-US".to_string()),
screen_height: Some(1080),
screen_width: Some(1920),
time_zone: Some(3600),
accept_header: Some("*".to_string()),
user_agent: Some("none".to_string()),
ip_address: None,
os_type: None,
os_version: None,
device_model: None,
accept_language: Some("en".to_string()),
}
}
<file_sep path="hyperswitch/crates/router/tests/connectors/trustpay.rs" role="context" start="35" end="37">
fn get_name(&self) -> String {
"trustpay".to_string()
}
<file_sep path="hyperswitch/crates/router/tests/connectors/trustpay.rs" role="context" start="145" end="158">
async fn should_refund_auto_captured_payment() {
let response = CONNECTOR
.make_payment_and_refund(
get_default_payment_authorize_data(),
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
<file_sep path="hyperswitch/crates/router/tests/connectors/trustpay.rs" role="context" start="116" end="141">
async fn should_sync_auto_captured_payment() {
let authorize_response = CONNECTOR
.make_payment(
get_default_payment_authorize_data(),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
assert_ne!(txn_id, None, "Empty connector transaction id");
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
}),
None,
)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Charged,);
}
<file_sep path="hyperswitch/crates/router/src/compatibility/stripe/customers/types.rs" role="context" start="202" end="207">
pub struct PaymentMethodData {
pub id: Option<String>,
pub object: &'static str,
pub card: Option<CardDetails>,
pub created: Option<time::PrimitiveDateTime>,
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/routes/payment_methods.rs<|crate|> router anchor=get_merchant_account kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/routes/payment_methods.rs" role="context" start="286" end="307">
async fn get_merchant_account(
state: &SessionState,
merchant_id: &id_type::MerchantId,
) -> CustomResult<(MerchantKeyStore, domain::MerchantAccount), errors::ApiErrorResponse> {
let key_manager_state = &state.into();
let key_store = state
.store
.get_merchant_key_store_by_merchant_id(
key_manager_state,
merchant_id,
&state.store.get_master_key().to_vec().into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
let merchant_account = state
.store
.find_merchant_account_by_merchant_id(key_manager_state, merchant_id, &key_store)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
Ok((key_store, merchant_account))
}
<file_sep path="hyperswitch/crates/router/src/routes/payment_methods.rs" role="context" start="285" end="285">
use common_utils::{errors::CustomResult, id_type, transformers::ForeignFrom};
use hyperswitch_domain_models::{
bulk_tokenization::CardNetworkTokenizeRequest, merchant_key_store::MerchantKeyStore,
};
use super::app::{AppState, SessionState};
use crate::{
core::{
api_locking,
errors::{self, utils::StorageErrorExt},
payment_methods::{self as payment_methods_routes, cards},
},
services::{self, api, authentication as auth, authorization::permissions::Permission},
types::{
api::payment_methods::{self, PaymentMethodId},
domain,
storage::payment_method::PaymentTokenData,
},
};
<file_sep path="hyperswitch/crates/router/src/routes/payment_methods.rs" role="context" start="371" end="403">
pub async fn save_payment_method_api(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<payment_methods::PaymentMethodCreate>,
path: web::Path<String>,
) -> HttpResponse {
let flow = Flow::PaymentMethodSave;
let payload = json_payload.into_inner();
let pm_id = path.into_inner();
let (auth, _) = match auth::check_client_secret_and_get_auth(req.headers(), &payload) {
Ok((auth, _auth_flow)) => (auth, _auth_flow),
Err(e) => return api::log_and_return_error_response(e),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
Box::pin(cards::add_payment_method_data(
state,
req,
auth.merchant_account,
auth.key_store,
pm_id.clone(),
))
},
&*auth,
api_locking::LockAction::NotApplicable,
))
.await
}
<file_sep path="hyperswitch/crates/router/src/routes/payment_methods.rs" role="context" start="314" end="364">
pub async fn migrate_payment_methods(
state: web::Data<AppState>,
req: HttpRequest,
MultipartForm(form): MultipartForm<migration::PaymentMethodsMigrateForm>,
) -> HttpResponse {
let flow = Flow::PaymentMethodsMigrate;
let (merchant_id, records, merchant_connector_id) =
match migration::get_payment_method_records(form) {
Ok((merchant_id, records, merchant_connector_id)) => {
(merchant_id, records, merchant_connector_id)
}
Err(e) => return api::log_and_return_error_response(e.into()),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
records,
|state, _, req, _| {
let merchant_id = merchant_id.clone();
let merchant_connector_id = merchant_connector_id.clone();
async move {
let (key_store, merchant_account) =
get_merchant_account(&state, &merchant_id).await?;
// Create customers if they are not already present
customers::migrate_customers(
state.clone(),
req.iter()
.map(|e| CustomerRequest::from((e.clone(), merchant_id.clone())))
.collect(),
merchant_account.clone(),
key_store.clone(),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?;
Box::pin(migration::migrate_payment_methods(
state,
req,
&merchant_id,
&merchant_account,
&key_store,
merchant_connector_id,
))
.await
}
},
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
<file_sep path="hyperswitch/crates/router/src/routes/payment_methods.rs" role="context" start="256" end="284">
pub async fn migrate_payment_method_api(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<payment_methods::PaymentMethodMigrate>,
) -> HttpResponse {
let flow = Flow::PaymentMethodsMigrate;
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, _, req, _| async move {
let merchant_id = req.merchant_id.clone();
let (key_store, merchant_account) = get_merchant_account(&state, &merchant_id).await?;
Box::pin(cards::migrate_payment_method(
state,
req,
&merchant_id,
&merchant_account,
&key_store,
))
.await
},
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
<file_sep path="hyperswitch/crates/router/src/routes/payment_methods.rs" role="context" start="225" end="253">
pub async fn payment_method_delete_api(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
) -> HttpResponse {
let flow = Flow::PaymentMethodsDelete;
let payload = web::Json(PaymentMethodId {
payment_method_id: path.into_inner(),
})
.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, pm, _| {
payment_methods_routes::delete_payment_method(
state,
pm,
auth.key_store,
auth.merchant_account,
)
},
&auth::V2ApiKeyAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
<file_sep path="hyperswitch/crates/router/src/routes/payment_methods.rs" role="context" start="1006" end="1046">
pub async fn tokenize_card_using_pm_api(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
json_payload: web::Json<payment_methods::CardNetworkTokenizeRequest>,
) -> HttpResponse {
let flow = Flow::TokenizeCardUsingPaymentMethodId;
let pm_id = path.into_inner();
let mut payload = json_payload.into_inner();
if let payment_methods::TokenizeDataRequest::ExistingPaymentMethod(ref mut pm_data) =
payload.data
{
pm_data.payment_method_id = pm_id;
} else {
return api::log_and_return_error_response(error_stack::report!(
errors::ApiErrorResponse::InvalidDataValue { field_name: "card" }
));
}
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, _, req, _| async move {
let merchant_id = req.merchant_id.clone();
let (key_store, merchant_account) = get_merchant_account(&state, &merchant_id).await?;
let res = Box::pin(cards::tokenize_card_flow(
&state,
CardNetworkTokenizeRequest::foreign_from(req),
&merchant_account,
&key_store,
))
.await?;
Ok(services::ApplicationResponse::Json(res))
},
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
<file_sep path="hyperswitch/crates/router/src/routes/payment_methods.rs" role="context" start="971" end="999">
pub async fn tokenize_card_api(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<payment_methods::CardNetworkTokenizeRequest>,
) -> HttpResponse {
let flow = Flow::TokenizeCard;
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, _, req, _| async move {
let merchant_id = req.merchant_id.clone();
let (key_store, merchant_account) = get_merchant_account(&state, &merchant_id).await?;
let res = Box::pin(cards::tokenize_card_flow(
&state,
CardNetworkTokenizeRequest::foreign_from(req),
&merchant_account,
&key_store,
))
.await?;
Ok(services::ApplicationResponse::Json(res))
},
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
<file_sep path="hyperswitch/crates/router/tests/utils.rs" role="context" start="389" end="391">
pub struct MerchantId {
merchant_id: common_utils::id_type::MerchantId,
}
<file_sep path="hyperswitch/v2_compatible_migrations/2024-08-28-081757_drop_not_null_constraints_on_v1_columns/up.sql" role="context" start="5" end="21">
ALTER COLUMN org_id DROP NOT NULL;
-- Create index on org_id in organization table
-- This is done to mullify the effects of droping primary key for v1
CREATE INDEX idx_organization_org_id ON organization (org_id);
------------------------ Merchant Account -------------------
-- Drop not null in merchant_account table for v1 columns that are dropped in v2
ALTER TABLE merchant_account
DROP CONSTRAINT merchant_account_pkey,
ALTER COLUMN merchant_id DROP NOT NULL,
ALTER COLUMN primary_business_details DROP NOT NULL,
ALTER COLUMN is_recon_enabled DROP NOT NULL;
-- This is done to mullify the effects of droping primary key for v1
CREATE INDEX idx_merchant_account_merchant_id ON merchant_account (merchant_id);
<file_sep path="hyperswitch/crates/api_models/src/errors/types.rs" role="context" start="86" end="100">
pub enum ApiErrorResponse {
Unauthorized(ApiError),
ForbiddenCommonResource(ApiError),
ForbiddenPrivateResource(ApiError),
Conflict(ApiError),
Gone(ApiError),
Unprocessable(ApiError),
InternalServerError(ApiError),
NotImplemented(ApiError),
ConnectorError(ApiError, #[serde(skip_serializing)] StatusCode),
NotFound(ApiError),
MethodNotAllowed(ApiError),
BadRequest(ApiError),
DomainError(ApiError),
}
| symbol_neighborhood |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.