text stringlengths 70 351k | source stringclasses 4 values |
|---|---|
<|meta_start|><|file|> hyperswitch/crates/router/src/services/api/generic_link_response.rs<|crate|> router anchor=build_generic_link_html kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/services/api/generic_link_response.rs" role="context" start="12" end="36">
pub fn build_generic_link_html(
boxed_generic_link_data: GenericLinksData,
locale: String,
) -> CustomResult<String, errors::ApiErrorResponse> {
match boxed_generic_link_data {
GenericLinksData::ExpiredLink(link_data) => build_generic_expired_link_html(&link_data),
GenericLinksData::PaymentMethodCollect(pm_collect_data) => {
build_pm_collect_link_html(&pm_collect_data)
}
GenericLinksData::PaymentMethodCollectStatus(pm_collect_data) => {
build_pm_collect_link_status_html(&pm_collect_data)
}
GenericLinksData::PayoutLink(payout_link_data) => {
build_payout_link_html(&payout_link_data, locale.as_str())
}
GenericLinksData::PayoutLinkStatus(pm_collect_data) => {
build_payout_link_status_html(&pm_collect_data, locale.as_str())
}
GenericLinksData::SecurePaymentLink(payment_link_data) => {
build_secure_payment_link_html(payment_link_data)
}
}
}
<file_sep path="hyperswitch/crates/router/src/services/api/generic_link_response.rs" role="context" start="11" end="11">
use common_utils::errors::CustomResult;
use hyperswitch_domain_models::api::{
GenericExpiredLinkData, GenericLinkFormData, GenericLinkStatusData, GenericLinksData,
};
use super::build_secure_payment_link_html;
use crate::core::errors;
<file_sep path="hyperswitch/crates/router/src/services/api/generic_link_response.rs" role="context" start="56" end="83">
fn build_html_template(
link_data: &GenericLinkFormData,
document: &'static str,
styles: &'static str,
) -> CustomResult<(Tera, Context), errors::ApiErrorResponse> {
let mut tera: Tera = Tera::default();
let mut context = Context::new();
// Insert dynamic context in CSS
let css_dynamic_context = "{{ color_scheme }}";
let css_template = styles.to_string();
let final_css = format!("{}\n{}", css_dynamic_context, css_template);
let _ = tera.add_raw_template("document_styles", &final_css);
context.insert("color_scheme", &link_data.css_data);
let css_style_tag = tera
.render("document_styles", &context)
.map(|css| format!("<style>{}</style>", css))
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to render CSS template")?;
// Insert HTML context
let html_template = document.to_string();
let _ = tera.add_raw_template("html_template", &html_template);
context.insert("css_style_tag", &css_style_tag);
Ok((tera, context))
}
<file_sep path="hyperswitch/crates/router/src/services/api/generic_link_response.rs" role="context" start="38" end="54">
pub fn build_generic_expired_link_html(
link_data: &GenericExpiredLinkData,
) -> CustomResult<String, errors::ApiErrorResponse> {
let mut tera = Tera::default();
let mut context = Context::new();
// Build HTML
let html_template = include_str!("../../core/generic_link/expired_link/index.html").to_string();
let _ = tera.add_raw_template("generic_expired_link", &html_template);
context.insert("title", &link_data.title);
context.insert("message", &link_data.message);
context.insert("theme", &link_data.theme);
tera.render("generic_expired_link", &context)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to render expired link HTML template")
}
<file_sep path="hyperswitch/crates/router/src/services/api/generic_link_response.rs" role="context" start="160" end="205">
pub fn build_payout_link_status_html(
link_data: &GenericLinkStatusData,
locale: &str,
) -> CustomResult<String, errors::ApiErrorResponse> {
let mut tera = Tera::default();
let mut context = Context::new();
// Insert dynamic context in CSS
let css_dynamic_context = "{{ color_scheme }}";
let css_template =
include_str!("../../core/generic_link/payout_link/status/styles.css").to_string();
let final_css = format!("{}\n{}", css_dynamic_context, css_template);
let _ = tera.add_raw_template("payout_link_status_styles", &final_css);
context.insert("color_scheme", &link_data.css_data);
let css_style_tag = tera
.render("payout_link_status_styles", &context)
.map(|css| format!("<style>{}</style>", css))
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to render payout link status CSS template")?;
// Insert dynamic context in JS
let js_dynamic_context = "{{ script_data }}";
let js_template =
include_str!("../../core/generic_link/payout_link/status/script.js").to_string();
let final_js = format!("{}\n{}", js_dynamic_context, js_template);
let _ = tera.add_raw_template("payout_link_status_script", &final_js);
context.insert("script_data", &link_data.js_data);
context::insert_locales_in_context_for_payout_link_status(&mut context, locale);
let js_script_tag = tera
.render("payout_link_status_script", &context)
.map(|js| format!("<script>{}</script>", js))
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to render payout link status JS template")?;
// Build HTML
let html_template =
include_str!("../../core/generic_link/payout_link/status/index.html").to_string();
let _ = tera.add_raw_template("payout_status_link", &html_template);
context.insert("css_style_tag", &css_style_tag);
context.insert("js_script_tag", &js_script_tag);
tera.render("payout_status_link", &context)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to render payout link status HTML template")
}
<file_sep path="hyperswitch/crates/router/src/services/api/generic_link_response.rs" role="context" start="207" end="253">
pub fn build_pm_collect_link_status_html(
link_data: &GenericLinkStatusData,
) -> CustomResult<String, errors::ApiErrorResponse> {
let mut tera = Tera::default();
let mut context = Context::new();
// Insert dynamic context in CSS
let css_dynamic_context = "{{ color_scheme }}";
let css_template =
include_str!("../../core/generic_link/payment_method_collect/status/styles.css")
.to_string();
let final_css = format!("{}\n{}", css_dynamic_context, css_template);
let _ = tera.add_raw_template("pm_collect_link_status_styles", &final_css);
context.insert("color_scheme", &link_data.css_data);
let css_style_tag = tera
.render("pm_collect_link_status_styles", &context)
.map(|css| format!("<style>{}</style>", css))
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to render payment method collect link status CSS template")?;
// Insert dynamic context in JS
let js_dynamic_context = "{{ collect_link_status_context }}";
let js_template =
include_str!("../../core/generic_link/payment_method_collect/status/script.js").to_string();
let final_js = format!("{}\n{}", js_dynamic_context, js_template);
let _ = tera.add_raw_template("pm_collect_link_status_script", &final_js);
context.insert("collect_link_status_context", &link_data.js_data);
let js_script_tag = tera
.render("pm_collect_link_status_script", &context)
.map(|js| format!("<script>{}</script>", js))
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to render payment method collect link status JS template")?;
// Build HTML
let html_template =
include_str!("../../core/generic_link/payment_method_collect/status/index.html")
.to_string();
let _ = tera.add_raw_template("payment_method_collect_status_link", &html_template);
context.insert("css_style_tag", &css_style_tag);
context.insert("js_script_tag", &js_script_tag);
tera.render("payment_method_collect_status_link", &context)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to render payment method collect link status HTML template")
}
<file_sep path="hyperswitch/crates/router/src/routes/app.rs" role="context" start="1894" end="1894">
pub struct PayoutLink;
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/coinbase.rs<|crate|> router<|connector|> coinbase 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/coinbase.rs" role="context" start="41" end="68">
fn get_default_payment_info() -> Option<utils::PaymentInfo> {
Some(utils::PaymentInfo {
address: Some(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,
)),
connector_meta_data: Some(json!({"pricing_type": "fixed_price"})),
..Default::default()
})
}
<file_sep path="hyperswitch/crates/router/tests/connectors/coinbase.rs" role="context" start="40" end="40">
use hyperswitch_domain_models::address::{Address, AddressDetails, PhoneDetails};
use masking::Secret;
use router::types::{self, api, domain, storage::enums, PaymentAddress};
use serde_json::json;
<file_sep path="hyperswitch/crates/router/tests/connectors/coinbase.rs" role="context" start="112" end="126">
async fn should_only_authorize_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);
let resp = response.response.ok().unwrap();
let endpoint = match resp {
types::PaymentsResponseData::TransactionResponse {
redirection_data, ..
} => Some(redirection_data),
_ => None,
};
assert!(endpoint.is_some())
}
<file_sep path="hyperswitch/crates/router/tests/connectors/coinbase.rs" role="context" start="70" end="108">
fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
Some(types::PaymentsAuthorizeData {
amount: 1,
currency: enums::Currency::USD,
payment_method_data: domain::PaymentMethodData::Crypto(domain::CryptoData {
pay_currency: None,
network: None,
}),
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("https://google.com/")),
webhook_url: None,
complete_authorize_url: None,
capture_method: 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/coinbase.rs" role="context" start="34" end="36">
fn get_name(&self) -> String {
"coinbase".to_string()
}
<file_sep path="hyperswitch/crates/router/tests/connectors/coinbase.rs" role="context" start="25" end="32">
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.coinbase
.expect("Missing connector authentication configuration")
.into(),
)
}
<file_sep path="hyperswitch/crates/router/tests/connectors/coinbase.rs" role="context" start="130" end="145">
async fn should_sync_authorized_payment() {
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
"ADFY3789".to_string(),
),
..Default::default()
}),
get_default_payment_info(),
)
.await
.expect("PSync response");
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
<file_sep path="hyperswitch/crates/router/tests/connectors/coinbase.rs" role="context" start="149" end="164">
async fn should_sync_unresolved_payment() {
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
"YJ6RFZXZ".to_string(),
),
..Default::default()
}),
get_default_payment_info(),
)
.await
.expect("PSync response");
assert_eq!(response.status, enums::AttemptStatus::Unresolved);
}
<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/utils/user/theme.rs<|crate|> router anchor=validate_lineage kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/utils/user/theme.rs" role="context" start="58" end="92">
pub async fn validate_lineage(state: &SessionState, lineage: &ThemeLineage) -> UserResult<()> {
match lineage {
ThemeLineage::Tenant { tenant_id } => {
validate_tenant(state, tenant_id)?;
Ok(())
}
ThemeLineage::Organization { tenant_id, org_id } => {
validate_tenant(state, tenant_id)?;
validate_org(state, org_id).await?;
Ok(())
}
ThemeLineage::Merchant {
tenant_id,
org_id,
merchant_id,
} => {
validate_tenant(state, tenant_id)?;
validate_org(state, org_id).await?;
validate_merchant(state, org_id, merchant_id).await?;
Ok(())
}
ThemeLineage::Profile {
tenant_id,
org_id,
merchant_id,
profile_id,
} => {
validate_tenant(state, tenant_id)?;
validate_org(state, org_id).await?;
let key_store = validate_merchant_and_get_key_store(state, org_id, merchant_id).await?;
validate_profile(state, profile_id, merchant_id, &key_store).await?;
Ok(())
}
}
}
<file_sep path="hyperswitch/crates/router/src/utils/user/theme.rs" role="context" start="57" end="57">
use common_utils::{ext_traits::AsyncExt, id_type, types::theme::ThemeLineage};
use crate::{
core::errors::{StorageErrorExt, UserErrors, UserResult},
routes::SessionState,
services::authentication::UserFromToken,
};
<file_sep path="hyperswitch/crates/router/src/utils/user/theme.rs" role="context" start="101" end="108">
async fn validate_org(state: &SessionState, org_id: &id_type::OrganizationId) -> UserResult<()> {
state
.accounts_store
.find_organization_by_org_id(org_id)
.await
.to_not_found_response(UserErrors::InvalidThemeLineage("org_id".to_string()))
.map(|_| ())
}
<file_sep path="hyperswitch/crates/router/src/utils/user/theme.rs" role="context" start="94" end="99">
fn validate_tenant(state: &SessionState, tenant_id: &id_type::TenantId) -> UserResult<()> {
if &state.tenant.tenant_id != tenant_id {
return Err(UserErrors::InvalidThemeLineage("tenant_id".to_string()).into());
}
Ok(())
}
<file_sep path="hyperswitch/crates/router/src/utils/user/theme.rs" role="context" start="46" end="56">
pub async fn upload_file_to_theme_bucket(
state: &SessionState,
path: &PathBuf,
data: Vec<u8>,
) -> UserResult<()> {
state
.theme_storage_client
.upload_file(path_buf_to_str(path)?, data)
.await
.change_context(UserErrors::ErrorUploadingFile)
}
<file_sep path="hyperswitch/crates/router/src/utils/user/theme.rs" role="context" start="35" end="44">
pub async fn retrieve_file_from_theme_bucket(
state: &SessionState,
path: &PathBuf,
) -> UserResult<Vec<u8>> {
state
.theme_storage_client
.retrieve_file(path_buf_to_str(path)?)
.await
.change_context(UserErrors::ErrorRetrievingFile)
}
<file_sep path="hyperswitch-card-vault/migrations/2023-10-21-104200_create-tables/up.sql" role="context" start="1" end="11">
-- Your SQL goes here
CREATE TABLE merchant (
id SERIAL,
tenant_id VARCHAR(255) NOT NULL,
merchant_id VARCHAR(255) NOT NULL,
enc_key BYTEA NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT now()::TIMESTAMP,
PRIMARY KEY (tenant_id, merchant_id)
);
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/utils.rs<|crate|> router<|connector|> utils anchor=get_connector_transaction_id 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="1114" end="1134">
pub fn get_connector_transaction_id(
response: Result<types::PaymentsResponseData, types::ErrorResponse>,
) -> Option<String> {
match response {
Ok(types::PaymentsResponseData::TransactionResponse { resource_id, .. }) => {
resource_id.get_connector_transaction_id().ok()
}
Ok(types::PaymentsResponseData::SessionResponse { .. }) => None,
Ok(types::PaymentsResponseData::SessionTokenResponse { .. }) => None,
Ok(types::PaymentsResponseData::TokenizationResponse { .. }) => None,
Ok(types::PaymentsResponseData::TransactionUnresolvedResponse { .. }) => None,
Ok(types::PaymentsResponseData::PreProcessingResponse { .. }) => None,
Ok(types::PaymentsResponseData::ConnectorCustomerResponse { .. }) => None,
Ok(types::PaymentsResponseData::ThreeDSEnrollmentResponse { .. }) => None,
Ok(types::PaymentsResponseData::MultipleCaptureResponse { .. }) => None,
Ok(types::PaymentsResponseData::IncrementalAuthorizationResponse { .. }) => None,
Ok(types::PaymentsResponseData::PostProcessingResponse { .. }) => None,
Ok(types::PaymentsResponseData::SessionUpdateResponse { .. }) => None,
Err(_) => None,
}
}
<file_sep path="hyperswitch/crates/router/tests/connectors/utils.rs" role="context" start="1113" end="1113">
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="1154" end="1182">
pub fn to_connector_auth_type(auth_type: ConnectorAuthType) -> types::ConnectorAuthType {
match auth_type {
ConnectorAuthType::HeaderKey { api_key } => types::ConnectorAuthType::HeaderKey { api_key },
ConnectorAuthType::BodyKey { api_key, key1 } => {
types::ConnectorAuthType::BodyKey { api_key, key1 }
}
ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} => types::ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
},
ConnectorAuthType::MultiAuthKey {
api_key,
key1,
api_secret,
key2,
} => types::ConnectorAuthType::MultiAuthKey {
api_key,
key1,
api_secret,
key2,
},
_ => types::ConnectorAuthType::NoKey,
}
}
<file_sep path="hyperswitch/crates/router/tests/connectors/utils.rs" role="context" start="1136" end="1152">
pub fn get_connector_metadata(
response: Result<types::PaymentsResponseData, types::ErrorResponse>,
) -> Option<serde_json::Value> {
match response {
Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: _,
redirection_data: _,
mandate_reference: _,
connector_metadata,
network_txn_id: _,
connector_response_reference_id: _,
incremental_authorization_allowed: _,
charges: _,
}) => connector_metadata,
_ => None,
}
}
<file_sep path="hyperswitch/crates/router/tests/connectors/utils.rs" role="context" start="1103" end="1111">
fn default() -> Self {
let data = types::PaymentMethodTokenizationData {
payment_method_data: types::domain::PaymentMethodData::Card(CCardType::default().0),
browser_info: None,
amount: Some(100),
currency: enums::Currency::USD,
};
Self(data)
}
<file_sep path="hyperswitch/crates/router/tests/connectors/utils.rs" role="context" start="1089" end="1099">
fn default() -> Self {
let data = types::ConnectorCustomerData {
payment_method_data: types::domain::PaymentMethodData::Card(CCardType::default().0),
description: None,
email: Email::from_str("test@juspay.in").ok(),
phone: None,
name: None,
preprocessing_id: None,
};
Self(data)
}
<file_sep path="hyperswitch/crates/router/tests/connectors/utils.rs" role="context" start="333" end="352">
async fn auth_capture_and_refund(
&self,
authorize_data: Option<types::PaymentsAuthorizeData>,
refund_data: Option<types::RefundsData>,
payment_info: Option<PaymentInfo>,
) -> Result<types::RefundExecuteRouterData, Report<ConnectorError>> {
//make a successful payment
let response = self
.authorize_and_capture_payment(authorize_data, None, payment_info.clone())
.await
.unwrap();
//try refund for previous payment
let transaction_id = get_connector_transaction_id(response.response).unwrap();
tokio::time::sleep(Duration::from_secs(self.get_request_interval())).await; // to avoid 404 error
Ok(self
.refund_payment(transaction_id, refund_data, payment_info)
.await
.unwrap())
}
<file_sep path="hyperswitch/crates/router/tests/connectors/utils.rs" role="context" start="217" end="234">
async fn authorize_and_capture_payment(
&self,
authorize_data: Option<types::PaymentsAuthorizeData>,
capture_data: Option<types::PaymentsCaptureData>,
payment_info: Option<PaymentInfo>,
) -> Result<types::PaymentsCaptureRouterData, Report<ConnectorError>> {
let authorize_response = self
.authorize_payment(authorize_data, payment_info.clone())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Authorized);
let txn_id = get_connector_transaction_id(authorize_response.response);
let response = self
.capture_payment(txn_id.unwrap(), capture_data, payment_info)
.await
.unwrap();
return Ok(response);
}
<file_sep path="hyperswitch/crates/router/src/connector/riskified/transformers/api.rs" role="context" start="614" end="616">
pub struct ErrorResponse {
pub error: ErrorData,
}
<file_sep path="hyperswitch/crates/api_models/src/errors/types.rs" role="context" start="42" end="52">
struct ErrorResponse<'a> {
#[serde(rename = "type")]
error_type: &'static str,
message: Cow<'a, str>,
code: String,
#[serde(flatten)]
extra: &'a Option<Extra>,
#[cfg(feature = "detailed_errors")]
#[serde(skip_serializing_if = "Option::is_none")]
stacktrace: Option<&'a serde_json::Value>,
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/utils.rs<|crate|> router<|connector|> utils anchor=get_connector_transaction_id 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="1114" end="1134">
pub fn get_connector_transaction_id(
response: Result<types::PaymentsResponseData, types::ErrorResponse>,
) -> Option<String> {
match response {
Ok(types::PaymentsResponseData::TransactionResponse { resource_id, .. }) => {
resource_id.get_connector_transaction_id().ok()
}
Ok(types::PaymentsResponseData::SessionResponse { .. }) => None,
Ok(types::PaymentsResponseData::SessionTokenResponse { .. }) => None,
Ok(types::PaymentsResponseData::TokenizationResponse { .. }) => None,
Ok(types::PaymentsResponseData::TransactionUnresolvedResponse { .. }) => None,
Ok(types::PaymentsResponseData::PreProcessingResponse { .. }) => None,
Ok(types::PaymentsResponseData::ConnectorCustomerResponse { .. }) => None,
Ok(types::PaymentsResponseData::ThreeDSEnrollmentResponse { .. }) => None,
Ok(types::PaymentsResponseData::MultipleCaptureResponse { .. }) => None,
Ok(types::PaymentsResponseData::IncrementalAuthorizationResponse { .. }) => None,
Ok(types::PaymentsResponseData::PostProcessingResponse { .. }) => None,
Ok(types::PaymentsResponseData::SessionUpdateResponse { .. }) => None,
Err(_) => None,
}
}
<file_sep path="hyperswitch/crates/router/tests/connectors/utils.rs" role="context" start="1113" end="1113">
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="1154" end="1182">
pub fn to_connector_auth_type(auth_type: ConnectorAuthType) -> types::ConnectorAuthType {
match auth_type {
ConnectorAuthType::HeaderKey { api_key } => types::ConnectorAuthType::HeaderKey { api_key },
ConnectorAuthType::BodyKey { api_key, key1 } => {
types::ConnectorAuthType::BodyKey { api_key, key1 }
}
ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} => types::ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
},
ConnectorAuthType::MultiAuthKey {
api_key,
key1,
api_secret,
key2,
} => types::ConnectorAuthType::MultiAuthKey {
api_key,
key1,
api_secret,
key2,
},
_ => types::ConnectorAuthType::NoKey,
}
}
<file_sep path="hyperswitch/crates/router/tests/connectors/utils.rs" role="context" start="1136" end="1152">
pub fn get_connector_metadata(
response: Result<types::PaymentsResponseData, types::ErrorResponse>,
) -> Option<serde_json::Value> {
match response {
Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: _,
redirection_data: _,
mandate_reference: _,
connector_metadata,
network_txn_id: _,
connector_response_reference_id: _,
incremental_authorization_allowed: _,
charges: _,
}) => connector_metadata,
_ => None,
}
}
<file_sep path="hyperswitch/crates/router/tests/connectors/utils.rs" role="context" start="1103" end="1111">
fn default() -> Self {
let data = types::PaymentMethodTokenizationData {
payment_method_data: types::domain::PaymentMethodData::Card(CCardType::default().0),
browser_info: None,
amount: Some(100),
currency: enums::Currency::USD,
};
Self(data)
}
<file_sep path="hyperswitch/crates/router/tests/connectors/utils.rs" role="context" start="1089" end="1099">
fn default() -> Self {
let data = types::ConnectorCustomerData {
payment_method_data: types::domain::PaymentMethodData::Card(CCardType::default().0),
description: None,
email: Email::from_str("test@juspay.in").ok(),
phone: None,
name: None,
preprocessing_id: None,
};
Self(data)
}
<file_sep path="hyperswitch/crates/router/tests/connectors/utils.rs" role="context" start="333" end="352">
async fn auth_capture_and_refund(
&self,
authorize_data: Option<types::PaymentsAuthorizeData>,
refund_data: Option<types::RefundsData>,
payment_info: Option<PaymentInfo>,
) -> Result<types::RefundExecuteRouterData, Report<ConnectorError>> {
//make a successful payment
let response = self
.authorize_and_capture_payment(authorize_data, None, payment_info.clone())
.await
.unwrap();
//try refund for previous payment
let transaction_id = get_connector_transaction_id(response.response).unwrap();
tokio::time::sleep(Duration::from_secs(self.get_request_interval())).await; // to avoid 404 error
Ok(self
.refund_payment(transaction_id, refund_data, payment_info)
.await
.unwrap())
}
<file_sep path="hyperswitch/crates/router/tests/connectors/utils.rs" role="context" start="217" end="234">
async fn authorize_and_capture_payment(
&self,
authorize_data: Option<types::PaymentsAuthorizeData>,
capture_data: Option<types::PaymentsCaptureData>,
payment_info: Option<PaymentInfo>,
) -> Result<types::PaymentsCaptureRouterData, Report<ConnectorError>> {
let authorize_response = self
.authorize_payment(authorize_data, payment_info.clone())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Authorized);
let txn_id = get_connector_transaction_id(authorize_response.response);
let response = self
.capture_payment(txn_id.unwrap(), capture_data, payment_info)
.await
.unwrap();
return Ok(response);
}
<file_sep path="hyperswitch/crates/router/src/connector/riskified/transformers/api.rs" role="context" start="614" end="616">
pub struct ErrorResponse {
pub error: ErrorData,
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payments/routing.rs<|crate|> router anchor=perform_eligibility_analysis 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="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="854" end="854">
use api_models::routing as api_routing;
use api_models::{
admin as admin_api,
enums::{self as api_enums, CountryAlpha2},
routing::ConnectorSelection,
};
use common_utils::ext_traits::AsyncExt;
use crate::core::payouts;
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="930" end="975">
pub async fn perform_eligibility_analysis_with_fallback(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
chosen: Vec<routing_types::RoutableConnectorChoice>,
transaction_data: &routing::TransactionData<'_>,
eligible_connectors: Option<Vec<api_enums::RoutableConnectors>>,
business_profile: &domain::Profile,
) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> {
let mut final_selection = perform_eligibility_analysis(
state,
key_store,
chosen,
transaction_data,
eligible_connectors.as_ref(),
business_profile.get_id(),
)
.await?;
let fallback_selection = perform_fallback_routing(
state,
key_store,
transaction_data,
eligible_connectors.as_ref(),
business_profile,
)
.await;
final_selection.append(
&mut fallback_selection
.unwrap_or_default()
.iter()
.filter(|&routable_connector_choice| {
!final_selection.contains(routable_connector_choice)
})
.cloned()
.collect::<Vec<_>>(),
);
let final_selected_connectors = final_selection
.iter()
.map(|item| item.connector)
.collect::<Vec<_>>();
logger::debug!(final_selected_connectors_for_routing=?final_selected_connectors, "List of final selected connectors for routing");
Ok(final_selection)
}
<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="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="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="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="111" end="111">
type RoutingResult<O> = oss_errors::CustomResult<O, errors::RoutingError>;
<file_sep path="hyperswitch/crates/router/src/routes/app.rs" role="context" start="104" end="125">
pub struct SessionState {
pub store: Box<dyn StorageInterface>,
/// Global store is used for global schema operations in tables like Users and Tenants
pub global_store: Box<dyn GlobalStorageInterface>,
pub accounts_store: Box<dyn AccountsStorageInterface>,
pub conf: Arc<settings::Settings<RawSecret>>,
pub api_client: Box<dyn crate::services::ApiClient>,
pub event_handler: EventsHandler,
#[cfg(feature = "email")]
pub email_client: Arc<Box<dyn EmailService>>,
#[cfg(feature = "olap")]
pub pool: AnalyticsProvider,
pub file_storage_client: Arc<dyn FileStorageInterface>,
pub request_id: Option<RequestId>,
pub base_url: String,
pub tenant: Tenant,
#[cfg(feature = "olap")]
pub opensearch_client: Option<Arc<OpenSearchClient>>,
pub grpc_client: Arc<GrpcClients>,
pub theme_storage_client: Arc<dyn FileStorageInterface>,
pub locale: 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/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>,
}
<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/routing.rs<|crate|> router anchor=ensure_algorithm_cached_v1 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="468" end="509">
async fn ensure_algorithm_cached_v1(
state: &SessionState,
merchant_id: &common_utils::id_type::MerchantId,
algorithm_id: &common_utils::id_type::RoutingId,
profile_id: &common_utils::id_type::ProfileId,
transaction_type: &api_enums::TransactionType,
) -> RoutingResult<Arc<CachedAlgorithm>> {
let key = {
match transaction_type {
common_enums::TransactionType::Payment => {
format!(
"routing_config_{}_{}",
merchant_id.get_string_repr(),
profile_id.get_string_repr(),
)
}
#[cfg(feature = "payouts")]
common_enums::TransactionType::Payout => {
format!(
"routing_config_po_{}_{}",
merchant_id.get_string_repr(),
profile_id.get_string_repr()
)
}
}
};
let cached_algorithm = ROUTING_CACHE
.get_val::<Arc<CachedAlgorithm>>(CacheKey {
key: key.clone(),
prefix: state.tenant.redis_key_prefix.clone(),
})
.await;
let algorithm = if let Some(algo) = cached_algorithm {
algo
} else {
refresh_routing_cache_v1(state, key.clone(), algorithm_id, profile_id).await?
};
Ok(algorithm)
}
<file_sep path="hyperswitch/crates/router/src/core/payments/routing.rs" role="context" start="467" end="467">
use std::{collections::HashMap, str::FromStr, sync::Arc};
use api_models::{
admin as admin_api,
enums::{self as api_enums, CountryAlpha2},
routing::ConnectorSelection,
};
use common_utils::ext_traits::AsyncExt;
use storage_impl::redis::cache::{CacheKey, CGRAPH_CACHE, ROUTING_CACHE};
use crate::core::payouts;
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="533" end="545">
pub fn perform_routing_for_single_straight_through_algorithm(
algorithm: &routing_types::StraightThroughAlgorithm,
) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> {
Ok(match algorithm {
routing_types::StraightThroughAlgorithm::Single(connector) => vec![(**connector).clone()],
routing_types::StraightThroughAlgorithm::Priority(_)
| routing_types::StraightThroughAlgorithm::VolumeSplit(_) => {
Err(errors::RoutingError::DslIncorrectSelectionAlgorithm)
.attach_printable("Unsupported algorithm received as a result of static routing")?
}
})
}
<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="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="302" end="410">
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(|cat| match cat.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(|mt| match mt {
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: payments_dsl_input.payment_attempt.payment_method,
payment_method_type: payments_dsl_input.payment_attempt.payment_method_type,
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.get_total_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.peek().chars().take(6).collect())
}
_ => None,
},
),
currency: payments_dsl_input.currency,
authentication_type: payments_dsl_input.payment_attempt.authentication_type,
capture_method: payments_dsl_input
.payment_attempt
.capture_method
.and_then(|cm| cm.foreign_into()),
business_country: payments_dsl_input
.payment_intent
.business_country
.map(api_enums::Country::from_alpha2),
billing_country: payments_dsl_input
.address
.get_payment_method_billing()
.and_then(|bic| bic.address.as_ref())
.and_then(|add| add.country)
.map(api_enums::Country::from_alpha2),
business_label: payments_dsl_input.payment_intent.business_label.clone(),
setup_future_usage: payments_dsl_input.payment_intent.setup_future_usage,
};
let metadata = payments_dsl_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);
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="1333" end="1370">
async fn get_chosen_connectors<'a>(
state: &'a SessionState,
key_store: &'a domain::MerchantKeyStore,
session_pm_input: &SessionRoutingPmTypeInput<'_>,
transaction_type: &api_enums::TransactionType,
profile_wrapper: &admin::ProfileWrapper,
) -> RoutingResult<Vec<api_models::routing::RoutableConnectorChoice>> {
let merchant_id = &key_store.merchant_id;
let MerchantAccountRoutingAlgorithm::V1(algorithm_id) = session_pm_input.routing_algorithm;
let chosen_connectors = if let Some(ref algorithm_id) = algorithm_id {
let cached_algorithm = ensure_algorithm_cached_v1(
state,
merchant_id,
algorithm_id,
session_pm_input.profile_id,
transaction_type,
)
.await?;
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) => execute_dsl_and_get_connector_v1(
session_pm_input.backend_input.clone(),
interpreter,
)?,
}
} else {
profile_wrapper
.get_default_fallback_list_of_connector_under_profile()
.change_context(errors::RoutingError::FallbackConfigFetchFailed)?
};
Ok(chosen_connectors)
}
<file_sep path="hyperswitch/crates/router/src/core/payments/routing.rs" role="context" start="1252" end="1330">
async fn perform_session_routing_for_pm_type(
session_pm_input: &SessionRoutingPmTypeInput<'_>,
transaction_type: &api_enums::TransactionType,
_business_profile: &domain::Profile,
) -> RoutingResult<Option<Vec<api_models::routing::RoutableConnectorChoice>>> {
let merchant_id = &session_pm_input.key_store.merchant_id;
let algorithm_id = match session_pm_input.routing_algorithm {
MerchantAccountRoutingAlgorithm::V1(algorithm_ref) => &algorithm_ref.algorithm_id,
};
let chosen_connectors = if let Some(ref algorithm_id) = algorithm_id {
let cached_algorithm = ensure_algorithm_cached_v1(
&session_pm_input.state.clone(),
merchant_id,
algorithm_id,
session_pm_input.profile_id,
transaction_type,
)
.await?;
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) => execute_dsl_and_get_connector_v1(
session_pm_input.backend_input.clone(),
interpreter,
)?,
}
} else {
routing::helpers::get_merchant_default_config(
&*session_pm_input.state.clone().store,
session_pm_input.profile_id.get_string_repr(),
transaction_type,
)
.await
.change_context(errors::RoutingError::FallbackConfigFetchFailed)?
};
let mut final_selection = perform_cgraph_filtering(
&session_pm_input.state.clone(),
session_pm_input.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 = routing::helpers::get_merchant_default_config(
&*session_pm_input.state.clone().store,
session_pm_input.profile_id.get_string_repr(),
transaction_type,
)
.await
.change_context(errors::RoutingError::FallbackConfigFetchFailed)?;
final_selection = perform_cgraph_filtering(
&session_pm_input.state.clone(),
session_pm_input.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="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="111" end="111">
type RoutingResult<O> = oss_errors::CustomResult<O, errors::RoutingError>;
<file_sep path="hyperswitch/crates/router/src/core/payments/routing.rs" role="context" start="66" end="71">
pub enum CachedAlgorithm {
Single(Box<routing_types::RoutableConnectorChoice>),
Priority(Vec<routing_types::RoutableConnectorChoice>),
VolumeSplit(Vec<routing_types::ConnectorVolumeSplit>),
Advanced(backend::VirInterpreterBackend<ConnectorSelection>),
}
<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/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/admin.rs" role="context" start="698" end="700">
pub struct MerchantId {
pub merchant_id: id_type::MerchantId,
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/admin.rs<|crate|> router anchor=validate_and_get_business_profile 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="2824" end="2872">
async fn validate_and_get_business_profile(
self,
merchant_account: &domain::MerchantAccount,
db: &dyn StorageInterface,
key_manager_state: &KeyManagerState,
key_store: &domain::MerchantKeyStore,
) -> RouterResult<domain::Profile> {
match self.profile_id.or(merchant_account.default_profile.clone()) {
Some(profile_id) => {
// Check whether this business profile belongs to the merchant
let business_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")
.change_context(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
Ok(business_profile)
}
None => match self.business_country.zip(self.business_label) {
Some((business_country, business_label)) => {
let profile_name = format!("{business_country}_{business_label}");
let business_profile = db
.find_business_profile_by_profile_name_merchant_id(
key_manager_state,
key_store,
&profile_name,
merchant_account.get_id(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {
id: profile_name,
})?;
Ok(business_profile)
}
_ => Err(report!(errors::ApiErrorResponse::MissingRequiredField {
field_name: "profile_id or business_country, business_label"
})),
},
}
}
<file_sep path="hyperswitch/crates/router/src/core/admin.rs" role="context" start="2823" end="2823">
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,
})
}
/// If profile_id is not passed, use default profile if available, or
/// If business_details (business_country and business_label) are passed, get the business_profile
/// or return a `MissingRequiredField` error
async fn validate_and_get_business_profile(
self,
merchant_account: &domain::MerchantAccount,
db: &dyn StorageInterface,
key_manager_state: &KeyManagerState,
key_store: &domain::MerchantKeyStore,
) -> RouterResult<domain::Profile> {
match self.profile_id.or(merchant_account.default_profile.clone()) {
Some(profile_id) => {
// Check whether this business profile belongs to the merchant
let business_profile = core_utils::validate_and_get_business_profile(
db,
<file_sep path="hyperswitch/crates/router/src/core/admin.rs" role="context" start="3014" end="3060">
async fn validate_pm_auth(
val: pii::SecretSerdeValue,
state: &SessionState,
merchant_id: &id_type::MerchantId,
key_store: &domain::MerchantKeyStore,
merchant_account: domain::MerchantAccount,
profile_id: &id_type::ProfileId,
) -> RouterResponse<()> {
let config =
serde_json::from_value::<api_models::pm_auth::PaymentMethodAuthConfig>(val.expose())
.change_context(errors::ApiErrorResponse::InvalidRequestData {
message: "invalid data received for payment method auth config".to_string(),
})
.attach_printable("Failed to deserialize Payment Method Auth config")?;
let all_mcas = state
.store
.find_merchant_connector_account_by_merchant_id_and_disabled_list(
&state.into(),
merchant_id,
true,
key_store,
)
.await
.change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: merchant_account.get_id().get_string_repr().to_owned(),
})?;
for conn_choice in config.enabled_payment_methods {
let pm_auth_mca = all_mcas
.iter()
.find(|mca| mca.get_id() == conn_choice.mca_id)
.ok_or(errors::ApiErrorResponse::GenericNotFoundError {
message: "payment method auth connector account not found".to_string(),
})?;
if &pm_auth_mca.profile_id != profile_id {
return Err(errors::ApiErrorResponse::GenericNotFoundError {
message: "payment method auth profile_id differs from connector profile_id"
.to_string(),
}
.into());
}
}
Ok(services::ApplicationResponse::StatusOk)
}
<file_sep path="hyperswitch/crates/router/src/core/admin.rs" role="context" start="2875" end="3011">
pub async fn create_connector(
state: SessionState,
req: api::MerchantConnectorCreate,
merchant_account: domain::MerchantAccount,
auth_profile_id: Option<id_type::ProfileId>,
key_store: domain::MerchantKeyStore,
) -> RouterResponse<api_models::admin::MerchantConnectorResponse> {
let store = state.store.as_ref();
let key_manager_state = &(&state).into();
#[cfg(feature = "dummy_connector")]
fp_utils::when(
req.connector_name
.validate_dummy_connector_create(state.conf.dummy_connector.enabled),
|| {
Err(errors::ApiErrorResponse::InvalidRequestData {
message: "Invalid connector name".to_string(),
})
},
)?;
let connector_metadata = ConnectorMetadata {
connector_metadata: &req.metadata,
};
let merchant_id = merchant_account.get_id();
connector_metadata.validate_apple_pay_certificates_in_mca_metadata()?;
#[cfg(feature = "v1")]
helpers::validate_business_details(
req.business_country,
req.business_label.as_ref(),
&merchant_account,
)?;
let business_profile = req
.clone()
.validate_and_get_business_profile(&merchant_account, store, key_manager_state, &key_store)
.await?;
core_utils::validate_profile_id_from_auth_layer(auth_profile_id, &business_profile)?;
let pm_auth_config_validation = PMAuthConfigValidation {
connector_type: &req.connector_type,
pm_auth_config: &req.pm_auth_config,
db: store,
merchant_id,
profile_id: business_profile.get_id(),
key_store: &key_store,
key_manager_state,
};
pm_auth_config_validation.validate_pm_auth_config().await?;
let connector_type_and_connector_enum = ConnectorTypeAndConnectorName {
connector_type: &req.connector_type,
connector_name: &req.connector_name,
};
let routable_connector = connector_type_and_connector_enum.get_routable_connector()?;
// The purpose of this merchant account update is just to update the
// merchant account `modified_at` field for KGraph cache invalidation
state
.store
.update_specific_fields_in_merchant(
key_manager_state,
merchant_id,
storage::MerchantAccountUpdate::ModifiedAtUpdate,
&key_store,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("error updating the merchant account when creating payment connector")?;
let merchant_connector_account = req
.clone()
.create_domain_model_from_request(
&state,
key_store.clone(),
&business_profile,
key_manager_state,
)
.await?;
let mca = state
.store
.insert_merchant_connector_account(
key_manager_state,
merchant_connector_account.clone(),
&key_store,
)
.await
.to_duplicate_response(
errors::ApiErrorResponse::DuplicateMerchantConnectorAccount {
profile_id: business_profile.get_id().get_string_repr().to_owned(),
connector_label: merchant_connector_account
.connector_label
.unwrap_or_default(),
},
)?;
#[cfg(feature = "v1")]
//update merchant default config
let merchant_default_config_update = MerchantDefaultConfigUpdate {
routable_connector: &routable_connector,
merchant_connector_id: &mca.get_id(),
store,
merchant_id,
profile_id: business_profile.get_id(),
transaction_type: &req.get_transaction_type(),
};
#[cfg(feature = "v2")]
//update merchant default config
let merchant_default_config_update = DefaultFallbackRoutingConfigUpdate {
routable_connector: &routable_connector,
merchant_connector_id: &mca.get_id(),
store,
business_profile,
key_store,
key_manager_state,
};
merchant_default_config_update
.retrieve_and_update_default_fallback_routing_algorithm_if_routable_connector_exists()
.await?;
metrics::MCA_CREATE.add(
1,
router_env::metric_attributes!(
("connector", req.connector_name.to_string()),
("merchant", merchant_id.clone()),
),
);
let mca_response = mca.foreign_try_into()?;
Ok(service_api::ApplicationResponse::Json(mca_response))
}
<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="2651" end="2669">
fn get_payment_methods_enabled(&self) -> RouterResult<Option<Vec<pii::SecretSerdeValue>>> {
let mut vec = Vec::new();
let payment_methods_enabled = match self.payment_methods_enabled.clone() {
Some(val) => {
for pm in val.into_iter() {
let pm_value = pm
.encode_to_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Failed while encoding to serde_json::Value, PaymentMethod",
)?;
vec.push(Secret::new(pm_value))
}
Some(vec)
}
None => None,
};
Ok(payment_methods_enabled)
}
<file_sep path="hyperswitch/crates/router/src/core/admin.rs" role="context" start="2617" end="2641">
async fn validate_and_get_business_profile(
self,
merchant_account: &domain::MerchantAccount,
db: &dyn StorageInterface,
key_manager_state: &KeyManagerState,
key_store: &domain::MerchantKeyStore,
) -> RouterResult<domain::Profile> {
let profile_id = self.profile_id;
// Check whether this profile belongs to the merchant
let business_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")
.change_context(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
Ok(business_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);
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payments/routing.rs<|crate|> router anchor=perform_fallback_routing 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="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="880" end="880">
use api_models::routing as api_routing;
use api_models::{
admin as admin_api,
enums::{self as api_enums, CountryAlpha2},
routing::ConnectorSelection,
};
use crate::core::admin;
use crate::core::payouts;
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="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/router/src/core/payments/routing.rs" role="context" start="930" end="975">
pub async fn perform_eligibility_analysis_with_fallback(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
chosen: Vec<routing_types::RoutableConnectorChoice>,
transaction_data: &routing::TransactionData<'_>,
eligible_connectors: Option<Vec<api_enums::RoutableConnectors>>,
business_profile: &domain::Profile,
) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> {
let mut final_selection = perform_eligibility_analysis(
state,
key_store,
chosen,
transaction_data,
eligible_connectors.as_ref(),
business_profile.get_id(),
)
.await?;
let fallback_selection = perform_fallback_routing(
state,
key_store,
transaction_data,
eligible_connectors.as_ref(),
business_profile,
)
.await;
final_selection.append(
&mut fallback_selection
.unwrap_or_default()
.iter()
.filter(|&routable_connector_choice| {
!final_selection.contains(routable_connector_choice)
})
.cloned()
.collect::<Vec<_>>(),
);
let final_selected_connectors = final_selection
.iter()
.map(|item| item.connector)
.collect::<Vec<_>>();
logger::debug!(final_selected_connectors_for_routing=?final_selected_connectors, "List of final selected connectors for routing");
Ok(final_selection)
}
<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="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="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="111" end="111">
type RoutingResult<O> = oss_errors::CustomResult<O, errors::RoutingError>;
<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/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>,
}
<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/transformers.rs<|crate|> router anchor=mk_basilisk_req kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/transformers.rs" role="context" start="335" end="382">
pub async fn mk_basilisk_req(
jwekey: &settings::Jwekey,
jws: &str,
locker_choice: api_enums::LockerChoice,
) -> CustomResult<encryption::JweBody, errors::VaultError> {
let jws_payload: Vec<&str> = jws.split('.').collect();
let generate_jws_body = |payload: Vec<&str>| -> Option<encryption::JwsBody> {
Some(encryption::JwsBody {
header: payload.first()?.to_string(),
payload: payload.get(1)?.to_string(),
signature: payload.get(2)?.to_string(),
})
};
let jws_body = generate_jws_body(jws_payload).ok_or(errors::VaultError::SaveCardFailed)?;
let payload = jws_body
.encode_to_vec()
.change_context(errors::VaultError::SaveCardFailed)?;
let public_key = match locker_choice {
api_enums::LockerChoice::HyperswitchCardVault => {
jwekey.vault_encryption_key.peek().as_bytes()
}
};
let jwe_encrypted =
encryption::encrypt_jwe(&payload, public_key, EncryptionAlgorithm::A256GCM, None)
.await
.change_context(errors::VaultError::SaveCardFailed)
.attach_printable("Error on jwe encrypt")?;
let jwe_payload: Vec<&str> = jwe_encrypted.split('.').collect();
let generate_jwe_body = |payload: Vec<&str>| -> Option<encryption::JweBody> {
Some(encryption::JweBody {
header: payload.first()?.to_string(),
iv: payload.get(2)?.to_string(),
encrypted_payload: payload.get(3)?.to_string(),
tag: payload.get(4)?.to_string(),
encrypted_key: payload.get(1)?.to_string(),
})
};
let jwe_body = generate_jwe_body(jwe_payload).ok_or(errors::VaultError::SaveCardFailed)?;
Ok(jwe_body)
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/transformers.rs" role="context" start="334" end="334">
use api_models::{enums as api_enums, payment_methods::Card};
use josekit::jwe;
use crate::{
configs::settings,
core::errors::{self, CustomResult},
headers,
pii::{prelude::*, Secret},
services::{api as services, encryption, EncryptionAlgorithm},
types::{api, domain},
utils::OptionExt,
};
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/transformers.rs" role="context" start="428" end="450">
pub fn mk_add_bank_response_hs(
bank: api::BankPayout,
bank_reference: String,
req: api::PaymentMethodCreate,
merchant_id: &id_type::MerchantId,
) -> api::PaymentMethodResponse {
api::PaymentMethodResponse {
merchant_id: merchant_id.to_owned(),
customer_id: req.customer_id,
payment_method_id: bank_reference,
payment_method: req.payment_method,
payment_method_type: req.payment_method_type,
bank_transfer: Some(bank),
card: None,
metadata: req.metadata,
created: Some(common_utils::date_time::now()),
recurring_enabled: false, // [#256]
installment_payment_enabled: false, // #[#256]
payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]),
last_used_at: Some(common_utils::date_time::now()),
client_secret: None,
}
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/transformers.rs" role="context" start="384" end="421">
pub async fn mk_add_locker_request_hs(
jwekey: &settings::Jwekey,
locker: &settings::Locker,
payload: &StoreLockerReq,
locker_choice: api_enums::LockerChoice,
tenant_id: id_type::TenantId,
request_id: Option<RequestId>,
) -> CustomResult<services::Request, errors::VaultError> {
let payload = payload
.encode_to_vec()
.change_context(errors::VaultError::RequestEncodingFailed)?;
let private_key = jwekey.vault_private_key.peek().as_bytes();
let jws = encryption::jws_sign_payload(&payload, &locker.locker_signing_key_id, private_key)
.await
.change_context(errors::VaultError::RequestEncodingFailed)?;
let jwe_payload = mk_basilisk_req(jwekey, &jws, locker_choice).await?;
let mut url = match locker_choice {
api_enums::LockerChoice::HyperswitchCardVault => locker.host.to_owned(),
};
url.push_str("/cards/add");
let mut request = services::Request::new(services::Method::Post, &url);
request.add_header(headers::CONTENT_TYPE, "application/json".into());
request.add_header(
headers::X_TENANT_ID,
tenant_id.get_string_repr().to_owned().into(),
);
if let Some(req_id) = request_id {
request.add_header(
headers::X_REQUEST_ID,
req_id.as_hyphenated().to_string().into(),
);
}
request.set_body(RequestContent::Json(Box::new(jwe_payload)));
Ok(request)
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/transformers.rs" role="context" start="289" end="333">
pub async fn create_jwe_body_for_vault(
jwekey: &settings::Jwekey,
jws: &str,
) -> CustomResult<encryption::JweBody, errors::VaultError> {
let jws_payload: Vec<&str> = jws.split('.').collect();
let generate_jws_body = |payload: Vec<&str>| -> Option<encryption::JwsBody> {
Some(encryption::JwsBody {
header: payload.first()?.to_string(),
payload: payload.get(1)?.to_string(),
signature: payload.get(2)?.to_string(),
})
};
let jws_body =
generate_jws_body(jws_payload).ok_or(errors::VaultError::RequestEncryptionFailed)?;
let payload = jws_body
.encode_to_vec()
.change_context(errors::VaultError::RequestEncodingFailed)?;
let public_key = jwekey.vault_encryption_key.peek().as_bytes();
let jwe_encrypted =
encryption::encrypt_jwe(&payload, public_key, EncryptionAlgorithm::A256GCM, None)
.await
.change_context(errors::VaultError::SaveCardFailed)
.attach_printable("Error on jwe encrypt")?;
let jwe_payload: Vec<&str> = jwe_encrypted.split('.').collect();
let generate_jwe_body = |payload: Vec<&str>| -> Option<encryption::JweBody> {
Some(encryption::JweBody {
header: payload.first()?.to_string(),
iv: payload.get(2)?.to_string(),
encrypted_payload: payload.get(3)?.to_string(),
tag: payload.get(4)?.to_string(),
encrypted_key: payload.get(1)?.to_string(),
})
};
let jwe_body =
generate_jwe_body(jwe_payload).ok_or(errors::VaultError::RequestEncodingFailed)?;
Ok(jwe_body)
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/transformers.rs" role="context" start="253" end="286">
pub async fn get_decrypted_vault_response_payload(
jwekey: &settings::Jwekey,
jwe_body: encryption::JweBody,
decryption_scheme: settings::DecryptionScheme,
) -> CustomResult<String, errors::VaultError> {
let public_key = jwekey.vault_encryption_key.peek().as_bytes();
let private_key = jwekey.vault_private_key.peek().as_bytes();
let jwt = get_dotted_jwe(jwe_body);
let alg = match decryption_scheme {
settings::DecryptionScheme::RsaOaep => jwe::RSA_OAEP,
settings::DecryptionScheme::RsaOaep256 => jwe::RSA_OAEP_256,
};
let jwe_decrypted = encryption::decrypt_jwe(
&jwt,
encryption::KeyIdCheck::SkipKeyIdCheck,
private_key,
alg,
)
.await
.change_context(errors::VaultError::SaveCardFailed)
.attach_printable("Jwe Decryption failed for JweBody for vault")?;
let jws = jwe_decrypted
.parse_struct("JwsBody")
.change_context(errors::VaultError::ResponseDeserializationFailed)?;
let jws_body = get_dotted_jws(jws);
encryption::verify_sign(jws_body, public_key)
.change_context(errors::VaultError::SaveCardFailed)
.attach_printable("Jws Decryption failed for JwsBody for vault")
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/transformers.rs" role="context" start="621" end="669">
pub async fn mk_get_card_request_hs(
jwekey: &settings::Jwekey,
locker: &settings::Locker,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
card_reference: &str,
locker_choice: Option<api_enums::LockerChoice>,
tenant_id: id_type::TenantId,
request_id: Option<RequestId>,
) -> CustomResult<services::Request, errors::VaultError> {
let merchant_customer_id = customer_id.to_owned();
let card_req_body = CardReqBody {
merchant_id: merchant_id.to_owned(),
merchant_customer_id,
card_reference: card_reference.to_owned(),
};
let payload = card_req_body
.encode_to_vec()
.change_context(errors::VaultError::RequestEncodingFailed)?;
let private_key = jwekey.vault_private_key.peek().as_bytes();
let jws = encryption::jws_sign_payload(&payload, &locker.locker_signing_key_id, private_key)
.await
.change_context(errors::VaultError::RequestEncodingFailed)?;
let target_locker = locker_choice.unwrap_or(api_enums::LockerChoice::HyperswitchCardVault);
let jwe_payload = mk_basilisk_req(jwekey, &jws, target_locker).await?;
let mut url = match target_locker {
api_enums::LockerChoice::HyperswitchCardVault => locker.host.to_owned(),
};
url.push_str("/cards/retrieve");
let mut request = services::Request::new(services::Method::Post, &url);
request.add_header(headers::CONTENT_TYPE, "application/json".into());
request.add_header(
headers::X_TENANT_ID,
tenant_id.get_string_repr().to_owned().into(),
);
if let Some(req_id) = request_id {
request.add_header(
headers::X_REQUEST_ID,
req_id.as_hyphenated().to_string().into(),
);
}
request.set_body(RequestContent::Json(Box::new(jwe_payload)));
Ok(request)
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/transformers.rs" role="context" start="945" end="945">
type Error = error_stack::Report<errors::ValidationError>;
<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/core/payment_methods/cards.rs<|crate|> router anchor=get_client_secret_or_add_payment_method_for_migration 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="1114" end="1212">
pub async fn get_client_secret_or_add_payment_method_for_migration(
state: &routes::SessionState,
req: api::PaymentMethodCreate,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
migration_status: &mut migration::RecordMigrationStatusBuilder,
) -> errors::RouterResponse<api::PaymentMethodResponse> {
let merchant_id = merchant_account.get_id();
let customer_id = req.customer_id.clone().get_required_value("customer_id")?;
#[cfg(not(feature = "payouts"))]
let condition = req.card.is_some();
#[cfg(feature = "payouts")]
let condition = req.card.is_some() || req.bank_transfer.is_some() || req.wallet.is_some();
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)?;
if condition {
Box::pin(save_migration_payment_method(
state,
req,
merchant_account,
key_store,
migration_status,
))
.await
} else {
let payment_method_id = generate_id(consts::ID_LENGTH, "pm");
let res = create_payment_method(
state,
&req,
&customer_id,
payment_method_id.as_str(),
None,
merchant_id,
None,
None,
None,
key_store,
connector_mandate_details.clone(),
Some(enums::PaymentMethodStatus::AwaitingData),
None,
merchant_account.storage_scheme,
payment_method_billing_address,
None,
None,
None,
None,
)
.await?;
migration_status.connector_mandate_details_migrated(
connector_mandate_details
.clone()
.and_then(|val| (val != json!({})).then_some(true))
.or_else(|| {
req.connector_mandate_details
.clone()
.and_then(|val| (!val.0.is_empty()).then_some(false))
}),
);
//card is not migrated in this case
migration_status.card_migrated(false);
if res.status == enums::PaymentMethodStatus::AwaitingData {
add_payment_method_status_update_task(
&*state.store,
&res,
enums::PaymentMethodStatus::AwaitingData,
enums::PaymentMethodStatus::Inactive,
merchant_id,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Failed to add payment method status update task in process tracker",
)?;
}
Ok(services::api::ApplicationResponse::Json(
api::PaymentMethodResponse::foreign_from((None, res)),
))
}
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="1113" end="1113">
Ok(services::api::ApplicationResponse::Json(
api::PaymentMethodResponse::foreign_from((None, res)),
))
}
}
#[cfg(all(
any(feature = "v1", feature = "v2"),
not(feature = "payment_methods_v2")
))]
#[instrument(skip_all)]
pub async fn get_client_secret_or_add_payment_method_for_migration(
state: &routes::SessionState,
req: api::PaymentMethodCreate,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
migration_status: &mut migration::RecordMigrationStatusBuilder,
) -> errors::RouterResponse<api::PaymentMethodResponse> {
let merchant_id = merchant_account.get_id();
let customer_id = req.customer_id.clone().get_required_value("customer_id")?;
#[cfg(not(feature = "payouts"))]
let condition = req.card.is_some();
#[cfg(feature = "payouts")]
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="1248" end="1447">
pub async fn add_payment_method_data(
state: routes::SessionState,
req: api::PaymentMethodCreate,
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
pm_id: String,
) -> errors::RouterResponse<api::PaymentMethodResponse> {
let db = &*state.store;
let pmd = req
.payment_method_data
.clone()
.get_required_value("payment_method_data")?;
req.payment_method.get_required_value("payment_method")?;
let client_secret = req
.client_secret
.clone()
.get_required_value("client_secret")?;
let payment_method = db
.find_payment_method(
&((&state).into()),
&key_store,
pm_id.as_str(),
merchant_account.storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::PaymentMethodNotFound)
.attach_printable("Unable to find payment method")?;
if payment_method.status != enums::PaymentMethodStatus::AwaitingData {
return Err((errors::ApiErrorResponse::ClientSecretExpired).into());
}
let customer_id = payment_method.customer_id.clone();
let customer = db
.find_customer_by_customer_id_merchant_id(
&(&state).into(),
&customer_id,
merchant_account.get_id(),
&key_store,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?;
let client_secret_expired =
authenticate_pm_client_secret_and_check_expiry(&client_secret, &payment_method)?;
if client_secret_expired {
return Err((errors::ApiErrorResponse::ClientSecretExpired).into());
};
let key_manager_state = (&state).into();
match pmd {
api_models::payment_methods::PaymentMethodCreateData::Card(card) => {
helpers::validate_card_expiry(&card.card_exp_month, &card.card_exp_year)?;
let resp = Box::pin(add_card_to_locker(
&state,
req.clone(),
&card,
&customer_id,
&merchant_account,
None,
))
.await
.change_context(errors::ApiErrorResponse::InternalServerError);
match resp {
Ok((mut pm_resp, duplication_check)) => {
if duplication_check.is_some() {
let pm_update = storage::PaymentMethodUpdate::StatusUpdate {
status: Some(enums::PaymentMethodStatus::Inactive),
};
db.update_payment_method(
&((&state).into()),
&key_store,
payment_method,
pm_update,
merchant_account.storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to add payment method in db")?;
get_or_insert_payment_method(
&state,
req.clone(),
&mut pm_resp,
&merchant_account,
&customer_id,
&key_store,
)
.await?;
return Ok(services::ApplicationResponse::Json(pm_resp));
} else {
let locker_id = pm_resp.payment_method_id.clone();
pm_resp.payment_method_id.clone_from(&pm_id);
pm_resp.client_secret = Some(client_secret.clone());
let card_isin = card.card_number.get_card_isin();
let card_info = db
.get_card_info(card_isin.as_str())
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get card info")?;
let updated_card = CardDetailsPaymentMethod {
issuer_country: card_info
.as_ref()
.and_then(|ci| ci.card_issuing_country.clone()),
last4_digits: Some(card.card_number.get_last4()),
expiry_month: Some(card.card_exp_month),
expiry_year: Some(card.card_exp_year),
nick_name: card.nick_name,
card_holder_name: card.card_holder_name,
card_network: card_info.as_ref().and_then(|ci| ci.card_network.clone()),
card_isin: Some(card_isin),
card_issuer: card_info.as_ref().and_then(|ci| ci.card_issuer.clone()),
card_type: card_info.as_ref().and_then(|ci| ci.card_type.clone()),
saved_to_locker: true,
};
let pm_data_encrypted: Encryptable<Secret<serde_json::Value>> =
create_encrypted_data(
&key_manager_state,
&key_store,
PaymentMethodsData::Card(updated_card),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt payment method data")?;
let pm_update = storage::PaymentMethodUpdate::AdditionalDataUpdate {
payment_method_data: Some(pm_data_encrypted.into()),
status: Some(enums::PaymentMethodStatus::Active),
locker_id: Some(locker_id),
network_token_requestor_reference_id: None,
payment_method: req.payment_method,
payment_method_issuer: req.payment_method_issuer,
payment_method_type: req.payment_method_type,
network_token_locker_id: None,
network_token_payment_method_data: None,
};
db.update_payment_method(
&((&state).into()),
&key_store,
payment_method,
pm_update,
merchant_account.storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to add payment method in db")?;
if customer.default_payment_method_id.is_none() {
let _ = set_default_payment_method(
&state,
merchant_account.get_id(),
key_store.clone(),
&customer_id,
pm_id,
merchant_account.storage_scheme,
)
.await
.map_err(|error| {
logger::error!(
?error,
"Failed to set the payment method as default"
)
});
}
return Ok(services::ApplicationResponse::Json(pm_resp));
}
}
Err(e) => {
let pm_update = storage::PaymentMethodUpdate::StatusUpdate {
status: Some(enums::PaymentMethodStatus::Inactive),
};
db.update_payment_method(
&((&state).into()),
&key_store,
payment_method,
pm_update,
merchant_account.storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update payment method in db")?;
return Err(e.attach_printable("Failed to add card to locker"));
}
}
}
}
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="1215" end="1240">
pub fn authenticate_pm_client_secret_and_check_expiry(
req_client_secret: &String,
payment_method: &domain::PaymentMethod,
) -> errors::CustomResult<bool, errors::ApiErrorResponse> {
let stored_client_secret = payment_method
.client_secret
.clone()
.get_required_value("client_secret")
.change_context(errors::ApiErrorResponse::MissingRequiredField {
field_name: "client_secret",
})
.attach_printable("client secret not found in db")?;
if req_client_secret != &stored_client_secret {
Err((errors::ApiErrorResponse::ClientSecretInvalid).into())
} else {
let current_timestamp = common_utils::date_time::now();
let session_expiry = payment_method
.created_at
.saturating_add(time::Duration::seconds(consts::DEFAULT_SESSION_EXPIRY));
let expired = current_timestamp > session_expiry;
Ok(expired)
}
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="1030" end="1107">
pub async fn get_client_secret_or_add_payment_method(
state: &routes::SessionState,
req: api::PaymentMethodCreate,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
) -> errors::RouterResponse<api::PaymentMethodResponse> {
let merchant_id = merchant_account.get_id();
let customer_id = req.customer_id.clone().get_required_value("customer_id")?;
#[cfg(not(feature = "payouts"))]
let condition = req.card.is_some();
#[cfg(feature = "payouts")]
let condition = req.card.is_some() || req.bank_transfer.is_some() || req.wallet.is_some();
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)?;
if condition {
Box::pin(add_payment_method(state, req, merchant_account, key_store)).await
} else {
let payment_method_id = generate_id(consts::ID_LENGTH, "pm");
let res = create_payment_method(
state,
&req,
&customer_id,
payment_method_id.as_str(),
None,
merchant_id,
None,
None,
None,
key_store,
connector_mandate_details,
Some(enums::PaymentMethodStatus::AwaitingData),
None,
merchant_account.storage_scheme,
payment_method_billing_address,
None,
None,
None,
None,
)
.await?;
if res.status == enums::PaymentMethodStatus::AwaitingData {
add_payment_method_status_update_task(
&*state.store,
&res,
enums::PaymentMethodStatus::AwaitingData,
enums::PaymentMethodStatus::Inactive,
merchant_id,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Failed to add payment method status update task in process tracker",
)?;
}
Ok(services::api::ApplicationResponse::Json(
api::PaymentMethodResponse::foreign_from((None, res)),
))
}
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="1005" end="1023">
pub fn get_card_bin_and_last4_digits_for_masked_card(
masked_card_number: &str,
) -> Result<(String, String), cards::CardNumberValidationErr> {
let last4_digits = masked_card_number
.chars()
.rev()
.take(4)
.collect::<String>()
.chars()
.rev()
.collect::<String>();
let card_isin = masked_card_number.chars().take(6).collect::<String>();
cards::validate::validate_card_number_chars(&card_isin)
.and_then(|_| cards::validate::validate_card_number_chars(&last4_digits))?;
Ok((card_isin, last4_digits))
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="381" end="502">
pub async fn migrate_payment_method(
state: routes::SessionState,
req: api::PaymentMethodMigrate,
merchant_id: &id_type::MerchantId,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
) -> errors::RouterResponse<api::PaymentMethodMigrateResponse> {
let mut req = req;
let card_details = &req.card.get_required_value("card")?;
let card_number_validation_result =
cards::CardNumber::from_str(card_details.card_number.peek());
let card_bin_details =
populate_bin_details_for_masked_card(card_details, &*state.store).await?;
req.card = Some(api_models::payment_methods::MigrateCardDetail {
card_issuing_country: card_bin_details.issuer_country.clone(),
card_network: card_bin_details.card_network.clone(),
card_issuer: card_bin_details.card_issuer.clone(),
card_type: card_bin_details.card_type.clone(),
..card_details.clone()
});
if let Some(connector_mandate_details) = &req.connector_mandate_details {
helpers::validate_merchant_connector_ids_in_connector_mandate_details(
&state,
key_store,
connector_mandate_details,
merchant_id,
card_bin_details.card_network.clone(),
)
.await?;
};
let should_require_connector_mandate_details = req.network_token.is_none();
let mut migration_status = migration::RecordMigrationStatusBuilder::new();
let resp = match card_number_validation_result {
Ok(card_number) => {
let payment_method_create_request =
api::PaymentMethodCreate::get_payment_method_create_from_payment_method_migrate(
card_number,
&req,
);
logger::debug!("Storing the card in locker and migrating the payment method");
get_client_secret_or_add_payment_method_for_migration(
&state,
payment_method_create_request,
merchant_account,
key_store,
&mut migration_status,
)
.await?
}
Err(card_validation_error) => {
logger::debug!("Card number to be migrated is invalid, skip saving in locker {card_validation_error}");
skip_locker_call_and_migrate_payment_method(
&state,
&req,
merchant_id.to_owned(),
key_store,
merchant_account,
card_bin_details.clone(),
should_require_connector_mandate_details,
&mut migration_status,
)
.await?
}
};
let payment_method_response = match resp {
services::ApplicationResponse::Json(response) => response,
_ => Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to fetch the payment method response")?,
};
let pm_id = payment_method_response.payment_method_id.clone();
let network_token = req.network_token.clone();
let network_token_migrated = match network_token {
Some(nt_detail) => {
logger::debug!("Network token migration");
let network_token_requestor_ref_id = nt_detail.network_token_requestor_ref_id.clone();
let network_token_data = &nt_detail.network_token_data;
Some(
save_network_token_and_update_payment_method(
&state,
&req,
key_store,
merchant_account,
network_token_data,
network_token_requestor_ref_id,
pm_id,
)
.await
.map_err(|err| logger::error!(?err, "Failed to save network token"))
.ok()
.unwrap_or_default(),
)
}
None => {
logger::debug!("Network token data is not available");
None
}
};
migration_status.network_token_migrated(network_token_migrated);
let migrate_status = migration_status.build();
Ok(services::ApplicationResponse::Json(
api::PaymentMethodMigrateResponse {
payment_method_response,
card_migrated: migrate_status.card_migrated,
network_token_migrated: migrate_status.network_token_migrated,
connector_mandate_details_migrated: migrate_status.connector_mandate_details_migrated,
network_transaction_id_migrated: migrate_status.network_transaction_migrated,
},
))
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="133" end="232">
pub async fn create_payment_method(
state: &routes::SessionState,
req: &api::PaymentMethodCreate,
customer_id: &id_type::CustomerId,
payment_method_id: &str,
locker_id: Option<String>,
merchant_id: &id_type::MerchantId,
pm_metadata: Option<serde_json::Value>,
customer_acceptance: Option<serde_json::Value>,
payment_method_data: crypto::OptionalEncryptableValue,
key_store: &domain::MerchantKeyStore,
connector_mandate_details: Option<serde_json::Value>,
status: Option<enums::PaymentMethodStatus>,
network_transaction_id: Option<String>,
storage_scheme: MerchantStorageScheme,
payment_method_billing_address: crypto::OptionalEncryptableValue,
card_scheme: Option<String>,
network_token_requestor_reference_id: Option<String>,
network_token_locker_id: Option<String>,
network_token_payment_method_data: crypto::OptionalEncryptableValue,
) -> errors::CustomResult<domain::PaymentMethod, errors::ApiErrorResponse> {
let db = &*state.store;
let customer = db
.find_customer_by_customer_id_merchant_id(
&state.into(),
customer_id,
merchant_id,
key_store,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?;
let client_secret = generate_id(
consts::ID_LENGTH,
format!("{payment_method_id}_secret").as_str(),
);
let current_time = common_utils::date_time::now();
let response = db
.insert_payment_method(
&state.into(),
key_store,
domain::PaymentMethod {
customer_id: customer_id.to_owned(),
merchant_id: merchant_id.to_owned(),
payment_method_id: payment_method_id.to_string(),
locker_id,
payment_method: req.payment_method,
payment_method_type: req.payment_method_type,
payment_method_issuer: req.payment_method_issuer.clone(),
scheme: req.card_network.clone().or(card_scheme),
metadata: pm_metadata.map(Secret::new),
payment_method_data,
connector_mandate_details,
customer_acceptance: customer_acceptance.map(Secret::new),
client_secret: Some(client_secret),
status: status.unwrap_or(enums::PaymentMethodStatus::Active),
network_transaction_id: network_transaction_id.to_owned(),
payment_method_issuer_code: None,
accepted_currency: None,
token: None,
cardholder_name: None,
issuer_name: None,
issuer_country: None,
payer_country: None,
is_stored: None,
swift_code: None,
direct_debit_token: None,
created_at: current_time,
last_modified: current_time,
last_used_at: current_time,
payment_method_billing_address,
updated_by: None,
version: common_types::consts::API_VERSION,
network_token_requestor_reference_id,
network_token_locker_id,
network_token_payment_method_data,
},
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to add payment method in db")?;
if customer.default_payment_method_id.is_none() && req.payment_method.is_some() {
let _ = set_default_payment_method(
state,
merchant_id,
key_store.clone(),
customer_id,
payment_method_id.to_owned(),
storage_scheme,
)
.await
.map_err(|error| logger::error!(?error, "Failed to set the payment method as default"));
}
Ok(response)
}
<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/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/src/core/api_keys.rs<|crate|> router anchor=update_api_key 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="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="270" end="270">
use diesel_models::{api_keys::ApiKey, enums as storage_enums};
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="426" end="487">
pub async fn revoke_api_key(
state: SessionState,
merchant_id: &common_utils::id_type::MerchantId,
key_id: &common_utils::id_type::ApiKeyId,
) -> RouterResponse<api::RevokeApiKeyResponse> {
let store = state.store.as_ref();
let api_key = store
.find_api_key_by_merchant_id_key_id_optional(merchant_id, key_id)
.await
.to_not_found_response(errors::ApiErrorResponse::ApiKeyNotFound)?;
let revoked = store
.revoke_api_key(merchant_id, key_id)
.await
.to_not_found_response(errors::ApiErrorResponse::ApiKeyNotFound)?;
if let Some(api_key) = api_key {
let hashed_api_key = api_key.hashed_api_key;
let state = state.clone();
authentication::decision::spawn_tracked_job(
async move {
authentication::decision::revoke_api_key(&state, hashed_api_key.into_inner().into())
.await
},
authentication::decision::REVOKE,
);
}
metrics::API_KEY_REVOKED.add(1, &[]);
#[cfg(feature = "email")]
{
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, then revoke it
if existing_process_tracker_task.is_some() {
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",
)?;
}
}
Ok(ApplicationResponse::Json(api::RevokeApiKeyResponse {
merchant_id: merchant_id.to_owned(),
key_id: key_id.to_owned(),
revoked,
}))
}
<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(())
}
<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="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="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/routes/app.rs" role="context" start="104" end="125">
pub struct SessionState {
pub store: Box<dyn StorageInterface>,
/// Global store is used for global schema operations in tables like Users and Tenants
pub global_store: Box<dyn GlobalStorageInterface>,
pub accounts_store: Box<dyn AccountsStorageInterface>,
pub conf: Arc<settings::Settings<RawSecret>>,
pub api_client: Box<dyn crate::services::ApiClient>,
pub event_handler: EventsHandler,
#[cfg(feature = "email")]
pub email_client: Arc<Box<dyn EmailService>>,
#[cfg(feature = "olap")]
pub pool: AnalyticsProvider,
pub file_storage_client: Arc<dyn FileStorageInterface>,
pub request_id: Option<RequestId>,
pub base_url: String,
pub tenant: Tenant,
#[cfg(feature = "olap")]
pub opensearch_client: Option<Arc<OpenSearchClient>>,
pub grpc_client: Arc<GrpcClients>,
pub theme_storage_client: Arc<dyn FileStorageInterface>,
pub locale: String,
}
<file_sep path="hyperswitch-encryption-service/migrations/2024-05-28-075150_create_dek_table/up.sql" role="context" start="1" end="9">
CREATE TABLE IF NOT EXISTS data_key_store (
id SERIAL PRIMARY KEY,
key_identifier VARCHAR(255) NOT NULL,
data_identifier VARCHAR(20) NOT NULL,
encryption_key bytea NOT NULL,
version VARCHAR(30) NOT NULL,
created_at TIMESTAMP NOT NULL
);
<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/payment_methods/cards.rs<|crate|> router anchor=get_pm_list_context 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="5041" end="5130">
pub async fn get_pm_list_context(
state: &routes::SessionState,
payment_method: &enums::PaymentMethod,
#[cfg(feature = "payouts")] key_store: &domain::MerchantKeyStore,
#[cfg(not(feature = "payouts"))] _key_store: &domain::MerchantKeyStore,
pm: &domain::PaymentMethod,
#[cfg(feature = "payouts")] parent_payment_method_token: Option<String>,
#[cfg(not(feature = "payouts"))] _parent_payment_method_token: Option<String>,
is_payment_associated: bool,
) -> Result<Option<PaymentMethodListContext>, error_stack::Report<errors::ApiErrorResponse>> {
let payment_method_retrieval_context = match payment_method {
enums::PaymentMethod::Card => {
let card_details = get_card_details_with_locker_fallback(pm, state).await?;
card_details.as_ref().map(|card| PaymentMethodListContext {
card_details: Some(card.clone()),
#[cfg(feature = "payouts")]
bank_transfer_details: None,
hyperswitch_token_data: is_payment_associated.then_some(
PaymentTokenData::permanent_card(
Some(pm.get_id().clone()),
pm.locker_id.clone().or(Some(pm.get_id().clone())),
pm.locker_id.clone().unwrap_or(pm.get_id().clone()),
pm.network_token_requestor_reference_id
.clone()
.or(Some(pm.get_id().clone())),
),
),
})
}
enums::PaymentMethod::BankDebit => {
// Retrieve the pm_auth connector details so that it can be tokenized
let bank_account_token_data = get_bank_account_connector_details(pm)
.await
.unwrap_or_else(|err| {
logger::error!(error=?err);
None
});
bank_account_token_data.map(|data| {
let token_data = PaymentTokenData::AuthBankDebit(data);
PaymentMethodListContext {
card_details: None,
#[cfg(feature = "payouts")]
bank_transfer_details: None,
hyperswitch_token_data: is_payment_associated.then_some(token_data),
}
})
}
enums::PaymentMethod::Wallet => Some(PaymentMethodListContext {
card_details: None,
#[cfg(feature = "payouts")]
bank_transfer_details: None,
hyperswitch_token_data: is_payment_associated
.then_some(PaymentTokenData::wallet_token(pm.get_id().clone())),
}),
#[cfg(feature = "payouts")]
enums::PaymentMethod::BankTransfer => Some(PaymentMethodListContext {
card_details: None,
bank_transfer_details: Some(
get_bank_from_hs_locker(
state,
key_store,
parent_payment_method_token.as_ref(),
&pm.customer_id,
&pm.merchant_id,
pm.locker_id.as_ref().unwrap_or(pm.get_id()),
)
.await?,
),
hyperswitch_token_data: parent_payment_method_token
.map(|token| PaymentTokenData::temporary_generic(token.clone())),
}),
_ => Some(PaymentMethodListContext {
card_details: None,
#[cfg(feature = "payouts")]
bank_transfer_details: None,
hyperswitch_token_data: is_payment_associated.then_some(
PaymentTokenData::temporary_generic(generate_id(consts::ID_LENGTH, "token")),
),
}),
};
Ok(payment_method_retrieval_context)
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="5040" end="5040">
&mut response,
))
.await?;
Ok(services::ApplicationResponse::Json(response))
}
#[cfg(all(
any(feature = "v2", feature = "v1"),
not(feature = "payment_methods_v2"),
not(feature = "customer_v2")
))]
pub async fn get_pm_list_context(
state: &routes::SessionState,
payment_method: &enums::PaymentMethod,
#[cfg(feature = "payouts")] key_store: &domain::MerchantKeyStore,
#[cfg(not(feature = "payouts"))] _key_store: &domain::MerchantKeyStore,
pm: &domain::PaymentMethod,
#[cfg(feature = "payouts")] parent_payment_method_token: Option<String>,
#[cfg(not(feature = "payouts"))] _parent_payment_method_token: Option<String>,
is_payment_associated: bool,
) -> Result<Option<PaymentMethodListContext>, error_stack::Report<errors::ApiErrorResponse>> {
let payment_method_retrieval_context = match payment_method {
enums::PaymentMethod::Card => {
let card_details = get_card_details_with_locker_fallback(pm, state).await?;
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="5178" end="5187">
pub async fn perform_surcharge_ops(
_payment_intent: Option<storage::PaymentIntent>,
_state: &routes::SessionState,
_merchant_account: &domain::MerchantAccount,
_key_store: domain::MerchantKeyStore,
_business_profile: Option<Profile>,
_response: &mut api::CustomerPaymentMethodsListResponse,
) -> Result<(), error_stack::Report<errors::ApiErrorResponse>> {
todo!()
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="5133" end="5175">
async fn perform_surcharge_ops(
payment_intent: Option<storage::PaymentIntent>,
state: &routes::SessionState,
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
business_profile: Option<Profile>,
response: &mut api::CustomerPaymentMethodsListResponse,
) -> Result<(), error_stack::Report<errors::ApiErrorResponse>> {
let payment_attempt = payment_intent
.as_ref()
.async_map(|payment_intent| async {
state
.store
.find_payment_attempt_by_payment_id_merchant_id_attempt_id(
payment_intent.get_id(),
merchant_account.get_id(),
&payment_intent.active_attempt.get_id(),
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)
})
.await
.transpose()?;
if let Some((payment_attempt, payment_intent, business_profile)) = payment_attempt
.zip(payment_intent)
.zip(business_profile)
.map(|((pa, pi), bp)| (pa, pi, bp))
{
call_surcharge_decision_management_for_saved_card(
state,
&merchant_account,
&key_store,
&business_profile,
&payment_attempt,
payment_intent,
response,
)
.await?;
}
Ok(())
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="4797" end="5034">
pub async fn list_customer_payment_method(
state: &routes::SessionState,
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
payment_intent: Option<storage::PaymentIntent>,
customer_id: &id_type::CustomerId,
limit: Option<i64>,
) -> errors::RouterResponse<api::CustomerPaymentMethodsListResponse> {
let db = &*state.store;
let key_manager_state = &state.into();
let off_session_payment_flag = payment_intent
.as_ref()
.map(|pi| {
matches!(
pi.setup_future_usage,
Some(common_enums::FutureUsage::OffSession)
)
})
.unwrap_or(false);
let customer = db
.find_customer_by_customer_id_merchant_id(
&state.into(),
customer_id,
merchant_account.get_id(),
&key_store,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?;
let is_requires_cvv = db
.find_config_by_key_unwrap_or(
&merchant_account.get_id().get_requires_cvv_key(),
Some("true".to_string()),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to fetch requires_cvv config")?;
let requires_cvv = is_requires_cvv.config != "false";
let resp = db
.find_payment_method_by_customer_id_merchant_id_status(
&(state.into()),
&key_store,
customer_id,
merchant_account.get_id(),
common_enums::PaymentMethodStatus::Active,
limit,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
let mut customer_pms = Vec::new();
let profile_id = payment_intent
.as_ref()
.map(|payment_intent| {
payment_intent
.profile_id
.clone()
.get_required_value("profile_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("profile_id is not set in payment_intent")
})
.transpose()?;
let business_profile = core_utils::validate_and_get_business_profile(
db,
key_manager_state,
&key_store,
profile_id.as_ref(),
merchant_account.get_id(),
)
.await?;
let is_connector_agnostic_mit_enabled = business_profile
.as_ref()
.and_then(|business_profile| business_profile.is_connector_agnostic_mit_enabled)
.unwrap_or(false);
for pm in resp.into_iter() {
let parent_payment_method_token = generate_id(consts::ID_LENGTH, "token");
let payment_method = pm
.get_payment_method_type()
.get_required_value("payment_method")?;
let pm_list_context = get_pm_list_context(
state,
&payment_method,
&key_store,
&pm,
Some(parent_payment_method_token.clone()),
true,
)
.await?;
if pm_list_context.is_none() {
continue;
}
let pm_list_context = pm_list_context.get_required_value("PaymentMethodListContext")?;
// Retrieve the masked bank details to be sent as a response
let bank_details = if payment_method == enums::PaymentMethod::BankDebit {
get_masked_bank_details(&pm).await.unwrap_or_else(|error| {
logger::error!(?error);
None
})
} else {
None
};
let payment_method_billing = pm
.payment_method_billing_address
.clone()
.map(|decrypted_data| decrypted_data.into_inner().expose())
.map(|decrypted_value| decrypted_value.parse_value("payment method billing address"))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to decrypt payment method billing address details")?;
let connector_mandate_details = pm
.get_common_mandate_reference()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to deserialize to Payment Mandate Reference ")?;
let mca_enabled = get_mca_status(
state,
&key_store,
profile_id.clone(),
merchant_account.get_id(),
is_connector_agnostic_mit_enabled,
Some(connector_mandate_details),
pm.network_transaction_id.as_ref(),
)
.await?;
let requires_cvv = if is_connector_agnostic_mit_enabled {
requires_cvv
&& !(off_session_payment_flag
&& (pm.connector_mandate_details.is_some()
|| pm.network_transaction_id.is_some()))
} else {
requires_cvv && !(off_session_payment_flag && pm.connector_mandate_details.is_some())
};
// Need validation for enabled payment method ,querying MCA
let pma = api::CustomerPaymentMethod {
payment_token: parent_payment_method_token.to_owned(),
payment_method_id: pm.payment_method_id.clone(),
customer_id: pm.customer_id.clone(),
payment_method,
payment_method_type: pm.get_payment_method_subtype(),
payment_method_issuer: pm.payment_method_issuer,
card: pm_list_context.card_details,
metadata: pm.metadata,
payment_method_issuer_code: pm.payment_method_issuer_code,
recurring_enabled: mca_enabled,
installment_payment_enabled: false,
payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]),
created: Some(pm.created_at),
#[cfg(feature = "payouts")]
bank_transfer: pm_list_context.bank_transfer_details,
bank: bank_details,
surcharge_details: None,
requires_cvv,
last_used_at: Some(pm.last_used_at),
default_payment_method_set: customer.default_payment_method_id.is_some()
&& customer.default_payment_method_id == Some(pm.payment_method_id),
billing: payment_method_billing,
};
if requires_cvv || mca_enabled {
customer_pms.push(pma.to_owned());
}
let redis_conn = state
.store
.get_redis_conn()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get redis connection")?;
let intent_fulfillment_time = business_profile
.as_ref()
.and_then(|b_profile| b_profile.get_order_fulfillment_time())
.unwrap_or(consts::DEFAULT_INTENT_FULFILLMENT_TIME);
let hyperswitch_token_data = pm_list_context
.hyperswitch_token_data
.get_required_value("PaymentTokenData")?;
ParentPaymentMethodToken::create_key_for_token((
&parent_payment_method_token,
pma.payment_method,
))
.insert(intent_fulfillment_time, hyperswitch_token_data, state)
.await?;
if let Some(metadata) = pma.metadata {
let pm_metadata_vec: payment_methods::PaymentMethodMetadata = metadata
.parse_value("PaymentMethodMetadata")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Failed to deserialize metadata to PaymentmethodMetadata struct",
)?;
for pm_metadata in pm_metadata_vec.payment_method_tokenization {
let key = format!(
"pm_token_{}_{}_{}",
parent_payment_method_token, pma.payment_method, pm_metadata.0
);
redis_conn
.set_key_with_expiry(&key.into(), pm_metadata.1, intent_fulfillment_time)
.await
.change_context(errors::StorageError::KVError)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to add data in redis")?;
}
}
}
let mut response = api::CustomerPaymentMethodsListResponse {
customer_payment_methods: customer_pms,
is_guest_customer: payment_intent.as_ref().map(|_| false), //to return this key only when the request is tied to a payment intent
};
Box::pin(perform_surcharge_ops(
payment_intent,
state,
merchant_account,
key_store,
business_profile,
&mut response,
))
.await?;
Ok(services::ApplicationResponse::Json(response))
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="4721" end="4790">
pub async fn do_list_customer_pm_fetch_customer_if_not_passed(
state: routes::SessionState,
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
req: Option<api::PaymentMethodListRequest>,
customer_id: Option<&id_type::CustomerId>,
ephemeral_api_key: Option<&str>,
) -> errors::RouterResponse<api::CustomerPaymentMethodsListResponse> {
let limit = req.clone().and_then(|pml_req| pml_req.limit);
let auth_cust = if let Some(key) = ephemeral_api_key {
let key = state
.store()
.get_ephemeral_key(key)
.await
.change_context(errors::ApiErrorResponse::Unauthorized)?;
Some(key.customer_id.clone())
} else {
None
};
let customer_id = customer_id.or(auth_cust.as_ref());
if let Some(customer_id) = customer_id {
Box::pin(list_customer_payment_method(
&state,
merchant_account,
key_store,
None,
customer_id,
limit,
))
.await
} else {
let cloned_secret = req.and_then(|r| r.client_secret.as_ref().cloned());
let payment_intent: Option<hyperswitch_domain_models::payments::PaymentIntent> =
helpers::verify_payment_intent_time_and_client_secret(
&state,
&merchant_account,
&key_store,
cloned_secret,
)
.await?;
match payment_intent
.as_ref()
.and_then(|intent| intent.customer_id.to_owned())
{
Some(customer_id) => {
Box::pin(list_customer_payment_method(
&state,
merchant_account,
key_store,
payment_intent,
&customer_id,
limit,
))
.await
}
None => {
let response = api::CustomerPaymentMethodsListResponse {
customer_payment_methods: Vec::new(),
is_guest_customer: Some(true),
};
Ok(services::ApplicationResponse::Json(response))
}
}
}
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="5598" end="5647">
pub async fn get_bank_from_hs_locker(
state: &routes::SessionState,
key_store: &domain::MerchantKeyStore,
temp_token: Option<&String>,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
token_ref: &str,
) -> errors::RouterResult<api::BankPayout> {
let payment_method = get_payment_method_from_hs_locker(
state,
key_store,
customer_id,
merchant_id,
token_ref,
None,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error getting payment method from locker")?;
let pm_parsed: api::PayoutMethodData = payment_method
.peek()
.to_string()
.parse_struct("PayoutMethodData")
.change_context(errors::ApiErrorResponse::InternalServerError)?;
match &pm_parsed {
api::PayoutMethodData::Bank(bank) => {
if let Some(token) = temp_token {
vault::Vault::store_payout_method_data_in_locker(
state,
Some(token.clone()),
&pm_parsed,
Some(customer_id.to_owned()),
key_store,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error storing payout method data in temporary locker")?;
}
Ok(bank.to_owned())
}
api::PayoutMethodData::Card(_) => Err(errors::ApiErrorResponse::InvalidRequestData {
message: "Expected bank details, found card details instead".to_string(),
}
.into()),
api::PayoutMethodData::Wallet(_) => Err(errors::ApiErrorResponse::InvalidRequestData {
message: "Expected bank details, found wallet details instead".to_string(),
}
.into()),
}
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="5428" end="5484">
pub async fn get_bank_account_connector_details(
pm: &domain::PaymentMethod,
) -> errors::RouterResult<Option<BankAccountTokenData>> {
let payment_method_data = pm
.payment_method_data
.clone()
.map(|x| x.into_inner().expose())
.map(
|v| -> Result<PaymentMethodsData, error_stack::Report<errors::ApiErrorResponse>> {
v.parse_value::<PaymentMethodsData>("PaymentMethodsData")
.change_context(errors::StorageError::DeserializationFailed)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to deserialize Payment Method Auth config")
},
)
.transpose()?;
match payment_method_data {
Some(pmd) => match pmd {
PaymentMethodsData::Card(_) => Err(errors::ApiErrorResponse::UnprocessableEntity {
message: "Card is not a valid entity".to_string(),
}
.into()),
PaymentMethodsData::WalletDetails(_) => {
Err(errors::ApiErrorResponse::UnprocessableEntity {
message: "Wallet is not a valid entity".to_string(),
}
.into())
}
PaymentMethodsData::BankDetails(bank_details) => {
let connector_details = bank_details
.connector_details
.first()
.ok_or(errors::ApiErrorResponse::InternalServerError)?;
let pm_type = pm
.get_payment_method_subtype()
.get_required_value("payment_method_type")
.attach_printable("PaymentMethodType not found")?;
let pm = pm
.get_payment_method_type()
.get_required_value("payment_method")
.attach_printable("PaymentMethod not found")?;
let token_data = BankAccountTokenData {
payment_method_type: pm_type,
payment_method: pm,
connector_details: connector_details.clone(),
};
Ok(Some(token_data))
}
},
None => Ok(None),
}
}
<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);
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/utils.rs<|crate|> router anchor=validate_id kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/utils.rs" role="context" start="471" end="477">
pub fn validate_id(id: String, key: &str) -> Result<String, errors::ApiErrorResponse> {
if id.len() > consts::MAX_ID_LENGTH {
Err(invalid_id_format_error(key))
} else {
Ok(id)
}
}
<file_sep path="hyperswitch/crates/router/src/core/utils.rs" role="context" start="470" end="470">
use std::{collections::HashSet, marker::PhantomData, str::FromStr};
use common_utils::{
errors::CustomResult,
ext_traits::AsyncExt,
types::{keymanager::KeyManagerState, ConnectorTransactionIdTrait, MinorUnit},
};
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="487" end="617">
pub fn get_split_refunds(
split_refund_input: super::refunds::transformers::SplitRefundInput,
) -> RouterResult<Option<router_request_types::SplitRefundsRequest>> {
match split_refund_input.split_payment_request.as_ref() {
Some(common_types::payments::SplitPaymentsRequest::StripeSplitPayment(stripe_payment)) => {
let (charge_id_option, charge_type_option) = match (
&split_refund_input.payment_charges,
&split_refund_input.split_payment_request,
) {
(
Some(common_types::payments::ConnectorChargeResponseData::StripeSplitPayment(
stripe_split_payment_response,
)),
_,
) => (
stripe_split_payment_response.charge_id.clone(),
Some(stripe_split_payment_response.charge_type.clone()),
),
(
_,
Some(common_types::payments::SplitPaymentsRequest::StripeSplitPayment(
stripe_split_payment_request,
)),
) => (
split_refund_input.charge_id,
Some(stripe_split_payment_request.charge_type.clone()),
),
(_, _) => (None, None),
};
if let Some(charge_id) = charge_id_option {
let options = super::refunds::validator::validate_stripe_charge_refund(
charge_type_option,
&split_refund_input.refund_request,
)?;
Ok(Some(
router_request_types::SplitRefundsRequest::StripeSplitRefund(
router_request_types::StripeSplitRefund {
charge_id,
charge_type: stripe_payment.charge_type.clone(),
transfer_account_id: stripe_payment.transfer_account_id.clone(),
options,
},
),
))
} else {
Ok(None)
}
}
Some(common_types::payments::SplitPaymentsRequest::AdyenSplitPayment(_)) => {
match &split_refund_input.payment_charges {
Some(common_types::payments::ConnectorChargeResponseData::AdyenSplitPayment(
adyen_split_payment_response,
)) => {
if let Some(common_types::refunds::SplitRefund::AdyenSplitRefund(
split_refund_request,
)) = split_refund_input.refund_request.clone()
{
super::refunds::validator::validate_adyen_charge_refund(
adyen_split_payment_response,
&split_refund_request,
)?;
Ok(Some(
router_request_types::SplitRefundsRequest::AdyenSplitRefund(
split_refund_request,
),
))
} else {
Ok(None)
}
}
_ => Ok(None),
}
}
Some(common_types::payments::SplitPaymentsRequest::XenditSplitPayment(_)) => {
match (
&split_refund_input.payment_charges,
&split_refund_input.refund_request,
) {
(
Some(common_types::payments::ConnectorChargeResponseData::XenditSplitPayment(
xendit_split_payment_response,
)),
Some(common_types::refunds::SplitRefund::XenditSplitRefund(
split_refund_request,
)),
) => {
let user_id = super::refunds::validator::validate_xendit_charge_refund(
xendit_split_payment_response,
split_refund_request,
)?;
Ok(user_id.map(|for_user_id| {
router_request_types::SplitRefundsRequest::XenditSplitRefund(
common_types::domain::XenditSplitSubMerchantData { for_user_id },
)
}))
}
(
Some(common_types::payments::ConnectorChargeResponseData::XenditSplitPayment(
xendit_split_payment_response,
)),
None,
) => {
let option_for_user_id = match xendit_split_payment_response {
common_types::payments::XenditChargeResponseData::MultipleSplits(
common_types::payments::XenditMultipleSplitResponse {
for_user_id, ..
},
) => for_user_id.clone(),
common_types::payments::XenditChargeResponseData::SingleSplit(
common_types::domain::XenditSplitSubMerchantData { for_user_id },
) => Some(for_user_id.clone()),
};
if option_for_user_id.is_some() {
Err(errors::ApiErrorResponse::MissingRequiredField {
field_name: "split_refunds.xendit_split_refund.for_user_id",
})?
} else {
Ok(None)
}
}
_ => Ok(None),
}
}
_ => Ok(None),
}
}
<file_sep path="hyperswitch/crates/router/src/core/utils.rs" role="context" start="479" end="484">
pub fn validate_uuid(uuid: String, key: &str) -> Result<String, errors::ApiErrorResponse> {
match (Uuid::parse_str(&uuid), uuid.len() > consts::MAX_ID_LENGTH) {
(Ok(_), false) => Ok(uuid),
(_, _) => Err(invalid_id_format_error(key)),
}
}
<file_sep path="hyperswitch/crates/router/src/core/utils.rs" role="context" start="461" end="469">
fn invalid_id_format_error(key: &str) -> errors::ApiErrorResponse {
errors::ApiErrorResponse::InvalidDataFormat {
field_name: key.to_string(),
expected_format: format!(
"length should be less than {} characters",
consts::MAX_ID_LENGTH
),
}
}
<file_sep path="hyperswitch/crates/router/src/core/utils.rs" role="context" start="451" end="459">
pub fn get_or_generate_uuid(
key: &str,
provided_id: Option<&String>,
) -> Result<String, errors::ApiErrorResponse> {
let validate_id = |id: String| validate_uuid(id, key);
provided_id
.cloned()
.map_or(Ok(generate_uuid()), validate_id)
}
<file_sep path="hyperswitch/crates/router/src/core/utils.rs" role="context" start="624" end="630">
fn validate_id_length_constraint() {
let payment_id =
"abcdefghijlkmnopqrstuvwzyzabcdefghijknlmnopsjkdnfjsknfkjsdnfspoig".to_string(); //length = 65
let result = validate_id(payment_id, "payment_id");
assert!(result.is_err());
}
<file_sep path="hyperswitch/crates/router/src/core/utils.rs" role="context" start="633" end="640">
fn validate_id_proper_response() {
let payment_id = "abcdefghijlkmnopqrstjhbjhjhkhbhgcxdfxvmhb".to_string();
let result = validate_id(payment_id.clone(), "payment_id");
assert!(result.is_ok());
let result = result.unwrap_or_default();
assert_eq!(result, payment_id);
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payment_methods/cards.rs<|crate|> router anchor=get_card_details_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="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="5343" end="5343">
} else {
logger::debug!(
"Getting card details from locker as it is not found in payment methods table"
);
get_card_details_from_locker(state, pm).await?
})
}
#[cfg(all(
any(feature = "v2", feature = "v1"),
not(feature = "payment_methods_v2")
))]
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")?;
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="5387" end="5422">
pub async fn get_masked_bank_details(
pm: &domain::PaymentMethod,
) -> errors::RouterResult<Option<MaskedBankDetails>> {
#[cfg(all(
any(feature = "v2", feature = "v1"),
not(feature = "payment_methods_v2")
))]
let payment_method_data = pm
.payment_method_data
.clone()
.map(|x| x.into_inner().expose())
.map(
|v| -> Result<PaymentMethodsData, error_stack::Report<errors::ApiErrorResponse>> {
v.parse_value::<PaymentMethodsData>("PaymentMethodsData")
.change_context(errors::StorageError::DeserializationFailed)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to deserialize Payment Method Auth config")
},
)
.transpose()?;
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
let payment_method_data = pm.payment_method_data.clone().map(|x| x.into_inner());
match payment_method_data {
Some(pmd) => match pmd {
PaymentMethodsData::Card(_) => Ok(None),
PaymentMethodsData::BankDetails(bank_details) => Ok(Some(MaskedBankDetails {
mask: bank_details.mask,
})),
PaymentMethodsData::WalletDetails(_) => Ok(None),
},
None => Err(report!(errors::ApiErrorResponse::InternalServerError))
.attach_printable("Unable to fetch payment method data"),
}
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="5367" end="5385">
pub async fn get_lookup_key_from_locker(
state: &routes::SessionState,
payment_token: &str,
pm: &domain::PaymentMethod,
merchant_key_store: &domain::MerchantKeyStore,
) -> errors::RouterResult<api::CardDetailFromLocker> {
let card_detail = get_card_details_from_locker(state, pm).await?;
let card = card_detail.clone();
let resp = TempLockerCardSupport::create_payment_method_data_in_temp_locker(
state,
payment_token,
card,
pm,
merchant_key_store,
)
.await?;
Ok(resp)
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="5315" end="5338">
pub async fn get_card_details_without_locker_fallback(
pm: &domain::PaymentMethod,
state: &routes::SessionState,
) -> errors::RouterResult<api::CardDetailFromLocker> {
let card_decrypted = pm
.payment_method_data
.clone()
.map(|x| x.into_inner().expose())
.and_then(|v| serde_json::from_value::<PaymentMethodsData>(v).ok())
.and_then(|pmd| match pmd {
PaymentMethodsData::Card(crd) => Some(api::CardDetailFromLocker::from(crd)),
_ => None,
});
Ok(if let Some(mut crd) = card_decrypted {
crd.scheme.clone_from(&pm.scheme);
crd
} else {
logger::debug!(
"Getting card details from locker as it is not found in payment methods table"
);
get_card_details_from_locker(state, pm).await?
})
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="5286" end="5309">
pub async fn get_card_details_with_locker_fallback(
pm: &domain::PaymentMethod,
state: &routes::SessionState,
) -> errors::RouterResult<Option<api::CardDetailFromLocker>> {
let card_decrypted = pm
.payment_method_data
.clone()
.map(|x| x.into_inner().expose())
.and_then(|v| serde_json::from_value::<PaymentMethodsData>(v).ok())
.and_then(|pmd| match pmd {
PaymentMethodsData::Card(crd) => Some(api::CardDetailFromLocker::from(crd)),
_ => None,
});
Ok(if let Some(mut crd) = card_decrypted {
crd.scheme.clone_from(&pm.scheme);
Some(crd)
} else {
logger::debug!(
"Getting card details from locker as it is not found in payment methods table"
);
Some(get_card_details_from_locker(state, pm).await?)
})
}
<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="565" end="565">
type Error = error_stack::Report<errors::ApiErrorResponse>;
<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);
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/api_keys.rs<|crate|> router anchor=revoke_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="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="492" end="492">
use common_utils::date_time;
use diesel_models::{api_keys::ApiKey, enums as storage_enums};
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="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="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="426" end="487">
pub async fn revoke_api_key(
state: SessionState,
merchant_id: &common_utils::id_type::MerchantId,
key_id: &common_utils::id_type::ApiKeyId,
) -> RouterResponse<api::RevokeApiKeyResponse> {
let store = state.store.as_ref();
let api_key = store
.find_api_key_by_merchant_id_key_id_optional(merchant_id, key_id)
.await
.to_not_found_response(errors::ApiErrorResponse::ApiKeyNotFound)?;
let revoked = store
.revoke_api_key(merchant_id, key_id)
.await
.to_not_found_response(errors::ApiErrorResponse::ApiKeyNotFound)?;
if let Some(api_key) = api_key {
let hashed_api_key = api_key.hashed_api_key;
let state = state.clone();
authentication::decision::spawn_tracked_job(
async move {
authentication::decision::revoke_api_key(&state, hashed_api_key.into_inner().into())
.await
},
authentication::decision::REVOKE,
);
}
metrics::API_KEY_REVOKED.add(1, &[]);
#[cfg(feature = "email")]
{
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, then revoke it
if existing_process_tracker_task.is_some() {
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",
)?;
}
}
Ok(ApplicationResponse::Json(api::RevokeApiKeyResponse {
merchant_id: merchant_id.to_owned(),
key_id: key_id.to_owned(),
revoked,
}))
}
<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(())
}
<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="562" end="564">
fn from(hashed_api_key: storage::HashedApiKey) -> Self {
Self(hashed_api_key.into_inner())
}
<file_sep path="hyperswitch/crates/router/src/db.rs" role="context" start="90" end="147">
pub trait StorageInterface:
Send
+ Sync
+ dyn_clone::DynClone
+ address::AddressInterface
+ api_keys::ApiKeyInterface
+ blocklist_lookup::BlocklistLookupInterface
+ configs::ConfigInterface
+ capture::CaptureInterface
+ customers::CustomerInterface
+ dashboard_metadata::DashboardMetadataInterface
+ dispute::DisputeInterface
+ ephemeral_key::EphemeralKeyInterface
+ ephemeral_key::ClientSecretInterface
+ events::EventInterface
+ file::FileMetadataInterface
+ FraudCheckInterface
+ locker_mock_up::LockerMockUpInterface
+ mandate::MandateInterface
+ merchant_account::MerchantAccountInterface
+ merchant_connector_account::ConnectorAccessToken
+ merchant_connector_account::MerchantConnectorAccountInterface
+ PaymentAttemptInterface<Error = StorageError>
+ PaymentIntentInterface<Error = StorageError>
+ PaymentMethodInterface<Error = StorageError>
+ blocklist::BlocklistInterface
+ blocklist_fingerprint::BlocklistFingerprintInterface
+ dynamic_routing_stats::DynamicRoutingStatsInterface
+ scheduler::SchedulerInterface
+ PayoutAttemptInterface<Error = StorageError>
+ PayoutsInterface<Error = StorageError>
+ refund::RefundInterface
+ reverse_lookup::ReverseLookupInterface
+ cards_info::CardsInfoInterface
+ merchant_key_store::MerchantKeyStoreInterface
+ MasterKeyInterface
+ payment_link::PaymentLinkInterface
+ RedisConnInterface
+ RequestIdStore
+ business_profile::ProfileInterface
+ routing_algorithm::RoutingAlgorithmInterface
+ gsm::GsmInterface
+ unified_translations::UnifiedTranslationsInterface
+ authorization::AuthorizationInterface
+ user::sample_data::BatchSampleDataInterface
+ health_check::HealthCheckDbInterface
+ user_authentication_method::UserAuthenticationMethodInterface
+ authentication::AuthenticationInterface
+ generic_link::GenericLinkInterface
+ relay::RelayInterface
+ user::theme::ThemeInterface
+ payment_method_session::PaymentMethodsSessionInterface
+ 'static
{
fn get_scheduler_db(&self) -> Box<dyn scheduler::SchedulerInterface>;
fn get_cache_store(&self) -> Box<(dyn RedisConnInterface + Send + Sync + 'static)>;
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payments/routing.rs<|crate|> router anchor=execute_dsl_and_get_connector_v1 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="547" end="565">
fn execute_dsl_and_get_connector_v1(
backend_input: dsl_inputs::BackendInput,
interpreter: &backend::VirInterpreterBackend<ConnectorSelection>,
) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> {
let routing_output: routing_types::RoutingAlgorithm = interpreter
.execute(backend_input)
.map(|out| out.connector_selection.foreign_into())
.change_context(errors::RoutingError::DslExecutionError)?;
Ok(match routing_output {
routing_types::RoutingAlgorithm::Priority(plist) => plist,
routing_types::RoutingAlgorithm::VolumeSplit(splits) => perform_volume_split(splits)
.change_context(errors::RoutingError::DslFinalConnectorSelectionFailed)?,
_ => Err(errors::RoutingError::DslIncorrectSelectionAlgorithm)
.attach_printable("Unsupported algorithm received as a result of static routing")?,
})
}
<file_sep path="hyperswitch/crates/router/src/core/payments/routing.rs" role="context" start="546" end="546">
use api_models::routing as api_routing;
use api_models::{
admin as admin_api,
enums::{self as api_enums, CountryAlpha2},
routing::ConnectorSelection,
};
use diesel_models::enums as storage_enums;
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 kgraph_utils::{
mca as mca_graph,
transformers::{IntoContext, IntoDirValue},
types::CountryCurrencyFilter,
};
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="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="533" end="545">
pub fn perform_routing_for_single_straight_through_algorithm(
algorithm: &routing_types::StraightThroughAlgorithm,
) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> {
Ok(match algorithm {
routing_types::StraightThroughAlgorithm::Single(connector) => vec![(**connector).clone()],
routing_types::StraightThroughAlgorithm::Priority(_)
| routing_types::StraightThroughAlgorithm::VolumeSplit(_) => {
Err(errors::RoutingError::DslIncorrectSelectionAlgorithm)
.attach_printable("Unsupported algorithm received as a result of static routing")?
}
})
}
<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="1333" end="1370">
async fn get_chosen_connectors<'a>(
state: &'a SessionState,
key_store: &'a domain::MerchantKeyStore,
session_pm_input: &SessionRoutingPmTypeInput<'_>,
transaction_type: &api_enums::TransactionType,
profile_wrapper: &admin::ProfileWrapper,
) -> RoutingResult<Vec<api_models::routing::RoutableConnectorChoice>> {
let merchant_id = &key_store.merchant_id;
let MerchantAccountRoutingAlgorithm::V1(algorithm_id) = session_pm_input.routing_algorithm;
let chosen_connectors = if let Some(ref algorithm_id) = algorithm_id {
let cached_algorithm = ensure_algorithm_cached_v1(
state,
merchant_id,
algorithm_id,
session_pm_input.profile_id,
transaction_type,
)
.await?;
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) => execute_dsl_and_get_connector_v1(
session_pm_input.backend_input.clone(),
interpreter,
)?,
}
} else {
profile_wrapper
.get_default_fallback_list_of_connector_under_profile()
.change_context(errors::RoutingError::FallbackConfigFetchFailed)?
};
Ok(chosen_connectors)
}
<file_sep path="hyperswitch/crates/router/src/core/payments/routing.rs" role="context" start="1252" end="1330">
async fn perform_session_routing_for_pm_type(
session_pm_input: &SessionRoutingPmTypeInput<'_>,
transaction_type: &api_enums::TransactionType,
_business_profile: &domain::Profile,
) -> RoutingResult<Option<Vec<api_models::routing::RoutableConnectorChoice>>> {
let merchant_id = &session_pm_input.key_store.merchant_id;
let algorithm_id = match session_pm_input.routing_algorithm {
MerchantAccountRoutingAlgorithm::V1(algorithm_ref) => &algorithm_ref.algorithm_id,
};
let chosen_connectors = if let Some(ref algorithm_id) = algorithm_id {
let cached_algorithm = ensure_algorithm_cached_v1(
&session_pm_input.state.clone(),
merchant_id,
algorithm_id,
session_pm_input.profile_id,
transaction_type,
)
.await?;
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) => execute_dsl_and_get_connector_v1(
session_pm_input.backend_input.clone(),
interpreter,
)?,
}
} else {
routing::helpers::get_merchant_default_config(
&*session_pm_input.state.clone().store,
session_pm_input.profile_id.get_string_repr(),
transaction_type,
)
.await
.change_context(errors::RoutingError::FallbackConfigFetchFailed)?
};
let mut final_selection = perform_cgraph_filtering(
&session_pm_input.state.clone(),
session_pm_input.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 = routing::helpers::get_merchant_default_config(
&*session_pm_input.state.clone().store,
session_pm_input.profile_id.get_string_repr(),
transaction_type,
)
.await
.change_context(errors::RoutingError::FallbackConfigFetchFailed)?;
final_selection = perform_cgraph_filtering(
&session_pm_input.state.clone(),
session_pm_input.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="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="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-10-19-101558_create_routing_algorithm_table/up.sql" role="context" start="1" end="13">
-- Your SQL goes here
CREATE TYPE "RoutingAlgorithmKind" AS ENUM ('single', 'priority', 'volume_split', 'advanced');
CREATE TABLE routing_algorithm (
algorithm_id VARCHAR(64) PRIMARY KEY,
profile_id VARCHAR(64) NOT NULL,
merchant_id VARCHAR(64) NOT NULL,
name VARCHAR(64) NOT NULL,
description VARCHAR(256),
kind "RoutingAlgorithmKind" NOT NULL,
algorithm_data JSONB NOT NULL,
created_at TIMESTAMP NOT NULL,
<file_sep path="hyperswitch/crates/api_models/src/enums.rs" role="context" start="23" end="28">
pub enum RoutingAlgorithm {
RoundRobin,
MaxConversion,
MinCost,
Custom,
}
<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/surcharge_decision_configs.rs<|crate|> router anchor=ensure_algorithm_cached kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/surcharge_decision_configs.rs" role="context" start="496" end="524">
pub async fn ensure_algorithm_cached(
store: &dyn StorageInterface,
merchant_id: &common_utils::id_type::MerchantId,
algorithm_id: &str,
) -> ConditionalConfigResult<VirInterpreterBackendCacheWrapper> {
let key = merchant_id.get_surcharge_dsk_key();
let value_to_cache = || async {
let config: diesel_models::Config = store.find_config_by_key(algorithm_id).await?;
let record: SurchargeDecisionManagerRecord = config
.config
.parse_struct("Program")
.change_context(errors::StorageError::DeserializationFailed)
.attach_printable("Error parsing routing algorithm from configs")?;
VirInterpreterBackendCacheWrapper::try_from(record)
.change_context(errors::StorageError::ValueNotFound("Program".to_string()))
.attach_printable("Error initializing DSL interpreter backend")
};
let interpreter = cache::get_or_populate_in_memory(
store.get_cache_store().as_ref(),
&key,
value_to_cache,
&SURCHARGE_CACHE,
)
.await
.change_context(ConfigError::CacheMiss)
.attach_printable("Unable to retrieve cached routing algorithm even after refresh")?;
Ok(interpreter)
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/surcharge_decision_configs.rs" role="context" start="495" end="495">
use api_models::{
payment_methods::SurchargeDetailsResponse,
payments, routing,
surcharge_decision_configs::{self, SurchargeDecisionConfigs, SurchargeDecisionManagerRecord},
};
use common_utils::{ext_traits::StringExt, types as common_utils_types};
use common_utils::{
ext_traits::{OptionExt, StringExt},
types as common_utils_types,
};
use euclid::{
backend,
backend::{inputs as dsl_inputs, EuclidBackend},
};
use storage_impl::redis::cache::{self, SURCHARGE_CACHE};
use crate::{
core::{
errors::{self, ConditionalConfigError as ConfigError},
payments::{
conditional_configs::ConditionalConfigResult, routing::make_dsl_input_for_surcharge,
types,
},
},
db::StorageInterface,
types::{
storage::{self, payment_attempt::PaymentAttemptExt},
transformers::ForeignTryFrom,
},
SessionState,
};
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/surcharge_decision_configs.rs" role="context" start="526" end="535">
pub fn execute_dsl_and_get_conditional_config(
backend_input: dsl_inputs::BackendInput,
interpreter: &backend::VirInterpreterBackend<SurchargeDecisionConfigs>,
) -> ConditionalConfigResult<SurchargeDecisionConfigs> {
let routing_output = interpreter
.execute(backend_input)
.map(|out| out.connector_selection)
.change_context(ConfigError::DslExecutionError)?;
Ok(routing_output)
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/surcharge_decision_configs.rs" role="context" start="457" end="493">
fn get_surcharge_details_from_surcharge_output(
surcharge_details: surcharge_decision_configs::SurchargeDetailsOutput,
payment_attempt: &storage::PaymentAttempt,
) -> ConditionalConfigResult<types::SurchargeDetails> {
let surcharge_amount = match surcharge_details.surcharge.clone() {
surcharge_decision_configs::SurchargeOutput::Fixed { amount } => amount,
surcharge_decision_configs::SurchargeOutput::Rate(percentage) => percentage
.apply_and_ceil_result(payment_attempt.net_amount.get_total_amount())
.change_context(ConfigError::DslExecutionError)
.attach_printable("Failed to Calculate surcharge amount by applying percentage")?,
};
let tax_on_surcharge_amount = surcharge_details
.tax_on_surcharge
.clone()
.map(|tax_on_surcharge| {
tax_on_surcharge
.apply_and_ceil_result(surcharge_amount)
.change_context(ConfigError::DslExecutionError)
.attach_printable("Failed to Calculate tax amount")
})
.transpose()?
.unwrap_or_default();
Ok(types::SurchargeDetails {
original_amount: payment_attempt.net_amount.get_order_amount(),
surcharge: match surcharge_details.surcharge {
surcharge_decision_configs::SurchargeOutput::Fixed { amount } => {
common_utils_types::Surcharge::Fixed(amount)
}
surcharge_decision_configs::SurchargeOutput::Rate(percentage) => {
common_utils_types::Surcharge::Rate(percentage)
}
},
tax_on_surcharge: surcharge_details.tax_on_surcharge,
surcharge_amount,
tax_on_surcharge_amount,
})
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/surcharge_decision_configs.rs" role="context" start="449" end="454">
fn get_surcharge_details_from_surcharge_output(
_surcharge_details: surcharge_decision_configs::SurchargeDetailsOutput,
_payment_attempt: &storage::PaymentAttempt,
) -> ConditionalConfigResult<types::SurchargeDetails> {
todo!()
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/surcharge_decision_configs.rs" role="context" start="120" end="237">
pub async fn perform_surcharge_decision_management_for_payment_method_list(
state: &SessionState,
algorithm_ref: routing::RoutingAlgorithmRef,
payment_attempt: &storage::PaymentAttempt,
payment_intent: &storage::PaymentIntent,
billing_address: Option<hyperswitch_domain_models::address::Address>,
response_payment_method_types: &mut [api_models::payment_methods::ResponsePaymentMethodsEnabled],
) -> ConditionalConfigResult<(
types::SurchargeMetadata,
surcharge_decision_configs::MerchantSurchargeConfigs,
)> {
let mut surcharge_metadata = types::SurchargeMetadata::new(payment_attempt.attempt_id.clone());
let (surcharge_source, merchant_surcharge_configs) = match (
payment_attempt.get_surcharge_details(),
algorithm_ref.surcharge_config_algo_id,
) {
(Some(request_surcharge_details), _) => (
SurchargeSource::Predetermined(request_surcharge_details),
surcharge_decision_configs::MerchantSurchargeConfigs::default(),
),
(None, Some(algorithm_id)) => {
let cached_algo = ensure_algorithm_cached(
&*state.store,
&payment_attempt.merchant_id,
algorithm_id.as_str(),
)
.await?;
let merchant_surcharge_config = cached_algo.merchant_surcharge_configs.clone();
(
SurchargeSource::Generate(cached_algo),
merchant_surcharge_config,
)
}
(None, None) => {
return Ok((
surcharge_metadata,
surcharge_decision_configs::MerchantSurchargeConfigs::default(),
))
}
};
let surcharge_source_log_message = match &surcharge_source {
SurchargeSource::Generate(_) => "Surcharge was calculated through surcharge rules",
SurchargeSource::Predetermined(_) => "Surcharge was sent in payment create request",
};
logger::debug!(payment_method_list_surcharge_source = surcharge_source_log_message);
let mut backend_input =
make_dsl_input_for_surcharge(payment_attempt, payment_intent, billing_address)
.change_context(ConfigError::InputConstructionError)?;
for payment_methods_enabled in response_payment_method_types.iter_mut() {
for payment_method_type_response in
&mut payment_methods_enabled.payment_method_types.iter_mut()
{
let payment_method_type = payment_method_type_response.payment_method_type;
backend_input.payment_method.payment_method_type = Some(payment_method_type);
backend_input.payment_method.payment_method =
Some(payment_methods_enabled.payment_method);
if let Some(card_network_list) = &mut payment_method_type_response.card_networks {
for card_network_type in card_network_list.iter_mut() {
backend_input.payment_method.card_network =
Some(card_network_type.card_network.clone());
let surcharge_details = surcharge_source
.generate_surcharge_details_and_populate_surcharge_metadata(
&backend_input,
payment_attempt,
(
&mut surcharge_metadata,
types::SurchargeKey::PaymentMethodData(
payment_methods_enabled.payment_method,
payment_method_type_response.payment_method_type,
Some(card_network_type.card_network.clone()),
),
),
)?;
card_network_type.surcharge_details = surcharge_details
.map(|surcharge_details| {
SurchargeDetailsResponse::foreign_try_from((
&surcharge_details,
payment_attempt,
))
.change_context(ConfigError::DslExecutionError)
.attach_printable("Error while constructing Surcharge response type")
})
.transpose()?;
}
} else {
let surcharge_details = surcharge_source
.generate_surcharge_details_and_populate_surcharge_metadata(
&backend_input,
payment_attempt,
(
&mut surcharge_metadata,
types::SurchargeKey::PaymentMethodData(
payment_methods_enabled.payment_method,
payment_method_type_response.payment_method_type,
None,
),
),
)?;
payment_method_type_response.surcharge_details = surcharge_details
.map(|surcharge_details| {
SurchargeDetailsResponse::foreign_try_from((
&surcharge_details,
payment_attempt,
))
.change_context(ConfigError::DslExecutionError)
.attach_printable("Error while constructing Surcharge response type")
})
.transpose()?;
}
}
}
Ok((surcharge_metadata, merchant_surcharge_configs))
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/surcharge_decision_configs.rs" role="context" start="240" end="289">
pub async fn perform_surcharge_decision_management_for_session_flow(
state: &SessionState,
algorithm_ref: routing::RoutingAlgorithmRef,
payment_attempt: &storage::PaymentAttempt,
payment_intent: &storage::PaymentIntent,
billing_address: Option<hyperswitch_domain_models::address::Address>,
payment_method_type_list: &Vec<common_enums::PaymentMethodType>,
) -> ConditionalConfigResult<types::SurchargeMetadata> {
let mut surcharge_metadata = types::SurchargeMetadata::new(payment_attempt.attempt_id.clone());
let surcharge_source = match (
payment_attempt.get_surcharge_details(),
algorithm_ref.surcharge_config_algo_id,
) {
(Some(request_surcharge_details), _) => {
SurchargeSource::Predetermined(request_surcharge_details)
}
(None, Some(algorithm_id)) => {
let cached_algo = ensure_algorithm_cached(
&*state.store,
&payment_attempt.merchant_id,
algorithm_id.as_str(),
)
.await?;
SurchargeSource::Generate(cached_algo)
}
(None, None) => return Ok(surcharge_metadata),
};
let mut backend_input =
make_dsl_input_for_surcharge(payment_attempt, payment_intent, billing_address)
.change_context(ConfigError::InputConstructionError)?;
for payment_method_type in payment_method_type_list {
backend_input.payment_method.payment_method_type = Some(*payment_method_type);
// in case of session flow, payment_method will always be wallet
backend_input.payment_method.payment_method = Some(payment_method_type.to_owned().into());
surcharge_source.generate_surcharge_details_and_populate_surcharge_metadata(
&backend_input,
payment_attempt,
(
&mut surcharge_metadata,
types::SurchargeKey::PaymentMethodData(
payment_method_type.to_owned().into(),
*payment_method_type,
None,
),
),
)?;
}
Ok(surcharge_metadata)
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/surcharge_decision_configs.rs" role="context" start="50" end="59">
fn try_from(value: SurchargeDecisionManagerRecord) -> Result<Self, Self::Error> {
let cached_algorithm = backend::VirInterpreterBackend::with_program(value.algorithm)
.change_context(ConfigError::DslBackendInitError)
.attach_printable("Error initializing DSL interpreter backend")?;
let merchant_surcharge_configs = value.merchant_surcharge_configs;
Ok(Self {
cached_algorithm,
merchant_surcharge_configs,
})
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/surcharge_decision_configs.rs" role="context" start="48" end="48">
type Error = error_stack::Report<ConfigError>;
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/surcharge_decision_configs.rs" role="context" start="42" end="45">
pub struct VirInterpreterBackendCacheWrapper {
cached_algorithm: backend::VirInterpreterBackend<SurchargeDecisionConfigs>,
merchant_surcharge_configs: surcharge_decision_configs::MerchantSurchargeConfigs,
}
<file_sep path="hyperswitch/crates/router/src/types/api/configs.rs" role="context" start="2" end="5">
pub struct Config {
pub key: String,
pub value: String,
}
<file_sep path="hyperswitch/migrations/2022-09-29-084920_create_initial_tables/up.sql" role="context" start="257" end="273">
first_name VARCHAR(255),
last_name VARCHAR(255),
phone_number VARCHAR(255),
country_code VARCHAR(255),
created_at TIMESTAMP NOT NULL DEFAULT now()::TIMESTAMP,
modified_at TIMESTAMP NOT NULL DEFAULT now()::TIMESTAMP
);
CREATE TABLE configs (
id SERIAL,
key VARCHAR(255) NOT NULL,
config TEXT NOT NULL,
PRIMARY KEY (key)
);
CREATE TABLE customers (
id SERIAL,
<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/core/payouts.rs<|crate|> router anchor=payouts_retrieve_core kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/payouts.rs" role="context" start="540" end="582">
pub async fn payouts_retrieve_core(
state: SessionState,
merchant_account: domain::MerchantAccount,
profile_id: Option<common_utils::id_type::ProfileId>,
key_store: domain::MerchantKeyStore,
req: payouts::PayoutRetrieveRequest,
) -> RouterResponse<payouts::PayoutCreateResponse> {
let mut payout_data = make_payout_data(
&state,
&merchant_account,
profile_id,
&key_store,
&payouts::PayoutRequest::PayoutRetrieveRequest(req.to_owned()),
&state.locale,
)
.await?;
let payout_attempt = payout_data.payout_attempt.to_owned();
let status = payout_attempt.status;
if matches!(req.force_sync, Some(true)) && helpers::should_call_retrieve(status) {
// Form connector data
let connector_call_type = get_connector_choice(
&state,
&merchant_account,
&key_store,
payout_attempt.connector.clone(),
None,
&mut payout_data,
None,
)
.await?;
complete_payout_retrieve(
&state,
&merchant_account,
connector_call_type,
&mut payout_data,
)
.await?;
}
response_handler(&state, &merchant_account, &payout_data).await
}
<file_sep path="hyperswitch/crates/router/src/core/payouts.rs" role="context" start="539" end="539">
use api_models::{self, enums as api_enums, payouts::PayoutLinkResponse};
use common_utils::{
consts,
ext_traits::{AsyncExt, ValueExt},
id_type::CustomerId,
link_utils::{GenericLinkStatus, GenericLinkUiConfig, PayoutLinkData, PayoutLinkStatus},
types::{MinorUnit, UnifiedCode, UnifiedMessage},
};
use crate::types::domain::behaviour::Conversion;
use crate::{
core::{
errors::{
self, ConnectorErrorExt, CustomResult, RouterResponse, RouterResult, StorageErrorExt,
},
payments::{self, customers, helpers as payment_helpers},
utils as core_utils,
},
db::StorageInterface,
routes::SessionState,
services,
types::{
self,
api::{self, payments as payment_api_types, payouts},
domain,
storage::{self, PaymentRoutingInfo},
transformers::ForeignFrom,
},
utils::{self, OptionExt},
};
<file_sep path="hyperswitch/crates/router/src/core/payouts.rs" role="context" start="678" end="768">
pub async fn payouts_fulfill_core(
state: SessionState,
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
req: payouts::PayoutActionRequest,
) -> RouterResponse<payouts::PayoutCreateResponse> {
let mut payout_data = make_payout_data(
&state,
&merchant_account,
None,
&key_store,
&payouts::PayoutRequest::PayoutActionRequest(req.to_owned()),
&state.locale,
)
.await?;
let payout_attempt = payout_data.payout_attempt.to_owned();
let status = payout_attempt.status;
// Verify if fulfillment can be triggered
if helpers::is_payout_terminal_state(status)
|| status != api_enums::PayoutStatus::RequiresFulfillment
{
return Err(report!(errors::ApiErrorResponse::InvalidRequestData {
message: format!(
"Payout {} cannot be fulfilled for status {}",
payout_attempt.payout_id, status
),
}));
}
// Form connector data
let connector_data = match &payout_attempt.connector {
Some(connector) => api::ConnectorData::get_payout_connector_by_name(
&state.conf.connectors,
connector,
api::GetToken::Connector,
payout_attempt.merchant_connector_id.clone(),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get the connector data")?,
_ => Err(errors::ApplicationError::InvalidConfigurationValueError(
"Connector not found in payout_attempt - should not reach here.".to_string(),
))
.change_context(errors::ApiErrorResponse::MissingRequiredField {
field_name: "connector",
})
.attach_printable("Connector not found for payout fulfillment")?,
};
// Trigger fulfillment
let customer_id = payout_data
.payouts
.customer_id
.clone()
.get_required_value("customer_id")?;
payout_data.payout_method_data = Some(
helpers::make_payout_method_data(
&state,
None,
payout_attempt.payout_token.as_deref(),
&customer_id,
&payout_attempt.merchant_id,
payout_data.payouts.payout_type,
&key_store,
Some(&mut payout_data),
merchant_account.storage_scheme,
)
.await?
.get_required_value("payout_method_data")?,
);
Box::pin(fulfill_payout(
&state,
&merchant_account,
&key_store,
&connector_data,
&mut payout_data,
))
.await
.attach_printable("Payout fulfillment failed for given Payout request")?;
if helpers::is_payout_err_state(status) {
return Err(report!(errors::ApiErrorResponse::PayoutFailed {
data: Some(
serde_json::json!({"payout_status": status.to_string(), "error_message": payout_attempt.error_message, "error_code": payout_attempt.error_code})
),
}));
}
response_handler(&state, &merchant_account, &payout_data).await
}
<file_sep path="hyperswitch/crates/router/src/core/payouts.rs" role="context" start="585" end="675">
pub async fn payouts_cancel_core(
state: SessionState,
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
req: payouts::PayoutActionRequest,
) -> RouterResponse<payouts::PayoutCreateResponse> {
let mut payout_data = make_payout_data(
&state,
&merchant_account,
None,
&key_store,
&payouts::PayoutRequest::PayoutActionRequest(req.to_owned()),
&state.locale,
)
.await?;
let payout_attempt = payout_data.payout_attempt.to_owned();
let status = payout_attempt.status;
// Verify if cancellation can be triggered
if helpers::is_payout_terminal_state(status) {
return Err(report!(errors::ApiErrorResponse::InvalidRequestData {
message: format!(
"Payout {} cannot be cancelled for status {}",
payout_attempt.payout_id, status
),
}));
// Make local cancellation
} else if helpers::is_eligible_for_local_payout_cancellation(status) {
let status = storage_enums::PayoutStatus::Cancelled;
let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate {
connector_payout_id: payout_attempt.connector_payout_id.to_owned(),
status,
error_message: Some("Cancelled by user".to_string()),
error_code: None,
is_eligible: None,
unified_code: None,
unified_message: None,
};
payout_data.payout_attempt = state
.store
.update_payout_attempt(
&payout_attempt,
updated_payout_attempt,
&payout_data.payouts,
merchant_account.storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating payout_attempt in db")?;
payout_data.payouts = state
.store
.update_payout(
&payout_data.payouts,
storage::PayoutsUpdate::StatusUpdate { status },
&payout_data.payout_attempt,
merchant_account.storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating payouts in db")?;
// Trigger connector's cancellation
} else {
// Form connector data
let connector_data = match &payout_attempt.connector {
Some(connector) => api::ConnectorData::get_payout_connector_by_name(
&state.conf.connectors,
connector,
api::GetToken::Connector,
payout_attempt.merchant_connector_id.clone(),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get the connector data")?,
_ => Err(errors::ApplicationError::InvalidConfigurationValueError(
"Connector not found in payout_attempt - should not reach here".to_string(),
))
.change_context(errors::ApiErrorResponse::MissingRequiredField {
field_name: "connector",
})
.attach_printable("Connector not found for payout cancellation")?,
};
cancel_payout(&state, &merchant_account, &connector_data, &mut payout_data)
.await
.attach_printable("Payout cancellation failed for given Payout request")?;
}
response_handler(&state, &merchant_account, &payout_data).await
}
<file_sep path="hyperswitch/crates/router/src/core/payouts.rs" role="context" start="457" end="536">
pub async fn payouts_update_core(
state: SessionState,
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
req: payouts::PayoutCreateRequest,
) -> RouterResponse<payouts::PayoutCreateResponse> {
let payout_id = req.payout_id.clone().get_required_value("payout_id")?;
let mut payout_data = make_payout_data(
&state,
&merchant_account,
None,
&key_store,
&payouts::PayoutRequest::PayoutCreateRequest(Box::new(req.to_owned())),
&state.locale,
)
.await?;
let payout_attempt = payout_data.payout_attempt.to_owned();
let status = payout_attempt.status;
// Verify update feasibility
if helpers::is_payout_terminal_state(status) || helpers::is_payout_initiated(status) {
return Err(report!(errors::ApiErrorResponse::InvalidRequestData {
message: format!(
"Payout {} cannot be updated for status {}",
payout_id, status
),
}));
}
helpers::update_payouts_and_payout_attempt(
&mut payout_data,
&merchant_account,
&req,
&state,
&key_store,
)
.await?;
let payout_attempt = payout_data.payout_attempt.to_owned();
if (req.connector.is_none(), payout_attempt.connector.is_some()) != (true, true) {
// if the connector is not updated but was provided during payout create
payout_data.payout_attempt.connector = None;
payout_data.payout_attempt.routing_info = None;
};
// Update payout method data in temp locker
if req.payout_method_data.is_some() {
let customer_id = payout_data
.payouts
.customer_id
.clone()
.get_required_value("customer_id when payout_method_data is provided")?;
payout_data.payout_method_data = helpers::make_payout_method_data(
&state,
req.payout_method_data.as_ref(),
payout_attempt.payout_token.as_deref(),
&customer_id,
&payout_attempt.merchant_id,
payout_data.payouts.payout_type,
&key_store,
Some(&mut payout_data),
merchant_account.storage_scheme,
)
.await?;
}
if let Some(true) = payout_data.payouts.confirm {
payouts_core(
&state,
&merchant_account,
&key_store,
&mut payout_data,
req.routing.clone(),
req.connector.clone(),
)
.await?;
}
response_handler(&state, &merchant_account, &payout_data).await
}
<file_sep path="hyperswitch/crates/router/src/core/payouts.rs" role="context" start="386" end="455">
pub async fn payouts_confirm_core(
state: SessionState,
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
req: payouts::PayoutCreateRequest,
) -> RouterResponse<payouts::PayoutCreateResponse> {
let mut payout_data = make_payout_data(
&state,
&merchant_account,
None,
&key_store,
&payouts::PayoutRequest::PayoutCreateRequest(Box::new(req.to_owned())),
&state.locale,
)
.await?;
let payout_attempt = payout_data.payout_attempt.to_owned();
let status = payout_attempt.status;
helpers::validate_payout_status_against_not_allowed_statuses(
status,
&[
storage_enums::PayoutStatus::Cancelled,
storage_enums::PayoutStatus::Success,
storage_enums::PayoutStatus::Failed,
storage_enums::PayoutStatus::Pending,
storage_enums::PayoutStatus::Ineligible,
storage_enums::PayoutStatus::RequiresFulfillment,
storage_enums::PayoutStatus::RequiresVendorAccountCreation,
],
"confirm",
)?;
helpers::update_payouts_and_payout_attempt(
&mut payout_data,
&merchant_account,
&req,
&state,
&key_store,
)
.await?;
let db = &*state.store;
payout_data.payout_link = payout_data
.payout_link
.clone()
.async_map(|pl| async move {
let payout_link_update = storage::PayoutLinkUpdate::StatusUpdate {
link_status: PayoutLinkStatus::Submitted,
};
db.update_payout_link(pl, payout_link_update)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating payout links in db")
})
.await
.transpose()?;
payouts_core(
&state,
&merchant_account,
&key_store,
&mut payout_data,
req.routing.clone(),
req.connector.clone(),
)
.await?;
response_handler(&state, &merchant_account, &payout_data).await
}
<file_sep path="hyperswitch/crates/router/src/core/payouts.rs" role="context" start="1860" end="1867">
pub async fn complete_payout_retrieve(
state: &SessionState,
merchant_account: &domain::MerchantAccount,
connector_call_type: api::ConnectorCallType,
payout_data: &mut PayoutData,
) -> RouterResult<()> {
todo!()
}
<file_sep path="hyperswitch/crates/router/src/core/payouts.rs" role="context" start="94" end="166">
pub async fn get_connector_choice(
state: &SessionState,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
connector: Option<String>,
routing_algorithm: Option<serde_json::Value>,
payout_data: &mut PayoutData,
eligible_connectors: Option<Vec<api_enums::PayoutConnectors>>,
) -> RouterResult<api::ConnectorCallType> {
let eligible_routable_connectors = eligible_connectors.map(|connectors| {
connectors
.into_iter()
.map(api::enums::RoutableConnectors::from)
.collect()
});
let connector_choice = helpers::get_default_payout_connector(state, routing_algorithm).await?;
match connector_choice {
api::ConnectorChoice::SessionMultiple(_) => {
Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Invalid connector choice - SessionMultiple")?
}
api::ConnectorChoice::StraightThrough(straight_through) => {
let request_straight_through: api::routing::StraightThroughAlgorithm = straight_through
.clone()
.parse_value("StraightThroughAlgorithm")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Invalid straight through routing rules format")?;
payout_data.payout_attempt.routing_info = Some(straight_through);
let mut routing_data = storage::RoutingData {
routed_through: connector,
merchant_connector_id: None,
algorithm: Some(request_straight_through.clone()),
routing_info: PaymentRoutingInfo {
algorithm: None,
pre_routing_results: None,
},
};
helpers::decide_payout_connector(
state,
merchant_account,
key_store,
Some(request_straight_through),
&mut routing_data,
payout_data,
eligible_routable_connectors,
)
.await
}
api::ConnectorChoice::Decide => {
let mut routing_data = storage::RoutingData {
routed_through: connector,
merchant_connector_id: None,
algorithm: None,
routing_info: PaymentRoutingInfo {
algorithm: None,
pre_routing_results: None,
},
};
helpers::decide_payout_connector(
state,
merchant_account,
key_store,
None,
&mut routing_data,
payout_data,
eligible_routable_connectors,
)
.await
}
}
}
<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/payouts.rs" role="context" start="20" end="24">
pub enum PayoutRequest {
PayoutActionRequest(PayoutActionRequest),
PayoutCreateRequest(Box<PayoutCreateRequest>),
PayoutRetrieveRequest(PayoutRetrieveRequest),
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payments/routing.rs<|crate|> router anchor=perform_session_routing_for_pm_type 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="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="1372" end="1372">
use api_models::routing as api_routing;
use api_models::{
admin as admin_api,
enums::{self as api_enums, CountryAlpha2},
routing::ConnectorSelection,
};
use crate::core::admin;
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="1434" end="1485">
pub fn make_dsl_input_for_surcharge(
payment_attempt: &oss_storage::PaymentAttempt,
payment_intent: &oss_storage::PaymentIntent,
billing_address: Option<Address>,
) -> RoutingResult<dsl_inputs::BackendInput> {
let mandate_data = dsl_inputs::MandateData {
mandate_acceptance_type: None,
mandate_type: None,
payment_type: None,
};
let payment_input = dsl_inputs::PaymentInput {
amount: payment_attempt.get_total_amount(),
// currency is always populated in payment_attempt during payment create
currency: payment_attempt
.currency
.get_required_value("currency")
.change_context(errors::RoutingError::DslMissingRequiredField {
field_name: "currency".to_string(),
})?,
authentication_type: payment_attempt.authentication_type,
card_bin: None,
capture_method: payment_attempt.capture_method,
business_country: payment_intent
.business_country
.map(api_enums::Country::from_alpha2),
billing_country: billing_address
.and_then(|bic| bic.address)
.and_then(|add| add.country)
.map(api_enums::Country::from_alpha2),
business_label: payment_intent.business_label.clone(),
setup_future_usage: payment_intent.setup_future_usage,
};
let metadata = 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 payment_method_input = dsl_inputs::PaymentMethodInput {
payment_method: None,
payment_method_type: None,
card_network: None,
};
let backend_input = dsl_inputs::BackendInput {
metadata,
payment: payment_input,
payment_method: payment_method_input,
mandate: mandate_data,
};
Ok(backend_input)
}
<file_sep path="hyperswitch/crates/router/src/core/payments/routing.rs" role="context" start="1425" end="1431">
pub fn make_dsl_input_for_surcharge(
_payment_attempt: &oss_storage::PaymentAttempt,
_payment_intent: &oss_storage::PaymentIntent,
_billing_address: Option<Address>,
) -> RoutingResult<dsl_inputs::BackendInput> {
todo!()
}
<file_sep path="hyperswitch/crates/router/src/core/payments/routing.rs" role="context" start="1333" end="1370">
async fn get_chosen_connectors<'a>(
state: &'a SessionState,
key_store: &'a domain::MerchantKeyStore,
session_pm_input: &SessionRoutingPmTypeInput<'_>,
transaction_type: &api_enums::TransactionType,
profile_wrapper: &admin::ProfileWrapper,
) -> RoutingResult<Vec<api_models::routing::RoutableConnectorChoice>> {
let merchant_id = &key_store.merchant_id;
let MerchantAccountRoutingAlgorithm::V1(algorithm_id) = session_pm_input.routing_algorithm;
let chosen_connectors = if let Some(ref algorithm_id) = algorithm_id {
let cached_algorithm = ensure_algorithm_cached_v1(
state,
merchant_id,
algorithm_id,
session_pm_input.profile_id,
transaction_type,
)
.await?;
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) => execute_dsl_and_get_connector_v1(
session_pm_input.backend_input.clone(),
interpreter,
)?,
}
} else {
profile_wrapper
.get_default_fallback_list_of_connector_under_profile()
.change_context(errors::RoutingError::FallbackConfigFetchFailed)?
};
Ok(chosen_connectors)
}
<file_sep path="hyperswitch/crates/router/src/core/payments/routing.rs" role="context" start="1252" end="1330">
async fn perform_session_routing_for_pm_type(
session_pm_input: &SessionRoutingPmTypeInput<'_>,
transaction_type: &api_enums::TransactionType,
_business_profile: &domain::Profile,
) -> RoutingResult<Option<Vec<api_models::routing::RoutableConnectorChoice>>> {
let merchant_id = &session_pm_input.key_store.merchant_id;
let algorithm_id = match session_pm_input.routing_algorithm {
MerchantAccountRoutingAlgorithm::V1(algorithm_ref) => &algorithm_ref.algorithm_id,
};
let chosen_connectors = if let Some(ref algorithm_id) = algorithm_id {
let cached_algorithm = ensure_algorithm_cached_v1(
&session_pm_input.state.clone(),
merchant_id,
algorithm_id,
session_pm_input.profile_id,
transaction_type,
)
.await?;
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) => execute_dsl_and_get_connector_v1(
session_pm_input.backend_input.clone(),
interpreter,
)?,
}
} else {
routing::helpers::get_merchant_default_config(
&*session_pm_input.state.clone().store,
session_pm_input.profile_id.get_string_repr(),
transaction_type,
)
.await
.change_context(errors::RoutingError::FallbackConfigFetchFailed)?
};
let mut final_selection = perform_cgraph_filtering(
&session_pm_input.state.clone(),
session_pm_input.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 = routing::helpers::get_merchant_default_config(
&*session_pm_input.state.clone().store,
session_pm_input.profile_id.get_string_repr(),
transaction_type,
)
.await
.change_context(errors::RoutingError::FallbackConfigFetchFailed)?;
final_selection = perform_cgraph_filtering(
&session_pm_input.state.clone(),
session_pm_input.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="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/router/src/core/payments/routing.rs" role="context" start="1107" end="1249">
pub async fn perform_session_flow_routing(
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 = session_input
.payment_intent
.profile_id
.clone()
.get_required_value("profile_id")
.change_context(errors::RoutingError::ProfileIdMissing)?;
let routing_algorithm: MerchantAccountRoutingAlgorithm = {
business_profile
.routing_algorithm
.clone()
.map(|val| val.parse_value("MerchantAccountRoutingAlgorithm"))
.transpose()
.change_context(errors::RoutingError::InvalidRoutingAlgorithmStructure)?
.unwrap_or_default()
};
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_attempt.get_total_amount(),
currency: session_input
.payment_intent
.currency
.get_required_value("Currency")
.change_context(errors::RoutingError::DslMissingRequiredField {
field_name: "currency".to_string(),
})?,
authentication_type: session_input.payment_attempt.authentication_type,
card_bin: None,
capture_method: session_input
.payment_attempt
.capture_method
.and_then(Option::<euclid_enums::CaptureMethod>::foreign_from),
business_country: session_input
.payment_intent
.business_country
.map(api_enums::Country::from_alpha2),
billing_country: session_input
.country
.map(storage_enums::Country::from_alpha2),
business_label: session_input.payment_intent.business_label.clone(),
setup_future_usage: 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 {
state: session_input.state,
key_store: session_input.key_store,
attempt_id: session_input.payment_attempt.get_id(),
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(
&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(
&session_pm_input.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/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="111" end="111">
type RoutingResult<O> = oss_errors::CustomResult<O, errors::RoutingError>;
<file_sep path="hyperswitch/crates/router/src/core/payments/routing.rs" role="context" start="93" end="101">
pub struct SessionRoutingPmTypeInput<'a> {
state: &'a SessionState,
key_store: &'a domain::MerchantKeyStore,
attempt_id: &'a str,
routing_algorithm: &'a MerchantAccountRoutingAlgorithm,
backend_input: dsl_inputs::BackendInput,
allowed_connectors: FxHashMap<String, api::GetToken>,
profile_id: &'a common_utils::id_type::ProfileId,
}
<file_sep path="hyperswitch/crates/router/src/routes/app.rs" role="context" start="1906" end="1906">
pub struct Profile;
<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>,
}
<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/routing.rs<|crate|> router anchor=get_chosen_connectors 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="1333" end="1370">
async fn get_chosen_connectors<'a>(
state: &'a SessionState,
key_store: &'a domain::MerchantKeyStore,
session_pm_input: &SessionRoutingPmTypeInput<'_>,
transaction_type: &api_enums::TransactionType,
profile_wrapper: &admin::ProfileWrapper,
) -> RoutingResult<Vec<api_models::routing::RoutableConnectorChoice>> {
let merchant_id = &key_store.merchant_id;
let MerchantAccountRoutingAlgorithm::V1(algorithm_id) = session_pm_input.routing_algorithm;
let chosen_connectors = if let Some(ref algorithm_id) = algorithm_id {
let cached_algorithm = ensure_algorithm_cached_v1(
state,
merchant_id,
algorithm_id,
session_pm_input.profile_id,
transaction_type,
)
.await?;
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) => execute_dsl_and_get_connector_v1(
session_pm_input.backend_input.clone(),
interpreter,
)?,
}
} else {
profile_wrapper
.get_default_fallback_list_of_connector_under_profile()
.change_context(errors::RoutingError::FallbackConfigFetchFailed)?
};
Ok(chosen_connectors)
}
<file_sep path="hyperswitch/crates/router/src/core/payments/routing.rs" role="context" start="1332" end="1332">
use api_models::routing as api_routing;
use api_models::{
admin as admin_api,
enums::{self as api_enums, CountryAlpha2},
routing::ConnectorSelection,
};
use crate::core::admin;
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="1425" end="1431">
pub fn make_dsl_input_for_surcharge(
_payment_attempt: &oss_storage::PaymentAttempt,
_payment_intent: &oss_storage::PaymentIntent,
_billing_address: Option<Address>,
) -> RoutingResult<dsl_inputs::BackendInput> {
todo!()
}
<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="1252" end="1330">
async fn perform_session_routing_for_pm_type(
session_pm_input: &SessionRoutingPmTypeInput<'_>,
transaction_type: &api_enums::TransactionType,
_business_profile: &domain::Profile,
) -> RoutingResult<Option<Vec<api_models::routing::RoutableConnectorChoice>>> {
let merchant_id = &session_pm_input.key_store.merchant_id;
let algorithm_id = match session_pm_input.routing_algorithm {
MerchantAccountRoutingAlgorithm::V1(algorithm_ref) => &algorithm_ref.algorithm_id,
};
let chosen_connectors = if let Some(ref algorithm_id) = algorithm_id {
let cached_algorithm = ensure_algorithm_cached_v1(
&session_pm_input.state.clone(),
merchant_id,
algorithm_id,
session_pm_input.profile_id,
transaction_type,
)
.await?;
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) => execute_dsl_and_get_connector_v1(
session_pm_input.backend_input.clone(),
interpreter,
)?,
}
} else {
routing::helpers::get_merchant_default_config(
&*session_pm_input.state.clone().store,
session_pm_input.profile_id.get_string_repr(),
transaction_type,
)
.await
.change_context(errors::RoutingError::FallbackConfigFetchFailed)?
};
let mut final_selection = perform_cgraph_filtering(
&session_pm_input.state.clone(),
session_pm_input.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 = routing::helpers::get_merchant_default_config(
&*session_pm_input.state.clone().store,
session_pm_input.profile_id.get_string_repr(),
transaction_type,
)
.await
.change_context(errors::RoutingError::FallbackConfigFetchFailed)?;
final_selection = perform_cgraph_filtering(
&session_pm_input.state.clone(),
session_pm_input.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="1107" end="1249">
pub async fn perform_session_flow_routing(
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 = session_input
.payment_intent
.profile_id
.clone()
.get_required_value("profile_id")
.change_context(errors::RoutingError::ProfileIdMissing)?;
let routing_algorithm: MerchantAccountRoutingAlgorithm = {
business_profile
.routing_algorithm
.clone()
.map(|val| val.parse_value("MerchantAccountRoutingAlgorithm"))
.transpose()
.change_context(errors::RoutingError::InvalidRoutingAlgorithmStructure)?
.unwrap_or_default()
};
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_attempt.get_total_amount(),
currency: session_input
.payment_intent
.currency
.get_required_value("Currency")
.change_context(errors::RoutingError::DslMissingRequiredField {
field_name: "currency".to_string(),
})?,
authentication_type: session_input.payment_attempt.authentication_type,
card_bin: None,
capture_method: session_input
.payment_attempt
.capture_method
.and_then(Option::<euclid_enums::CaptureMethod>::foreign_from),
business_country: session_input
.payment_intent
.business_country
.map(api_enums::Country::from_alpha2),
billing_country: session_input
.country
.map(storage_enums::Country::from_alpha2),
business_label: session_input.payment_intent.business_label.clone(),
setup_future_usage: 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 {
state: session_input.state,
key_store: session_input.key_store,
attempt_id: session_input.payment_attempt.get_id(),
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(
&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(
&session_pm_input.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/router/src/core/payments/routing.rs" role="context" start="468" end="509">
async fn ensure_algorithm_cached_v1(
state: &SessionState,
merchant_id: &common_utils::id_type::MerchantId,
algorithm_id: &common_utils::id_type::RoutingId,
profile_id: &common_utils::id_type::ProfileId,
transaction_type: &api_enums::TransactionType,
) -> RoutingResult<Arc<CachedAlgorithm>> {
let key = {
match transaction_type {
common_enums::TransactionType::Payment => {
format!(
"routing_config_{}_{}",
merchant_id.get_string_repr(),
profile_id.get_string_repr(),
)
}
#[cfg(feature = "payouts")]
common_enums::TransactionType::Payout => {
format!(
"routing_config_po_{}_{}",
merchant_id.get_string_repr(),
profile_id.get_string_repr()
)
}
}
};
let cached_algorithm = ROUTING_CACHE
.get_val::<Arc<CachedAlgorithm>>(CacheKey {
key: key.clone(),
prefix: state.tenant.redis_key_prefix.clone(),
})
.await;
let algorithm = if let Some(algo) = cached_algorithm {
algo
} else {
refresh_routing_cache_v1(state, key.clone(), algorithm_id, profile_id).await?
};
Ok(algorithm)
}
<file_sep path="hyperswitch/crates/router/src/core/payments/routing.rs" role="context" start="547" end="565">
fn execute_dsl_and_get_connector_v1(
backend_input: dsl_inputs::BackendInput,
interpreter: &backend::VirInterpreterBackend<ConnectorSelection>,
) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> {
let routing_output: routing_types::RoutingAlgorithm = interpreter
.execute(backend_input)
.map(|out| out.connector_selection.foreign_into())
.change_context(errors::RoutingError::DslExecutionError)?;
Ok(match routing_output {
routing_types::RoutingAlgorithm::Priority(plist) => plist,
routing_types::RoutingAlgorithm::VolumeSplit(splits) => perform_volume_split(splits)
.change_context(errors::RoutingError::DslFinalConnectorSelectionFailed)?,
_ => Err(errors::RoutingError::DslIncorrectSelectionAlgorithm)
.attach_printable("Unsupported algorithm received as a result of static routing")?,
})
}
<file_sep path="hyperswitch/crates/router/src/core/payments/routing.rs" role="context" start="116" end="118">
enum MerchantAccountRoutingAlgorithm {
V1(routing_types::RoutingAlgorithmRef),
}
<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/core/webhooks/incoming.rs<|crate|> router anchor=get_payment_attempt_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/core/webhooks/incoming.rs" role="context" start="1117" end="1151">
async fn get_payment_attempt_from_object_reference_id(
state: &SessionState,
object_reference_id: webhooks::ObjectReferenceId,
merchant_account: &domain::MerchantAccount,
) -> CustomResult<PaymentAttempt, errors::ApiErrorResponse> {
let db = &*state.store;
match object_reference_id {
api::ObjectReferenceId::PaymentId(api::PaymentIdType::ConnectorTransactionId(ref id)) => db
.find_payment_attempt_by_merchant_id_connector_txn_id(
merchant_account.get_id(),
id,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::WebhookResourceNotFound),
api::ObjectReferenceId::PaymentId(api::PaymentIdType::PaymentAttemptId(ref id)) => db
.find_payment_attempt_by_attempt_id_merchant_id(
id,
merchant_account.get_id(),
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::WebhookResourceNotFound),
api::ObjectReferenceId::PaymentId(api::PaymentIdType::PreprocessingId(ref id)) => db
.find_payment_attempt_by_preprocessing_id_merchant_id(
id,
merchant_account.get_id(),
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::WebhookResourceNotFound),
_ => Err(errors::ApiErrorResponse::WebhookProcessingFailure)
.attach_printable("received a non-payment id for retrieving payment")?,
}
}
<file_sep path="hyperswitch/crates/router/src/core/webhooks/incoming.rs" role="context" start="1116" end="1116">
| webhooks::WebhookFlow::Subscription
| webhooks::WebhookFlow::ReturnResponse
| webhooks::WebhookFlow::BankTransfer
| webhooks::WebhookFlow::Mandate
| webhooks::WebhookFlow::ExternalAuthentication
| webhooks::WebhookFlow::FraudCheck => Err(errors::ApiErrorResponse::NotSupported {
message: "Relay webhook flow types not supported".to_string(),
})?,
};
Ok(result_response)
}
async fn get_payment_attempt_from_object_reference_id(
state: &SessionState,
object_reference_id: webhooks::ObjectReferenceId,
merchant_account: &domain::MerchantAccount,
) -> CustomResult<PaymentAttempt, errors::ApiErrorResponse> {
let db = &*state.store;
match object_reference_id {
api::ObjectReferenceId::PaymentId(api::PaymentIdType::ConnectorTransactionId(ref id)) => db
.find_payment_attempt_by_merchant_id_connector_txn_id(
merchant_account.get_id(),
id,
merchant_account.storage_scheme,
)
<file_sep path="hyperswitch/crates/router/src/core/webhooks/incoming.rs" role="context" start="1234" end="1407">
async fn external_authentication_incoming_webhook_flow(
state: SessionState,
req_state: ReqState,
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
source_verified: bool,
event_type: webhooks::IncomingWebhookEvent,
request_details: &IncomingWebhookRequestDetails<'_>,
connector: &ConnectorEnum,
object_ref_id: api::ObjectReferenceId,
business_profile: domain::Profile,
merchant_connector_account: domain::MerchantConnectorAccount,
) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> {
if source_verified {
let authentication_details = connector
.get_external_authentication_details(request_details)
.switch()?;
let trans_status = authentication_details.trans_status;
let authentication_update = storage::AuthenticationUpdate::PostAuthenticationUpdate {
authentication_status: common_enums::AuthenticationStatus::foreign_from(
trans_status.clone(),
),
trans_status,
authentication_value: authentication_details.authentication_value,
eci: authentication_details.eci,
};
let authentication =
if let webhooks::ObjectReferenceId::ExternalAuthenticationID(authentication_id_type) =
object_ref_id
{
match authentication_id_type {
webhooks::AuthenticationIdType::AuthenticationId(authentication_id) => state
.store
.find_authentication_by_merchant_id_authentication_id(
merchant_account.get_id(),
authentication_id.clone(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::AuthenticationNotFound {
id: authentication_id,
})
.attach_printable("Error while fetching authentication record"),
webhooks::AuthenticationIdType::ConnectorAuthenticationId(
connector_authentication_id,
) => state
.store
.find_authentication_by_merchant_id_connector_authentication_id(
merchant_account.get_id().clone(),
connector_authentication_id.clone(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::AuthenticationNotFound {
id: connector_authentication_id,
})
.attach_printable("Error while fetching authentication record"),
}
} else {
Err(errors::ApiErrorResponse::WebhookProcessingFailure).attach_printable(
"received a non-external-authentication id for retrieving authentication",
)
}?;
let updated_authentication = state
.store
.update_authentication_by_merchant_id_authentication_id(
authentication,
authentication_update,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error while updating authentication")?;
// Check if it's a payment authentication flow, payment_id would be there only for payment authentication flows
if let Some(payment_id) = updated_authentication.payment_id {
let is_pull_mechanism_enabled = helper_utils::check_if_pull_mechanism_for_external_3ds_enabled_from_connector_metadata(merchant_connector_account.metadata.map(|metadata| metadata.expose()));
// Merchant doesn't have pull mechanism enabled and if it's challenge flow, we have to authorize whenever we receive a ARes webhook
if !is_pull_mechanism_enabled
&& updated_authentication.authentication_type
== Some(common_enums::DecoupledAuthenticationType::Challenge)
&& event_type == webhooks::IncomingWebhookEvent::ExternalAuthenticationARes
{
let payment_confirm_req = api::PaymentsRequest {
payment_id: Some(api_models::payments::PaymentIdType::PaymentIntentId(
payment_id,
)),
merchant_id: Some(merchant_account.get_id().clone()),
..Default::default()
};
let payments_response = Box::pin(payments::payments_core::<
api::Authorize,
api::PaymentsResponse,
_,
_,
_,
payments::PaymentData<api::Authorize>,
>(
state.clone(),
req_state,
merchant_account.clone(),
None,
key_store.clone(),
payments::PaymentConfirm,
payment_confirm_req,
services::api::AuthFlow::Merchant,
payments::CallConnectorAction::Trigger,
None,
HeaderPayload::with_source(enums::PaymentSource::ExternalAuthenticator),
None, // Platform merchant account
))
.await?;
match payments_response {
services::ApplicationResponse::JsonWithHeaders((payments_response, _)) => {
let payment_id = payments_response.payment_id.clone();
let status = payments_response.status;
let event_type: Option<enums::EventType> =
payments_response.status.foreign_into();
// Set poll_id as completed in redis to allow the fetch status of poll through retrieve_poll_status api from client
let poll_id = core_utils::get_poll_id(
merchant_account.get_id(),
core_utils::get_external_authentication_request_poll_id(&payment_id),
);
let redis_conn = state
.store
.get_redis_conn()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get redis connection")?;
redis_conn
.set_key_without_modifying_ttl(
&poll_id.into(),
api_models::poll::PollStatus::Completed.to_string(),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to add poll_id in redis")?;
// If event is NOT an UnsupportedEvent, trigger Outgoing Webhook
if let Some(outgoing_event_type) = event_type {
let primary_object_created_at = payments_response.created;
Box::pin(super::create_event_and_trigger_outgoing_webhook(
state,
merchant_account,
business_profile,
&key_store,
outgoing_event_type,
enums::EventClass::Payments,
payment_id.get_string_repr().to_owned(),
enums::EventObjectType::PaymentDetails,
api::OutgoingWebhookContent::PaymentDetails(Box::new(
payments_response,
)),
primary_object_created_at,
))
.await?;
};
let response = WebhookResponseTracker::Payment { payment_id, status };
Ok(response)
}
_ => Err(errors::ApiErrorResponse::WebhookProcessingFailure).attach_printable(
"Did not get payment id as object reference id in webhook payments flow",
)?,
}
} else {
Ok(WebhookResponseTracker::NoEffect)
}
} else {
Ok(WebhookResponseTracker::NoEffect)
}
} else {
logger::error!(
"Webhook source verification failed for external authentication webhook flow"
);
Err(report!(
errors::ApiErrorResponse::WebhookAuthenticationFailed
))
}
}
<file_sep path="hyperswitch/crates/router/src/core/webhooks/incoming.rs" role="context" start="1154" end="1230">
async fn get_or_update_dispute_object(
state: SessionState,
option_dispute: Option<diesel_models::dispute::Dispute>,
dispute_details: api::disputes::DisputePayload,
merchant_id: &common_utils::id_type::MerchantId,
organization_id: &common_utils::id_type::OrganizationId,
payment_attempt: &PaymentAttempt,
event_type: webhooks::IncomingWebhookEvent,
business_profile: &domain::Profile,
connector_name: &str,
) -> CustomResult<diesel_models::dispute::Dispute, errors::ApiErrorResponse> {
let db = &*state.store;
match option_dispute {
None => {
metrics::INCOMING_DISPUTE_WEBHOOK_NEW_RECORD_METRIC.add(1, &[]);
let dispute_id = generate_id(consts::ID_LENGTH, "dp");
let new_dispute = diesel_models::dispute::DisputeNew {
dispute_id,
amount: dispute_details.amount.clone(),
currency: dispute_details.currency.to_string(),
dispute_stage: dispute_details.dispute_stage,
dispute_status: common_enums::DisputeStatus::foreign_try_from(event_type)
.change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
.attach_printable("event type to dispute status mapping failed")?,
payment_id: payment_attempt.payment_id.to_owned(),
connector: connector_name.to_owned(),
attempt_id: payment_attempt.attempt_id.to_owned(),
merchant_id: merchant_id.to_owned(),
connector_status: dispute_details.connector_status,
connector_dispute_id: dispute_details.connector_dispute_id,
connector_reason: dispute_details.connector_reason,
connector_reason_code: dispute_details.connector_reason_code,
challenge_required_by: dispute_details.challenge_required_by,
connector_created_at: dispute_details.created_at,
connector_updated_at: dispute_details.updated_at,
profile_id: Some(business_profile.get_id().to_owned()),
evidence: None,
merchant_connector_id: payment_attempt.merchant_connector_id.clone(),
dispute_amount: dispute_details.amount.parse::<i64>().unwrap_or(0),
organization_id: organization_id.clone(),
dispute_currency: Some(dispute_details.currency),
};
state
.store
.insert_dispute(new_dispute.clone())
.await
.to_not_found_response(errors::ApiErrorResponse::WebhookResourceNotFound)
}
Some(dispute) => {
logger::info!("Dispute Already exists, Updating the dispute details");
metrics::INCOMING_DISPUTE_WEBHOOK_UPDATE_RECORD_METRIC.add(1, &[]);
let dispute_status = diesel_models::enums::DisputeStatus::foreign_try_from(event_type)
.change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
.attach_printable("event type to dispute state conversion failure")?;
crate::core::utils::validate_dispute_stage_and_dispute_status(
dispute.dispute_stage,
dispute.dispute_status,
dispute_details.dispute_stage,
dispute_status,
)
.change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
.attach_printable("dispute stage and status validation failed")?;
let update_dispute = diesel_models::dispute::DisputeUpdate::Update {
dispute_stage: dispute_details.dispute_stage,
dispute_status,
connector_status: dispute_details.connector_status,
connector_reason: dispute_details.connector_reason,
connector_reason_code: dispute_details.connector_reason_code,
challenge_required_by: dispute_details.challenge_required_by,
connector_updated_at: dispute_details.updated_at,
};
db.update_dispute(dispute, update_dispute)
.await
.to_not_found_response(errors::ApiErrorResponse::WebhookResourceNotFound)
}
}
}
<file_sep path="hyperswitch/crates/router/src/core/webhooks/incoming.rs" role="context" start="1079" end="1115">
async fn relay_incoming_webhook_flow(
state: SessionState,
merchant_account: domain::MerchantAccount,
business_profile: domain::Profile,
merchant_key_store: domain::MerchantKeyStore,
webhook_details: api::IncomingWebhookDetails,
event_type: webhooks::IncomingWebhookEvent,
source_verified: bool,
) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> {
let flow_type: api::WebhookFlow = event_type.into();
let result_response = match flow_type {
webhooks::WebhookFlow::Refund => Box::pin(relay_refunds_incoming_webhook_flow(
state,
merchant_account,
business_profile,
merchant_key_store,
webhook_details,
event_type,
source_verified,
))
.await
.attach_printable("Incoming webhook flow for relay refund failed")?,
webhooks::WebhookFlow::Payment
| webhooks::WebhookFlow::Payout
| webhooks::WebhookFlow::Dispute
| webhooks::WebhookFlow::Subscription
| webhooks::WebhookFlow::ReturnResponse
| webhooks::WebhookFlow::BankTransfer
| webhooks::WebhookFlow::Mandate
| webhooks::WebhookFlow::ExternalAuthentication
| webhooks::WebhookFlow::FraudCheck => Err(errors::ApiErrorResponse::NotSupported {
message: "Relay webhook flow types not supported".to_string(),
})?,
};
Ok(result_response)
}
<file_sep path="hyperswitch/crates/router/src/core/webhooks/incoming.rs" role="context" start="979" end="1077">
async fn refunds_incoming_webhook_flow(
state: SessionState,
merchant_account: domain::MerchantAccount,
business_profile: domain::Profile,
key_store: domain::MerchantKeyStore,
webhook_details: api::IncomingWebhookDetails,
connector_name: &str,
source_verified: bool,
event_type: webhooks::IncomingWebhookEvent,
) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> {
let db = &*state.store;
//find refund by connector refund id
let refund = match webhook_details.object_reference_id {
webhooks::ObjectReferenceId::RefundId(refund_id_type) => match refund_id_type {
webhooks::RefundIdType::RefundId(id) => db
.find_refund_by_merchant_id_refund_id(
merchant_account.get_id(),
&id,
merchant_account.storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::WebhookResourceNotFound)
.attach_printable("Failed to fetch the refund")?,
webhooks::RefundIdType::ConnectorRefundId(id) => db
.find_refund_by_merchant_id_connector_refund_id_connector(
merchant_account.get_id(),
&id,
connector_name,
merchant_account.storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::WebhookResourceNotFound)
.attach_printable("Failed to fetch the refund")?,
},
_ => Err(errors::ApiErrorResponse::WebhookProcessingFailure)
.attach_printable("received a non-refund id when processing refund webhooks")?,
};
let refund_id = refund.refund_id.to_owned();
//if source verified then update refund status else trigger refund sync
let updated_refund = if source_verified {
let refund_update = storage::RefundUpdate::StatusUpdate {
connector_refund_id: None,
sent_to_gateway: true,
refund_status: common_enums::RefundStatus::foreign_try_from(event_type)
.change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
.attach_printable("failed refund status mapping from event type")?,
updated_by: merchant_account.storage_scheme.to_string(),
processor_refund_data: None,
};
db.update_refund(
refund.to_owned(),
refund_update,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::WebhookResourceNotFound)
.attach_printable_lazy(|| format!("Failed while updating refund: refund_id: {refund_id}"))?
} else {
Box::pin(refunds::refund_retrieve_core_with_refund_id(
state.clone(),
merchant_account.clone(),
None,
key_store.clone(),
api_models::refunds::RefundsRetrieveRequest {
refund_id: refund_id.to_owned(),
force_sync: Some(true),
merchant_connector_details: None,
},
))
.await
.attach_printable_lazy(|| format!("Failed while updating refund: refund_id: {refund_id}"))?
};
let event_type: Option<enums::EventType> = updated_refund.refund_status.foreign_into();
// If event is NOT an UnsupportedEvent, trigger Outgoing Webhook
if let Some(outgoing_event_type) = event_type {
let refund_response: api_models::refunds::RefundResponse =
updated_refund.clone().foreign_into();
Box::pin(super::create_event_and_trigger_outgoing_webhook(
state,
merchant_account,
business_profile,
&key_store,
outgoing_event_type,
enums::EventClass::Refunds,
refund_id,
enums::EventObjectType::RefundDetails,
api::OutgoingWebhookContent::RefundDetails(Box::new(refund_response)),
Some(updated_refund.created_at),
))
.await?;
}
Ok(WebhookResponseTracker::Refund {
payment_id: updated_refund.payment_id,
refund_id: updated_refund.refund_id,
status: updated_refund.refund_status,
})
}
<file_sep path="hyperswitch/crates/router/src/core/webhooks/incoming.rs" role="context" start="1683" end="1766">
async fn bank_transfer_webhook_flow(
state: SessionState,
req_state: ReqState,
merchant_account: domain::MerchantAccount,
business_profile: domain::Profile,
key_store: domain::MerchantKeyStore,
webhook_details: api::IncomingWebhookDetails,
source_verified: bool,
) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> {
let response = if source_verified {
let payment_attempt = get_payment_attempt_from_object_reference_id(
&state,
webhook_details.object_reference_id,
&merchant_account,
)
.await?;
let payment_id = payment_attempt.payment_id;
let request = api::PaymentsRequest {
payment_id: Some(api_models::payments::PaymentIdType::PaymentIntentId(
payment_id,
)),
payment_token: payment_attempt.payment_token,
..Default::default()
};
Box::pin(payments::payments_core::<
api::Authorize,
api::PaymentsResponse,
_,
_,
_,
payments::PaymentData<api::Authorize>,
>(
state.clone(),
req_state,
merchant_account.to_owned(),
None,
key_store.clone(),
payments::PaymentConfirm,
request,
services::api::AuthFlow::Merchant,
payments::CallConnectorAction::Trigger,
None,
HeaderPayload::with_source(common_enums::PaymentSource::Webhook),
None, //Platform merchant account
))
.await
} else {
Err(report!(
errors::ApiErrorResponse::WebhookAuthenticationFailed
))
};
match response? {
services::ApplicationResponse::JsonWithHeaders((payments_response, _)) => {
let payment_id = payments_response.payment_id.clone();
let event_type: Option<enums::EventType> = payments_response.status.foreign_into();
let status = payments_response.status;
// If event is NOT an UnsupportedEvent, trigger Outgoing Webhook
if let Some(outgoing_event_type) = event_type {
let primary_object_created_at = payments_response.created;
Box::pin(super::create_event_and_trigger_outgoing_webhook(
state,
merchant_account,
business_profile,
&key_store,
outgoing_event_type,
enums::EventClass::Payments,
payment_id.get_string_repr().to_owned(),
enums::EventObjectType::PaymentDetails,
api::OutgoingWebhookContent::PaymentDetails(Box::new(payments_response)),
primary_object_created_at,
))
.await?;
}
Ok(WebhookResponseTracker::Payment { payment_id, status })
}
_ => Err(errors::ApiErrorResponse::WebhookProcessingFailure)
.attach_printable("received non-json response from payments core")?,
}
}
<file_sep path="hyperswitch/crates/router/src/core/webhooks/incoming.rs" role="context" start="1979" end="2124">
async fn update_connector_mandate_details(
state: &SessionState,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
object_ref_id: api::ObjectReferenceId,
connector: &ConnectorEnum,
request_details: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<(), errors::ApiErrorResponse> {
let webhook_connector_mandate_details = connector
.get_mandate_details(request_details)
.switch()
.attach_printable("Could not find connector mandate details in incoming webhook body")?;
let webhook_connector_network_transaction_id = connector
.get_network_txn_id(request_details)
.switch()
.attach_printable(
"Could not find connector network transaction id in incoming webhook body",
)?;
// Either one OR both of the fields are present
if webhook_connector_mandate_details.is_some()
|| webhook_connector_network_transaction_id.is_some()
{
let payment_attempt =
get_payment_attempt_from_object_reference_id(state, object_ref_id, merchant_account)
.await?;
if let Some(ref payment_method_id) = payment_attempt.payment_method_id {
let key_manager_state = &state.into();
let payment_method_info = state
.store
.find_payment_method(
key_manager_state,
key_store,
payment_method_id,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
// Update connector's mandate details
let updated_connector_mandate_details =
if let Some(webhook_mandate_details) = webhook_connector_mandate_details {
let mandate_details = payment_method_info
.get_common_mandate_reference()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to deserialize to Payment Mandate Reference")?;
let merchant_connector_account_id = payment_attempt
.merchant_connector_id
.clone()
.get_required_value("merchant_connector_id")?;
if mandate_details.payments.as_ref().map_or(true, |payments| {
!payments.0.contains_key(&merchant_connector_account_id)
}) {
// Update the payment attempt to maintain consistency across tables.
let (mandate_metadata, connector_mandate_request_reference_id) =
payment_attempt
.connector_mandate_detail
.as_ref()
.map(|details| {
(
details.mandate_metadata.clone(),
details.connector_mandate_request_reference_id.clone(),
)
})
.unwrap_or((None, None));
let connector_mandate_reference_id = ConnectorMandateReferenceId {
connector_mandate_id: Some(
webhook_mandate_details
.connector_mandate_id
.peek()
.to_string(),
),
payment_method_id: Some(payment_method_id.to_string()),
mandate_metadata,
connector_mandate_request_reference_id,
};
let attempt_update =
storage::PaymentAttemptUpdate::ConnectorMandateDetailUpdate {
connector_mandate_detail: Some(connector_mandate_reference_id),
updated_by: merchant_account.storage_scheme.to_string(),
};
state
.store
.update_payment_attempt_with_attempt_id(
payment_attempt.clone(),
attempt_update,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
insert_mandate_details(
&payment_attempt,
&webhook_mandate_details,
Some(mandate_details),
)?
} else {
logger::info!(
"Skipping connector mandate details update since they are already present."
);
None
}
} else {
None
};
let connector_mandate_details_value = updated_connector_mandate_details
.map(|common_mandate| {
common_mandate.get_mandate_details_value().map_err(|err| {
router_env::logger::error!(
"Failed to get get_mandate_details_value : {:?}",
err
);
errors::ApiErrorResponse::MandateUpdateFailed
})
})
.transpose()?;
let pm_update = diesel_models::PaymentMethodUpdate::ConnectorNetworkTransactionIdAndMandateDetailsUpdate {
connector_mandate_details: connector_mandate_details_value.map(masking::Secret::new),
network_transaction_id: webhook_connector_network_transaction_id
.map(|webhook_network_transaction_id| webhook_network_transaction_id.get_id().clone()),
};
state
.store
.update_payment_method(
key_manager_state,
key_store,
payment_method_info,
pm_update,
merchant_account.storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update payment method in db")?;
}
}
Ok(())
}
<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-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/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/payment_methods/cards.rs<|crate|> router anchor=add_card_hs 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="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="2549" end="2549">
}
#[cfg(all(feature = "v2", feature = "customer_v2"))]
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!()
}
#[instrument(skip_all)]
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>,
),
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="2625" end="2680">
pub async fn get_payment_method_from_hs_locker<'a>(
state: &'a routes::SessionState,
key_store: &domain::MerchantKeyStore,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
payment_method_reference: &'a str,
locker_choice: Option<api_enums::LockerChoice>,
) -> errors::CustomResult<Secret<String>, errors::VaultError> {
let locker = &state.conf.locker;
let jwekey = state.conf.jwekey.get_inner();
let payment_method_data = if !locker.mock_locker {
let request = payment_methods::mk_get_card_request_hs(
jwekey,
locker,
customer_id,
merchant_id,
payment_method_reference,
locker_choice,
state.tenant.tenant_id.clone(),
state.request_id,
)
.await
.change_context(errors::VaultError::FetchPaymentMethodFailed)
.attach_printable("Making get payment method request failed")?;
let get_card_resp = call_locker_api::<payment_methods::RetrieveCardResp>(
state,
request,
"get_pm_from_locker",
locker_choice,
)
.await
.change_context(errors::VaultError::FetchPaymentMethodFailed)?;
let retrieve_card_resp = get_card_resp
.payload
.get_required_value("RetrieveCardRespPayload")
.change_context(errors::VaultError::FetchPaymentMethodFailed)
.attach_printable("Failed to retrieve field - payload from RetrieveCardResp")?;
let enc_card_data = retrieve_card_resp
.enc_card_data
.get_required_value("enc_card_data")
.change_context(errors::VaultError::FetchPaymentMethodFailed)
.attach_printable(
"Failed to retrieve field - enc_card_data from RetrieveCardRespPayload",
)?;
decode_and_decrypt_locker_data(state, key_store, enc_card_data.peek().to_string()).await?
} else {
mock_get_payment_method(state, key_store, payment_method_reference)
.await?
.payment_method
.payment_method_data
};
Ok(payment_method_data)
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="2594" end="2622">
pub async fn decode_and_decrypt_locker_data(
state: &routes::SessionState,
key_store: &domain::MerchantKeyStore,
enc_card_data: String,
) -> errors::CustomResult<Secret<String>, errors::VaultError> {
// Fetch key
let key = key_store.key.get_inner().peek();
// Decode
let decoded_bytes = hex::decode(&enc_card_data)
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Failed to decode hex string into bytes")?;
// Decrypt
domain::types::crypto_operation(
&state.into(),
type_name!(payment_method::PaymentMethod),
domain::types::CryptoOperation::DecryptOptional(Some(Encryption::new(
decoded_bytes.into(),
))),
Identifier::Merchant(key_store.merchant_id.clone()),
key,
)
.await
.and_then(|val| val.try_into_optionaloperation())
.change_context(errors::VaultError::FetchPaymentMethodFailed)?
.map_or(
Err(report!(errors::VaultError::FetchPaymentMethodFailed)),
|d| Ok(d.into_inner()),
)
}
<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="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="2683" end="2720">
pub async fn add_card_to_hs_locker(
state: &routes::SessionState,
payload: &payment_methods::StoreLockerReq,
customer_id: &id_type::CustomerId,
locker_choice: api_enums::LockerChoice,
) -> errors::CustomResult<payment_methods::StoreCardRespPayload, errors::VaultError> {
let locker = &state.conf.locker;
let jwekey = state.conf.jwekey.get_inner();
let db = &*state.store;
let stored_card_response = if !locker.mock_locker {
let request = payment_methods::mk_add_locker_request_hs(
jwekey,
locker,
payload,
locker_choice,
state.tenant.tenant_id.clone(),
state.request_id,
)
.await?;
call_locker_api::<payment_methods::StoreCardResp>(
state,
request,
"add_card_to_hs_locker",
Some(locker_choice),
)
.await
.change_context(errors::VaultError::SaveCardFailed)?
} else {
let card_id = generate_id(consts::ID_LENGTH, "card");
mock_call_to_locker_hs(db, &card_id, payload, None, None, Some(customer_id)).await?
};
let stored_card = stored_card_response
.payload
.get_required_value("StoreCardRespPayload")
.change_context(errors::VaultError::SaveCardFailed)?;
Ok(stored_card)
}
<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/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/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/core/payment_link.rs<|crate|> router anchor=initiate_payment_link_flow kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/payment_link.rs" role="context" start="411" end="456">
pub async fn initiate_payment_link_flow(
state: SessionState,
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
merchant_id: common_utils::id_type::MerchantId,
payment_id: common_utils::id_type::PaymentId,
) -> RouterResponse<services::PaymentLinkFormData> {
let (_, payment_details, payment_link_config) =
form_payment_link_data(&state, merchant_account, key_store, merchant_id, payment_id)
.await?;
let css_script = get_color_scheme_css(&payment_link_config);
let js_script = get_js_script(&payment_details)?;
match payment_details {
PaymentLinkData::PaymentLinkStatusDetails(status_details) => {
let payment_link_error_data = services::PaymentLinkStatusData {
js_script,
css_script,
};
logger::info!(
"payment link data, for building payment link status page {:?}",
status_details
);
Ok(services::ApplicationResponse::PaymentLinkForm(Box::new(
services::api::PaymentLinkAction::PaymentLinkStatus(payment_link_error_data),
)))
}
PaymentLinkData::PaymentLinkDetails(payment_details) => {
let html_meta_tags = get_meta_tags_html(&payment_details);
let payment_link_data = services::PaymentLinkFormData {
js_script,
sdk_url: state.conf.payment_link.sdk_url.clone(),
css_script,
html_meta_tags,
};
logger::info!(
"payment link data, for building open payment link {:?}",
payment_link_data
);
Ok(services::ApplicationResponse::PaymentLinkForm(Box::new(
services::api::PaymentLinkAction::PaymentLinkFormData(payment_link_data),
)))
}
}
}
<file_sep path="hyperswitch/crates/router/src/core/payment_link.rs" role="context" start="410" end="410">
use api_models::{
admin::PaymentLinkConfig,
payments::{PaymentLinkData, PaymentLinkStatusWrap},
};
use common_utils::{
consts::{DEFAULT_LOCALE, DEFAULT_SESSION_EXPIRY},
ext_traits::{OptionExt, ValueExt},
types::{AmountConvertor, StringMajorUnitForCore},
};
use hyperswitch_domain_models::api::{GenericLinks, GenericLinksData};
use router_env::logger;
use crate::{
consts::{
self, DEFAULT_ALLOWED_DOMAINS, DEFAULT_BACKGROUND_COLOR, DEFAULT_DISPLAY_SDK_ONLY,
DEFAULT_ENABLE_BUTTON_ONLY_ON_FORM_READY, DEFAULT_ENABLE_SAVED_PAYMENT_METHOD,
DEFAULT_HIDE_CARD_NICKNAME_FIELD, DEFAULT_MERCHANT_LOGO, DEFAULT_PRODUCT_IMG,
DEFAULT_SDK_LAYOUT, DEFAULT_SHOW_CARD_FORM,
},
errors::RouterResponse,
get_payment_link_config_value, get_payment_link_config_value_based_on_priority,
routes::SessionState,
services,
types::{
api::payment_link::PaymentLinkResponseExt,
domain,
storage::{enums as storage_enums, payment_link::PaymentLink},
transformers::{ForeignFrom, ForeignInto},
},
};
<file_sep path="hyperswitch/crates/router/src/core/payment_link.rs" role="context" start="469" end="479">
fn get_color_scheme_css(payment_link_config: &PaymentLinkConfig) -> String {
let background_primary_color = payment_link_config
.background_colour
.clone()
.unwrap_or(payment_link_config.theme.clone());
format!(
":root {{
--primary-color: {background_primary_color};
}}"
)
}
<file_sep path="hyperswitch/crates/router/src/core/payment_link.rs" role="context" start="462" end="467">
fn get_js_script(payment_details: &PaymentLinkData) -> RouterResult<String> {
let payment_details_str = serde_json::to_string(payment_details)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to serialize PaymentLinkData")?;
Ok(format!("window.__PAYMENT_DETAILS = {payment_details_str};"))
}
<file_sep path="hyperswitch/crates/router/src/core/payment_link.rs" role="context" start="308" end="409">
pub async fn initiate_secure_payment_link_flow(
state: SessionState,
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
merchant_id: common_utils::id_type::MerchantId,
payment_id: common_utils::id_type::PaymentId,
request_headers: &header::HeaderMap,
) -> RouterResponse<services::PaymentLinkFormData> {
let (payment_link, payment_link_details, payment_link_config) =
form_payment_link_data(&state, merchant_account, key_store, merchant_id, payment_id)
.await?;
validator::validate_secure_payment_link_render_request(
request_headers,
&payment_link,
&payment_link_config,
)?;
let css_script = get_color_scheme_css(&payment_link_config);
match payment_link_details {
PaymentLinkData::PaymentLinkStatusDetails(ref status_details) => {
let js_script = get_js_script(&payment_link_details)?;
let payment_link_error_data = services::PaymentLinkStatusData {
js_script,
css_script,
};
logger::info!(
"payment link data, for building payment link status page {:?}",
status_details
);
Ok(services::ApplicationResponse::PaymentLinkForm(Box::new(
services::api::PaymentLinkAction::PaymentLinkStatus(payment_link_error_data),
)))
}
PaymentLinkData::PaymentLinkDetails(link_details) => {
let secure_payment_link_details = api_models::payments::SecurePaymentLinkDetails {
enabled_saved_payment_method: payment_link_config.enabled_saved_payment_method,
hide_card_nickname_field: payment_link_config.hide_card_nickname_field,
show_card_form_by_default: payment_link_config.show_card_form_by_default,
payment_link_details: *link_details.to_owned(),
payment_button_text: payment_link_config.payment_button_text,
custom_message_for_card_terms: payment_link_config.custom_message_for_card_terms,
payment_button_colour: payment_link_config.payment_button_colour,
skip_status_screen: payment_link_config.skip_status_screen,
background_colour: payment_link_config.background_colour,
payment_button_text_colour: payment_link_config.payment_button_text_colour,
sdk_ui_rules: payment_link_config.sdk_ui_rules,
payment_link_ui_rules: payment_link_config.payment_link_ui_rules,
enable_button_only_on_form_ready: payment_link_config
.enable_button_only_on_form_ready,
};
let js_script = format!(
"window.__PAYMENT_DETAILS = {}",
serde_json::to_string(&secure_payment_link_details)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to serialize PaymentLinkData")?
);
let html_meta_tags = get_meta_tags_html(&link_details);
let payment_link_data = services::PaymentLinkFormData {
js_script,
sdk_url: state.conf.payment_link.sdk_url.clone(),
css_script,
html_meta_tags,
};
let allowed_domains = payment_link_config
.allowed_domains
.clone()
.ok_or(report!(errors::ApiErrorResponse::InternalServerError))
.attach_printable_lazy(|| {
format!(
"Invalid list of allowed_domains found - {:?}",
payment_link_config.allowed_domains.clone()
)
})?;
if allowed_domains.is_empty() {
return Err(report!(errors::ApiErrorResponse::InternalServerError))
.attach_printable_lazy(|| {
format!(
"Invalid list of allowed_domains found - {:?}",
payment_link_config.allowed_domains.clone()
)
});
}
let link_data = GenericLinks {
allowed_domains,
data: GenericLinksData::SecurePaymentLink(payment_link_data),
locale: DEFAULT_LOCALE.to_string(),
};
logger::info!(
"payment link data, for building secure payment link {:?}",
link_data
);
Ok(services::ApplicationResponse::GenericLinkForm(Box::new(
link_data,
)))
}
}
}
<file_sep path="hyperswitch/crates/router/src/core/payment_link.rs" role="context" start="78" end="306">
pub async fn form_payment_link_data(
state: &SessionState,
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
merchant_id: common_utils::id_type::MerchantId,
payment_id: common_utils::id_type::PaymentId,
) -> RouterResult<(PaymentLink, PaymentLinkData, PaymentLinkConfig)> {
let db = &*state.store;
let key_manager_state = &state.into();
let payment_intent = db
.find_payment_intent_by_payment_id_merchant_id(
&(state).into(),
&payment_id,
&merchant_id,
&key_store,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
let payment_link_id = payment_intent
.payment_link_id
.get_required_value("payment_link_id")
.change_context(errors::ApiErrorResponse::PaymentLinkNotFound)?;
let merchant_name_from_merchant_account = merchant_account
.merchant_name
.clone()
.map(|merchant_name| merchant_name.into_inner().peek().to_owned())
.unwrap_or_default();
let payment_link = db
.find_payment_link_by_payment_link_id(&payment_link_id)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentLinkNotFound)?;
let payment_link_config =
if let Some(pl_config_value) = payment_link.payment_link_config.clone() {
extract_payment_link_config(pl_config_value)?
} else {
PaymentLinkConfig {
theme: DEFAULT_BACKGROUND_COLOR.to_string(),
logo: DEFAULT_MERCHANT_LOGO.to_string(),
seller_name: merchant_name_from_merchant_account,
sdk_layout: DEFAULT_SDK_LAYOUT.to_owned(),
display_sdk_only: DEFAULT_DISPLAY_SDK_ONLY,
enabled_saved_payment_method: DEFAULT_ENABLE_SAVED_PAYMENT_METHOD,
hide_card_nickname_field: DEFAULT_HIDE_CARD_NICKNAME_FIELD,
show_card_form_by_default: DEFAULT_SHOW_CARD_FORM,
allowed_domains: DEFAULT_ALLOWED_DOMAINS,
transaction_details: None,
background_image: None,
details_layout: None,
branding_visibility: None,
payment_button_text: None,
custom_message_for_card_terms: None,
payment_button_colour: None,
skip_status_screen: None,
background_colour: None,
payment_button_text_colour: None,
sdk_ui_rules: None,
payment_link_ui_rules: None,
enable_button_only_on_form_ready: DEFAULT_ENABLE_BUTTON_ONLY_ON_FORM_READY,
}
};
let profile_id = payment_link
.profile_id
.clone()
.or(payment_intent.profile_id)
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Profile id missing in payment link and payment intent")?;
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(),
})?;
let return_url = if let Some(payment_create_return_url) = payment_intent.return_url.clone() {
payment_create_return_url
} else {
business_profile
.return_url
.ok_or(errors::ApiErrorResponse::MissingRequiredField {
field_name: "return_url",
})?
};
let (currency, client_secret) = validate_sdk_requirements(
payment_intent.currency,
payment_intent.client_secret.clone(),
)?;
let required_conversion_type = StringMajorUnitForCore;
let amount = required_conversion_type
.convert(payment_intent.amount, currency)
.change_context(errors::ApiErrorResponse::AmountConversionFailed {
amount_type: "StringMajorUnit",
})?;
let order_details = validate_order_details(payment_intent.order_details.clone(), currency)?;
let session_expiry = payment_link.fulfilment_time.unwrap_or_else(|| {
payment_intent
.created_at
.saturating_add(time::Duration::seconds(DEFAULT_SESSION_EXPIRY))
});
// converting first letter of merchant name to upperCase
let merchant_name = capitalize_first_char(&payment_link_config.seller_name);
let payment_link_status = check_payment_link_status(session_expiry);
let is_payment_link_terminal_state = check_payment_link_invalid_conditions(
payment_intent.status,
&[
storage_enums::IntentStatus::Cancelled,
storage_enums::IntentStatus::Failed,
storage_enums::IntentStatus::Processing,
storage_enums::IntentStatus::RequiresCapture,
storage_enums::IntentStatus::RequiresMerchantAction,
storage_enums::IntentStatus::Succeeded,
storage_enums::IntentStatus::PartiallyCaptured,
storage_enums::IntentStatus::RequiresCustomerAction,
],
);
if is_payment_link_terminal_state
|| payment_link_status == api_models::payments::PaymentLinkStatus::Expired
{
let status = match payment_link_status {
api_models::payments::PaymentLinkStatus::Active => {
logger::info!("displaying status page as the requested payment link has reached terminal state with payment status as {:?}", payment_intent.status);
PaymentLinkStatusWrap::IntentStatus(payment_intent.status)
}
api_models::payments::PaymentLinkStatus::Expired => {
if is_payment_link_terminal_state {
logger::info!("displaying status page as the requested payment link has reached terminal state with payment status as {:?}", payment_intent.status);
PaymentLinkStatusWrap::IntentStatus(payment_intent.status)
} else {
logger::info!(
"displaying status page as the requested payment link has expired"
);
PaymentLinkStatusWrap::PaymentLinkStatus(
api_models::payments::PaymentLinkStatus::Expired,
)
}
}
};
let attempt_id = payment_intent.active_attempt.get_id().clone();
let payment_attempt = db
.find_payment_attempt_by_payment_id_merchant_id_attempt_id(
&payment_intent.payment_id,
&merchant_id,
&attempt_id.clone(),
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
let payment_details = api_models::payments::PaymentLinkStatusDetails {
amount,
currency,
payment_id: payment_intent.payment_id,
merchant_name,
merchant_logo: payment_link_config.logo.clone(),
created: payment_link.created_at,
status,
error_code: payment_attempt.error_code,
error_message: payment_attempt.error_message,
redirect: false,
theme: payment_link_config.theme.clone(),
return_url: return_url.clone(),
locale: Some(state.clone().locale),
transaction_details: payment_link_config.transaction_details.clone(),
unified_code: payment_attempt.unified_code,
unified_message: payment_attempt.unified_message,
};
return Ok((
payment_link,
PaymentLinkData::PaymentLinkStatusDetails(Box::new(payment_details)),
payment_link_config,
));
};
let payment_link_details = api_models::payments::PaymentLinkDetails {
amount,
currency,
payment_id: payment_intent.payment_id,
merchant_name,
order_details,
return_url,
session_expiry,
pub_key: merchant_account.publishable_key,
client_secret,
merchant_logo: payment_link_config.logo.clone(),
max_items_visible_after_collapse: 3,
theme: payment_link_config.theme.clone(),
merchant_description: payment_intent.description,
sdk_layout: payment_link_config.sdk_layout.clone(),
display_sdk_only: payment_link_config.display_sdk_only,
hide_card_nickname_field: payment_link_config.hide_card_nickname_field,
show_card_form_by_default: payment_link_config.show_card_form_by_default,
locale: Some(state.clone().locale),
transaction_details: payment_link_config.transaction_details.clone(),
background_image: payment_link_config.background_image.clone(),
details_layout: payment_link_config.details_layout,
branding_visibility: payment_link_config.branding_visibility,
payment_button_text: payment_link_config.payment_button_text.clone(),
custom_message_for_card_terms: payment_link_config.custom_message_for_card_terms.clone(),
payment_button_colour: payment_link_config.payment_button_colour.clone(),
skip_status_screen: payment_link_config.skip_status_screen,
background_colour: payment_link_config.background_colour.clone(),
payment_button_text_colour: payment_link_config.payment_button_text_colour.clone(),
sdk_ui_rules: payment_link_config.sdk_ui_rules.clone(),
payment_link_ui_rules: payment_link_config.payment_link_ui_rules.clone(),
status: payment_intent.status,
enable_button_only_on_form_ready: payment_link_config.enable_button_only_on_form_ready,
};
Ok((
payment_link,
PaymentLinkData::PaymentLinkDetails(Box::new(payment_link_details)),
payment_link_config,
))
}
<file_sep path="hyperswitch/crates/router/src/core/payment_link.rs" role="context" start="481" end="491">
fn get_meta_tags_html(payment_details: &api_models::payments::PaymentLinkDetails) -> String {
format!(
r#"<meta property="og:title" content="Payment request from {0}"/>
<meta property="og:description" content="{1}"/>"#,
payment_details.merchant_name.clone(),
payment_details
.merchant_description
.clone()
.unwrap_or_default()
)
}
<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/admin.rs" role="context" start="698" end="700">
pub struct MerchantId {
pub merchant_id: id_type::MerchantId,
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/routes/app.rs<|crate|> router anchor=with_storage kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/routes/app.rs" role="context" start="308" end="418">
pub async fn with_storage(
conf: settings::Settings<SecuredSecret>,
storage_impl: StorageImpl,
shut_down_signal: oneshot::Sender<()>,
api_client: Box<dyn crate::services::ApiClient>,
) -> Self {
#[allow(clippy::expect_used)]
let secret_management_client = conf
.secrets_management
.get_secret_management_client()
.await
.expect("Failed to create secret management client");
let conf = Box::pin(secrets_transformers::fetch_raw_secrets(
conf,
&*secret_management_client,
))
.await;
#[allow(clippy::expect_used)]
let encryption_client = conf
.encryption_management
.get_encryption_management_client()
.await
.expect("Failed to create encryption client");
Box::pin(async move {
let testable = storage_impl == StorageImpl::PostgresqlTest;
#[allow(clippy::expect_used)]
let event_handler = conf
.events
.get_event_handler()
.await
.expect("Failed to create event handler");
#[allow(clippy::expect_used)]
#[cfg(feature = "olap")]
let opensearch_client = conf
.opensearch
.get_opensearch_client()
.await
.expect("Failed to initialize OpenSearch client.")
.map(Arc::new);
#[allow(clippy::expect_used)]
let cache_store = get_cache_store(&conf.clone(), shut_down_signal, testable)
.await
.expect("Failed to create store");
let global_store: Box<dyn GlobalStorageInterface> = Self::get_store_interface(
&storage_impl,
&event_handler,
&conf,
&conf.multitenancy.global_tenant,
Arc::clone(&cache_store),
testable,
)
.await
.get_global_storage_interface();
#[cfg(feature = "olap")]
let pools = conf
.multitenancy
.tenants
.get_pools_map(conf.analytics.get_inner())
.await;
let stores = conf
.multitenancy
.tenants
.get_store_interface_map(&storage_impl, &conf, Arc::clone(&cache_store), testable)
.await;
let accounts_store = conf
.multitenancy
.tenants
.get_accounts_store_interface_map(
&storage_impl,
&conf,
Arc::clone(&cache_store),
testable,
)
.await;
#[cfg(feature = "email")]
let email_client = Arc::new(create_email_client(&conf).await);
let file_storage_client = conf.file_storage.get_file_storage_client().await;
let theme_storage_client = conf.theme.storage.get_file_storage_client().await;
let grpc_client = conf.grpc_client.get_grpc_client_interface().await;
Self {
flow_name: String::from("default"),
stores,
global_store,
accounts_store,
conf: Arc::new(conf),
#[cfg(feature = "email")]
email_client,
api_client,
event_handler,
#[cfg(feature = "olap")]
pools,
#[cfg(feature = "olap")]
opensearch_client,
request_id: None,
file_storage_client,
encryption_client,
grpc_client,
theme_storage_client,
}
})
.await
}
<file_sep path="hyperswitch/crates/router/src/routes/app.rs" role="context" start="307" end="307">
use std::{collections::HashMap, sync::Arc};
use external_services::email::{
no_email::NoEmailClient, ses::AwsSes, smtp::SmtpServer, EmailClientConfigs, EmailService,
};
use external_services::{
file_storage::FileStorageInterface,
grpc_client::{GrpcClients, GrpcHeaders},
};
use hyperswitch_interfaces::{
encryption_interface::EncryptionManagementInterface,
secrets_interface::secret_state::{RawSecret, SecuredSecret},
};
use storage_impl::{config::TenantConfig, redis::RedisStore, MockDb};
use tokio::sync::oneshot;
use self::settings::Tenant;
pub use crate::analytics::opensearch::OpenSearchClient;
use crate::analytics::AnalyticsProvider;
use crate::errors::RouterResult;
use crate::routes::cards_info::{
card_iin_info, create_cards_info, migrate_cards_info, update_cards_info,
};
use crate::routes::feature_matrix;
use crate::routes::fraud_check as frm_routes;
use crate::routes::recon as recon_routes;
pub use crate::{
configs::settings,
db::{
AccountsStorageInterface, CommonStorageInterface, GlobalStorageInterface, StorageImpl,
StorageInterface,
},
events::EventsHandler,
services::{get_cache_store, get_store},
};
use crate::{
configs::{secrets_transformers, Settings},
db::kafka_store::{KafkaStore, TenantID},
routes::hypersense as hypersense_routes,
};
<file_sep path="hyperswitch/crates/router/src/routes/app.rs" role="context" start="461" end="473">
pub async fn new(
conf: settings::Settings<SecuredSecret>,
shut_down_signal: oneshot::Sender<()>,
api_client: Box<dyn crate::services::ApiClient>,
) -> Self {
Box::pin(Self::with_storage(
conf,
StorageImpl::Postgresql,
shut_down_signal,
api_client,
))
.await
}
<file_sep path="hyperswitch/crates/router/src/routes/app.rs" role="context" start="423" end="459">
pub async fn get_store_interface(
storage_impl: &StorageImpl,
event_handler: &EventsHandler,
conf: &Settings,
tenant: &dyn TenantConfig,
cache_store: Arc<RedisStore>,
testable: bool,
) -> Box<dyn CommonStorageInterface> {
match storage_impl {
StorageImpl::Postgresql | StorageImpl::PostgresqlTest => match event_handler {
EventsHandler::Kafka(kafka_client) => Box::new(
KafkaStore::new(
#[allow(clippy::expect_used)]
get_store(&conf.clone(), tenant, Arc::clone(&cache_store), testable)
.await
.expect("Failed to create store"),
kafka_client.clone(),
TenantID(tenant.get_tenant_id().get_string_repr().to_owned()),
tenant,
)
.await,
),
EventsHandler::Logs(_) => Box::new(
#[allow(clippy::expect_used)]
get_store(conf, tenant, Arc::clone(&cache_store), testable)
.await
.expect("Failed to create store"),
),
},
#[allow(clippy::expect_used)]
StorageImpl::Mock => Box::new(
MockDb::new(&conf.redis)
.await
.expect("Failed to create mock store"),
),
}
}
<file_sep path="hyperswitch/crates/router/src/routes/app.rs" role="context" start="285" end="302">
pub async fn create_email_client(
settings: &settings::Settings<RawSecret>,
) -> Box<dyn EmailService> {
match &settings.email.client_config {
EmailClientConfigs::Ses { aws_ses } => Box::new(
AwsSes::create(
&settings.email,
aws_ses,
settings.proxy.https_url.to_owned(),
)
.await,
),
EmailClientConfigs::Smtp { smtp } => {
Box::new(SmtpServer::create(&settings.email, smtp.clone()).await)
}
EmailClientConfigs::NoEmailClient => Box::new(NoEmailClient::create().await),
}
}
<file_sep path="hyperswitch/crates/router/src/routes/app.rs" role="context" start="279" end="281">
fn as_ref(&self) -> &Self {
self
}
<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/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/connector/stripe/transformers.rs<|crate|> router anchor=get_missing_fields 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="4420" end="4426">
fn get_missing_fields(connector_error: &errors::ConnectorError) -> Vec<&'static str> {
if let errors::ConnectorError::MissingRequiredFields { field_names } = connector_error {
return field_names.to_vec();
}
vec![]
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="4419" end="4419">
use common_utils::{
errors::CustomResult,
ext_traits::{ByteSliceExt, Encode},
pii::{self, Email},
request::RequestContent,
types::MinorUnit,
};
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="4428" end="4444">
fn create_stripe_shipping_address(
name: String,
line1: Option<String>,
country: Option<CountryAlpha2>,
zip: Option<String>,
) -> StripeShippingAddress {
StripeShippingAddress {
name: Secret::new(name),
line1: line1.map(Secret::new),
country,
zip: zip.map(Secret::new),
city: Some(String::from("city")),
line2: Some(Secret::new(String::from("line2"))),
state: Some(Secret::new(String::from("state"))),
phone: Some(Secret::new(String::from("pbone number"))),
}
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="4394" end="4418">
fn should_return_error_when_missing_multiple_fields() {
// Arrange
let expected_missing_field_names: Vec<&'static str> =
vec!["shipping.address.zip", "shipping.address.country"];
let stripe_shipping_address = create_stripe_shipping_address(
"name".to_string(),
Some("line1".to_string()),
None,
None,
);
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();
for field in missing_fields {
assert!(expected_missing_field_names.contains(&field));
}
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="4370" end="4391">
fn should_return_err_for_empty_zip() {
// Arrange
let stripe_shipping_address = create_stripe_shipping_address(
"name".to_string(),
Some("line1".to_string()),
Some(CountryAlpha2::AD),
None,
);
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.zip");
}
<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");
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/ebanx/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/ebanx/transformers.rs" role="context" start="389" end="403">
fn try_from(
item: types::PayoutsResponseRouterData<F, EbanxCancelResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(types::PayoutsResponseData {
status: Some(storage_enums::PayoutStatus::from(item.response.status)),
connector_payout_id: item.data.request.connector_payout_id.clone(),
payout_eligible: None,
should_add_next_step_to_process_tracker: false,
error_code: None,
error_message: None,
}),
..item.data
})
}
<file_sep path="hyperswitch/crates/router/src/connector/ebanx/transformers.rs" role="context" start="388" end="388">
use common_utils::types::FloatMajorUnit;
use crate::{
connector::utils::{AddressDetailsData, RouterData},
connector::utils::{CustomerDetails, PayoutsData},
types::{api, storage::enums as storage_enums},
};
use crate::{core::errors, types};
<file_sep path="hyperswitch/crates/router/src/connector/ebanx/transformers.rs" role="context" start="373" end="381">
fn from(item: EbanxCancelStatus) -> Self {
match item {
EbanxCancelStatus::Success => Self::Cancelled,
EbanxCancelStatus::ApiError
| EbanxCancelStatus::AuthenticationError
| EbanxCancelStatus::InvalidRequestError
| EbanxCancelStatus::RequestError => Self::Failed,
}
}
<file_sep path="hyperswitch/crates/router/src/connector/ebanx/transformers.rs" role="context" start="330" end="349">
fn try_from(item: &types::PayoutsRouterData<F>) -> Result<Self, Self::Error> {
let request = item.request.to_owned();
let ebanx_auth_type = EbanxAuthType::try_from(&item.connector_auth_type)?;
let payout_type = request.get_payout_type()?;
match payout_type {
storage_enums::PayoutType::Bank => Ok(Self {
integration_key: ebanx_auth_type.integration_key,
uid: request
.connector_payout_id
.to_owned()
.ok_or(errors::ConnectorError::MissingRequiredField { field_name: "uid" })?,
}),
storage_enums::PayoutType::Card | storage_enums::PayoutType::Wallet => {
Err(errors::ConnectorError::NotSupported {
message: "Payout Method Not Supported".to_string(),
connector: "Ebanx",
})?
}
}
}
<file_sep path="hyperswitch/crates/router/src/connector/ebanx/transformers.rs" role="context" start="97" end="146">
fn try_from(
item: &EbanxRouterData<&types::PayoutsRouterData<api::PoCreate>>,
) -> Result<Self, Self::Error> {
let ebanx_auth_type = EbanxAuthType::try_from(&item.router_data.connector_auth_type)?;
match item.router_data.get_payout_method_data()? {
PayoutMethodData::Bank(Bank::Pix(pix_data)) => {
let bank_info = EbanxBankDetails {
bank_account: Some(pix_data.bank_account_number),
bank_branch: pix_data.bank_branch,
bank_name: pix_data.bank_name,
account_type: Some(EbanxBankAccountType::CheckingAccount),
};
let billing_address = item.router_data.get_billing_address()?;
let customer_details = item.router_data.request.get_customer_details()?;
let document_type = pix_data.tax_id.clone().map(|tax_id| {
if tax_id.clone().expose().len() == 11 {
EbanxDocumentType::NaturalPersonsRegister
} else {
EbanxDocumentType::NationalRegistryOfLegalEntities
}
});
let payee = EbanxPayoutDetails {
name: billing_address.get_full_name()?,
email: customer_details.email.clone(),
bank_info,
document_type,
document: pix_data.tax_id.to_owned(),
};
Ok(Self {
amount: item.amount,
integration_key: ebanx_auth_type.integration_key,
country: customer_details.get_customer_phone_country_code()?,
currency: item.router_data.request.source_currency,
external_reference: item.router_data.connector_request_reference_id.to_owned(),
target: EbanxPayoutType::PixKey,
target_account: pix_data.pix_key,
payee,
})
}
PayoutMethodData::Card(_) | PayoutMethodData::Bank(_) | PayoutMethodData::Wallet(_) => {
Err(errors::ConnectorError::NotSupported {
message: "Payment Method Not Supported".to_string(),
connector: "Ebanx",
})?
}
}
}
<file_sep path="hyperswitch/crates/router/src/connector/ebanx/transformers.rs" role="context" start="96" end="96">
type Error = error_stack::Report<errors::ConnectorError>;
<file_sep path="hyperswitch/crates/router/src/connector/ebanx/transformers.rs" role="context" start="354" end="358">
pub struct EbanxCancelResponse {
#[serde(rename = "type")]
status: EbanxCancelStatus,
message: String,
}
<file_sep path="hyperswitch/crates/router/src/types.rs" role="context" start="229" end="230">
pub type PayoutsResponseRouterData<F, R> =
ResponseRouterData<F, R, PayoutsData, PayoutsResponseData>;
<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=get_transaction_metadata 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="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="4173" end="4173">
use std::{collections::HashMap, ops::Deref};
use masking::{ExposeInterface, ExposeOptionInterface, Mask, PeekInterface, Secret};
use serde_json::Value;
<file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="4240" end="4253">
pub(super) fn transform_headers_for_connect_platform(
charge_type: api::enums::PaymentChargeType,
transfer_account_id: String,
header: &mut Vec<(String, services::request::Maskable<String>)>,
) {
if let api::enums::PaymentChargeType::Stripe(api::enums::StripeChargeType::Direct) = charge_type
{
let mut customer_account_header = vec![(
headers::STRIPE_COMPATIBLE_CONNECT_ACCOUNT.to_string(),
transfer_account_id.into_masked(),
)];
header.append(&mut customer_account_header);
}
}
<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="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="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="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="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="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/api_models/src/payment_methods.rs" role="context" start="1670" end="1670">
type Value = PaymentMethodListRequest;
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/compatibility/stripe/webhooks.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/webhooks.rs" role="context" start="327" end="342">
fn from(value: api::OutgoingWebhookContent) -> Self {
match value {
api::OutgoingWebhookContent::PaymentDetails(payment) => {
Self::PaymentIntent(Box::new((*payment).into()))
}
api::OutgoingWebhookContent::RefundDetails(refund) => Self::Refund((*refund).into()),
api::OutgoingWebhookContent::DisputeDetails(dispute) => {
Self::Dispute((*dispute).into())
}
api::OutgoingWebhookContent::MandateDetails(mandate) => {
Self::Mandate((*mandate).into())
}
#[cfg(feature = "payouts")]
api::OutgoingWebhookContent::PayoutDetails(payout) => Self::Payout((*payout).into()),
}
}
<file_sep path="hyperswitch/crates/router/src/compatibility/stripe/webhooks.rs" role="context" start="326" end="326">
use api_models::payouts as payout_models;
use api_models::{
enums::{Currency, DisputeStatus, MandateStatus},
webhooks::{self as api},
};
<file_sep path="hyperswitch/crates/router/src/compatibility/stripe/webhooks.rs" role="context" start="303" end="323">
fn from(value: api::OutgoingWebhook) -> Self {
Self {
id: value.event_id,
stype: get_stripe_event_type(value.event_type),
data: StripeWebhookObject::from(value.content),
object: "event",
// put this conversion it into a function
created: u64::try_from(value.timestamp.assume_utc().unix_timestamp()).unwrap_or_else(
|error| {
logger::error!(
%error,
"incorrect value for `webhook.timestamp` provided {}", value.timestamp
);
// Current timestamp converted to Unix timestamp should have a positive value
// for many years to come
u64::try_from(date_time::now().assume_utc().unix_timestamp())
.unwrap_or_default()
},
),
}
}
<file_sep path="hyperswitch/crates/router/src/compatibility/stripe/webhooks.rs" role="context" start="265" end="300">
fn get_stripe_event_type(event_type: api_models::enums::EventType) -> &'static str {
match event_type {
api_models::enums::EventType::PaymentSucceeded => "payment_intent.succeeded",
api_models::enums::EventType::PaymentFailed => "payment_intent.payment_failed",
api_models::enums::EventType::PaymentProcessing => "payment_intent.processing",
api_models::enums::EventType::PaymentCancelled => "payment_intent.canceled",
// the below are not really stripe compatible because stripe doesn't provide this
api_models::enums::EventType::ActionRequired => "action.required",
api_models::enums::EventType::RefundSucceeded => "refund.succeeded",
api_models::enums::EventType::RefundFailed => "refund.failed",
api_models::enums::EventType::DisputeOpened => "dispute.failed",
api_models::enums::EventType::DisputeExpired => "dispute.expired",
api_models::enums::EventType::DisputeAccepted => "dispute.accepted",
api_models::enums::EventType::DisputeCancelled => "dispute.cancelled",
api_models::enums::EventType::DisputeChallenged => "dispute.challenged",
api_models::enums::EventType::DisputeWon => "dispute.won",
api_models::enums::EventType::DisputeLost => "dispute.lost",
api_models::enums::EventType::MandateActive => "mandate.active",
api_models::enums::EventType::MandateRevoked => "mandate.revoked",
// as per this doc https://stripe.com/docs/api/events/types#event_types-payment_intent.amount_capturable_updated
api_models::enums::EventType::PaymentAuthorized => {
"payment_intent.amount_capturable_updated"
}
// stripe treats partially captured payments as succeeded.
api_models::enums::EventType::PaymentCaptured => "payment_intent.succeeded",
api_models::enums::EventType::PayoutSuccess => "payout.paid",
api_models::enums::EventType::PayoutFailed => "payout.failed",
api_models::enums::EventType::PayoutInitiated => "payout.created",
api_models::enums::EventType::PayoutCancelled => "payout.canceled",
api_models::enums::EventType::PayoutProcessing => "payout.created",
api_models::enums::EventType::PayoutExpired => "payout.failed",
api_models::enums::EventType::PayoutReversed => "payout.reconciliation_completed",
}
}
<file_sep path="hyperswitch/crates/router/src/compatibility/stripe/webhooks.rs" role="context" start="218" end="227">
fn from(res: api_models::disputes::DisputeResponse) -> Self {
Self {
id: res.dispute_id,
amount: res.amount,
currency: res.currency,
payment_intent: res.payment_id,
reason: res.connector_reason,
status: StripeDisputeStatus::from(res.dispute_status),
}
}
<file_sep path="hyperswitch/v2_compatible_migrations/2024-08-28-081721_add_v2_columns/up.sql" role="context" start="59" end="70">
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/webhooks.rs" role="context" start="337" end="349">
pub enum OutgoingWebhookContent {
#[schema(value_type = PaymentsResponse, title = "PaymentsResponse")]
PaymentDetails(Box<payments::PaymentsResponse>),
#[schema(value_type = RefundResponse, title = "RefundResponse")]
RefundDetails(Box<refunds::RefundResponse>),
#[schema(value_type = DisputeResponse, title = "DisputeResponse")]
DisputeDetails(Box<disputes::DisputeResponse>),
#[schema(value_type = MandateResponse, title = "MandateResponse")]
MandateDetails(Box<mandates::MandateResponse>),
#[cfg(feature = "payouts")]
#[schema(value_type = PayoutCreateResponse, title = "PayoutCreateResponse")]
PayoutDetails(Box<payouts::PayoutCreateResponse>),
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/services/email/types.rs<|crate|> router anchor=get_email_data 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="343" end="378">
async fn get_email_data(&self, base_url: &str) -> CustomResult<EmailContents, EmailError> {
let token = EmailToken::new_token(
self.recipient_email.clone(),
None,
domain::Origin::VerifyEmail,
&self.settings,
)
.await
.change_context(EmailError::TokenGenerationFailure)?;
let verify_email_link = get_link_with_token(
base_url,
token,
"verify_email",
&self.auth_id,
&self.theme_id,
);
let body = html::get_html_body(EmailBody::Verify {
link: verify_email_link,
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!(
"Welcome to the {} 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="342" end="342">
use common_utils::{errors::CustomResult, pii, types::theme::EmailThemeConfig};
use external_services::email::{EmailContents, EmailData, EmailError};
use crate::{
core::errors::{UserErrors, UserResult},
services::jwt,
types::domain,
};
<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/router/src/services/email/types.rs" role="context" start="324" end="330">
pub fn get_base_url(state: &SessionState) -> &str {
if !state.conf.multitenancy.enabled {
&state.conf.user.base_url
} else {
&state.tenant.user.control_center_url
}
}
<file_sep path="hyperswitch/crates/router/src/services/email/types.rs" role="context" start="306" end="322">
pub fn get_link_with_token(
base_url: impl std::fmt::Display,
token: impl std::fmt::Display,
action: impl std::fmt::Display,
auth_id: &Option<impl std::fmt::Display>,
theme_id: &Option<impl std::fmt::Display>,
) -> String {
let mut email_url = format!("{base_url}/user/{action}?token={token}");
if let Some(auth_id) = auth_id {
email_url = format!("{email_url}&auth_id={auth_id}");
}
if let Some(theme_id) = theme_id {
email_url = format!("{email_url}&theme_id={theme_id}");
}
email_url
}
<file_sep path="hyperswitch/crates/router/src/services/email/types.rs" role="context" start="274" end="289">
pub async fn new_token(
email: domain::UserEmail,
entity: Option<Entity>,
flow: domain::Origin,
settings: &configs::Settings,
) -> UserResult<String> {
let expiration_duration = std::time::Duration::from_secs(consts::EMAIL_TOKEN_TIME_IN_SECS);
let exp = jwt::generate_exp(expiration_duration)?.as_secs();
let token_payload = Self {
email: email.get_secret().expose(),
flow,
exp,
entity,
};
jwt::generate_jwt(&token_payload, settings).await
}
<file_sep path="hyperswitch/crates/router/src/services/email/types.rs" role="context" start="89" end="246">
pub fn get_html_body(email_body: EmailBody) -> String {
match email_body {
EmailBody::Verify {
link,
entity_name,
entity_logo_url,
primary_color,
background_color,
foreground_color,
} => {
format!(
include_str!("assets/verify.html"),
link = link,
entity_name = entity_name,
entity_logo_url = entity_logo_url,
primary_color = primary_color,
background_color = background_color,
foreground_color = foreground_color
)
}
EmailBody::Reset {
link,
user_name,
entity_name,
entity_logo_url,
primary_color,
background_color,
foreground_color,
} => {
format!(
include_str!("assets/reset.html"),
link = link,
username = user_name,
entity_name = entity_name,
entity_logo_url = entity_logo_url,
primary_color = primary_color,
background_color = background_color,
foreground_color = foreground_color
)
}
EmailBody::MagicLink {
link,
user_name,
entity_name,
entity_logo_url,
primary_color,
background_color,
foreground_color,
} => {
format!(
include_str!("assets/magic_link.html"),
username = user_name,
link = link,
entity_name = entity_name,
entity_logo_url = entity_logo_url,
primary_color = primary_color,
background_color = background_color,
foreground_color = foreground_color
)
}
EmailBody::InviteUser {
link,
user_name,
entity_name,
entity_logo_url,
primary_color,
background_color,
foreground_color,
} => {
format!(
include_str!("assets/invite.html"),
username = user_name,
link = link,
entity_name = entity_name,
entity_logo_url = entity_logo_url,
primary_color = primary_color,
background_color = background_color,
foreground_color = foreground_color
)
}
// TODO: Change the linked html for accept invite from email
EmailBody::AcceptInviteFromEmail {
link,
user_name,
entity_name,
entity_logo_url,
primary_color,
background_color,
foreground_color,
} => {
format!(
include_str!("assets/invite.html"),
username = user_name,
link = link,
entity_name = entity_name,
entity_logo_url = entity_logo_url,
primary_color = primary_color,
background_color = background_color,
foreground_color = foreground_color
)
}
EmailBody::ReconActivation { user_name } => {
format!(
include_str!("assets/recon_activation.html"),
username = user_name,
)
}
EmailBody::BizEmailProd {
user_name,
poc_email,
legal_business_name,
business_location,
business_website,
product_type,
} => {
format!(
include_str!("assets/bizemailprod.html"),
poc_email = poc_email,
legal_business_name = legal_business_name,
business_location = business_location,
business_website = business_website,
username = user_name,
product_type = product_type
)
}
EmailBody::ProFeatureRequest {
feature_name,
merchant_id,
user_name,
user_email,
} => format!(
"Dear Hyperswitch Support Team,
Dashboard Pro Feature Request,
Feature name : {feature_name}
Merchant ID : {}
Merchant Name : {user_name}
Email : {user_email}
(note: This is an auto generated email. Use merchant email for any further communications)",
merchant_id.get_string_repr()
),
EmailBody::ApiKeyExpiryReminder {
expires_in,
api_key_name,
prefix,
} => format!(
include_str!("assets/api_key_expiry_reminder.html"),
api_key_name = api_key_name,
prefix = prefix,
expires_in = expires_in,
),
EmailBody::WelcomeToCommunity => {
include_str!("assets/welcome_to_community.html").to_string()
}
}
}
<file_sep path="hyperswitch/crates/router/src/services/email/types.rs" role="context" start="332" end="338">
pub struct VerifyEmail {
pub recipient_email: domain::UserEmail,
pub settings: std::sync::Arc<configs::Settings>,
pub auth_id: Option<String>,
pub theme_id: Option<String>,
pub theme_config: EmailThemeConfig,
}
<file_sep path="hyperswitch/crates/router/src/services/email/types.rs" role="context" start="250" end="255">
pub struct EmailToken {
email: String,
flow: domain::Origin,
exp: u64,
entity: Option<Entity>,
}
<file_sep path="hyperswitch/crates/router/src/types/domain/user/decision_manager.rs" role="context" start="149" end="158">
pub enum Origin {
#[serde(rename = "sign_in_with_sso")]
SignInWithSSO,
SignIn,
SignUp,
MagicLink,
VerifyEmail,
AcceptInvitationFromEmail,
ResetPassword,
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/stripe/transformers.rs<|crate|> router anchor=foreign_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="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="4195" end="4195">
use common_utils::{
errors::CustomResult,
ext_traits::{ByteSliceExt, Encode},
pii::{self, Email},
request::RequestContent,
types::MinorUnit,
};
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="4255" end="4281">
pub fn construct_charge_response<T>(
charge_id: String,
request: &T,
) -> Option<common_types::payments::ConnectorChargeResponseData>
where
T: connector_util::SplitPaymentData,
{
let charge_request = request.get_split_payment_data();
if let Some(common_types::payments::SplitPaymentsRequest::StripeSplitPayment(
stripe_split_payment,
)) = charge_request
{
let stripe_charge_response = common_types::payments::StripeChargeResponseData {
charge_id: Some(charge_id),
charge_type: stripe_split_payment.charge_type,
application_fees: stripe_split_payment.application_fees,
transfer_account_id: stripe_split_payment.transfer_account_id,
};
Some(
common_types::payments::ConnectorChargeResponseData::StripeSplitPayment(
stripe_charge_response,
),
)
} else {
None
}
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="4240" end="4253">
pub(super) fn transform_headers_for_connect_platform(
charge_type: api::enums::PaymentChargeType,
transfer_account_id: String,
header: &mut Vec<(String, services::request::Maskable<String>)>,
) {
if let api::enums::PaymentChargeType::Stripe(api::enums::StripeChargeType::Direct) = charge_type
{
let mut customer_account_header = vec![(
headers::STRIPE_COMPATIBLE_CONNECT_ACCOUNT.to_string(),
transfer_account_id.into_masked(),
)];
header.append(&mut customer_account_header);
}
}
<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="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="2884" end="2951">
fn try_from(
item: types::ResponseRouterData<F, SetupIntentResponse, T, types::PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let redirect_data = item.response.next_action.clone();
let redirection_data = redirect_data
.and_then(|redirection_data| redirection_data.get_url())
.map(|redirection_url| {
services::RedirectForm::from((redirection_url, services::Method::Get))
});
let mandate_reference = item.response.payment_method.map(|payment_method_id| {
// Implemented Save and re-use payment information for recurring charges
// For more info: https://docs.stripe.com/recurring-payments#accept-recurring-payments
// For backward compatibility payment_method_id & connector_mandate_id is being populated with the same value
let connector_mandate_id = Some(payment_method_id.clone());
let payment_method_id = Some(payment_method_id);
types::MandateReference {
connector_mandate_id,
payment_method_id,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
}
});
let status = enums::AttemptStatus::from(item.response.status);
let connector_response_data = item
.response
.latest_attempt
.as_ref()
.and_then(extract_payment_method_connector_response_from_latest_attempt);
let response = if connector_util::is_payment_failure(status) {
types::PaymentsResponseData::foreign_try_from((
&item.response.last_setup_error,
item.http_code,
item.response.id.clone(),
))
} else {
let network_transaction_id = match item.response.latest_attempt {
Some(LatestAttempt::PaymentIntentAttempt(attempt)) => attempt
.payment_method_details
.and_then(|payment_method_details| match payment_method_details {
StripePaymentMethodDetailsResponse::Card { card } => {
card.network_transaction_id
}
_ => None,
}),
_ => None,
};
Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(mandate_reference),
connector_metadata: None,
network_txn_id: network_transaction_id,
connector_response_reference_id: Some(item.response.id),
incremental_authorization_allowed: None,
charges: None,
})
};
Ok(Self {
status,
response,
connector_response: connector_response_data,
..item.data
})
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="2741" end="2876">
fn try_from(
item: types::ResponseRouterData<
F,
PaymentIntentSyncResponse,
T,
types::PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let redirect_data = item.response.next_action.clone();
let redirection_data = redirect_data
.and_then(|redirection_data| redirection_data.get_url())
.map(|redirection_url| {
services::RedirectForm::from((redirection_url, services::Method::Get))
});
let mandate_reference = item
.response
.payment_method
.clone()
.map(|payment_method_id| {
// Implemented Save and re-use payment information for recurring charges
// For more info: https://docs.stripe.com/recurring-payments#accept-recurring-payments
// For backward compatibility payment_method_id & connector_mandate_id is being populated with the same value
let connector_mandate_id = Some(payment_method_id.clone().expose());
let payment_method_id = match item.response.latest_charge.clone() {
Some(StripeChargeEnum::ChargeObject(charge)) => {
match charge.payment_method_details {
Some(StripePaymentMethodDetailsResponse::Bancontact { bancontact }) => {
bancontact
.attached_payment_method
.map(|attached_payment_method| attached_payment_method.expose())
.unwrap_or(payment_method_id.expose())
}
Some(StripePaymentMethodDetailsResponse::Ideal { ideal }) => ideal
.attached_payment_method
.map(|attached_payment_method| attached_payment_method.expose())
.unwrap_or(payment_method_id.expose()),
Some(StripePaymentMethodDetailsResponse::Sofort { sofort }) => sofort
.attached_payment_method
.map(|attached_payment_method| attached_payment_method.expose())
.unwrap_or(payment_method_id.expose()),
Some(StripePaymentMethodDetailsResponse::Blik)
| Some(StripePaymentMethodDetailsResponse::Eps)
| Some(StripePaymentMethodDetailsResponse::Fpx)
| Some(StripePaymentMethodDetailsResponse::Giropay)
| Some(StripePaymentMethodDetailsResponse::Przelewy24)
| Some(StripePaymentMethodDetailsResponse::Card { .. })
| Some(StripePaymentMethodDetailsResponse::Klarna)
| Some(StripePaymentMethodDetailsResponse::Affirm)
| Some(StripePaymentMethodDetailsResponse::AfterpayClearpay)
| Some(StripePaymentMethodDetailsResponse::AmazonPay)
| Some(StripePaymentMethodDetailsResponse::ApplePay)
| Some(StripePaymentMethodDetailsResponse::Ach)
| Some(StripePaymentMethodDetailsResponse::Sepa)
| Some(StripePaymentMethodDetailsResponse::Becs)
| Some(StripePaymentMethodDetailsResponse::Bacs)
| Some(StripePaymentMethodDetailsResponse::Wechatpay)
| Some(StripePaymentMethodDetailsResponse::Alipay)
| Some(StripePaymentMethodDetailsResponse::CustomerBalance)
| Some(StripePaymentMethodDetailsResponse::Cashapp { .. })
| None => payment_method_id.expose(),
}
}
Some(StripeChargeEnum::ChargeId(_)) | None => payment_method_id.expose(),
};
types::MandateReference {
connector_mandate_id,
payment_method_id: Some(payment_method_id),
mandate_metadata: None,
connector_mandate_request_reference_id: None,
}
});
let connector_metadata =
get_connector_metadata(item.response.next_action.as_ref(), item.response.amount)?;
let status = enums::AttemptStatus::from(item.response.status.to_owned());
let connector_response_data = item
.response
.latest_charge
.as_ref()
.and_then(extract_payment_method_connector_response_from_latest_charge);
let response = if connector_util::is_payment_failure(status) {
types::PaymentsResponseData::foreign_try_from((
&item.response.payment_intent_fields.last_payment_error,
item.http_code,
item.response.id.clone(),
))
} else {
let network_transaction_id = match item.response.latest_charge.clone() {
Some(StripeChargeEnum::ChargeObject(charge_object)) => charge_object
.payment_method_details
.and_then(|payment_method_details| match payment_method_details {
StripePaymentMethodDetailsResponse::Card { card } => {
card.network_transaction_id
}
_ => None,
}),
_ => None,
};
let charges = item
.response
.latest_charge
.as_ref()
.map(|charge| match charge {
StripeChargeEnum::ChargeId(charges) => charges.clone(),
StripeChargeEnum::ChargeObject(charge) => charge.id.clone(),
})
.and_then(|charge_id| construct_charge_response(charge_id, &item.data.request));
Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(mandate_reference),
connector_metadata,
network_txn_id: network_transaction_id,
connector_response_reference_id: Some(item.response.id.clone()),
incremental_authorization_allowed: None,
charges,
})
};
Ok(Self {
status: enums::AttemptStatus::from(item.response.status.to_owned()),
response,
amount_captured: item
.response
.amount_received
.map(|amount| amount.get_amount_as_i64()),
minor_amount_captured: item.response.amount_received,
connector_response: connector_response_data,
..item.data
})
}
<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/connector/stripe/transformers.rs" role="context" start="3368" end="3370">
pub struct ErrorResponse {
pub error: ErrorDetails,
}
<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/core/payouts/retry.rs<|crate|> router anchor=do_gsm_single_connector_actions kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/payouts/retry.rs" role="context" start="91" end="151">
pub async fn do_gsm_single_connector_actions(
state: &app::SessionState,
original_connector_data: api::ConnectorData,
payout_data: &mut PayoutData,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
) -> RouterResult<()> {
let mut retries = None;
metrics::AUTO_PAYOUT_RETRY_ELIGIBLE_REQUEST_COUNT.add(1, &[]);
let mut previous_gsm = None; // to compare previous status
loop {
let gsm = get_gsm(state, &original_connector_data, payout_data).await?;
// if the error config is same as previous, we break out of the loop
if let Ordering::Equal = gsm.cmp(&previous_gsm) {
break;
}
previous_gsm.clone_from(&gsm);
match get_gsm_decision(gsm) {
api_models::gsm::GsmDecision::Retry => {
retries = get_retries(
state,
retries,
merchant_account.get_id(),
PayoutRetryType::SingleConnector,
)
.await;
if retries.is_none() || retries == Some(0) {
metrics::AUTO_PAYOUT_RETRY_EXHAUSTED_COUNT.add(1, &[]);
logger::info!("retries exhausted for auto_retry payment");
break;
}
Box::pin(do_retry(
&state.clone(),
original_connector_data.to_owned(),
merchant_account,
key_store,
payout_data,
))
.await?;
retries = retries.map(|i| i - 1);
}
api_models::gsm::GsmDecision::Requeue => {
Err(report!(errors::ApiErrorResponse::NotImplemented {
message: errors::NotImplementedMessage::Reason(
"Requeue not implemented".to_string(),
),
}))?
}
api_models::gsm::GsmDecision::DoDefault => break,
}
}
Ok(())
}
<file_sep path="hyperswitch/crates/router/src/core/payouts/retry.rs" role="context" start="90" end="90">
use std::{cmp::Ordering, str::FromStr, vec::IntoIter};
use common_enums::PayoutRetryType;
use error_stack::{report, ResultExt};
use router_env::{
logger,
tracing::{self, instrument},
};
use super::{call_connector_payout, PayoutData};
use crate::{
core::{
errors::{self, RouterResult, StorageErrorExt},
payouts,
},
db::StorageInterface,
routes::{self, app, metrics},
types::{api, domain, storage},
utils,
};
<file_sep path="hyperswitch/crates/router/src/core/payouts/retry.rs" role="context" start="185" end="202">
pub async fn get_gsm(
state: &app::SessionState,
original_connector_data: &api::ConnectorData,
payout_data: &PayoutData,
) -> RouterResult<Option<storage::gsm::GatewayStatusMap>> {
let error_code = payout_data.payout_attempt.error_code.to_owned();
let error_message = payout_data.payout_attempt.error_message.to_owned();
let connector_name = Some(original_connector_data.connector_name.to_string());
Ok(payouts::helpers::get_gsm_record(
state,
error_code,
error_message,
connector_name,
common_utils::consts::PAYOUT_FLOW_STR,
)
.await)
}
<file_sep path="hyperswitch/crates/router/src/core/payouts/retry.rs" role="context" start="154" end="182">
pub async fn get_retries(
state: &app::SessionState,
retries: Option<i32>,
merchant_id: &common_utils::id_type::MerchantId,
retry_type: PayoutRetryType,
) -> Option<i32> {
match retries {
Some(retries) => Some(retries),
None => {
let key = merchant_id.get_max_auto_single_connector_payout_retries_enabled(retry_type);
let db = &*state.store;
db.find_config_by_key(key.as_str())
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.and_then(|retries_config| {
retries_config
.config
.parse::<i32>()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Retries config parsing failed")
})
.map_err(|err| {
logger::error!(retries_error=?err);
None::<i32>
})
.ok()
}
}
}
<file_sep path="hyperswitch/crates/router/src/core/payouts/retry.rs" role="context" start="24" end="87">
pub async fn do_gsm_multiple_connector_actions(
state: &app::SessionState,
mut connectors: IntoIter<api::ConnectorData>,
original_connector_data: api::ConnectorData,
payout_data: &mut PayoutData,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
) -> RouterResult<()> {
let mut retries = None;
metrics::AUTO_PAYOUT_RETRY_ELIGIBLE_REQUEST_COUNT.add(1, &[]);
let mut connector = original_connector_data;
loop {
let gsm = get_gsm(state, &connector, payout_data).await?;
match get_gsm_decision(gsm) {
api_models::gsm::GsmDecision::Retry => {
retries = get_retries(
state,
retries,
merchant_account.get_id(),
PayoutRetryType::MultiConnector,
)
.await;
if retries.is_none() || retries == Some(0) {
metrics::AUTO_PAYOUT_RETRY_EXHAUSTED_COUNT.add(1, &[]);
logger::info!("retries exhausted for auto_retry payout");
break;
}
if connectors.len() == 0 {
logger::info!("connectors exhausted for auto_retry payout");
metrics::AUTO_PAYOUT_RETRY_EXHAUSTED_COUNT.add(1, &[]);
break;
}
connector = super::get_next_connector(&mut connectors)?;
Box::pin(do_retry(
&state.clone(),
connector.to_owned(),
merchant_account,
key_store,
payout_data,
))
.await?;
retries = retries.map(|i| i - 1);
}
api_models::gsm::GsmDecision::Requeue => {
Err(report!(errors::ApiErrorResponse::NotImplemented {
message: errors::NotImplementedMessage::Reason(
"Requeue not implemented".to_string(),
),
}))?
}
api_models::gsm::GsmDecision::DoDefault => break,
}
}
Ok(())
}
<file_sep path="hyperswitch/crates/router/src/core/payouts/retry.rs" role="context" start="205" end="224">
pub fn get_gsm_decision(
option_gsm: Option<storage::gsm::GatewayStatusMap>,
) -> api_models::gsm::GsmDecision {
let option_gsm_decision = option_gsm
.and_then(|gsm| {
api_models::gsm::GsmDecision::from_str(gsm.decision.as_str())
.map_err(|err| {
let api_error = report!(err).change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("gsm decision parsing failed");
logger::warn!(get_gsm_decision_parse_error=?api_error, "error fetching gsm decision");
api_error
})
.ok()
});
if option_gsm_decision.is_some() {
metrics::AUTO_PAYOUT_RETRY_GSM_MATCH_COUNT.add(1, &[]);
}
option_gsm_decision.unwrap_or_default()
}
<file_sep path="hyperswitch/crates/router/src/core/payouts/retry.rs" role="context" start="228" end="247">
pub async fn do_retry(
state: &routes::SessionState,
connector: api::ConnectorData,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
payout_data: &mut PayoutData,
) -> RouterResult<()> {
metrics::AUTO_RETRY_PAYOUT_COUNT.add(1, &[]);
modify_trackers(state, &connector, merchant_account, payout_data).await?;
Box::pin(call_connector_payout(
state,
merchant_account,
key_store,
&connector,
payout_data,
))
.await
}
<file_sep path="hyperswitch/crates/router/src/core/payouts.rs" role="context" start="68" end="81">
pub struct PayoutData {
pub billing_address: Option<domain::Address>,
pub business_profile: domain::Profile,
pub customer_details: Option<domain::Customer>,
pub merchant_connector_account: Option<payment_helpers::MerchantConnectorAccountType>,
pub payouts: storage::Payouts,
pub payout_attempt: storage::PayoutAttempt,
pub payout_method_data: Option<payouts::PayoutMethodData>,
pub profile_id: common_utils::id_type::ProfileId,
pub should_terminate: bool,
pub payout_link: Option<PayoutLink>,
pub current_locale: String,
pub payment_method: Option<PaymentMethod>,
}
<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),
}
<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/payouts/retry.rs<|crate|> router anchor=do_gsm_multiple_connector_actions kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/payouts/retry.rs" role="context" start="24" end="87">
pub async fn do_gsm_multiple_connector_actions(
state: &app::SessionState,
mut connectors: IntoIter<api::ConnectorData>,
original_connector_data: api::ConnectorData,
payout_data: &mut PayoutData,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
) -> RouterResult<()> {
let mut retries = None;
metrics::AUTO_PAYOUT_RETRY_ELIGIBLE_REQUEST_COUNT.add(1, &[]);
let mut connector = original_connector_data;
loop {
let gsm = get_gsm(state, &connector, payout_data).await?;
match get_gsm_decision(gsm) {
api_models::gsm::GsmDecision::Retry => {
retries = get_retries(
state,
retries,
merchant_account.get_id(),
PayoutRetryType::MultiConnector,
)
.await;
if retries.is_none() || retries == Some(0) {
metrics::AUTO_PAYOUT_RETRY_EXHAUSTED_COUNT.add(1, &[]);
logger::info!("retries exhausted for auto_retry payout");
break;
}
if connectors.len() == 0 {
logger::info!("connectors exhausted for auto_retry payout");
metrics::AUTO_PAYOUT_RETRY_EXHAUSTED_COUNT.add(1, &[]);
break;
}
connector = super::get_next_connector(&mut connectors)?;
Box::pin(do_retry(
&state.clone(),
connector.to_owned(),
merchant_account,
key_store,
payout_data,
))
.await?;
retries = retries.map(|i| i - 1);
}
api_models::gsm::GsmDecision::Requeue => {
Err(report!(errors::ApiErrorResponse::NotImplemented {
message: errors::NotImplementedMessage::Reason(
"Requeue not implemented".to_string(),
),
}))?
}
api_models::gsm::GsmDecision::DoDefault => break,
}
}
Ok(())
}
<file_sep path="hyperswitch/crates/router/src/core/payouts/retry.rs" role="context" start="23" end="23">
use std::{cmp::Ordering, str::FromStr, vec::IntoIter};
use common_enums::PayoutRetryType;
use error_stack::{report, ResultExt};
use router_env::{
logger,
tracing::{self, instrument},
};
use super::{call_connector_payout, PayoutData};
use crate::{
core::{
errors::{self, RouterResult, StorageErrorExt},
payouts,
},
db::StorageInterface,
routes::{self, app, metrics},
types::{api, domain, storage},
utils,
};
<file_sep path="hyperswitch/crates/router/src/core/payouts/retry.rs" role="context" start="154" end="182">
pub async fn get_retries(
state: &app::SessionState,
retries: Option<i32>,
merchant_id: &common_utils::id_type::MerchantId,
retry_type: PayoutRetryType,
) -> Option<i32> {
match retries {
Some(retries) => Some(retries),
None => {
let key = merchant_id.get_max_auto_single_connector_payout_retries_enabled(retry_type);
let db = &*state.store;
db.find_config_by_key(key.as_str())
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.and_then(|retries_config| {
retries_config
.config
.parse::<i32>()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Retries config parsing failed")
})
.map_err(|err| {
logger::error!(retries_error=?err);
None::<i32>
})
.ok()
}
}
}
<file_sep path="hyperswitch/crates/router/src/core/payouts/retry.rs" role="context" start="91" end="151">
pub async fn do_gsm_single_connector_actions(
state: &app::SessionState,
original_connector_data: api::ConnectorData,
payout_data: &mut PayoutData,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
) -> RouterResult<()> {
let mut retries = None;
metrics::AUTO_PAYOUT_RETRY_ELIGIBLE_REQUEST_COUNT.add(1, &[]);
let mut previous_gsm = None; // to compare previous status
loop {
let gsm = get_gsm(state, &original_connector_data, payout_data).await?;
// if the error config is same as previous, we break out of the loop
if let Ordering::Equal = gsm.cmp(&previous_gsm) {
break;
}
previous_gsm.clone_from(&gsm);
match get_gsm_decision(gsm) {
api_models::gsm::GsmDecision::Retry => {
retries = get_retries(
state,
retries,
merchant_account.get_id(),
PayoutRetryType::SingleConnector,
)
.await;
if retries.is_none() || retries == Some(0) {
metrics::AUTO_PAYOUT_RETRY_EXHAUSTED_COUNT.add(1, &[]);
logger::info!("retries exhausted for auto_retry payment");
break;
}
Box::pin(do_retry(
&state.clone(),
original_connector_data.to_owned(),
merchant_account,
key_store,
payout_data,
))
.await?;
retries = retries.map(|i| i - 1);
}
api_models::gsm::GsmDecision::Requeue => {
Err(report!(errors::ApiErrorResponse::NotImplemented {
message: errors::NotImplementedMessage::Reason(
"Requeue not implemented".to_string(),
),
}))?
}
api_models::gsm::GsmDecision::DoDefault => break,
}
}
Ok(())
}
<file_sep path="hyperswitch/crates/router/src/core/payouts/retry.rs" role="context" start="228" end="247">
pub async fn do_retry(
state: &routes::SessionState,
connector: api::ConnectorData,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
payout_data: &mut PayoutData,
) -> RouterResult<()> {
metrics::AUTO_RETRY_PAYOUT_COUNT.add(1, &[]);
modify_trackers(state, &connector, merchant_account, payout_data).await?;
Box::pin(call_connector_payout(
state,
merchant_account,
key_store,
&connector,
payout_data,
))
.await
}
<file_sep path="hyperswitch/crates/router/src/core/payouts.rs" role="context" start="68" end="81">
pub struct PayoutData {
pub billing_address: Option<domain::Address>,
pub business_profile: domain::Profile,
pub customer_details: Option<domain::Customer>,
pub merchant_connector_account: Option<payment_helpers::MerchantConnectorAccountType>,
pub payouts: storage::Payouts,
pub payout_attempt: storage::PayoutAttempt,
pub payout_method_data: Option<payouts::PayoutMethodData>,
pub profile_id: common_utils::id_type::ProfileId,
pub should_terminate: bool,
pub payout_link: Option<PayoutLink>,
pub current_locale: String,
pub payment_method: Option<PaymentMethod>,
}
<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/src/core/payments/routing.rs<|crate|> router anchor=perform_session_routing_for_pm_type 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="1252" end="1330">
async fn perform_session_routing_for_pm_type(
session_pm_input: &SessionRoutingPmTypeInput<'_>,
transaction_type: &api_enums::TransactionType,
_business_profile: &domain::Profile,
) -> RoutingResult<Option<Vec<api_models::routing::RoutableConnectorChoice>>> {
let merchant_id = &session_pm_input.key_store.merchant_id;
let algorithm_id = match session_pm_input.routing_algorithm {
MerchantAccountRoutingAlgorithm::V1(algorithm_ref) => &algorithm_ref.algorithm_id,
};
let chosen_connectors = if let Some(ref algorithm_id) = algorithm_id {
let cached_algorithm = ensure_algorithm_cached_v1(
&session_pm_input.state.clone(),
merchant_id,
algorithm_id,
session_pm_input.profile_id,
transaction_type,
)
.await?;
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) => execute_dsl_and_get_connector_v1(
session_pm_input.backend_input.clone(),
interpreter,
)?,
}
} else {
routing::helpers::get_merchant_default_config(
&*session_pm_input.state.clone().store,
session_pm_input.profile_id.get_string_repr(),
transaction_type,
)
.await
.change_context(errors::RoutingError::FallbackConfigFetchFailed)?
};
let mut final_selection = perform_cgraph_filtering(
&session_pm_input.state.clone(),
session_pm_input.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 = routing::helpers::get_merchant_default_config(
&*session_pm_input.state.clone().store,
session_pm_input.profile_id.get_string_repr(),
transaction_type,
)
.await
.change_context(errors::RoutingError::FallbackConfigFetchFailed)?;
final_selection = perform_cgraph_filtering(
&session_pm_input.state.clone(),
session_pm_input.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="1251" end="1251">
use api_models::routing as api_routing;
use api_models::{
admin as admin_api,
enums::{self as api_enums, CountryAlpha2},
routing::ConnectorSelection,
};
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="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="1333" end="1370">
async fn get_chosen_connectors<'a>(
state: &'a SessionState,
key_store: &'a domain::MerchantKeyStore,
session_pm_input: &SessionRoutingPmTypeInput<'_>,
transaction_type: &api_enums::TransactionType,
profile_wrapper: &admin::ProfileWrapper,
) -> RoutingResult<Vec<api_models::routing::RoutableConnectorChoice>> {
let merchant_id = &key_store.merchant_id;
let MerchantAccountRoutingAlgorithm::V1(algorithm_id) = session_pm_input.routing_algorithm;
let chosen_connectors = if let Some(ref algorithm_id) = algorithm_id {
let cached_algorithm = ensure_algorithm_cached_v1(
state,
merchant_id,
algorithm_id,
session_pm_input.profile_id,
transaction_type,
)
.await?;
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) => execute_dsl_and_get_connector_v1(
session_pm_input.backend_input.clone(),
interpreter,
)?,
}
} else {
profile_wrapper
.get_default_fallback_list_of_connector_under_profile()
.change_context(errors::RoutingError::FallbackConfigFetchFailed)?
};
Ok(chosen_connectors)
}
<file_sep path="hyperswitch/crates/router/src/core/payments/routing.rs" role="context" start="1107" end="1249">
pub async fn perform_session_flow_routing(
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 = session_input
.payment_intent
.profile_id
.clone()
.get_required_value("profile_id")
.change_context(errors::RoutingError::ProfileIdMissing)?;
let routing_algorithm: MerchantAccountRoutingAlgorithm = {
business_profile
.routing_algorithm
.clone()
.map(|val| val.parse_value("MerchantAccountRoutingAlgorithm"))
.transpose()
.change_context(errors::RoutingError::InvalidRoutingAlgorithmStructure)?
.unwrap_or_default()
};
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_attempt.get_total_amount(),
currency: session_input
.payment_intent
.currency
.get_required_value("Currency")
.change_context(errors::RoutingError::DslMissingRequiredField {
field_name: "currency".to_string(),
})?,
authentication_type: session_input.payment_attempt.authentication_type,
card_bin: None,
capture_method: session_input
.payment_attempt
.capture_method
.and_then(Option::<euclid_enums::CaptureMethod>::foreign_from),
business_country: session_input
.payment_intent
.business_country
.map(api_enums::Country::from_alpha2),
billing_country: session_input
.country
.map(storage_enums::Country::from_alpha2),
business_label: session_input.payment_intent.business_label.clone(),
setup_future_usage: 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 {
state: session_input.state,
key_store: session_input.key_store,
attempt_id: session_input.payment_attempt.get_id(),
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(
&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(
&session_pm_input.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/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/router/src/core/payments/routing.rs" role="context" start="468" end="509">
async fn ensure_algorithm_cached_v1(
state: &SessionState,
merchant_id: &common_utils::id_type::MerchantId,
algorithm_id: &common_utils::id_type::RoutingId,
profile_id: &common_utils::id_type::ProfileId,
transaction_type: &api_enums::TransactionType,
) -> RoutingResult<Arc<CachedAlgorithm>> {
let key = {
match transaction_type {
common_enums::TransactionType::Payment => {
format!(
"routing_config_{}_{}",
merchant_id.get_string_repr(),
profile_id.get_string_repr(),
)
}
#[cfg(feature = "payouts")]
common_enums::TransactionType::Payout => {
format!(
"routing_config_po_{}_{}",
merchant_id.get_string_repr(),
profile_id.get_string_repr()
)
}
}
};
let cached_algorithm = ROUTING_CACHE
.get_val::<Arc<CachedAlgorithm>>(CacheKey {
key: key.clone(),
prefix: state.tenant.redis_key_prefix.clone(),
})
.await;
let algorithm = if let Some(algo) = cached_algorithm {
algo
} else {
refresh_routing_cache_v1(state, key.clone(), algorithm_id, profile_id).await?
};
Ok(algorithm)
}
<file_sep path="hyperswitch/crates/router/src/core/payments/routing.rs" role="context" start="547" end="565">
fn execute_dsl_and_get_connector_v1(
backend_input: dsl_inputs::BackendInput,
interpreter: &backend::VirInterpreterBackend<ConnectorSelection>,
) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> {
let routing_output: routing_types::RoutingAlgorithm = interpreter
.execute(backend_input)
.map(|out| out.connector_selection.foreign_into())
.change_context(errors::RoutingError::DslExecutionError)?;
Ok(match routing_output {
routing_types::RoutingAlgorithm::Priority(plist) => plist,
routing_types::RoutingAlgorithm::VolumeSplit(splits) => perform_volume_split(splits)
.change_context(errors::RoutingError::DslFinalConnectorSelectionFailed)?,
_ => Err(errors::RoutingError::DslIncorrectSelectionAlgorithm)
.attach_printable("Unsupported algorithm received as a result of static routing")?,
})
}
<file_sep path="hyperswitch/crates/router/src/core/payments/routing.rs" role="context" start="116" end="118">
enum MerchantAccountRoutingAlgorithm {
V1(routing_types::RoutingAlgorithmRef),
}
<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/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/core/refunds.rs<|crate|> router anchor=refund_retrieve_core kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/refunds.rs" role="context" start="478" end="568">
pub async fn refund_retrieve_core(
state: SessionState,
merchant_account: domain::MerchantAccount,
profile_id: Option<common_utils::id_type::ProfileId>,
key_store: domain::MerchantKeyStore,
request: refunds::RefundsRetrieveRequest,
refund: storage::Refund,
) -> RouterResult<storage::Refund> {
let db = &*state.store;
let merchant_id = merchant_account.get_id();
core_utils::validate_profile_id_from_auth_layer(profile_id, &refund)?;
let payment_id = &refund.payment_id;
let payment_intent = db
.find_payment_intent_by_payment_id_merchant_id(
&(&state).into(),
payment_id,
merchant_id,
&key_store,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
let payment_attempt = db
.find_payment_attempt_by_connector_transaction_id_payment_id_merchant_id(
&refund.connector_transaction_id,
payment_id,
merchant_id,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::InternalServerError)?;
let creds_identifier = request
.merchant_connector_details
.as_ref()
.map(|mcd| mcd.creds_identifier.to_owned());
request
.merchant_connector_details
.to_owned()
.async_map(|mcd| async {
helpers::insert_merchant_connector_creds_to_config(db, merchant_id, mcd).await
})
.await
.transpose()?;
let split_refunds_req = core_utils::get_split_refunds(SplitRefundInput {
split_payment_request: payment_intent.split_payments.clone(),
payment_charges: payment_attempt.charges.clone(),
charge_id: payment_attempt.charge_id.clone(),
refund_request: refund.split_refunds.clone(),
})?;
let unified_translated_message = if let (Some(unified_code), Some(unified_message)) =
(refund.unified_code.clone(), refund.unified_message.clone())
{
helpers::get_unified_translation(
&state,
unified_code,
unified_message.clone(),
state.locale.to_string(),
)
.await
.or(Some(unified_message))
} else {
refund.unified_message
};
let refund = storage::Refund {
unified_message: unified_translated_message,
..refund
};
let response = if should_call_refund(&refund, request.force_sync.unwrap_or(false)) {
Box::pin(sync_refund_with_gateway(
&state,
&merchant_account,
&key_store,
&payment_attempt,
&payment_intent,
&refund,
creds_identifier,
split_refunds_req,
))
.await
} else {
Ok(refund)
}?;
Ok(response)
}
<file_sep path="hyperswitch/crates/router/src/core/refunds.rs" role="context" start="477" end="477">
use common_utils::{
ext_traits::AsyncExt,
types::{ConnectorTransactionId, MinorUnit},
};
use crate::{
consts,
core::{
errors::{self, ConnectorErrorExt, RouterResponse, RouterResult, StorageErrorExt},
payments::{self, access_token, helpers},
refunds::transformers::SplitRefundInput,
utils as core_utils,
},
db, logger,
routes::{metrics, SessionState},
services,
types::{
self,
api::{self, refunds},
domain,
storage::{self, enums},
transformers::{ForeignFrom, ForeignInto},
},
utils::{self, OptionExt},
workflows::payment_sync,
};
<file_sep path="hyperswitch/crates/router/src/core/refunds.rs" role="context" start="589" end="769">
pub async fn sync_refund_with_gateway(
state: &SessionState,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
payment_attempt: &storage::PaymentAttempt,
payment_intent: &storage::PaymentIntent,
refund: &storage::Refund,
creds_identifier: Option<String>,
split_refunds: Option<SplitRefundsRequest>,
) -> RouterResult<storage::Refund> {
let connector_id = refund.connector.to_string();
let connector: api::ConnectorData = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
&connector_id,
api::GetToken::Connector,
payment_attempt.merchant_connector_id.clone(),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get the connector")?;
let storage_scheme = merchant_account.storage_scheme;
let currency = payment_attempt.currency.get_required_value("currency")?;
let mut router_data = core_utils::construct_refund_router_data::<api::RSync>(
state,
&connector_id,
merchant_account,
key_store,
(payment_attempt.get_total_amount(), currency),
payment_intent,
payment_attempt,
refund,
creds_identifier.clone(),
split_refunds,
)
.await?;
let add_access_token_result = access_token::add_access_token(
state,
&connector,
merchant_account,
&router_data,
creds_identifier.as_deref(),
)
.await?;
logger::debug!(refund_retrieve_router_data=?router_data);
access_token::update_router_data_with_access_token_result(
&add_access_token_result,
&mut router_data,
&payments::CallConnectorAction::Trigger,
);
let router_data_res = if !(add_access_token_result.connector_supports_access_token
&& router_data.access_token.is_none())
{
let connector_integration: services::BoxedRefundConnectorIntegrationInterface<
api::RSync,
types::RefundsData,
types::RefundsResponseData,
> = connector.connector.get_connector_integration();
let mut refund_sync_router_data = services::execute_connector_processing_step(
state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
)
.await
.to_refund_failed_response()?;
// Initiating connector integrity checks
let integrity_result = check_refund_integrity(
&refund_sync_router_data.request,
&refund_sync_router_data.response,
);
refund_sync_router_data.integrity_check = integrity_result;
refund_sync_router_data
} else {
router_data
};
let refund_update = match router_data_res.response {
Err(error_message) => {
let refund_status = match error_message.status_code {
// marking failure for 2xx because this is genuine refund failure
200..=299 => Some(enums::RefundStatus::Failure),
_ => None,
};
storage::RefundUpdate::ErrorUpdate {
refund_status,
refund_error_message: error_message.reason.or(Some(error_message.message)),
refund_error_code: Some(error_message.code),
updated_by: storage_scheme.to_string(),
connector_refund_id: None,
processor_refund_data: None,
unified_code: None,
unified_message: None,
issuer_error_code: error_message.network_decline_code,
issuer_error_message: error_message.network_error_message,
}
}
Ok(response) => match router_data_res.integrity_check.clone() {
Err(err) => {
metrics::INTEGRITY_CHECK_FAILED.add(
1,
router_env::metric_attributes!(
("connector", connector.connector_name.to_string()),
("merchant_id", merchant_account.get_id().clone()),
),
);
let (refund_connector_transaction_id, processor_refund_data) = err
.connector_transaction_id
.map_or((None, None), |refund_id| {
let (refund_id, refund_data) =
ConnectorTransactionId::form_id_and_data(refund_id);
(Some(refund_id), refund_data)
});
storage::RefundUpdate::ErrorUpdate {
refund_status: Some(enums::RefundStatus::ManualReview),
refund_error_message: Some(format!(
"Integrity Check Failed! as data mismatched for fields {}",
err.field_names
)),
refund_error_code: Some("IE".to_string()),
updated_by: storage_scheme.to_string(),
connector_refund_id: refund_connector_transaction_id,
processor_refund_data,
unified_code: None,
unified_message: None,
issuer_error_code: None,
issuer_error_message: None,
}
}
Ok(()) => {
let (connector_refund_id, processor_refund_data) =
ConnectorTransactionId::form_id_and_data(response.connector_refund_id);
storage::RefundUpdate::Update {
connector_refund_id,
refund_status: response.refund_status,
sent_to_gateway: true,
refund_error_message: None,
refund_arn: "".to_string(),
updated_by: storage_scheme.to_string(),
processor_refund_data,
}
}
},
};
let response = state
.store
.update_refund(
refund.to_owned(),
refund_update,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::RefundNotFound)
.attach_printable_lazy(|| {
format!(
"Unable to update refund with refund_id: {}",
refund.refund_id
)
})?;
utils::trigger_refund_outgoing_webhook(
state,
merchant_account,
&response,
payment_attempt.profile_id.clone(),
key_store,
)
.await
.map_err(|error| logger::warn!(refunds_outgoing_webhook_error=?error))
.ok();
Ok(response)
}
<file_sep path="hyperswitch/crates/router/src/core/refunds.rs" role="context" start="570" end="585">
fn should_call_refund(refund: &diesel_models::refund::Refund, force_sync: bool) -> bool {
// This implies, we cannot perform a refund sync & `the connector_refund_id`
// doesn't exist
let predicate1 = refund.connector_refund_id.is_some();
// This allows refund sync at connector level if force_sync is enabled, or
// checks if the refund has failed
let predicate2 = force_sync
|| !matches!(
refund.refund_status,
diesel_models::enums::RefundStatus::Failure
| diesel_models::enums::RefundStatus::Success
);
predicate1 && predicate2
}
<file_sep path="hyperswitch/crates/router/src/core/refunds.rs" role="context" start="451" end="475">
pub async fn refund_response_wrapper<F, Fut, T, Req>(
state: SessionState,
merchant_account: domain::MerchantAccount,
profile_id: Option<common_utils::id_type::ProfileId>,
key_store: domain::MerchantKeyStore,
request: Req,
f: F,
) -> RouterResponse<refunds::RefundResponse>
where
F: Fn(
SessionState,
domain::MerchantAccount,
Option<common_utils::id_type::ProfileId>,
domain::MerchantKeyStore,
Req,
) -> Fut,
Fut: futures::Future<Output = RouterResult<T>>,
T: ForeignInto<refunds::RefundResponse>,
{
Ok(services::ApplicationResponse::Json(
f(state, merchant_account, profile_id, key_store, request)
.await?
.foreign_into(),
))
}
<file_sep path="hyperswitch/crates/router/src/core/refunds.rs" role="context" start="433" end="447">
pub fn check_refund_integrity<T, Request>(
request: &Request,
refund_response_data: &Result<types::RefundsResponseData, ErrorResponse>,
) -> Result<(), common_utils::errors::IntegrityCheckError>
where
T: FlowIntegrity,
Request: GetIntegrityObject<T> + CheckIntegrity<Request, T>,
{
let connector_refund_id = refund_response_data
.as_ref()
.map(|resp_data| resp_data.connector_refund_id.clone())
.ok();
request.check_integrity(request, connector_refund_id.to_owned())
}
<file_sep path="hyperswitch/crates/router/src/core/refunds.rs" role="context" start="1053" end="1088">
pub async fn refund_retrieve_core_with_internal_reference_id(
state: SessionState,
merchant_account: domain::MerchantAccount,
profile_id: Option<common_utils::id_type::ProfileId>,
key_store: domain::MerchantKeyStore,
refund_internal_request_id: String,
force_sync: Option<bool>,
) -> RouterResult<storage::Refund> {
let db = &*state.store;
let merchant_id = merchant_account.get_id();
let refund = db
.find_refund_by_internal_reference_id_merchant_id(
&refund_internal_request_id,
merchant_id,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?;
let request = refunds::RefundsRetrieveRequest {
refund_id: refund.refund_id.clone(),
force_sync,
merchant_connector_details: None,
};
Box::pin(refund_retrieve_core(
state.clone(),
merchant_account,
profile_id,
key_store,
request,
refund,
))
.await
}
<file_sep path="hyperswitch/crates/router/src/core/refunds.rs" role="context" start="1091" end="1120">
pub async fn refund_retrieve_core_with_refund_id(
state: SessionState,
merchant_account: domain::MerchantAccount,
profile_id: Option<common_utils::id_type::ProfileId>,
key_store: domain::MerchantKeyStore,
request: refunds::RefundsRetrieveRequest,
) -> RouterResult<storage::Refund> {
let refund_id = request.refund_id.clone();
let db = &*state.store;
let merchant_id = merchant_account.get_id();
let refund = db
.find_refund_by_merchant_id_refund_id(
merchant_id,
refund_id.as_str(),
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?;
Box::pin(refund_retrieve_core(
state.clone(),
merchant_account,
profile_id,
key_store,
request,
refund,
))
.await
}
<file_sep path="hyperswitch/v2_compatible_migrations/2024-08-28-081721_add_v2_columns/up.sql" role="context" start="59" end="70">
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);
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payment_methods.rs<|crate|> router anchor=update_payment_method_core 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="1928" end="2027">
pub async fn update_payment_method_core(
state: &SessionState,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
request: api::PaymentMethodUpdate,
payment_method_id: &id_type::GlobalPaymentMethodId,
) -> RouterResult<api::PaymentMethodResponse> {
let db = state.store.as_ref();
let payment_method = db
.find_payment_method(
&((state).into()),
key_store,
payment_method_id,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
let current_vault_id = payment_method.locker_id.clone();
when(
payment_method.status == enums::PaymentMethodStatus::AwaitingData,
|| {
Err(errors::ApiErrorResponse::InvalidRequestData {
message: "This Payment method is awaiting data and hence cannot be updated"
.to_string(),
})
},
)?;
let pmd: domain::PaymentMethodVaultingData =
vault::retrieve_payment_method_from_vault(state, merchant_account, &payment_method)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to retrieve payment method from vault")?
.data;
let vault_request_data = request.payment_method_data.map(|payment_method_data| {
pm_transforms::generate_pm_vaulting_req_from_update_request(pmd, payment_method_data)
});
let (vaulting_response, fingerprint_id) = match vault_request_data {
// cannot use async map because of problems related to lifetimes
// to overcome this, we will have to use a move closure and add some clones
Some(ref vault_request_data) => {
Some(
vault_payment_method(
state,
vault_request_data,
merchant_account,
key_store,
// using current vault_id for now,
// will have to refactor this to generate new one on each vaulting later on
current_vault_id,
&payment_method.customer_id,
)
.await
.attach_printable("Failed to add payment method in vault")?,
)
}
None => None,
}
.unzip();
let vault_id = vaulting_response
.map(|vaulting_response| vaulting_response.vault_id.get_string_repr().clone());
let pm_update = create_pm_additional_data_update(
vault_request_data.as_ref(),
state,
key_store,
vault_id,
fingerprint_id,
&payment_method,
request.connector_token_details,
None,
None,
None,
)
.await
.attach_printable("Unable to create Payment method data")?;
let payment_method = db
.update_payment_method(
&((state).into()),
key_store,
payment_method,
pm_update,
merchant_account.storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update payment method in db")?;
let response = pm_transforms::generate_payment_method_response(&payment_method, &None)?;
// Add a PT task to handle payment_method delete from vault
Ok(response)
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods.rs" role="context" start="1927" end="1927">
&merchant_account,
&key_store,
req,
payment_method_id,
)
.await?;
Ok(services::ApplicationResponse::Json(response))
}
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
#[instrument(skip_all)]
pub async fn update_payment_method_core(
state: &SessionState,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
request: api::PaymentMethodUpdate,
payment_method_id: &id_type::GlobalPaymentMethodId,
) -> RouterResult<api::PaymentMethodResponse> {
let db = state.store.as_ref();
let payment_method = db
.find_payment_method(
&((state).into()),
key_store,
<file_sep path="hyperswitch/crates/router/src/core/payment_methods.rs" role="context" start="2047" end="2113">
pub async fn delete_payment_method_core(
state: SessionState,
pm_id: id_type::GlobalPaymentMethodId,
key_store: domain::MerchantKeyStore,
merchant_account: domain::MerchantAccount,
) -> RouterResult<api::PaymentMethodDeleteResponse> {
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
let payment_method = db
.find_payment_method(
&((&state).into()),
&key_store,
&pm_id,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
when(
payment_method.status == enums::PaymentMethodStatus::Inactive,
|| Err(errors::ApiErrorResponse::PaymentMethodNotFound),
)?;
let vault_id = payment_method
.locker_id
.clone()
.get_required_value("locker_id")
.attach_printable("Missing locker_id in PaymentMethod")?;
let _customer = db
.find_customer_by_global_id(
key_manager_state,
&payment_method.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")?;
// Soft delete
let pm_update = storage::PaymentMethodUpdate::StatusUpdate {
status: Some(enums::PaymentMethodStatus::Inactive),
};
db.update_payment_method(
&((&state).into()),
&key_store,
payment_method,
pm_update,
merchant_account.storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update payment method in db")?;
vault::delete_payment_method_data_from_vault(&state, &merchant_account, vault_id)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to delete payment method from vault")?;
let response = api::PaymentMethodDeleteResponse { id: pm_id };
Ok(response)
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods.rs" role="context" start="2031" end="2043">
pub async fn delete_payment_method(
state: SessionState,
pm_id: api::PaymentMethodId,
key_store: domain::MerchantKeyStore,
merchant_account: domain::MerchantAccount,
) -> RouterResponse<api::PaymentMethodDeleteResponse> {
let pm_id = id_type::GlobalPaymentMethodId::generate_from_string(pm_id.payment_method_id)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to generate GlobalPaymentMethodId")?;
let response = delete_payment_method_core(state, pm_id, key_store, merchant_account).await?;
Ok(services::ApplicationResponse::Json(response))
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods.rs" role="context" start="1907" end="1924">
pub async fn update_payment_method(
state: SessionState,
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
req: api::PaymentMethodUpdate,
payment_method_id: &id_type::GlobalPaymentMethodId,
) -> RouterResponse<api::PaymentMethodResponse> {
let response = update_payment_method_core(
&state,
&merchant_account,
&key_store,
req,
payment_method_id,
)
.await?;
Ok(services::ApplicationResponse::Json(response))
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods.rs" role="context" start="1873" end="1903">
pub async fn retrieve_payment_method(
state: SessionState,
pm: api::PaymentMethodId,
key_store: domain::MerchantKeyStore,
merchant_account: domain::MerchantAccount,
) -> RouterResponse<api::PaymentMethodResponse> {
let db = state.store.as_ref();
let pm_id = id_type::GlobalPaymentMethodId::generate_from_string(pm.payment_method_id)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to generate GlobalPaymentMethodId")?;
let payment_method = db
.find_payment_method(
&((&state).into()),
&key_store,
&pm_id,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
let single_use_token_in_cache = get_single_use_token_from_store(
&state.clone(),
payment_method_data::SingleUseTokenKey::store_key(&pm_id.clone()),
)
.await
.unwrap_or_default();
transformers::generate_payment_method_response(&payment_method, &single_use_token_in_cache)
.map(services::ApplicationResponse::Json)
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods.rs" role="context" start="2410" end="2441">
pub async fn payment_methods_session_update_payment_method(
state: SessionState,
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
payment_method_session_id: id_type::GlobalPaymentMethodSessionId,
request: payment_methods::PaymentMethodSessionUpdateSavedPaymentMethod,
) -> RouterResponse<payment_methods::PaymentMethodResponse> {
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
// Validate if the session still exists
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_update_request = request.payment_method_update_request;
let updated_payment_method = update_payment_method_core(
&state,
&merchant_account,
&key_store,
payment_method_update_request,
&request.payment_method_id,
)
.await
.attach_printable("Failed to update saved payment method")?;
Ok(services::ApplicationResponse::Json(updated_payment_method))
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods.rs" role="context" start="1614" end="1677">
pub async fn create_pm_additional_data_update(
pmd: Option<&domain::PaymentMethodVaultingData>,
state: &SessionState,
key_store: &domain::MerchantKeyStore,
vault_id: Option<String>,
vault_fingerprint_id: Option<String>,
payment_method: &domain::PaymentMethod,
connector_token_details: Option<payment_methods::ConnectorTokenDetails>,
nt_data: Option<NetworkTokenPaymentMethodDetails>,
payment_method_type: Option<common_enums::PaymentMethod>,
payment_method_subtype: Option<common_enums::PaymentMethodType>,
) -> RouterResult<storage::PaymentMethodUpdate> {
let encrypted_payment_method_data = pmd
.map(
|payment_method_vaulting_data| match payment_method_vaulting_data {
domain::PaymentMethodVaultingData::Card(card) => {
payment_method_data::PaymentMethodsData::Card(
payment_method_data::CardDetailsPaymentMethod::from(card.clone()),
)
}
domain::PaymentMethodVaultingData::NetworkToken(network_token) => {
payment_method_data::PaymentMethodsData::NetworkToken(
payment_method_data::NetworkTokenDetailsPaymentMethod::from(
network_token.clone(),
),
)
}
},
)
.async_map(|payment_method_details| async {
let key_manager_state = &(state).into();
cards::create_encrypted_data(key_manager_state, key_store, payment_method_details)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt Payment method data")
})
.await
.transpose()?
.map(From::from);
let connector_mandate_details_update = connector_token_details
.map(|connector_token| {
create_connector_token_details_update(connector_token, payment_method)
})
.map(From::from);
let pm_update = storage::PaymentMethodUpdate::GenericUpdate {
status: Some(enums::PaymentMethodStatus::Active),
locker_id: vault_id,
payment_method_type_v2: payment_method_type,
payment_method_subtype,
payment_method_data: encrypted_payment_method_data,
network_token_requestor_reference_id: nt_data
.clone()
.map(|data| data.network_token_requestor_reference_id),
network_token_locker_id: nt_data.clone().map(|data| data.network_token_locker_id),
network_token_payment_method_data: nt_data.map(|data| data.network_token_pmd.into()),
connector_mandate_details: connector_mandate_details_update,
locker_fingerprint_id: vault_fingerprint_id,
};
Ok(pm_update)
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods.rs" role="context" start="1681" end="1723">
pub async fn vault_payment_method(
state: &SessionState,
pmd: &domain::PaymentMethodVaultingData,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
existing_vault_id: Option<domain::VaultId>,
customer_id: &id_type::GlobalCustomerId,
) -> RouterResult<(pm_types::AddVaultResponse, String)> {
let db = &*state.store;
// get fingerprint_id from vault
let fingerprint_id_from_vault =
vault::get_fingerprint_id_from_vault(state, pmd, customer_id.get_string_repr().to_owned())
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get fingerprint_id from vault")?;
// throw back error if payment method is duplicated
when(
db.find_payment_method_by_fingerprint_id(
&(state.into()),
key_store,
&fingerprint_id_from_vault,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to find payment method by fingerprint_id")
.inspect_err(|e| logger::error!("Vault Fingerprint_id error: {:?}", e))
.is_ok(),
|| {
Err(report!(errors::ApiErrorResponse::DuplicatePaymentMethod)
.attach_printable("Cannot vault duplicate payment method"))
},
)?;
let resp_from_vault =
vault::add_payment_method_to_vault(state, merchant_account, pmd, existing_vault_id)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to add payment method in vault")?;
Ok((resp_from_vault, fingerprint_id_from_vault))
}
<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);
<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/refunds.rs<|crate|> router anchor=schedule_refund_execution kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/refunds.rs" role="context" start="1290" end="1380">
pub async fn schedule_refund_execution(
state: &SessionState,
refund: storage::Refund,
refund_type: api_models::refunds::RefundType,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
payment_attempt: &storage::PaymentAttempt,
payment_intent: &storage::PaymentIntent,
creds_identifier: Option<String>,
split_refunds: Option<SplitRefundsRequest>,
) -> RouterResult<storage::Refund> {
// refunds::RefundResponse> {
let db = &*state.store;
let runner = storage::ProcessTrackerRunner::RefundWorkflowRouter;
let task = "EXECUTE_REFUND";
let task_id = format!("{runner}_{task}_{}", refund.internal_reference_id);
let refund_process = db
.find_process_by_id(&task_id)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to find the process id")?;
let result = match refund.refund_status {
enums::RefundStatus::Pending | enums::RefundStatus::ManualReview => {
match (refund.sent_to_gateway, refund_process) {
(false, None) => {
// Execute the refund task based on refund_type
match refund_type {
api_models::refunds::RefundType::Scheduled => {
add_refund_execute_task(db, &refund, runner)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| format!("Failed while pushing refund execute task to scheduler, refund_id: {}", refund.refund_id))?;
Ok(refund)
}
api_models::refunds::RefundType::Instant => {
let update_refund = Box::pin(trigger_refund_to_gateway(
state,
&refund,
merchant_account,
key_store,
payment_attempt,
payment_intent,
creds_identifier,
split_refunds,
))
.await;
match update_refund {
Ok(updated_refund_data) => {
add_refund_sync_task(db, &updated_refund_data, runner)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| format!(
"Failed while pushing refund sync task in scheduler: refund_id: {}",
refund.refund_id
))?;
Ok(updated_refund_data)
}
Err(err) => Err(err),
}
}
}
}
_ => {
// Sync the refund for status check
//[#300]: return refund status response
match refund_type {
api_models::refunds::RefundType::Scheduled => {
add_refund_sync_task(db, &refund, runner)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| format!("Failed while pushing refund sync task in scheduler: refund_id: {}", refund.refund_id))?;
Ok(refund)
}
api_models::refunds::RefundType::Instant => {
// [#255]: This is not possible in schedule_refund_execution as it will always be scheduled
// sync_refund_with_gateway(data, &refund).await
Ok(refund)
}
}
}
}
}
// [#255]: This is not allowed to be otherwise or all
_ => Ok(refund),
}?;
Ok(result)
}
<file_sep path="hyperswitch/crates/router/src/core/refunds.rs" role="context" start="1289" end="1289">
use api_models::admin::MerchantConnectorInfo;
use hyperswitch_domain_models::{
router_data::ErrorResponse, router_request_types::SplitRefundsRequest,
};
use scheduler::{consumer::types::process_data, utils as process_tracker_utils};
use crate::{
consts,
core::{
errors::{self, ConnectorErrorExt, RouterResponse, RouterResult, StorageErrorExt},
payments::{self, access_token, helpers},
refunds::transformers::SplitRefundInput,
utils as core_utils,
},
db, logger,
routes::{metrics, SessionState},
services,
types::{
self,
api::{self, refunds},
domain,
storage::{self, enums},
transformers::{ForeignFrom, ForeignInto},
},
utils::{self, OptionExt},
workflows::payment_sync,
};
<file_sep path="hyperswitch/crates/router/src/core/refunds.rs" role="context" start="1456" end="1469">
pub async fn start_refund_workflow(
state: &SessionState,
refund_tracker: &storage::ProcessTracker,
) -> Result<(), errors::ProcessTrackerError> {
match refund_tracker.name.as_deref() {
Some("EXECUTE_REFUND") => {
Box::pin(trigger_refund_execute_workflow(state, refund_tracker)).await
}
Some("SYNC_REFUND") => {
Box::pin(sync_refund_with_gateway_workflow(state, refund_tracker)).await
}
_ => Err(errors::ProcessTrackerError::JobNotFound),
}
}
<file_sep path="hyperswitch/crates/router/src/core/refunds.rs" role="context" start="1383" end="1453">
pub async fn sync_refund_with_gateway_workflow(
state: &SessionState,
refund_tracker: &storage::ProcessTracker,
) -> Result<(), errors::ProcessTrackerError> {
let key_manager_state = &state.into();
let refund_core =
serde_json::from_value::<storage::RefundCoreWorkflow>(refund_tracker.tracking_data.clone())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| {
format!(
"unable to convert into refund_core {:?}",
refund_tracker.tracking_data
)
})?;
let key_store = state
.store
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&refund_core.merchant_id,
&state.store.get_master_key().to_vec().into(),
)
.await?;
let merchant_account = state
.store
.find_merchant_account_by_merchant_id(
key_manager_state,
&refund_core.merchant_id,
&key_store,
)
.await?;
let response = Box::pin(refund_retrieve_core_with_internal_reference_id(
state.clone(),
merchant_account,
None,
key_store,
refund_core.refund_internal_reference_id,
Some(true),
))
.await?;
let terminal_status = [
enums::RefundStatus::Success,
enums::RefundStatus::Failure,
enums::RefundStatus::TransactionFailure,
];
match response.refund_status {
status if terminal_status.contains(&status) => {
state
.store
.as_scheduler()
.finish_process_with_business_status(
refund_tracker.clone(),
business_status::COMPLETED_BY_PT,
)
.await?
}
_ => {
_ = payment_sync::retry_sync_task(
&*state.store,
response.connector,
response.merchant_id,
refund_tracker.to_owned(),
)
.await?;
}
}
Ok(())
}
<file_sep path="hyperswitch/crates/router/src/core/refunds.rs" role="context" start="1259" end="1283">
fn foreign_from(refund: storage::Refund) -> Self {
let refund = refund;
Self {
payment_id: refund.payment_id,
refund_id: refund.refund_id,
amount: refund.refund_amount,
currency: refund.currency.to_string(),
reason: refund.refund_reason,
status: refund.refund_status.foreign_into(),
profile_id: refund.profile_id,
metadata: refund.metadata,
error_message: refund.refund_error_message,
error_code: refund.refund_error_code,
created_at: Some(refund.created_at),
updated_at: Some(refund.modified_at),
connector: refund.connector,
merchant_connector_id: refund.merchant_connector_id,
split_refunds: refund.split_refunds,
unified_code: refund.unified_code,
unified_message: refund.unified_message,
issuer_error_code: refund.issuer_error_code,
issuer_error_message: refund.issuer_error_message,
}
}
<file_sep path="hyperswitch/crates/router/src/core/refunds.rs" role="context" start="1228" end="1256">
pub async fn get_aggregates_for_refunds(
state: SessionState,
merchant: domain::MerchantAccount,
profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
time_range: common_utils::types::TimeRange,
) -> RouterResponse<api_models::refunds::RefundAggregateResponse> {
let db = state.store.as_ref();
let refund_status_with_count = db
.get_refund_status_with_count(
merchant.get_id(),
profile_id_list,
&time_range,
merchant.storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to find status count")?;
let mut status_map: HashMap<enums::RefundStatus, i64> =
refund_status_with_count.into_iter().collect();
for status in enums::RefundStatus::iter() {
status_map.entry(status).or_default();
}
Ok(services::ApplicationResponse::Json(
api_models::refunds::RefundAggregateResponse {
status_with_count: status_map,
},
))
}
<file_sep path="hyperswitch/crates/router/src/core/refunds.rs" role="context" start="811" end="980">
pub async fn validate_and_create_refund(
state: &SessionState,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
payment_attempt: &storage::PaymentAttempt,
payment_intent: &storage::PaymentIntent,
refund_amount: MinorUnit,
req: refunds::RefundRequest,
creds_identifier: Option<String>,
) -> RouterResult<refunds::RefundResponse> {
let db = &*state.store;
let split_refunds = core_utils::get_split_refunds(SplitRefundInput {
split_payment_request: payment_intent.split_payments.clone(),
payment_charges: payment_attempt.charges.clone(),
charge_id: payment_attempt.charge_id.clone(),
refund_request: req.split_refunds.clone(),
})?;
// Only for initial dev and testing
let refund_type = req.refund_type.unwrap_or_default();
// If Refund Id not passed in request Generate one.
let refund_id = core_utils::get_or_generate_id("refund_id", &req.refund_id, "ref")?;
let predicate = req
.merchant_id
.as_ref()
.map(|merchant_id| merchant_id != merchant_account.get_id());
utils::when(predicate.unwrap_or(false), || {
Err(report!(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "merchant_id".to_string(),
expected_format: "merchant_id from merchant account".to_string()
})
.attach_printable("invalid merchant_id in request"))
})?;
let connector_transaction_id = payment_attempt.clone().connector_transaction_id.ok_or_else(|| {
report!(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Transaction in invalid. Missing field \"connector_transaction_id\" in payment_attempt.")
})?;
let all_refunds = db
.find_refund_by_merchant_id_connector_transaction_id(
merchant_account.get_id(),
&connector_transaction_id,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?;
let currency = payment_attempt.currency.get_required_value("currency")?;
//[#249]: Add Connector Based Validation here.
validator::validate_payment_order_age(&payment_intent.created_at, state.conf.refund.max_age)
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "created_at".to_string(),
expected_format: format!(
"created_at not older than {} days",
state.conf.refund.max_age,
),
})?;
let total_amount_captured = payment_intent
.amount_captured
.unwrap_or(payment_attempt.get_total_amount());
validator::validate_refund_amount(
total_amount_captured.get_amount_as_i64(),
&all_refunds,
refund_amount.get_amount_as_i64(),
)
.change_context(errors::ApiErrorResponse::RefundAmountExceedsPaymentAmount)?;
validator::validate_maximum_refund_against_payment_attempt(
&all_refunds,
state.conf.refund.max_attempts,
)
.change_context(errors::ApiErrorResponse::MaximumRefundCount)?;
let connector = payment_attempt
.connector
.clone()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("No connector populated in payment attempt")?;
let (connector_transaction_id, processor_transaction_data) =
ConnectorTransactionId::form_id_and_data(connector_transaction_id);
let refund_create_req = storage::RefundNew {
refund_id: refund_id.to_string(),
internal_reference_id: utils::generate_id(consts::ID_LENGTH, "refid"),
external_reference_id: Some(refund_id.clone()),
payment_id: req.payment_id,
merchant_id: merchant_account.get_id().clone(),
connector_transaction_id,
connector,
refund_type: req.refund_type.unwrap_or_default().foreign_into(),
total_amount: payment_attempt.get_total_amount(),
refund_amount,
currency,
created_at: common_utils::date_time::now(),
modified_at: common_utils::date_time::now(),
refund_status: enums::RefundStatus::Pending,
metadata: req.metadata,
description: req.reason.clone(),
attempt_id: payment_attempt.attempt_id.clone(),
refund_reason: req.reason,
profile_id: payment_intent.profile_id.clone(),
merchant_connector_id: payment_attempt.merchant_connector_id.clone(),
charges: None,
split_refunds: req.split_refunds,
connector_refund_id: None,
sent_to_gateway: Default::default(),
refund_arn: None,
updated_by: Default::default(),
organization_id: merchant_account.organization_id.clone(),
processor_transaction_data,
processor_refund_data: None,
};
let refund = match db
.insert_refund(refund_create_req, merchant_account.storage_scheme)
.await
{
Ok(refund) => {
Box::pin(schedule_refund_execution(
state,
refund.clone(),
refund_type,
merchant_account,
key_store,
payment_attempt,
payment_intent,
creds_identifier,
split_refunds,
))
.await?
}
Err(err) => {
if err.current_context().is_db_unique_violation() {
Err(errors::ApiErrorResponse::DuplicateRefundRequest)?
} else {
return Err(err)
.change_context(errors::ApiErrorResponse::RefundNotFound)
.attach_printable("Inserting Refund failed");
}
}
};
let unified_translated_message = if let (Some(unified_code), Some(unified_message)) =
(refund.unified_code.clone(), refund.unified_message.clone())
{
helpers::get_unified_translation(
state,
unified_code,
unified_message.clone(),
state.locale.to_string(),
)
.await
.or(Some(unified_message))
} else {
refund.unified_message
};
let refund = storage::Refund {
unified_message: unified_translated_message,
..refund
};
Ok(refund.foreign_into())
}
<file_sep path="hyperswitch/crates/router/src/core/refunds.rs" role="context" start="1606" end="1642">
pub async fn add_refund_sync_task(
db: &dyn db::StorageInterface,
refund: &storage::Refund,
runner: storage::ProcessTrackerRunner,
) -> RouterResult<storage::ProcessTracker> {
let task = "SYNC_REFUND";
let process_tracker_id = format!("{runner}_{task}_{}", refund.internal_reference_id);
let schedule_time = common_utils::date_time::now();
let refund_workflow_tracking_data = refund_to_refund_core_workflow_model(refund);
let tag = ["REFUND"];
let process_tracker_entry = storage::ProcessTrackerNew::new(
process_tracker_id,
task,
runner,
tag,
refund_workflow_tracking_data,
None,
schedule_time,
common_types::consts::API_VERSION,
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to construct refund sync process tracker task")?;
let response = db
.insert_process(process_tracker_entry)
.await
.to_duplicate_response(errors::ApiErrorResponse::DuplicateRefundRequest)
.attach_printable_lazy(|| {
format!(
"Failed while inserting task in process_tracker: refund_id: {}",
refund.refund_id
)
})?;
metrics::TASKS_ADDED_COUNT.add(1, router_env::metric_attributes!(("flow", "Refund")));
Ok(response)
}
<file_sep path="hyperswitch/crates/router/src/core/refunds.rs" role="context" start="139" end="431">
pub async fn trigger_refund_to_gateway(
state: &SessionState,
refund: &storage::Refund,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
payment_attempt: &storage::PaymentAttempt,
payment_intent: &storage::PaymentIntent,
creds_identifier: Option<String>,
split_refunds: Option<SplitRefundsRequest>,
) -> RouterResult<storage::Refund> {
let routed_through = payment_attempt
.connector
.clone()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to retrieve connector from payment attempt")?;
let storage_scheme = merchant_account.storage_scheme;
metrics::REFUND_COUNT.add(
1,
router_env::metric_attributes!(("connector", routed_through.clone())),
);
let connector: api::ConnectorData = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
&routed_through,
api::GetToken::Connector,
payment_attempt.merchant_connector_id.clone(),
)?;
let currency = payment_attempt.currency.ok_or_else(|| {
report!(errors::ApiErrorResponse::InternalServerError).attach_printable(
"Transaction in invalid. Missing field \"currency\" in payment_attempt.",
)
})?;
validator::validate_for_valid_refunds(payment_attempt, connector.connector_name)?;
let mut router_data = core_utils::construct_refund_router_data(
state,
&routed_through,
merchant_account,
key_store,
(payment_attempt.get_total_amount(), currency),
payment_intent,
payment_attempt,
refund,
creds_identifier.clone(),
split_refunds,
)
.await?;
let add_access_token_result = access_token::add_access_token(
state,
&connector,
merchant_account,
&router_data,
creds_identifier.as_deref(),
)
.await?;
logger::debug!(refund_router_data=?router_data);
access_token::update_router_data_with_access_token_result(
&add_access_token_result,
&mut router_data,
&payments::CallConnectorAction::Trigger,
);
let router_data_res = if !(add_access_token_result.connector_supports_access_token
&& router_data.access_token.is_none())
{
let connector_integration: services::BoxedRefundConnectorIntegrationInterface<
api::Execute,
types::RefundsData,
types::RefundsResponseData,
> = connector.connector.get_connector_integration();
let router_data_res = services::execute_connector_processing_step(
state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
)
.await;
let option_refund_error_update =
router_data_res
.as_ref()
.err()
.and_then(|error| match error.current_context() {
errors::ConnectorError::NotImplemented(message) => {
Some(storage::RefundUpdate::ErrorUpdate {
refund_status: Some(enums::RefundStatus::Failure),
refund_error_message: Some(
errors::ConnectorError::NotImplemented(message.to_owned())
.to_string(),
),
refund_error_code: Some("NOT_IMPLEMENTED".to_string()),
updated_by: storage_scheme.to_string(),
connector_refund_id: None,
processor_refund_data: None,
unified_code: None,
unified_message: None,
issuer_error_code: None,
issuer_error_message: None,
})
}
errors::ConnectorError::NotSupported { message, connector } => {
Some(storage::RefundUpdate::ErrorUpdate {
refund_status: Some(enums::RefundStatus::Failure),
refund_error_message: Some(format!(
"{message} is not supported by {connector}"
)),
refund_error_code: Some("NOT_SUPPORTED".to_string()),
updated_by: storage_scheme.to_string(),
connector_refund_id: None,
processor_refund_data: None,
unified_code: None,
unified_message: None,
issuer_error_code: None,
issuer_error_message: None,
})
}
_ => None,
});
// Update the refund status as failure if connector_error is NotImplemented
if let Some(refund_error_update) = option_refund_error_update {
state
.store
.update_refund(
refund.to_owned(),
refund_error_update,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| {
format!(
"Failed while updating refund: refund_id: {}",
refund.refund_id
)
})?;
}
let mut refund_router_data_res = router_data_res.to_refund_failed_response()?;
// Initiating Integrity check
let integrity_result = check_refund_integrity(
&refund_router_data_res.request,
&refund_router_data_res.response,
);
refund_router_data_res.integrity_check = integrity_result;
refund_router_data_res
} else {
router_data
};
let refund_update = match router_data_res.response {
Err(err) => {
let option_gsm = helpers::get_gsm_record(
state,
Some(err.code.clone()),
Some(err.message.clone()),
connector.connector_name.to_string(),
consts::REFUND_FLOW_STR.to_string(),
)
.await;
// Note: Some connectors do not have a separate list of refund errors
// In such cases, the error codes and messages are stored under "Authorize" flow in GSM table
// So we will have to fetch the GSM using Authorize flow in case GSM is not found using "refund_flow"
let option_gsm = if option_gsm.is_none() {
helpers::get_gsm_record(
state,
Some(err.code.clone()),
Some(err.message.clone()),
connector.connector_name.to_string(),
consts::AUTHORIZE_FLOW_STR.to_string(),
)
.await
} else {
option_gsm
};
let gsm_unified_code = option_gsm.as_ref().and_then(|gsm| gsm.unified_code.clone());
let gsm_unified_message = option_gsm.and_then(|gsm| gsm.unified_message);
let (unified_code, unified_message) = if let Some((code, message)) =
gsm_unified_code.as_ref().zip(gsm_unified_message.as_ref())
{
(code.to_owned(), message.to_owned())
} else {
(
consts::DEFAULT_UNIFIED_ERROR_CODE.to_owned(),
consts::DEFAULT_UNIFIED_ERROR_MESSAGE.to_owned(),
)
};
storage::RefundUpdate::ErrorUpdate {
refund_status: Some(enums::RefundStatus::Failure),
refund_error_message: err.reason.or(Some(err.message)),
refund_error_code: Some(err.code),
updated_by: storage_scheme.to_string(),
connector_refund_id: None,
processor_refund_data: None,
unified_code: Some(unified_code),
unified_message: Some(unified_message),
issuer_error_code: err.network_decline_code,
issuer_error_message: err.network_error_message,
}
}
Ok(response) => {
// match on connector integrity checks
match router_data_res.integrity_check.clone() {
Err(err) => {
let (refund_connector_transaction_id, processor_refund_data) =
err.connector_transaction_id.map_or((None, None), |txn_id| {
let (refund_id, refund_data) =
ConnectorTransactionId::form_id_and_data(txn_id);
(Some(refund_id), refund_data)
});
metrics::INTEGRITY_CHECK_FAILED.add(
1,
router_env::metric_attributes!(
("connector", connector.connector_name.to_string()),
("merchant_id", merchant_account.get_id().clone()),
),
);
storage::RefundUpdate::ErrorUpdate {
refund_status: Some(enums::RefundStatus::ManualReview),
refund_error_message: Some(format!(
"Integrity Check Failed! as data mismatched for fields {}",
err.field_names
)),
refund_error_code: Some("IE".to_string()),
updated_by: storage_scheme.to_string(),
connector_refund_id: refund_connector_transaction_id,
processor_refund_data,
unified_code: None,
unified_message: None,
issuer_error_code: None,
issuer_error_message: None,
}
}
Ok(()) => {
if response.refund_status == diesel_models::enums::RefundStatus::Success {
metrics::SUCCESSFUL_REFUND.add(
1,
router_env::metric_attributes!((
"connector",
connector.connector_name.to_string(),
)),
)
}
let (connector_refund_id, processor_refund_data) =
ConnectorTransactionId::form_id_and_data(response.connector_refund_id);
storage::RefundUpdate::Update {
connector_refund_id,
refund_status: response.refund_status,
sent_to_gateway: true,
refund_error_message: None,
refund_arn: "".to_string(),
updated_by: storage_scheme.to_string(),
processor_refund_data,
}
}
}
}
};
let response = state
.store
.update_refund(
refund.to_owned(),
refund_update,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| {
format!(
"Failed while updating refund: refund_id: {}",
refund.refund_id
)
})?;
utils::trigger_refund_outgoing_webhook(
state,
merchant_account,
&response,
payment_attempt.profile_id.clone(),
key_store,
)
.await
.map_err(|error| logger::warn!(refunds_outgoing_webhook_error=?error))
.ok();
Ok(response)
}
<file_sep path="hyperswitch/v2_compatible_migrations/2024-08-28-081721_add_v2_columns/up.sql" role="context" start="59" end="70">
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/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=create_payment_method 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="133" end="232">
pub async fn create_payment_method(
state: &routes::SessionState,
req: &api::PaymentMethodCreate,
customer_id: &id_type::CustomerId,
payment_method_id: &str,
locker_id: Option<String>,
merchant_id: &id_type::MerchantId,
pm_metadata: Option<serde_json::Value>,
customer_acceptance: Option<serde_json::Value>,
payment_method_data: crypto::OptionalEncryptableValue,
key_store: &domain::MerchantKeyStore,
connector_mandate_details: Option<serde_json::Value>,
status: Option<enums::PaymentMethodStatus>,
network_transaction_id: Option<String>,
storage_scheme: MerchantStorageScheme,
payment_method_billing_address: crypto::OptionalEncryptableValue,
card_scheme: Option<String>,
network_token_requestor_reference_id: Option<String>,
network_token_locker_id: Option<String>,
network_token_payment_method_data: crypto::OptionalEncryptableValue,
) -> errors::CustomResult<domain::PaymentMethod, errors::ApiErrorResponse> {
let db = &*state.store;
let customer = db
.find_customer_by_customer_id_merchant_id(
&state.into(),
customer_id,
merchant_id,
key_store,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?;
let client_secret = generate_id(
consts::ID_LENGTH,
format!("{payment_method_id}_secret").as_str(),
);
let current_time = common_utils::date_time::now();
let response = db
.insert_payment_method(
&state.into(),
key_store,
domain::PaymentMethod {
customer_id: customer_id.to_owned(),
merchant_id: merchant_id.to_owned(),
payment_method_id: payment_method_id.to_string(),
locker_id,
payment_method: req.payment_method,
payment_method_type: req.payment_method_type,
payment_method_issuer: req.payment_method_issuer.clone(),
scheme: req.card_network.clone().or(card_scheme),
metadata: pm_metadata.map(Secret::new),
payment_method_data,
connector_mandate_details,
customer_acceptance: customer_acceptance.map(Secret::new),
client_secret: Some(client_secret),
status: status.unwrap_or(enums::PaymentMethodStatus::Active),
network_transaction_id: network_transaction_id.to_owned(),
payment_method_issuer_code: None,
accepted_currency: None,
token: None,
cardholder_name: None,
issuer_name: None,
issuer_country: None,
payer_country: None,
is_stored: None,
swift_code: None,
direct_debit_token: None,
created_at: current_time,
last_modified: current_time,
last_used_at: current_time,
payment_method_billing_address,
updated_by: None,
version: common_types::consts::API_VERSION,
network_token_requestor_reference_id,
network_token_locker_id,
network_token_payment_method_data,
},
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to add payment method in db")?;
if customer.default_payment_method_id.is_none() && req.payment_method.is_some() {
let _ = set_default_payment_method(
state,
merchant_id,
key_store.clone(),
customer_id,
payment_method_id.to_owned(),
storage_scheme,
)
.await
.map_err(|error| logger::error!(?error, "Failed to set the payment method as default"));
}
Ok(response)
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="132" end="132">
use crate::{
core::payment_methods as pm_core, headers, types::payment_methods as pm_types,
utils::ConnectorResponseExt,
};
#[cfg(all(
any(feature = "v1", feature = "v2"),
not(feature = "payment_methods_v2"),
not(feature = "customer_v2")
))]
#[instrument(skip_all)]
#[allow(clippy::too_many_arguments)]
pub async fn create_payment_method(
state: &routes::SessionState,
req: &api::PaymentMethodCreate,
customer_id: &id_type::CustomerId,
payment_method_id: &str,
locker_id: Option<String>,
merchant_id: &id_type::MerchantId,
pm_metadata: Option<serde_json::Value>,
customer_acceptance: Option<serde_json::Value>,
payment_method_data: crypto::OptionalEncryptableValue,
key_store: &domain::MerchantKeyStore,
connector_mandate_details: Option<serde_json::Value>,
status: Option<enums::PaymentMethodStatus>,
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="269" end="278">
pub fn store_default_payment_method(
_req: &api::PaymentMethodCreate,
_customer_id: &id_type::CustomerId,
_merchant_id: &id_type::MerchantId,
) -> (
api::PaymentMethodResponse,
Option<payment_methods::DataDuplicationCheck>,
) {
todo!()
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="238" end="266">
pub fn store_default_payment_method(
req: &api::PaymentMethodCreate,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
) -> (
api::PaymentMethodResponse,
Option<payment_methods::DataDuplicationCheck>,
) {
let pm_id = generate_id(consts::ID_LENGTH, "pm");
let payment_method_response = api::PaymentMethodResponse {
merchant_id: merchant_id.to_owned(),
customer_id: Some(customer_id.to_owned()),
payment_method_id: pm_id,
payment_method: req.payment_method,
payment_method_type: req.payment_method_type,
#[cfg(feature = "payouts")]
bank_transfer: None,
card: None,
metadata: req.metadata.clone(),
created: Some(common_utils::date_time::now()),
recurring_enabled: false, //[#219]
installment_payment_enabled: false, //[#219]
payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]),
last_used_at: Some(common_utils::date_time::now()),
client_secret: None,
};
(payment_method_response, None)
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="1030" end="1107">
pub async fn get_client_secret_or_add_payment_method(
state: &routes::SessionState,
req: api::PaymentMethodCreate,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
) -> errors::RouterResponse<api::PaymentMethodResponse> {
let merchant_id = merchant_account.get_id();
let customer_id = req.customer_id.clone().get_required_value("customer_id")?;
#[cfg(not(feature = "payouts"))]
let condition = req.card.is_some();
#[cfg(feature = "payouts")]
let condition = req.card.is_some() || req.bank_transfer.is_some() || req.wallet.is_some();
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)?;
if condition {
Box::pin(add_payment_method(state, req, merchant_account, key_store)).await
} else {
let payment_method_id = generate_id(consts::ID_LENGTH, "pm");
let res = create_payment_method(
state,
&req,
&customer_id,
payment_method_id.as_str(),
None,
merchant_id,
None,
None,
None,
key_store,
connector_mandate_details,
Some(enums::PaymentMethodStatus::AwaitingData),
None,
merchant_account.storage_scheme,
payment_method_billing_address,
None,
None,
None,
None,
)
.await?;
if res.status == enums::PaymentMethodStatus::AwaitingData {
add_payment_method_status_update_task(
&*state.store,
&res,
enums::PaymentMethodStatus::AwaitingData,
enums::PaymentMethodStatus::Inactive,
merchant_id,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Failed to add payment method status update task in process tracker",
)?;
}
Ok(services::api::ApplicationResponse::Json(
api::PaymentMethodResponse::foreign_from((None, res)),
))
}
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="1114" end="1212">
pub async fn get_client_secret_or_add_payment_method_for_migration(
state: &routes::SessionState,
req: api::PaymentMethodCreate,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
migration_status: &mut migration::RecordMigrationStatusBuilder,
) -> errors::RouterResponse<api::PaymentMethodResponse> {
let merchant_id = merchant_account.get_id();
let customer_id = req.customer_id.clone().get_required_value("customer_id")?;
#[cfg(not(feature = "payouts"))]
let condition = req.card.is_some();
#[cfg(feature = "payouts")]
let condition = req.card.is_some() || req.bank_transfer.is_some() || req.wallet.is_some();
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)?;
if condition {
Box::pin(save_migration_payment_method(
state,
req,
merchant_account,
key_store,
migration_status,
))
.await
} else {
let payment_method_id = generate_id(consts::ID_LENGTH, "pm");
let res = create_payment_method(
state,
&req,
&customer_id,
payment_method_id.as_str(),
None,
merchant_id,
None,
None,
None,
key_store,
connector_mandate_details.clone(),
Some(enums::PaymentMethodStatus::AwaitingData),
None,
merchant_account.storage_scheme,
payment_method_billing_address,
None,
None,
None,
None,
)
.await?;
migration_status.connector_mandate_details_migrated(
connector_mandate_details
.clone()
.and_then(|val| (val != json!({})).then_some(true))
.or_else(|| {
req.connector_mandate_details
.clone()
.and_then(|val| (!val.0.is_empty()).then_some(false))
}),
);
//card is not migrated in this case
migration_status.card_migrated(false);
if res.status == enums::PaymentMethodStatus::AwaitingData {
add_payment_method_status_update_task(
&*state.store,
&res,
enums::PaymentMethodStatus::AwaitingData,
enums::PaymentMethodStatus::Inactive,
merchant_id,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Failed to add payment method status update task in process tracker",
)?;
}
Ok(services::api::ApplicationResponse::Json(
api::PaymentMethodResponse::foreign_from((None, res)),
))
}
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="5487" end="5570">
pub async fn set_default_payment_method(
state: &routes::SessionState,
merchant_id: &id_type::MerchantId,
key_store: domain::MerchantKeyStore,
customer_id: &id_type::CustomerId,
payment_method_id: String,
storage_scheme: MerchantStorageScheme,
) -> errors::RouterResponse<api_models::payment_methods::CustomerDefaultPaymentMethodResponse> {
let db = &*state.store;
let key_manager_state = &state.into();
// check for the customer
// TODO: customer need not be checked again here, this function can take an optional customer and check for existence of customer based on the optional value
let customer = db
.find_customer_by_customer_id_merchant_id(
key_manager_state,
customer_id,
merchant_id,
&key_store,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?;
// check for the presence of payment_method
let payment_method = db
.find_payment_method(
&(state.into()),
&key_store,
&payment_method_id,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
let pm = payment_method
.get_payment_method_type()
.get_required_value("payment_method")?;
utils::when(
&payment_method.customer_id != customer_id || payment_method.merchant_id != *merchant_id,
|| {
Err(errors::ApiErrorResponse::PreconditionFailed {
message: "The payment_method_id is not valid".to_string(),
})
},
)?;
utils::when(
Some(payment_method_id.clone()) == customer.default_payment_method_id,
|| {
Err(errors::ApiErrorResponse::PreconditionFailed {
message: "Payment Method is already set as default".to_string(),
})
},
)?;
let customer_id = customer.customer_id.clone();
let customer_update = CustomerUpdate::UpdateDefaultPaymentMethod {
default_payment_method_id: Some(Some(payment_method_id.to_owned())),
};
// update the db with the default payment method id
let updated_customer_details = db
.update_customer_by_customer_id_merchant_id(
key_manager_state,
customer_id.to_owned(),
merchant_id.to_owned(),
customer,
customer_update,
&key_store,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update the default payment method id for the customer")?;
let resp = api_models::payment_methods::CustomerDefaultPaymentMethodResponse {
default_payment_method_id: updated_customer_details.default_payment_method_id,
customer_id,
payment_method_type: payment_method.get_payment_method_subtype(),
payment_method: pm,
};
Ok(services::ApplicationResponse::Json(resp))
}
<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);
| 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="2526" end="2620">
fn try_from(
item: types::ResponseRouterData<F, PaymentIntentResponse, T, types::PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let redirect_data = item.response.next_action.clone();
let redirection_data = redirect_data
.and_then(|redirection_data| redirection_data.get_url())
.map(|redirection_url| {
services::RedirectForm::from((redirection_url, services::Method::Get))
});
let mandate_reference = item.response.payment_method.map(|payment_method_id| {
// Implemented Save and re-use payment information for recurring charges
// For more info: https://docs.stripe.com/recurring-payments#accept-recurring-payments
// For backward compatibility payment_method_id & connector_mandate_id is being populated with the same value
let connector_mandate_id = Some(payment_method_id.clone().expose());
let payment_method_id = Some(payment_method_id.expose());
types::MandateReference {
connector_mandate_id,
payment_method_id,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
}
});
//Note: we might have to call retrieve_setup_intent to get the network_transaction_id in case its not sent in PaymentIntentResponse
// Or we identify the mandate txns before hand and always call SetupIntent in case of mandate payment call
let network_txn_id = match item.response.latest_charge.as_ref() {
Some(StripeChargeEnum::ChargeObject(charge_object)) => charge_object
.payment_method_details
.as_ref()
.and_then(|payment_method_details| match payment_method_details {
StripePaymentMethodDetailsResponse::Card { card } => {
card.network_transaction_id.clone()
}
_ => None,
}),
_ => None,
};
let connector_metadata =
get_connector_metadata(item.response.next_action.as_ref(), item.response.amount)?;
let status = enums::AttemptStatus::from(item.response.status);
let response = if connector_util::is_payment_failure(status) {
types::PaymentsResponseData::foreign_try_from((
&item.response.last_payment_error,
item.http_code,
item.response.id.clone(),
))
} else {
let charges = item
.response
.latest_charge
.as_ref()
.map(|charge| match charge {
StripeChargeEnum::ChargeId(charges) => charges.clone(),
StripeChargeEnum::ChargeObject(charge) => charge.id.clone(),
})
.and_then(|charge_id| construct_charge_response(charge_id, &item.data.request));
Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(mandate_reference),
connector_metadata,
network_txn_id,
connector_response_reference_id: Some(item.response.id),
incremental_authorization_allowed: None,
charges,
})
};
let connector_response_data = item
.response
.latest_charge
.as_ref()
.and_then(extract_payment_method_connector_response_from_latest_charge);
Ok(Self {
status,
// client_secret: Some(item.response.client_secret.clone().as_str()),
// description: item.response.description.map(|x| x.as_str()),
// statement_descriptor_suffix: item.response.statement_descriptor_suffix.map(|x| x.as_str()),
// three_ds_form,
response,
amount_captured: item
.response
.amount_received
.map(|amount| amount.get_amount_as_i64()),
minor_amount_captured: item.response.amount_received,
connector_response: connector_response_data,
..item.data
})
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="2525" end="2525">
use std::{collections::HashMap, ops::Deref};
use api_models::{self, enums as api_enums, payments};
use common_utils::{
errors::CustomResult,
ext_traits::{ByteSliceExt, Encode},
pii::{self, Email},
request::RequestContent,
types::MinorUnit,
};
use error_stack::ResultExt;
use hyperswitch_domain_models::mandates::AcceptanceType;
use masking::{ExposeInterface, ExposeOptionInterface, Mask, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use time::PrimitiveDateTime;
use url::Url;
pub use self::connect::*;
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="2741" end="2876">
fn try_from(
item: types::ResponseRouterData<
F,
PaymentIntentSyncResponse,
T,
types::PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let redirect_data = item.response.next_action.clone();
let redirection_data = redirect_data
.and_then(|redirection_data| redirection_data.get_url())
.map(|redirection_url| {
services::RedirectForm::from((redirection_url, services::Method::Get))
});
let mandate_reference = item
.response
.payment_method
.clone()
.map(|payment_method_id| {
// Implemented Save and re-use payment information for recurring charges
// For more info: https://docs.stripe.com/recurring-payments#accept-recurring-payments
// For backward compatibility payment_method_id & connector_mandate_id is being populated with the same value
let connector_mandate_id = Some(payment_method_id.clone().expose());
let payment_method_id = match item.response.latest_charge.clone() {
Some(StripeChargeEnum::ChargeObject(charge)) => {
match charge.payment_method_details {
Some(StripePaymentMethodDetailsResponse::Bancontact { bancontact }) => {
bancontact
.attached_payment_method
.map(|attached_payment_method| attached_payment_method.expose())
.unwrap_or(payment_method_id.expose())
}
Some(StripePaymentMethodDetailsResponse::Ideal { ideal }) => ideal
.attached_payment_method
.map(|attached_payment_method| attached_payment_method.expose())
.unwrap_or(payment_method_id.expose()),
Some(StripePaymentMethodDetailsResponse::Sofort { sofort }) => sofort
.attached_payment_method
.map(|attached_payment_method| attached_payment_method.expose())
.unwrap_or(payment_method_id.expose()),
Some(StripePaymentMethodDetailsResponse::Blik)
| Some(StripePaymentMethodDetailsResponse::Eps)
| Some(StripePaymentMethodDetailsResponse::Fpx)
| Some(StripePaymentMethodDetailsResponse::Giropay)
| Some(StripePaymentMethodDetailsResponse::Przelewy24)
| Some(StripePaymentMethodDetailsResponse::Card { .. })
| Some(StripePaymentMethodDetailsResponse::Klarna)
| Some(StripePaymentMethodDetailsResponse::Affirm)
| Some(StripePaymentMethodDetailsResponse::AfterpayClearpay)
| Some(StripePaymentMethodDetailsResponse::AmazonPay)
| Some(StripePaymentMethodDetailsResponse::ApplePay)
| Some(StripePaymentMethodDetailsResponse::Ach)
| Some(StripePaymentMethodDetailsResponse::Sepa)
| Some(StripePaymentMethodDetailsResponse::Becs)
| Some(StripePaymentMethodDetailsResponse::Bacs)
| Some(StripePaymentMethodDetailsResponse::Wechatpay)
| Some(StripePaymentMethodDetailsResponse::Alipay)
| Some(StripePaymentMethodDetailsResponse::CustomerBalance)
| Some(StripePaymentMethodDetailsResponse::Cashapp { .. })
| None => payment_method_id.expose(),
}
}
Some(StripeChargeEnum::ChargeId(_)) | None => payment_method_id.expose(),
};
types::MandateReference {
connector_mandate_id,
payment_method_id: Some(payment_method_id),
mandate_metadata: None,
connector_mandate_request_reference_id: None,
}
});
let connector_metadata =
get_connector_metadata(item.response.next_action.as_ref(), item.response.amount)?;
let status = enums::AttemptStatus::from(item.response.status.to_owned());
let connector_response_data = item
.response
.latest_charge
.as_ref()
.and_then(extract_payment_method_connector_response_from_latest_charge);
let response = if connector_util::is_payment_failure(status) {
types::PaymentsResponseData::foreign_try_from((
&item.response.payment_intent_fields.last_payment_error,
item.http_code,
item.response.id.clone(),
))
} else {
let network_transaction_id = match item.response.latest_charge.clone() {
Some(StripeChargeEnum::ChargeObject(charge_object)) => charge_object
.payment_method_details
.and_then(|payment_method_details| match payment_method_details {
StripePaymentMethodDetailsResponse::Card { card } => {
card.network_transaction_id
}
_ => None,
}),
_ => None,
};
let charges = item
.response
.latest_charge
.as_ref()
.map(|charge| match charge {
StripeChargeEnum::ChargeId(charges) => charges.clone(),
StripeChargeEnum::ChargeObject(charge) => charge.id.clone(),
})
.and_then(|charge_id| construct_charge_response(charge_id, &item.data.request));
Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(mandate_reference),
connector_metadata,
network_txn_id: network_transaction_id,
connector_response_reference_id: Some(item.response.id.clone()),
incremental_authorization_allowed: None,
charges,
})
};
Ok(Self {
status: enums::AttemptStatus::from(item.response.status.to_owned()),
response,
amount_captured: item
.response
.amount_received
.map(|amount| amount.get_amount_as_i64()),
minor_amount_captured: item.response.amount_received,
connector_response: connector_response_data,
..item.data
})
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="2623" end="2732">
pub fn get_connector_metadata(
next_action: Option<&StripeNextActionResponse>,
amount: MinorUnit,
) -> CustomResult<Option<Value>, errors::ConnectorError> {
let next_action_response = next_action
.and_then(|next_action_response| match next_action_response {
StripeNextActionResponse::DisplayBankTransferInstructions(response) => {
match response.financial_addresses.clone() {
FinancialInformation::StripeFinancialInformation(financial_addresses) => {
let bank_instructions = financial_addresses.first();
let (sepa_bank_instructions, bacs_bank_instructions) = bank_instructions
.map_or((None, None), |financial_address| {
(
financial_address.iban.to_owned().map(
|sepa_financial_details| SepaFinancialDetails {
account_holder_name: sepa_financial_details
.account_holder_name,
bic: sepa_financial_details.bic,
country: sepa_financial_details.country,
iban: sepa_financial_details.iban,
reference: response.reference.to_owned(),
},
),
financial_address.sort_code.to_owned(),
)
});
let bank_transfer_instructions = SepaAndBacsBankTransferInstructions {
sepa_bank_instructions,
bacs_bank_instructions,
receiver: SepaAndBacsReceiver {
amount_received: amount - response.amount_remaining,
amount_remaining: response.amount_remaining,
},
};
Some(bank_transfer_instructions.encode_to_value())
}
FinancialInformation::AchFinancialInformation(financial_addresses) => {
let mut ach_financial_information = HashMap::new();
for address in financial_addresses {
match address.financial_details {
AchFinancialDetails::Aba(aba_details) => {
ach_financial_information
.insert("account_number", aba_details.account_number);
ach_financial_information
.insert("bank_name", aba_details.bank_name);
ach_financial_information
.insert("routing_number", aba_details.routing_number);
}
AchFinancialDetails::Swift(swift_details) => {
ach_financial_information
.insert("swift_code", swift_details.swift_code);
}
}
}
let ach_financial_information_value =
serde_json::to_value(ach_financial_information).ok()?;
let ach_transfer_instruction =
serde_json::from_value::<payments::AchTransfer>(
ach_financial_information_value,
)
.ok()?;
let bank_transfer_instructions = payments::BankTransferNextStepsData {
bank_transfer_instructions:
payments::BankTransferInstructions::AchCreditTransfer(Box::new(
ach_transfer_instruction,
)),
receiver: None,
};
Some(bank_transfer_instructions.encode_to_value())
}
}
}
StripeNextActionResponse::WechatPayDisplayQrCode(response) => {
let wechat_pay_instructions = QrCodeNextInstructions {
image_data_url: response.image_data_url.to_owned(),
display_to_timestamp: None,
};
Some(wechat_pay_instructions.encode_to_value())
}
StripeNextActionResponse::CashappHandleRedirectOrDisplayQrCode(response) => {
let cashapp_qr_instructions: QrCodeNextInstructions = QrCodeNextInstructions {
image_data_url: response.qr_code.image_url_png.to_owned(),
display_to_timestamp: response.qr_code.expires_at.to_owned(),
};
Some(cashapp_qr_instructions.encode_to_value())
}
StripeNextActionResponse::MultibancoDisplayDetails(response) => {
let multibanco_bank_transfer_instructions = payments::BankTransferNextStepsData {
bank_transfer_instructions: payments::BankTransferInstructions::Multibanco(
Box::new(payments::MultibancoTransferInstructions {
reference: response.clone().reference,
entity: response.clone().entity.expose(),
}),
),
receiver: None,
};
Some(multibanco_bank_transfer_instructions.encode_to_value())
}
_ => None,
})
.transpose()
.change_context(errors::ConnectorError::ResponseHandlingFailed)?;
Ok(next_action_response)
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="2504" end="2517">
fn extract_payment_method_connector_response_from_latest_attempt(
stripe_latest_attempt: &LatestAttempt,
) -> Option<types::ConnectorResponseData> {
if let LatestAttempt::PaymentIntentAttempt(intent_attempt) = stripe_latest_attempt {
intent_attempt
.payment_method_details
.as_ref()
.and_then(StripePaymentMethodDetailsResponse::get_additional_payment_method_data)
} else {
None
}
.map(types::AdditionalPaymentMethodConnectorResponse::from)
.map(types::ConnectorResponseData::with_additional_payment_method_data)
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="2489" end="2502">
fn extract_payment_method_connector_response_from_latest_charge(
stripe_charge_enum: &StripeChargeEnum,
) -> Option<types::ConnectorResponseData> {
if let StripeChargeEnum::ChargeObject(charge_object) = stripe_charge_enum {
charge_object
.payment_method_details
.as_ref()
.and_then(StripePaymentMethodDetailsResponse::get_additional_payment_method_data)
} else {
None
}
.map(types::AdditionalPaymentMethodConnectorResponse::from)
.map(types::ConnectorResponseData::with_additional_payment_method_data)
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="4255" end="4281">
pub fn construct_charge_response<T>(
charge_id: String,
request: &T,
) -> Option<common_types::payments::ConnectorChargeResponseData>
where
T: connector_util::SplitPaymentData,
{
let charge_request = request.get_split_payment_data();
if let Some(common_types::payments::SplitPaymentsRequest::StripeSplitPayment(
stripe_split_payment,
)) = charge_request
{
let stripe_charge_response = common_types::payments::StripeChargeResponseData {
charge_id: Some(charge_id),
charge_type: stripe_split_payment.charge_type,
application_fees: stripe_split_payment.application_fees,
transfer_account_id: stripe_split_payment.transfer_account_id,
};
Some(
common_types::payments::ConnectorChargeResponseData::StripeSplitPayment(
stripe_charge_response,
),
)
} else {
None
}
}
<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/connector/stripe/transformers.rs" role="context" start="2337" end="2379">
pub enum StripePaymentMethodDetailsResponse {
//only ideal, sofort and bancontact is supported by stripe for recurring payment in bank redirect
Ideal {
ideal: StripeBankRedirectDetails,
},
Sofort {
sofort: StripeBankRedirectDetails,
},
Bancontact {
bancontact: StripeBankRedirectDetails,
},
//other payment method types supported by stripe. To avoid deserialization error.
Blik,
Eps,
Fpx,
Giropay,
#[serde(rename = "p24")]
Przelewy24,
Card {
card: StripeAdditionalCardDetails,
},
Cashapp {
cashapp: StripeCashappDetails,
},
Klarna,
Affirm,
AfterpayClearpay,
AmazonPay,
ApplePay,
#[serde(rename = "us_bank_account")]
Ach,
#[serde(rename = "sepa_debit")]
Sepa,
#[serde(rename = "au_becs_debit")]
Becs,
#[serde(rename = "bacs_debit")]
Bacs,
#[serde(rename = "wechat_pay")]
Wechatpay,
Alipay,
CustomerBalance,
}
<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/connector/gpayments.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/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="527" end="527">
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="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="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="513" end="519">
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/gpayments.rs" role="context" start="494" end="511">
fn handle_response(
&self,
data: &types::authentication::PreAuthNRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::authentication::PreAuthNRouterData, errors::ConnectorError> {
let response: gpayments_types::GpaymentsPreAuthenticationResponse = res
.response
.parse_struct("gpayments GpaymentsPreAuthenticationResponse")
.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/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/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/types/api.rs<|crate|> router anchor=convert_connector kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/types/api.rs" role="context" start="642" end="650">
fn convert_connector(
connector_name: enums::TaxConnectors,
) -> CustomResult<ConnectorEnum, errors::ApiErrorResponse> {
match connector_name {
enums::TaxConnectors::Taxjar => {
Ok(ConnectorEnum::Old(Box::new(connector::Taxjar::new())))
}
}
}
<file_sep path="hyperswitch/crates/router/src/types/api.rs" role="context" start="641" end="641">
use crate::{
configs::settings::Connectors,
connector, consts,
core::{
errors::{self, CustomResult},
payments::types as payments_types,
},
services::connector_integration_interface::ConnectorEnum,
types::{self, api::enums as api_enums},
};
<file_sep path="hyperswitch/crates/router/src/types/api.rs" role="context" start="631" end="640">
pub fn get_connector_by_name(name: &str) -> CustomResult<Self, errors::ApiErrorResponse> {
let connector_name = enums::TaxConnectors::from_str(name)
.change_context(errors::ApiErrorResponse::IncorrectConnectorNameGiven)
.attach_printable_lazy(|| format!("unable to parse connector: {name}"))?;
let connector = Self::convert_connector(connector_name)?;
Ok(Self {
connector,
connector_name,
})
}
<file_sep path="hyperswitch/crates/router/src/types/api.rs" role="context" start="612" end="621">
fn test_convert_connector_parsing_fail_for_camel_case() {
let result = enums::Connector::from_str("Paypal");
assert!(result.is_err());
let result = enums::Connector::from_str("Authorizedotnet");
assert!(result.is_err());
let result = enums::Connector::from_str("Opennode");
assert!(result.is_err());
}
<file_sep path="hyperswitch/crates/router/src/types/api.rs" role="context" start="267" end="285">
pub fn get_payout_connector_by_name(
_connectors: &Connectors,
name: &str,
connector_type: GetToken,
connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
) -> CustomResult<Self, errors::ApiErrorResponse> {
let connector = Self::convert_connector(name)?;
let payout_connector_name = api_enums::PayoutConnectors::from_str(name)
.change_context(errors::ConnectorError::InvalidConnectorName)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| format!("unable to parse payout connector name {name}"))?;
let connector_name = api_enums::Connector::from(payout_connector_name);
Ok(Self {
connector,
connector_name,
get_token: connector_type,
merchant_connector_id: connector_id,
})
}
<file_sep path="hyperswitch/crates/router/src/types/api.rs" role="context" start="247" end="264">
pub fn get_connector_by_name(
_connectors: &Connectors,
name: &str,
connector_type: GetToken,
connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
) -> CustomResult<Self, errors::ApiErrorResponse> {
let connector = Self::convert_connector(name)?;
let connector_name = api_enums::Connector::from_str(name)
.change_context(errors::ConnectorError::InvalidConnectorName)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| format!("unable to parse connector name {name}"))?;
Ok(Self {
connector,
connector_name,
get_token: connector_type,
merchant_connector_id: connector_id,
})
}
<file_sep path="hyperswitch/crates/router/src/types/api.rs" role="context" start="133" end="145">
pub fn new(
payment_method_sub_type: api_enums::PaymentMethodType,
connector: ConnectorData,
business_sub_label: Option<String>,
payment_method_type: api_enums::PaymentMethod,
) -> Self {
Self {
payment_method_sub_type,
connector,
business_sub_label,
payment_method_type,
}
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/plaid.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/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)))
}
<file_sep path="hyperswitch/crates/router/src/connector/plaid.rs" role="context" start="365" end="365">
use common_utils::types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector};
use transformers as plaid;
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, RequestContent, Response,
},
utils::BytesExt,
};
<file_sep path="hyperswitch/crates/router/src/connector/plaid.rs" role="context" start="397" end="414">
fn handle_response(
&self,
data: &types::PaymentsPostProcessingRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsPostProcessingRouterData, errors::ConnectorError> {
let response: plaid::PlaidLinkTokenResponse = res
.response
.parse_struct("PlaidLinkTokenResponse")
.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/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="358" end="364">
fn get_url(
&self,
_req: &types::PaymentsPostProcessingRouterData,
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}/link/token/create", self.base_url(connectors)))
}
<file_sep path="hyperswitch/crates/router/src/connector/plaid.rs" role="context" start="354" end="356">
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
<file_sep path="hyperswitch/crates/router/src/connector/plaid.rs" role="context" start="293" end="309">
fn build_request(
&self,
req: &types::PaymentsSyncRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Post)
.url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
.set_body(types::PaymentsSyncType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
<file_sep path="hyperswitch/crates/router/src/connector/plaid.rs" role="context" start="208" end="228">
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,
)?)
.attach_default_headers()
.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/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/transformers.rs" role="context" start="68" end="77">
pub struct PlaidLinkTokenRequest {
client_name: String,
country_codes: Vec<String>,
language: String,
products: Vec<String>,
user: User,
payment_initiation: PlaidPaymentInitiation,
redirect_uri: Option<String>,
android_package_name: Option<String>,
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/utils.rs<|crate|> router anchor=convert_back_amount_to_minor_units 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="3087" end="3095">
pub fn convert_back_amount_to_minor_units<T>(
amount_convertor: &dyn AmountConvertor<Output = T>,
amount: T,
currency: enums::Currency,
) -> Result<MinorUnit, error_stack::Report<errors::ConnectorError>> {
amount_convertor
.convert_back(amount, currency)
.change_context(errors::ConnectorError::AmountConversionFailed)
}
<file_sep path="hyperswitch/crates/router/src/connector/utils.rs" role="context" start="3086" end="3086">
use api_models::{
enums::{CanadaStatesAbbreviation, UsStatesAbbreviation},
payments,
};
use common_utils::{
date_time,
errors::{ParsingError, ReportSwitchExt},
ext_traits::StringExt,
id_type,
pii::{self, Email, IpAddress},
types::{AmountConvertor, MinorUnit},
};
use diesel_models::{enums, types::OrderDetailsWithAmount};
use error_stack::{report, ResultExt};
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="3114" end="3128">
pub fn get_sync_integrity_object<T>(
amount_convertor: &dyn AmountConvertor<Output = T>,
amount: T,
currency: String,
) -> Result<SyncIntegrityObject, error_stack::Report<errors::ConnectorError>> {
let currency_enum = enums::Currency::from_str(currency.to_uppercase().as_str())
.change_context(errors::ConnectorError::ParsingFailed)?;
let amount_in_minor_unit =
convert_back_amount_to_minor_units(amount_convertor, amount, currency_enum)?;
Ok(SyncIntegrityObject {
amount: Some(amount_in_minor_unit),
currency: Some(currency_enum),
})
}
<file_sep path="hyperswitch/crates/router/src/connector/utils.rs" role="context" start="3097" end="3112">
pub fn get_authorise_integrity_object<T>(
amount_convertor: &dyn AmountConvertor<Output = T>,
amount: T,
currency: String,
) -> Result<AuthoriseIntegrityObject, error_stack::Report<errors::ConnectorError>> {
let currency_enum = enums::Currency::from_str(currency.to_uppercase().as_str())
.change_context(errors::ConnectorError::ParsingFailed)?;
let amount_in_minor_unit =
convert_back_amount_to_minor_units(amount_convertor, amount, currency_enum)?;
Ok(AuthoriseIntegrityObject {
amount: amount_in_minor_unit,
currency: currency_enum,
})
}
<file_sep path="hyperswitch/crates/router/src/connector/utils.rs" role="context" start="3077" end="3085">
pub fn convert_amount<T>(
amount_convertor: &dyn AmountConvertor<Output = T>,
amount: MinorUnit,
currency: enums::Currency,
) -> Result<T, error_stack::Report<errors::ConnectorError>> {
amount_convertor
.convert(amount, currency)
.change_context(errors::ConnectorError::AmountConversionFailed)
}
<file_sep path="hyperswitch/crates/router/src/connector/utils.rs" role="context" start="3056" end="3075">
pub fn get_mandate_details(
setup_mandate_details: Option<&mandates::MandateData>,
) -> Result<Option<&mandates::MandateAmountData>, error_stack::Report<errors::ConnectorError>> {
setup_mandate_details
.map(|mandate_data| match &mandate_data.mandate_type {
Some(mandates::MandateDataType::SingleUse(mandate))
| Some(mandates::MandateDataType::MultiUse(Some(mandate))) => Ok(mandate),
Some(mandates::MandateDataType::MultiUse(None)) => {
Err(errors::ConnectorError::MissingRequiredField {
field_name: "setup_future_usage.mandate_data.mandate_type.multi_use.amount",
}
.into())
}
None => Err(errors::ConnectorError::MissingRequiredField {
field_name: "setup_future_usage.mandate_data.mandate_type",
}
.into()),
})
.transpose()
}
<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/core/payment_methods.rs" role="context" start="2129" end="2129">
type Output = hyperswitch_domain_models::payment_methods::DecryptedPaymentMethodSession;
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/riskified.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/riskified.rs" role="context" start="426" end="433">
fn get_request_body(
&self,
req: &frm_types::FrmFulfillmentRouterData,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let req_obj = riskified::RiskifiedFulfillmentRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(req_obj)))
}
<file_sep path="hyperswitch/crates/router/src/connector/riskified.rs" role="context" start="425" end="425">
use common_utils::{crypto, ext_traits::ByteSliceExt, request::RequestContent};
use transformers as riskified;
use super::utils::{self as connector_utils, FrmTransactionRouterDataRequest};
use crate::{
configs::settings,
core::errors::{self, CustomResult},
services::{self, ConnectorIntegration, ConnectorSpecifications, ConnectorValidation},
types::{
self,
api::{self, ConnectorCommon, ConnectorCommonExt},
},
};
use crate::{
consts,
events::connector_api_logs::ConnectorEvent,
headers,
services::request,
types::{api::fraud_check as frm_api, fraud_check as frm_types, ErrorResponse, Response},
utils::BytesExt,
};
<file_sep path="hyperswitch/crates/router/src/connector/riskified.rs" role="context" start="457" end="476">
fn handle_response(
&self,
data: &frm_types::FrmFulfillmentRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<frm_types::FrmFulfillmentRouterData, errors::ConnectorError> {
let response: riskified::RiskifiedFulfilmentResponse = res
.response
.parse_struct("RiskifiedFulfilmentResponse fulfilment")
.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/riskified.rs" role="context" start="435" end="455">
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/riskified.rs" role="context" start="418" end="424">
fn get_url(
&self,
_req: &frm_types::FrmFulfillmentRouterData,
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}{}", self.base_url(connectors), "/fulfill"))
}
<file_sep path="hyperswitch/crates/router/src/connector/riskified.rs" role="context" start="414" end="416">
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
<file_sep path="hyperswitch/crates/router/src/connector/riskified.rs" role="context" start="336" end="356">
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/riskified.rs" role="context" start="47" end="51">
pub fn new() -> &'static Self {
&Self {
amount_converter: &StringMajorUnitForConnector,
}
}
<file_sep path="hyperswitch/crates/router/src/types/fraud_check.rs" role="context" start="64" end="65">
pub type FrmFulfillmentRouterData =
RouterData<api::Fulfillment, FraudCheckFulfillmentData, FraudCheckResponseData>;
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/ebanx.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/ebanx.rs" role="context" start="319" end="326">
fn get_request_body(
&self,
req: &types::PayoutsRouterData<api::PoCancel>,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = ebanx::EbanxPayoutCancelRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
<file_sep path="hyperswitch/crates/router/src/connector/ebanx.rs" role="context" start="318" end="318">
use common_utils::request::RequestContent;
use common_utils::types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector};
use transformers as ebanx;
use crate::{
configs::settings,
core::errors::{self, CustomResult},
events::connector_api_logs::ConnectorEvent,
services::{ConnectorIntegration, ConnectorSpecifications, ConnectorValidation},
types::{
self,
api::{self, ConnectorCommon, ConnectorCommonExt},
},
utils::BytesExt,
};
use crate::{
headers,
services::{self, request},
};
<file_sep path="hyperswitch/crates/router/src/connector/ebanx.rs" role="context" start="347" end="366">
fn handle_response(
&self,
data: &types::PayoutsRouterData<api::PoCancel>,
event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PayoutsRouterData<api::PoCancel>, errors::ConnectorError> {
let response: ebanx::EbanxCancelResponse = res
.response
.parse_struct("EbanxCancelResponse")
.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/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))
}
<file_sep path="hyperswitch/crates/router/src/connector/ebanx.rs" role="context" start="311" end="317">
fn get_headers(
&self,
req: &types::PayoutsRouterData<api::PoCancel>,
_connectors: &settings::Connectors,
) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, _connectors)
}
<file_sep path="hyperswitch/crates/router/src/connector/ebanx.rs" role="context" start="303" end="309">
fn get_url(
&self,
_req: &types::PayoutsRouterData<api::PoCancel>,
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}ws/payout/cancel", connectors.ebanx.base_url,))
}
<file_sep path="hyperswitch/crates/router/src/connector/ebanx.rs" role="context" start="167" end="183">
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/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/types.rs" role="context" start="226" end="226">
pub type PayoutsRouterData<F> = RouterData<F, PayoutsData, PayoutsResponseData>;
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/services/email/types.rs<|crate|> router anchor=new_token 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="274" end="289">
pub async fn new_token(
email: domain::UserEmail,
entity: Option<Entity>,
flow: domain::Origin,
settings: &configs::Settings,
) -> UserResult<String> {
let expiration_duration = std::time::Duration::from_secs(consts::EMAIL_TOKEN_TIME_IN_SECS);
let exp = jwt::generate_exp(expiration_duration)?.as_secs();
let token_payload = Self {
email: email.get_secret().expose(),
flow,
exp,
entity,
};
jwt::generate_jwt(&token_payload, settings).await
}
<file_sep path="hyperswitch/crates/router/src/services/email/types.rs" role="context" start="273" end="273">
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="297" end="299">
pub fn get_entity(&self) -> Option<&Entity> {
self.entity.as_ref()
}
<file_sep path="hyperswitch/crates/router/src/services/email/types.rs" role="context" start="291" end="295">
pub fn get_email(&self) -> UserResult<domain::UserEmail> {
pii::Email::try_from(self.email.clone())
.change_context(UserErrors::InternalServerError)
.and_then(domain::UserEmail::from_pii_email)
}
<file_sep path="hyperswitch/crates/router/src/services/email/types.rs" role="context" start="268" end="270">
pub fn get_entity_id(&self) -> &str {
&self.entity_id
}
<file_sep path="hyperswitch/crates/router/src/services/email/types.rs" role="context" start="264" end="266">
pub fn get_entity_type(&self) -> EntityType {
self.entity_type
}
<file_sep path="hyperswitch/crates/router/src/services/email/types.rs" role="context" start="343" end="378">
async fn get_email_data(&self, base_url: &str) -> CustomResult<EmailContents, EmailError> {
let token = EmailToken::new_token(
self.recipient_email.clone(),
None,
domain::Origin::VerifyEmail,
&self.settings,
)
.await
.change_context(EmailError::TokenGenerationFailure)?;
let verify_email_link = get_link_with_token(
base_url,
token,
"verify_email",
&self.auth_id,
&self.theme_id,
);
let body = html::get_html_body(EmailBody::Verify {
link: verify_email_link,
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!(
"Welcome to the {} 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="258" end="261">
pub struct Entity {
pub entity_id: String,
pub entity_type: EntityType,
}
<file_sep path="hyperswitch/crates/router/src/types/domain/user/decision_manager.rs" role="context" start="149" end="158">
pub enum Origin {
#[serde(rename = "sign_in_with_sso")]
SignInWithSSO,
SignIn,
SignUp,
MagicLink,
VerifyEmail,
AcceptInvitationFromEmail,
ResetPassword,
}
<file_sep path="hyperswitch-card-vault/migrations/2024-09-28-170243_add_created_at_to_entity/up.sql" role="context" start="1" end="3">
-- Your SQL goes here
ALTER TABLE entity
ADD COLUMN IF NOT EXISTS created_at TIMESTAMP NOT NULL DEFAULT now()::TIMESTAMP;
<file_sep path="hyperswitch/crates/api_models/src/user_role.rs" role="context" start="66" end="69">
pub struct Entity {
pub entity_id: String,
pub entity_type: common_enums::EntityType,
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/nmi.rs<|crate|> router anchor=build_request 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="673" end="688">
fn build_request(
&self,
req: &types::PaymentsCancelRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Post)
.url(&types::PaymentsVoidType::get_url(self, req, connectors)?)
.headers(types::PaymentsVoidType::get_headers(self, req, connectors)?)
.set_body(types::PaymentsVoidType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
<file_sep path="hyperswitch/crates/router/src/connector/nmi.rs" role="context" start="672" end="672">
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="707" end="713">
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="690" end="705">
fn handle_response(
&self,
data: &types::PaymentsCancelRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PaymentsCancelRouterData, 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="664" end="671">
fn get_request_body(
&self,
req: &types::PaymentsCancelRouterData,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = nmi::NmiCancelRequest::try_from(req)?;
Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))
}
<file_sep path="hyperswitch/crates/router/src/connector/nmi.rs" role="context" start="656" end="662">
fn get_url(
&self,
_req: &types::PaymentsCancelRouterData,
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}api/transact.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="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/core/relay.rs" role="context" start="97" end="97">
type Request = relay_api_models::RelayRefundRequestData;
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/nmi.rs<|crate|> router anchor=build_request 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="523" end="538">
fn build_request(
&self,
req: &types::PaymentsSyncRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Post)
.url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
.headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
.set_body(types::PaymentsSyncType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
<file_sep path="hyperswitch/crates/router/src/connector/nmi.rs" role="context" start="522" end="522">
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="557" end="563">
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="540" end="555">
fn handle_response(
&self,
data: &types::PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
let response = nmi::SyncResponse::try_from(res.response.to_vec())?;
event_builder.map(|i| i.set_response_body(&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="514" end="521">
fn get_request_body(
&self,
req: &types::PaymentsSyncRouterData,
_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="506" end="512">
fn get_url(
&self,
_req: &types::PaymentsSyncRouterData,
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="37" end="41">
pub const fn new() -> &'static Self {
&Self {
amount_converter: &FloatMajorUnitForConnector,
}
}
<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/core/relay.rs" role="context" start="97" end="97">
type Request = relay_api_models::RelayRefundRequestData;
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/stripe.rs<|crate|> router anchor=build_request kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="1644" end="1660">
fn build_request(
&self,
req: &types::UploadFileRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Post)
.url(&types::UploadFileType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::UploadFileType::get_headers(self, req, connectors)?)
.set_body(types::UploadFileType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="1643" end="1643">
use common_utils::{
request::RequestContent,
types::{AmountConvertor, MinorUnit, MinorUnitForConnector},
};
use self::transformers as stripe;
use super::utils::{self as connector_utils, PaymentMethodDataType, RefundsRequestData};
use crate::{
configs::settings,
consts,
core::{
errors::{self, CustomResult},
payments,
},
events::connector_api_logs::ConnectorEvent,
headers,
services::{
self,
request::{self, Mask},
ConnectorSpecifications, ConnectorValidation,
},
types::{
self,
api::{self, ConnectorCommon, ConnectorCommonExt},
domain,
},
utils::{crypto, ByteSliceExt, BytesExt, OptionExt},
};
type Verify = dyn services::ConnectorIntegration<
api::SetupMandate,
types::SetupMandateRequestData,
types::PaymentsResponseData,
>;
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="1686" end="1725">
fn get_error_response(
&self,
res: types::Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
let response: stripe::ErrorResponse = res
.response
.parse_struct("ErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(types::ErrorResponse {
status_code: res.status_code,
code: response
.error
.code
.clone()
.unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()),
message: response
.error
.code
.unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()),
reason: response.error.message.map(|message| {
response
.error
.decline_code
.map(|decline_code| {
format!("message - {}, decline_code - {}", message, decline_code)
})
.unwrap_or(message)
}),
attempt_status: None,
connector_transaction_id: response.error.payment_intent.map(|pi| pi.id),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
})
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="1663" end="1684">
fn handle_response(
&self,
data: &types::UploadFileRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<
types::RouterData<api::Upload, types::UploadFileRequestData, types::UploadFileResponse>,
errors::ConnectorError,
> {
let response: stripe::FileUploadResponse = res
.response
.parse_struct("Stripe FileUploadResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(types::UploadFileRouterData {
response: Ok(types::UploadFileResponse {
provider_file_id: response.file_id,
}),
..data.clone()
})
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="1635" end="1642">
fn get_request_body(
&self,
req: &types::UploadFileRouterData,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = transformers::construct_file_upload_request(req.clone())?;
Ok(RequestContent::FormData(connector_req))
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="1624" end="1633">
fn get_url(
&self,
_req: &types::UploadFileRouterData,
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}{}",
connectors.stripe.base_url_file_upload, "v1/files"
))
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="2663" end="2673">
fn get_url(
&self,
req: &types::PayoutsRouterData<api::PoRecipientAccount>,
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_customer_id = req.get_connector_customer_id()?;
Ok(format!(
"{}v1/accounts/{}/external_accounts",
connectors.stripe.base_url, connector_customer_id
))
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="2675" end="2681">
fn get_headers(
&self,
req: &types::PayoutsRouterData<api::PoRecipientAccount>,
connectors: &settings::Connectors,
) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
<file_sep path="hyperswitch/crates/router/src/core/relay.rs" role="context" start="97" end="97">
type Request = relay_api_models::RelayRefundRequestData;
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/nmi.rs<|crate|> router anchor=build_request 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="600" end="617">
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)?)
.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/nmi.rs" role="context" start="599" end="599">
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="636" end="642">
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="619" end="634">
fn handle_response(
&self,
data: &types::PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PaymentsCaptureRouterData, 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="585" end="598">
fn get_request_body(
&self,
req: &types::PaymentsCaptureRouterData,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = connector_utils::convert_amount(
self.amount_converter,
req.request.minor_amount_to_capture,
req.request.currency,
)?;
let connector_router_data = nmi::NmiRouterData::from((amount, req));
let connector_req = nmi::NmiCaptureRequest::try_from(&connector_router_data)?;
Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))
}
<file_sep path="hyperswitch/crates/router/src/connector/nmi.rs" role="context" start="577" end="583">
fn get_url(
&self,
_req: &types::PaymentsCaptureRouterData,
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}api/transact.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="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/core/relay.rs" role="context" start="97" end="97">
type Request = relay_api_models::RelayRefundRequestData;
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/plaid.rs<|crate|> router anchor=build_request kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/connector/plaid.rs" role="context" start="293" end="309">
fn build_request(
&self,
req: &types::PaymentsSyncRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Post)
.url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
.set_body(types::PaymentsSyncType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
<file_sep path="hyperswitch/crates/router/src/connector/plaid.rs" role="context" start="292" end="292">
use common_utils::types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector};
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, RequestContent, Response,
},
utils::BytesExt,
};
<file_sep path="hyperswitch/crates/router/src/connector/plaid.rs" role="context" start="330" end="336">
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/plaid.rs" role="context" start="311" end="328">
fn handle_response(
&self,
data: &types::PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
let response: plaid::PlaidSyncResponse = res
.response
.parse_struct("PlaidSyncResponse")
.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/plaid.rs" role="context" start="282" end="291">
fn get_url(
&self,
_req: &types::PaymentsSyncRouterData,
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}/payment_initiation/payment/get",
self.base_url(connectors)
))
}
<file_sep path="hyperswitch/crates/router/src/connector/plaid.rs" role="context" start="273" end="280">
fn get_request_body(
&self,
req: &types::PaymentsSyncRouterData,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = plaid::PlaidSyncRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
<file_sep path="hyperswitch/crates/router/src/connector/plaid.rs" role="context" start="346" end="352">
fn get_headers(
&self,
req: &types::PaymentsPostProcessingRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
<file_sep path="hyperswitch/crates/router/src/connector/plaid.rs" role="context" start="358" end="364">
fn get_url(
&self,
_req: &types::PaymentsPostProcessingRouterData,
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}/link/token/create", self.base_url(connectors)))
}
<file_sep path="hyperswitch/crates/router/src/core/relay.rs" role="context" start="97" end="97">
type Request = relay_api_models::RelayRefundRequestData;
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/stripe.rs<|crate|> router anchor=build_request kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="387" end="403">
fn build_request(
&self,
req: &types::TokenizationRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Post)
.url(&types::TokenizationType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::TokenizationType::get_headers(self, req, connectors)?)
.set_body(types::TokenizationType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="386" end="386">
use common_utils::{
request::RequestContent,
types::{AmountConvertor, MinorUnit, MinorUnitForConnector},
};
use self::transformers as stripe;
use super::utils::{self as connector_utils, PaymentMethodDataType, RefundsRequestData};
use crate::{
configs::settings,
consts,
core::{
errors::{self, CustomResult},
payments,
},
events::connector_api_logs::ConnectorEvent,
headers,
services::{
self,
request::{self, Mask},
ConnectorSpecifications, ConnectorValidation,
},
types::{
self,
api::{self, ConnectorCommon, ConnectorCommonExt},
domain,
},
utils::{crypto, ByteSliceExt, BytesExt, OptionExt},
};
type Verify = dyn services::ConnectorIntegration<
api::SetupMandate,
types::SetupMandateRequestData,
types::PaymentsResponseData,
>;
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="430" end="469">
fn get_error_response(
&self,
res: types::Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
let response: stripe::ErrorResponse = res
.response
.parse_struct("ErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(types::ErrorResponse {
status_code: res.status_code,
code: response
.error
.code
.clone()
.unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()),
message: response
.error
.code
.unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()),
reason: response.error.message.map(|message| {
response
.error
.decline_code
.map(|decline_code| {
format!("message - {}, decline_code - {}", message, decline_code)
})
.unwrap_or(message)
}),
attempt_status: None,
connector_transaction_id: response.error.payment_intent.map(|pi| pi.id),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
})
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="405" end="428">
fn handle_response(
&self,
data: &types::TokenizationRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::TokenizationRouterData, errors::ConnectorError>
where
types::PaymentsResponseData: Clone,
{
let response: stripe::StripeTokenResponse = res
.response
.parse_struct("StripeTokenResponse")
.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/stripe.rs" role="context" start="378" end="385">
fn get_request_body(
&self,
req: &types::TokenizationRouterData,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = stripe::TokenRequest::try_from(req)?;
Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="370" end="376">
fn get_url(
&self,
_req: &types::TokenizationRouterData,
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}{}", self.base_url(connectors), "v1/tokens"))
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="48" end="52">
pub const fn new() -> &'static Self {
&Self {
amount_converter: &MinorUnitForConnector,
}
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="2663" end="2673">
fn get_url(
&self,
req: &types::PayoutsRouterData<api::PoRecipientAccount>,
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_customer_id = req.get_connector_customer_id()?;
Ok(format!(
"{}v1/accounts/{}/external_accounts",
connectors.stripe.base_url, connector_customer_id
))
}
<file_sep path="hyperswitch/crates/router/src/core/relay.rs" role="context" start="97" end="97">
type Request = relay_api_models::RelayRefundRequestData;
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/nmi.rs<|crate|> router anchor=build_request 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="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="819" end="819">
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="855" end="861">
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="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="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="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/core/relay.rs" role="context" start="97" end="97">
type Request = relay_api_models::RelayRefundRequestData;
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/nmi.rs<|crate|> router anchor=build_request 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="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/connector/nmi.rs" role="context" start="359" end="359">
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="398" end="404">
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="381" end="396">
fn handle_response(
&self,
data: &types::PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PaymentsAuthorizeRouterData, 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="345" end="358">
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 = nmi::NmiRouterData::from((amount, req));
let connector_req = nmi::NmiPaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))
}
<file_sep path="hyperswitch/crates/router/src/connector/nmi.rs" role="context" start="337" end="343">
fn get_url(
&self,
_req: &types::PaymentsAuthorizeRouterData,
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}api/transact.php", self.base_url(connectors)))
}
<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="37" end="41">
pub const fn new() -> &'static Self {
&Self {
amount_converter: &FloatMajorUnitForConnector,
}
}
<file_sep path="hyperswitch/crates/router/src/core/relay.rs" role="context" start="97" end="97">
type Request = relay_api_models::RelayRefundRequestData;
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/wellsfargopayout.rs<|crate|> router anchor=build_request 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="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="517" end="517">
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="555" end="561">
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="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="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="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="33" end="37">
pub fn new() -> &'static Self {
&Self {
amount_converter: &StringMinorUnitForConnector,
}
}
<file_sep path="hyperswitch/crates/router/src/core/relay.rs" role="context" start="97" end="97">
type Request = relay_api_models::RelayRefundRequestData;
<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=build_request 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="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="353" end="353">
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="393" end="399">
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="374" end="391">
fn handle_response(
&self,
data: &types::PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> {
let response: wellsfargopayout::WellsfargopayoutPaymentsResponse = res
.response
.parse_struct("Wellsfargopayout PaymentsCaptureResponse")
.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="346" end="352">
fn get_request_body(
&self,
_req: &types::PaymentsCaptureRouterData,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_request_body method".to_string()).into())
}
<file_sep path="hyperswitch/crates/router/src/connector/wellsfargopayout.rs" role="context" start="338" end="344">
fn get_url(
&self,
_req: &types::PaymentsCaptureRouterData,
_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="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="33" end="37">
pub fn new() -> &'static Self {
&Self {
amount_converter: &StringMinorUnitForConnector,
}
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/stripe.rs<|crate|> router anchor=build_request kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="529" end="547">
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/stripe.rs" role="context" start="528" end="528">
use common_utils::{
request::RequestContent,
types::{AmountConvertor, MinorUnit, MinorUnitForConnector},
};
use self::transformers as stripe;
use super::utils::{self as connector_utils, PaymentMethodDataType, RefundsRequestData};
use crate::{
configs::settings,
consts,
core::{
errors::{self, CustomResult},
payments,
},
events::connector_api_logs::ConnectorEvent,
headers,
services::{
self,
request::{self, Mask},
ConnectorSpecifications, ConnectorValidation,
},
types::{
self,
api::{self, ConnectorCommon, ConnectorCommonExt},
domain,
},
utils::{crypto, ByteSliceExt, BytesExt, OptionExt},
};
type Verify = dyn services::ConnectorIntegration<
api::SetupMandate,
types::SetupMandateRequestData,
types::PaymentsResponseData,
>;
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="586" end="625">
fn get_error_response(
&self,
res: types::Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
let response: stripe::ErrorResponse = res
.response
.parse_struct("ErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(types::ErrorResponse {
status_code: res.status_code,
code: response
.error
.code
.clone()
.unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()),
message: response
.error
.code
.unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()),
reason: response.error.message.map(|message| {
response
.error
.decline_code
.map(|decline_code| {
format!("message - {}, decline_code - {}", message, decline_code)
})
.unwrap_or(message)
}),
attempt_status: None,
connector_transaction_id: response.error.payment_intent.map(|pi| pi.id),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
})
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="549" end="584">
fn handle_response(
&self,
data: &types::PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError>
where
types::PaymentsCaptureData: Clone,
types::PaymentsResponseData: Clone,
{
let response: stripe::PaymentIntentResponse = res
.response
.parse_struct("PaymentIntentResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
let response_integrity_object = connector_utils::get_capture_integrity_object(
self.amount_converter,
response.amount_received,
response.currency.clone(),
)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
let new_router_data = types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed);
new_router_data.map(|mut router_data| {
router_data.request.integrity_object = Some(response_integrity_object);
router_data
})
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="515" end="527">
fn get_request_body(
&self,
req: &types::PaymentsCaptureRouterData,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = connector_utils::convert_amount(
self.amount_converter,
req.request.minor_amount_to_capture,
req.request.currency,
)?;
let connector_req = stripe::CaptureRequest::try_from(amount)?;
Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="499" end="513">
fn get_url(
&self,
req: &types::PaymentsCaptureRouterData,
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let id = req.request.connector_transaction_id.as_str();
Ok(format!(
"{}{}/{}/capture",
self.base_url(connectors),
"v1/payment_intents",
id
))
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="2683" end="2690">
fn get_request_body(
&self,
req: &types::PayoutsRouterData<api::PoRecipientAccount>,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = stripe::StripeConnectRecipientAccountCreateRequest::try_from(req)?;
Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="48" end="52">
pub const fn new() -> &'static Self {
&Self {
amount_converter: &MinorUnitForConnector,
}
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/nmi.rs<|crate|> router anchor=build_request 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="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="748" end="748">
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="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="733" end="747">
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 = nmi::NmiRouterData::from((refund_amount, req));
let connector_req = nmi::NmiRefundRequest::try_from(&connector_router_data)?;
Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))
}
<file_sep path="hyperswitch/crates/router/src/connector/nmi.rs" role="context" start="725" end="731">
fn get_url(
&self,
_req: &types::RefundsRouterData<api::Execute>,
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}api/transact.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="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)))
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/stripe.rs<|crate|> router anchor=build_request kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="1895" end="1912">
fn build_request(
&self,
req: &types::SubmitEvidenceRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
let request = services::RequestBuilder::new()
.method(services::Method::Post)
.url(&types::SubmitEvidenceType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::SubmitEvidenceType::get_headers(
self, req, connectors,
)?)
.set_body(types::SubmitEvidenceType::get_request_body(
self, req, connectors,
)?)
.build();
Ok(Some(request))
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="1894" end="1894">
use common_utils::{
request::RequestContent,
types::{AmountConvertor, MinorUnit, MinorUnitForConnector},
};
use self::transformers as stripe;
use super::utils::{self as connector_utils, PaymentMethodDataType, RefundsRequestData};
use crate::{
configs::settings,
consts,
core::{
errors::{self, CustomResult},
payments,
},
events::connector_api_logs::ConnectorEvent,
headers,
services::{
self,
request::{self, Mask},
ConnectorSpecifications, ConnectorValidation,
},
types::{
self,
api::{self, ConnectorCommon, ConnectorCommonExt},
domain,
},
utils::{crypto, ByteSliceExt, BytesExt, OptionExt},
};
type Verify = dyn services::ConnectorIntegration<
api::SetupMandate,
types::SetupMandateRequestData,
types::PaymentsResponseData,
>;
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="1936" end="1975">
fn get_error_response(
&self,
res: types::Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
let response: stripe::ErrorResponse = res
.response
.parse_struct("ErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(types::ErrorResponse {
status_code: res.status_code,
code: response
.error
.code
.clone()
.unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()),
message: response
.error
.code
.unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()),
reason: response.error.message.map(|message| {
response
.error
.decline_code
.map(|decline_code| {
format!("message - {}, decline_code - {}", message, decline_code)
})
.unwrap_or(message)
}),
attempt_status: None,
connector_transaction_id: response.error.payment_intent.map(|pi| pi.id),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
})
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="1915" end="1934">
fn handle_response(
&self,
data: &types::SubmitEvidenceRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::SubmitEvidenceRouterData, errors::ConnectorError> {
let response: stripe::DisputeObj = res
.response
.parse_struct("Stripe DisputeObj")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(types::SubmitEvidenceRouterData {
response: Ok(types::SubmitEvidenceResponse {
dispute_status: api_models::enums::DisputeStatus::DisputeChallenged,
connector_status: Some(response.status),
}),
..data.clone()
})
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="1886" end="1893">
fn get_request_body(
&self,
req: &types::SubmitEvidenceRouterData,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = stripe::Evidence::try_from(req)?;
Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="1873" end="1884">
fn get_url(
&self,
req: &types::SubmitEvidenceRouterData,
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}{}{}",
self.base_url(connectors),
"v1/disputes/",
req.request.connector_dispute_id
))
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="48" end="52">
pub const fn new() -> &'static Self {
&Self {
amount_converter: &MinorUnitForConnector,
}
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="2663" end="2673">
fn get_url(
&self,
req: &types::PayoutsRouterData<api::PoRecipientAccount>,
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_customer_id = req.get_connector_customer_id()?;
Ok(format!(
"{}v1/accounts/{}/external_accounts",
connectors.stripe.base_url, connector_customer_id
))
}
<file_sep path="hyperswitch/crates/router/src/core/relay.rs" role="context" start="97" end="97">
type Request = relay_api_models::RelayRefundRequestData;
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/services/email/types.rs<|crate|> router anchor=get_link_with_token kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/services/email/types.rs" role="context" start="306" end="322">
pub fn get_link_with_token(
base_url: impl std::fmt::Display,
token: impl std::fmt::Display,
action: impl std::fmt::Display,
auth_id: &Option<impl std::fmt::Display>,
theme_id: &Option<impl std::fmt::Display>,
) -> String {
let mut email_url = format!("{base_url}/user/{action}?token={token}");
if let Some(auth_id) = auth_id {
email_url = format!("{email_url}&auth_id={auth_id}");
}
if let Some(theme_id) = theme_id {
email_url = format!("{email_url}&theme_id={theme_id}");
}
email_url
}
<file_sep path="hyperswitch/crates/router/src/services/email/types.rs" role="context" start="305" end="305">
use api_models::user::dashboard_metadata::ProdIntent;
<file_sep path="hyperswitch/crates/router/src/services/email/types.rs" role="context" start="343" end="378">
async fn get_email_data(&self, base_url: &str) -> CustomResult<EmailContents, EmailError> {
let token = EmailToken::new_token(
self.recipient_email.clone(),
None,
domain::Origin::VerifyEmail,
&self.settings,
)
.await
.change_context(EmailError::TokenGenerationFailure)?;
let verify_email_link = get_link_with_token(
base_url,
token,
"verify_email",
&self.auth_id,
&self.theme_id,
);
let body = html::get_html_body(EmailBody::Verify {
link: verify_email_link,
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!(
"Welcome to the {} 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="324" end="330">
pub fn get_base_url(state: &SessionState) -> &str {
if !state.conf.multitenancy.enabled {
&state.conf.user.base_url
} else {
&state.tenant.user.control_center_url
}
}
<file_sep path="hyperswitch/crates/router/src/services/email/types.rs" role="context" start="301" end="303">
pub fn get_flow(&self) -> domain::Origin {
self.flow.clone()
}
<file_sep path="hyperswitch/crates/router/src/services/email/types.rs" role="context" start="297" end="299">
pub fn get_entity(&self) -> Option<&Entity> {
self.entity.as_ref()
}
<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(),
})
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/wellsfargopayout.rs<|crate|> router anchor=build_request 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="207" end="227">
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,
)?)
.attach_default_headers()
.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/connector/wellsfargopayout.rs" role="context" start="206" end="206">
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="248" end="254">
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="229" end="246">
fn handle_response(
&self,
data: &types::PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: wellsfargopayout::WellsfargopayoutPaymentsResponse = res
.response
.parse_struct("Wellsfargopayout PaymentsAuthorizeResponse")
.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="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="181" end="187">
fn get_url(
&self,
_req: &types::PaymentsAuthorizeRouterData,
_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="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="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=build_request 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="207" end="227">
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,
)?)
.attach_default_headers()
.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/connector/wellsfargopayout.rs" role="context" start="206" end="206">
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="248" end="254">
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="229" end="246">
fn handle_response(
&self,
data: &types::PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: wellsfargopayout::WellsfargopayoutPaymentsResponse = res
.response
.parse_struct("Wellsfargopayout PaymentsAuthorizeResponse")
.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="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="181" end="187">
fn get_url(
&self,
_req: &types::PaymentsAuthorizeRouterData,
_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="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="33" end="37">
pub fn new() -> &'static Self {
&Self {
amount_converter: &StringMinorUnitForConnector,
}
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/stripe.rs<|crate|> router anchor=build_request kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="874" end="894">
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,
)?)
.attach_default_headers()
.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/connector/stripe.rs" role="context" start="873" end="873">
use common_utils::{
request::RequestContent,
types::{AmountConvertor, MinorUnit, MinorUnitForConnector},
};
use self::transformers as stripe;
use super::utils::{self as connector_utils, PaymentMethodDataType, RefundsRequestData};
use crate::{
configs::settings,
consts,
core::{
errors::{self, CustomResult},
payments,
},
events::connector_api_logs::ConnectorEvent,
headers,
services::{
self,
request::{self, Mask},
ConnectorSpecifications, ConnectorValidation,
},
types::{
self,
api::{self, ConnectorCommon, ConnectorCommonExt},
domain,
},
utils::{crypto, ByteSliceExt, BytesExt, OptionExt},
};
type Verify = dyn services::ConnectorIntegration<
api::SetupMandate,
types::SetupMandateRequestData,
types::PaymentsResponseData,
>;
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="929" end="966">
fn get_error_response(
&self,
res: types::Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
let response: stripe::ErrorResponse = res
.response
.parse_struct("ErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(types::ErrorResponse {
status_code: res.status_code,
code: response
.error
.code
.clone()
.unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()),
message: response
.error
.code
.unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()),
reason: response.error.message.map(|message| {
response
.error
.decline_code
.map(|decline_code| {
format!("message - {}, decline_code - {}", message, decline_code)
})
.unwrap_or(message)
}),
attempt_status: None,
connector_transaction_id: response.error.payment_intent.map(|pi| pi.id),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
})
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="896" end="927">
fn handle_response(
&self,
data: &types::PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: stripe::PaymentIntentResponse = res
.response
.parse_struct("PaymentIntentResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
let response_integrity_object = connector_utils::get_authorise_integrity_object(
self.amount_converter,
response.amount,
response.currency.clone(),
)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
let new_router_data = types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed);
new_router_data.map(|mut router_data| {
router_data.request.integrity_object = Some(response_integrity_object);
router_data
})
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="859" end="872">
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_req = stripe::PaymentIntentRequest::try_from((req, amount))?;
Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="847" end="857">
fn get_url(
&self,
_req: &types::PaymentsAuthorizeRouterData,
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}{}",
self.base_url(connectors),
"v1/payment_intents"
))
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="48" end="52">
pub const fn new() -> &'static Self {
&Self {
amount_converter: &MinorUnitForConnector,
}
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="2663" end="2673">
fn get_url(
&self,
req: &types::PayoutsRouterData<api::PoRecipientAccount>,
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_customer_id = req.get_connector_customer_id()?;
Ok(format!(
"{}v1/accounts/{}/external_accounts",
connectors.stripe.base_url, connector_customer_id
))
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/stripe.rs<|crate|> router anchor=build_request kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="252" end="272">
fn build_request(
&self,
req: &types::ConnectorCustomerRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Post)
.url(&types::ConnectorCustomerType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::ConnectorCustomerType::get_headers(
self, req, connectors,
)?)
.set_body(types::ConnectorCustomerType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="251" end="251">
use common_utils::{
request::RequestContent,
types::{AmountConvertor, MinorUnit, MinorUnitForConnector},
};
use self::transformers as stripe;
use super::utils::{self as connector_utils, PaymentMethodDataType, RefundsRequestData};
use crate::{
configs::settings,
consts,
core::{
errors::{self, CustomResult},
payments,
},
events::connector_api_logs::ConnectorEvent,
headers,
services::{
self,
request::{self, Mask},
ConnectorSpecifications, ConnectorValidation,
},
types::{
self,
api::{self, ConnectorCommon, ConnectorCommonExt},
domain,
},
utils::{crypto, ByteSliceExt, BytesExt, OptionExt},
};
type Verify = dyn services::ConnectorIntegration<
api::SetupMandate,
types::SetupMandateRequestData,
types::PaymentsResponseData,
>;
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="299" end="338">
fn get_error_response(
&self,
res: types::Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
let response: stripe::ErrorResponse = res
.response
.parse_struct("ErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(types::ErrorResponse {
status_code: res.status_code,
code: response
.error
.code
.clone()
.unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()),
message: response
.error
.code
.unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()),
reason: response.error.message.map(|message| {
response
.error
.decline_code
.map(|decline_code| {
format!("message - {}, decline_code - {}", message, decline_code)
})
.unwrap_or(message)
}),
attempt_status: None,
connector_transaction_id: response.error.payment_intent.map(|pi| pi.id),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
})
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="274" end="297">
fn handle_response(
&self,
data: &types::ConnectorCustomerRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::ConnectorCustomerRouterData, errors::ConnectorError>
where
types::PaymentsResponseData: Clone,
{
let response: stripe::StripeCustomerResponse = res
.response
.parse_struct("StripeCustomerResponse")
.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/stripe.rs" role="context" start="243" end="250">
fn get_request_body(
&self,
req: &types::ConnectorCustomerRouterData,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = stripe::CustomerRequest::try_from(req)?;
Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="235" end="241">
fn get_url(
&self,
_req: &types::ConnectorCustomerRouterData,
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}{}", self.base_url(connectors), "v1/customers"))
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="2663" end="2673">
fn get_url(
&self,
req: &types::PayoutsRouterData<api::PoRecipientAccount>,
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_customer_id = req.get_connector_customer_id()?;
Ok(format!(
"{}v1/accounts/{}/external_accounts",
connectors.stripe.base_url, connector_customer_id
))
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="2675" end="2681">
fn get_headers(
&self,
req: &types::PayoutsRouterData<api::PoRecipientAccount>,
connectors: &settings::Connectors,
) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
<file_sep path="hyperswitch/crates/router/src/core/relay.rs" role="context" start="97" end="97">
type Request = relay_api_models::RelayRefundRequestData;
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/stripe.rs<|crate|> router anchor=build_request kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="2438" end="2454">
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/stripe.rs" role="context" start="2437" end="2437">
use common_utils::{
request::RequestContent,
types::{AmountConvertor, MinorUnit, MinorUnitForConnector},
};
use self::transformers as stripe;
use super::utils::{self as connector_utils, PaymentMethodDataType, RefundsRequestData};
use crate::{
configs::settings,
consts,
core::{
errors::{self, CustomResult},
payments,
},
events::connector_api_logs::ConnectorEvent,
headers,
services::{
self,
request::{self, Mask},
ConnectorSpecifications, ConnectorValidation,
},
types::{
self,
api::{self, ConnectorCommon, ConnectorCommonExt},
domain,
},
utils::{crypto, ByteSliceExt, BytesExt, OptionExt},
};
type Verify = dyn services::ConnectorIntegration<
api::SetupMandate,
types::SetupMandateRequestData,
types::PaymentsResponseData,
>;
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="2474" end="2480">
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/stripe.rs" role="context" start="2456" end="2472">
fn handle_response(
&self,
data: &types::PayoutsRouterData<api::PoCreate>,
event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PayoutsRouterData<api::PoCreate>, errors::ConnectorError> {
let response: stripe::StripeConnectPayoutCreateResponse = res
.response
.parse_struct("StripeConnectPayoutCreateResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_error_response_body(&response));
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="2429" end="2436">
fn get_request_body(
&self,
req: &types::PayoutsRouterData<api::PoCreate>,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = stripe::StripeConnectPayoutCreateRequest::try_from(req)?;
Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="2421" end="2427">
fn get_headers(
&self,
req: &types::PayoutsRouterData<api::PoCreate>,
connectors: &settings::Connectors,
) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="2683" end="2690">
fn get_request_body(
&self,
req: &types::PayoutsRouterData<api::PoRecipientAccount>,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = stripe::StripeConnectRecipientAccountCreateRequest::try_from(req)?;
Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="48" end="52">
pub const fn new() -> &'static Self {
&Self {
amount_converter: &MinorUnitForConnector,
}
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/stripe.rs<|crate|> router anchor=build_request kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="2360" end="2376">
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::Post)
.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))
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="2359" end="2359">
use common_utils::{
request::RequestContent,
types::{AmountConvertor, MinorUnit, MinorUnitForConnector},
};
use self::transformers as stripe;
use super::utils::{self as connector_utils, PaymentMethodDataType, RefundsRequestData};
use crate::{
configs::settings,
consts,
core::{
errors::{self, CustomResult},
payments,
},
events::connector_api_logs::ConnectorEvent,
headers,
services::{
self,
request::{self, Mask},
ConnectorSpecifications, ConnectorValidation,
},
types::{
self,
api::{self, ConnectorCommon, ConnectorCommonExt},
domain,
},
utils::{crypto, ByteSliceExt, BytesExt, OptionExt},
};
type Verify = dyn services::ConnectorIntegration<
api::SetupMandate,
types::SetupMandateRequestData,
types::PaymentsResponseData,
>;
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="2396" end="2402">
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/stripe.rs" role="context" start="2378" end="2394">
fn handle_response(
&self,
data: &types::PayoutsRouterData<api::PoCancel>,
event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PayoutsRouterData<api::PoCancel>, errors::ConnectorError> {
let response: stripe::StripeConnectReversalResponse = res
.response
.parse_struct("StripeConnectReversalResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_error_response_body(&response));
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="2351" end="2358">
fn get_request_body(
&self,
req: &types::RouterData<api::PoCancel, types::PayoutsData, types::PayoutsResponseData>,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = stripe::StripeConnectReversalRequest::try_from(req)?;
Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="2343" end="2349">
fn get_headers(
&self,
req: &types::PayoutsRouterData<api::PoCancel>,
_connectors: &settings::Connectors,
) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, _connectors)
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="48" end="52">
pub const fn new() -> &'static Self {
&Self {
amount_converter: &MinorUnitForConnector,
}
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="2663" end="2673">
fn get_url(
&self,
req: &types::PayoutsRouterData<api::PoRecipientAccount>,
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_customer_id = req.get_connector_customer_id()?;
Ok(format!(
"{}v1/accounts/{}/external_accounts",
connectors.stripe.base_url, connector_customer_id
))
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/ebanx.rs<|crate|> router anchor=build_request 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="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))
}
<file_sep path="hyperswitch/crates/router/src/connector/ebanx.rs" role="context" start="327" end="327">
use common_utils::request::RequestContent;
use common_utils::types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector};
use crate::{
configs::settings,
core::errors::{self, CustomResult},
events::connector_api_logs::ConnectorEvent,
services::{ConnectorIntegration, ConnectorSpecifications, ConnectorValidation},
types::{
self,
api::{self, ConnectorCommon, ConnectorCommonExt},
},
utils::BytesExt,
};
use crate::{
headers,
services::{self, request},
};
<file_sep path="hyperswitch/crates/router/src/connector/ebanx.rs" role="context" start="368" end="374">
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/ebanx.rs" role="context" start="347" end="366">
fn handle_response(
&self,
data: &types::PayoutsRouterData<api::PoCancel>,
event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PayoutsRouterData<api::PoCancel>, errors::ConnectorError> {
let response: ebanx::EbanxCancelResponse = res
.response
.parse_struct("EbanxCancelResponse")
.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/ebanx.rs" role="context" start="319" end="326">
fn get_request_body(
&self,
req: &types::PayoutsRouterData<api::PoCancel>,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = ebanx::EbanxPayoutCancelRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
<file_sep path="hyperswitch/crates/router/src/connector/ebanx.rs" role="context" start="311" end="317">
fn get_headers(
&self,
req: &types::PayoutsRouterData<api::PoCancel>,
_connectors: &settings::Connectors,
) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, _connectors)
}
<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,
}
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/ebanx.rs<|crate|> router anchor=build_request 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="167" end="183">
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/ebanx.rs" role="context" start="166" end="166">
use common_utils::request::RequestContent;
use common_utils::types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector};
use crate::{
configs::settings,
core::errors::{self, CustomResult},
events::connector_api_logs::ConnectorEvent,
services::{ConnectorIntegration, ConnectorSpecifications, ConnectorValidation},
types::{
self,
api::{self, ConnectorCommon, ConnectorCommonExt},
},
utils::BytesExt,
};
use crate::{
headers,
services::{self, request},
};
<file_sep path="hyperswitch/crates/router/src/connector/ebanx.rs" role="context" start="206" end="212">
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/ebanx.rs" role="context" start="185" end="204">
fn handle_response(
&self,
data: &types::PayoutsRouterData<api::PoCreate>,
event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PayoutsRouterData<api::PoCreate>, errors::ConnectorError> {
let response: ebanx::EbanxPayoutResponse = res
.response
.parse_struct("EbanxPayoutResponse")
.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/ebanx.rs" role="context" start="152" end="165">
fn get_request_body(
&self,
req: &types::PayoutsRouterData<api::PoCreate>,
_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 = ebanx::EbanxRouterData::from((amount, req));
let connector_req = ebanx::EbanxPayoutCreateRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
<file_sep path="hyperswitch/crates/router/src/connector/ebanx.rs" role="context" start="144" end="150">
fn get_headers(
&self,
req: &types::PayoutsRouterData<api::PoCreate>,
connectors: &settings::Connectors,
) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
<file_sep path="hyperswitch/crates/router/src/connector/ebanx.rs" role="context" start="303" end="309">
fn get_url(
&self,
_req: &types::PayoutsRouterData<api::PoCancel>,
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}ws/payout/cancel", connectors.ebanx.base_url,))
}
<file_sep path="hyperswitch/crates/router/src/connector/ebanx.rs" role="context" start="311" end="317">
fn get_headers(
&self,
req: &types::PayoutsRouterData<api::PoCancel>,
_connectors: &settings::Connectors,
) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, _connectors)
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/wise.rs<|crate|> router anchor=build_request 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="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.rs" role="context" start="563" end="563">
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="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="583" end="602">
fn handle_response(
&self,
data: &types::PayoutsRouterData<api::PoCreate>,
event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PayoutsRouterData<api::PoCreate>, errors::ConnectorError> {
let response: wise::WisePayoutResponse = res
.response
.parse_struct("WisePayoutResponse")
.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="555" end="562">
fn get_request_body(
&self,
req: &types::PayoutsRouterData<api::PoCreate>,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = wise::WisePayoutCreateRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
<file_sep path="hyperswitch/crates/router/src/connector/wise.rs" role="context" start="547" end="553">
fn get_headers(
&self,
req: &types::PayoutsRouterData<api::PoCreate>,
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="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/core/relay.rs" role="context" start="97" end="97">
type Request = relay_api_models::RelayRefundRequestData;
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/wise.rs<|crate|> router anchor=build_request 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="398" end="414">
fn build_request(
&self,
req: &types::PayoutsRouterData<api::PoQuote>,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
let request = services::RequestBuilder::new()
.method(services::Method::Post)
.url(&types::PayoutQuoteType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PayoutQuoteType::get_headers(self, req, connectors)?)
.set_body(types::PayoutQuoteType::get_request_body(
self, req, connectors,
)?)
.build();
Ok(Some(request))
}
<file_sep path="hyperswitch/crates/router/src/connector/wise.rs" role="context" start="397" end="397">
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="438" end="444">
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="417" end="436">
fn handle_response(
&self,
data: &types::PayoutsRouterData<api::PoQuote>,
event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PayoutsRouterData<api::PoQuote>, errors::ConnectorError> {
let response: wise::WisePayoutQuoteResponse = res
.response
.parse_struct("WisePayoutQuoteResponse")
.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="383" end="396">
fn get_request_body(
&self,
req: &types::PayoutsRouterData<api::PoQuote>,
_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::WisePayoutQuoteRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
<file_sep path="hyperswitch/crates/router/src/connector/wise.rs" role="context" start="375" end="381">
fn get_headers(
&self,
req: &types::PayoutsRouterData<api::PoQuote>,
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="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)
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/plaid.rs<|crate|> router anchor=build_request 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="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="374" end="374">
use common_utils::types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector};
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, RequestContent, Response,
},
utils::BytesExt,
};
<file_sep path="hyperswitch/crates/router/src/connector/plaid.rs" role="context" start="416" end="422">
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/plaid.rs" role="context" start="397" end="414">
fn handle_response(
&self,
data: &types::PaymentsPostProcessingRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsPostProcessingRouterData, errors::ConnectorError> {
let response: plaid::PlaidLinkTokenResponse = res
.response
.parse_struct("PlaidLinkTokenResponse")
.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/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)))
}
<file_sep path="hyperswitch/crates/router/src/connector/plaid.rs" role="context" start="358" end="364">
fn get_url(
&self,
_req: &types::PaymentsPostProcessingRouterData,
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}/link/token/create", self.base_url(connectors)))
}
<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,
}
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/stripe.rs<|crate|> router anchor=build_request kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="1162" end="1180">
fn build_request(
&self,
req: &types::RouterData<
api::SetupMandate,
types::SetupMandateRequestData,
types::PaymentsResponseData,
>,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Post)
.url(&Verify::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(Verify::get_headers(self, req, connectors)?)
.set_body(Verify::get_request_body(self, req, connectors)?)
.build(),
))
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="1161" end="1161">
use common_utils::{
request::RequestContent,
types::{AmountConvertor, MinorUnit, MinorUnitForConnector},
};
use self::transformers as stripe;
use super::utils::{self as connector_utils, PaymentMethodDataType, RefundsRequestData};
use super::utils::{PayoutsData, RouterData};
use crate::{
configs::settings,
consts,
core::{
errors::{self, CustomResult},
payments,
},
events::connector_api_logs::ConnectorEvent,
headers,
services::{
self,
request::{self, Mask},
ConnectorSpecifications, ConnectorValidation,
},
types::{
self,
api::{self, ConnectorCommon, ConnectorCommonExt},
domain,
},
utils::{crypto, ByteSliceExt, BytesExt, OptionExt},
};
type Verify = dyn services::ConnectorIntegration<
api::SetupMandate,
types::SetupMandateRequestData,
types::PaymentsResponseData,
>;
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="1220" end="1259">
fn get_error_response(
&self,
res: types::Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
let response: stripe::ErrorResponse = res
.response
.parse_struct("ErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(types::ErrorResponse {
status_code: res.status_code,
code: response
.error
.code
.clone()
.unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()),
message: response
.error
.code
.unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()),
reason: response.error.message.map(|message| {
response
.error
.decline_code
.map(|decline_code| {
format!("message - {}, decline_code - {}", message, decline_code)
})
.unwrap_or(message)
}),
attempt_status: None,
connector_transaction_id: response.error.payment_intent.map(|pi| pi.id),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
})
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="1182" end="1218">
fn handle_response(
&self,
data: &types::RouterData<
api::SetupMandate,
types::SetupMandateRequestData,
types::PaymentsResponseData,
>,
event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<
types::RouterData<
api::SetupMandate,
types::SetupMandateRequestData,
types::PaymentsResponseData,
>,
errors::ConnectorError,
>
where
api::SetupMandate: Clone,
types::SetupMandateRequestData: Clone,
types::PaymentsResponseData: Clone,
{
let response: stripe::SetupIntentResponse = res
.response
.parse_struct("SetupIntentResponse")
.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/stripe.rs" role="context" start="1149" end="1160">
fn get_request_body(
&self,
req: &types::RouterData<
api::SetupMandate,
types::SetupMandateRequestData,
types::PaymentsResponseData,
>,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = stripe::SetupIntentRequest::try_from(req)?;
Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="1133" end="1147">
fn get_url(
&self,
_req: &types::RouterData<
api::SetupMandate,
types::SetupMandateRequestData,
types::PaymentsResponseData,
>,
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}{}",
self.base_url(connectors),
"v1/setup_intents"
))
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="48" end="52">
pub const fn new() -> &'static Self {
&Self {
amount_converter: &MinorUnitForConnector,
}
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="2663" end="2673">
fn get_url(
&self,
req: &types::PayoutsRouterData<api::PoRecipientAccount>,
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_customer_id = req.get_connector_customer_id()?;
Ok(format!(
"{}v1/accounts/{}/external_accounts",
connectors.stripe.base_url, connector_customer_id
))
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="1099" end="1103">
type Verify = dyn services::ConnectorIntegration<
api::SetupMandate,
types::SetupMandateRequestData,
types::PaymentsResponseData,
>;
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/nmi.rs<|crate|> router anchor=build_request 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="447" end="467">
fn build_request(
&self,
req: &types::PaymentsCompleteAuthorizeRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Post)
.url(&types::PaymentsCompleteAuthorizeType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::PaymentsCompleteAuthorizeType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsCompleteAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
<file_sep path="hyperswitch/crates/router/src/connector/nmi.rs" role="context" start="446" end="446">
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="486" end="492">
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="469" end="484">
fn handle_response(
&self,
data: &types::PaymentsCompleteAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> {
let response: nmi::NmiCompleteResponse = 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="433" end="446">
fn get_request_body(
&self,
req: &types::PaymentsCompleteAuthorizeRouterData,
_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 = nmi::NmiRouterData::from((amount, req));
let connector_req = nmi::NmiCompleteRequest::try_from(&connector_router_data)?;
Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))
}
<file_sep path="hyperswitch/crates/router/src/connector/nmi.rs" role="context" start="426" end="432">
fn get_url(
&self,
_req: &types::PaymentsCompleteAuthorizeRouterData,
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}api/transact.php", self.base_url(connectors)))
}
<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,
}
}
<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)
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/wellsfargopayout.rs<|crate|> router anchor=build_request 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="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="447" end="447">
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="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="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="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="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="33" end="37">
pub fn new() -> &'static Self {
&Self {
amount_converter: &StringMinorUnitForConnector,
}
}
<file_sep path="hyperswitch/crates/router/src/core/relay.rs" role="context" start="97" end="97">
type Request = relay_api_models::RelayRefundRequestData;
<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/stripe.rs<|crate|> router anchor=build_request kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="1338" end="1355">
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/stripe.rs" role="context" start="1337" end="1337">
use common_utils::{
request::RequestContent,
types::{AmountConvertor, MinorUnit, MinorUnitForConnector},
};
use self::transformers as stripe;
use super::utils::{self as connector_utils, PaymentMethodDataType, RefundsRequestData};
use crate::{
configs::settings,
consts,
core::{
errors::{self, CustomResult},
payments,
},
events::connector_api_logs::ConnectorEvent,
headers,
services::{
self,
request::{self, Mask},
ConnectorSpecifications, ConnectorValidation,
},
types::{
self,
api::{self, ConnectorCommon, ConnectorCommonExt},
domain,
},
utils::{crypto, ByteSliceExt, BytesExt, OptionExt},
};
type Verify = dyn services::ConnectorIntegration<
api::SetupMandate,
types::SetupMandateRequestData,
types::PaymentsResponseData,
>;
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="1392" end="1431">
fn get_error_response(
&self,
res: types::Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
let response: stripe::ErrorResponse = res
.response
.parse_struct("ErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(types::ErrorResponse {
status_code: res.status_code,
code: response
.error
.code
.clone()
.unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()),
message: response
.error
.code
.unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()),
reason: response.error.message.map(|message| {
response
.error
.decline_code
.map(|decline_code| {
format!("message - {}, decline_code - {}", message, decline_code)
})
.unwrap_or(message)
}),
attempt_status: None,
connector_transaction_id: response.error.payment_intent.map(|pi| pi.id),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
})
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="1358" end="1390">
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: stripe::RefundResponse =
res.response
.parse_struct("Stripe RefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
let response_integrity_object = connector_utils::get_refund_integrity_object(
self.amount_converter,
response.amount,
response.currency.clone(),
)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
let new_router_data = types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
});
new_router_data
.map(|mut router_data| {
router_data.request.integrity_object = Some(response_integrity_object);
router_data
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="1316" end="1336">
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 request_body = match req.request.split_refunds.as_ref() {
Some(SplitRefundsRequest::StripeSplitRefund(_)) => RequestContent::FormUrlEncoded(
Box::new(stripe::ChargeRefundRequest::try_from(req)?),
),
_ => RequestContent::FormUrlEncoded(Box::new(stripe::RefundRequest::try_from((
req,
refund_amount,
))?)),
};
Ok(request_body)
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="1308" end="1314">
fn get_url(
&self,
_req: &types::RefundsRouterData<api::Execute>,
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}{}", self.base_url(connectors), "v1/refunds"))
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="48" end="52">
pub const fn new() -> &'static Self {
&Self {
amount_converter: &MinorUnitForConnector,
}
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="2675" end="2681">
fn get_headers(
&self,
req: &types::PayoutsRouterData<api::PoRecipientAccount>,
connectors: &settings::Connectors,
) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/riskified.rs<|crate|> router anchor=build_request 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="204" end="222">
fn build_request(
&self,
req: &frm_types::FrmCheckoutRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Post)
.url(&frm_types::FrmCheckoutType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(frm_types::FrmCheckoutType::get_headers(
self, req, connectors,
)?)
.set_body(frm_types::FrmCheckoutType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
<file_sep path="hyperswitch/crates/router/src/connector/riskified.rs" role="context" start="203" end="203">
use super::utils::{self as connector_utils, FrmTransactionRouterDataRequest};
use crate::{
configs::settings,
core::errors::{self, CustomResult},
services::{self, ConnectorIntegration, ConnectorSpecifications, ConnectorValidation},
types::{
self,
api::{self, ConnectorCommon, ConnectorCommonExt},
},
};
use crate::{
consts,
events::connector_api_logs::ConnectorEvent,
headers,
services::request,
types::{api::fraud_check as frm_api, fraud_check as frm_types, ErrorResponse, Response},
utils::BytesExt,
};
<file_sep path="hyperswitch/crates/router/src/connector/riskified.rs" role="context" start="242" end="248">
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/riskified.rs" role="context" start="224" end="241">
fn handle_response(
&self,
data: &frm_types::FrmCheckoutRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<frm_types::FrmCheckoutRouterData, errors::ConnectorError> {
let response: riskified::RiskifiedPaymentsResponse = res
.response
.parse_struct("RiskifiedPaymentsResponse Checkout")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
<frm_types::FrmCheckoutRouterData>::try_from(types::ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
<file_sep path="hyperswitch/crates/router/src/connector/riskified.rs" role="context" start="185" end="202">
fn get_request_body(
&self,
req: &frm_types::FrmCheckoutRouterData,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_converter,
MinorUnit::new(req.request.amount),
req.request
.currency
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "currency",
})?,
)?;
let req_data = riskified::RiskifiedRouterData::from((amount, req));
let req_obj = riskified::RiskifiedPaymentsCheckoutRequest::try_from(&req_data)?;
Ok(RequestContent::Json(Box::new(req_obj)))
}
<file_sep path="hyperswitch/crates/router/src/connector/riskified.rs" role="context" start="177" end="183">
fn get_url(
&self,
_req: &frm_types::FrmCheckoutRouterData,
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}{}", self.base_url(connectors), "/decide"))
}
<file_sep path="hyperswitch/crates/router/src/connector/riskified.rs" role="context" start="426" end="433">
fn get_request_body(
&self,
req: &frm_types::FrmFulfillmentRouterData,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let req_obj = riskified::RiskifiedFulfillmentRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(req_obj)))
}
<file_sep path="hyperswitch/crates/router/src/connector/riskified.rs" role="context" start="406" end="412">
fn get_headers(
&self,
req: &frm_types::FrmFulfillmentRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/stripe.rs<|crate|> router anchor=build_request kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="2604" end="2622">
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/stripe.rs" role="context" start="2603" end="2603">
use common_utils::{
request::RequestContent,
types::{AmountConvertor, MinorUnit, MinorUnitForConnector},
};
use self::transformers as stripe;
use super::utils::{self as connector_utils, PaymentMethodDataType, RefundsRequestData};
use crate::{
configs::settings,
consts,
core::{
errors::{self, CustomResult},
payments,
},
events::connector_api_logs::ConnectorEvent,
headers,
services::{
self,
request::{self, Mask},
ConnectorSpecifications, ConnectorValidation,
},
types::{
self,
api::{self, ConnectorCommon, ConnectorCommonExt},
domain,
},
utils::{crypto, ByteSliceExt, BytesExt, OptionExt},
};
type Verify = dyn services::ConnectorIntegration<
api::SetupMandate,
types::SetupMandateRequestData,
types::PaymentsResponseData,
>;
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="2642" end="2648">
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/stripe.rs" role="context" start="2624" end="2640">
fn handle_response(
&self,
data: &types::PayoutsRouterData<api::PoRecipient>,
event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PayoutsRouterData<api::PoRecipient>, errors::ConnectorError> {
let response: stripe::StripeConnectRecipientCreateResponse = res
.response
.parse_struct("StripeConnectRecipientCreateResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_error_response_body(&response));
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="2595" end="2602">
fn get_request_body(
&self,
req: &types::PayoutsRouterData<api::PoRecipient>,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = stripe::StripeConnectRecipientCreateRequest::try_from(req)?;
Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="2587" end="2593">
fn get_headers(
&self,
req: &types::PayoutsRouterData<api::PoRecipient>,
connectors: &settings::Connectors,
) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="48" end="52">
pub const fn new() -> &'static Self {
&Self {
amount_converter: &MinorUnitForConnector,
}
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="2663" end="2673">
fn get_url(
&self,
req: &types::PayoutsRouterData<api::PoRecipientAccount>,
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_customer_id = req.get_connector_customer_id()?;
Ok(format!(
"{}v1/accounts/{}/external_accounts",
connectors.stripe.base_url, connector_customer_id
))
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/wise.rs<|crate|> router anchor=build_request 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="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="482" end="482">
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="525" end="531">
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="504" end="523">
fn handle_response(
&self,
data: &types::PayoutsRouterData<api::PoRecipient>,
event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PayoutsRouterData<api::PoRecipient>, errors::ConnectorError> {
let response: wise::WiseRecipientCreateResponse = res
.response
.parse_struct("WiseRecipientCreateResponse")
.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="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)))
}
<file_sep path="hyperswitch/crates/router/src/connector/wise.rs" role="context" start="460" end="466">
fn get_headers(
&self,
req: &types::PayoutsRouterData<api::PoRecipient>,
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="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="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)))
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/riskified.rs<|crate|> router anchor=build_request kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/connector/riskified.rs" role="context" start="336" end="356">
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/riskified.rs" role="context" start="335" end="335">
use super::utils::{self as connector_utils, FrmTransactionRouterDataRequest};
use crate::{
configs::settings,
core::errors::{self, CustomResult},
services::{self, ConnectorIntegration, ConnectorSpecifications, ConnectorValidation},
types::{
self,
api::{self, ConnectorCommon, ConnectorCommonExt},
},
};
use crate::{
consts,
events::connector_api_logs::ConnectorEvent,
headers,
services::request,
types::{api::fraud_check as frm_api, fraud_check as frm_types, ErrorResponse, Response},
utils::BytesExt,
};
<file_sep path="hyperswitch/crates/router/src/connector/riskified.rs" role="context" start="389" end="395">
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/riskified.rs" role="context" start="358" end="388">
fn handle_response(
&self,
data: &frm_types::FrmTransactionRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<frm_types::FrmTransactionRouterData, errors::ConnectorError> {
let response: riskified::RiskifiedTransactionResponse = res
.response
.parse_struct("RiskifiedPaymentsResponse Transaction")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
match response {
riskified::RiskifiedTransactionResponse::FailedResponse(response_data) => {
<frm_types::FrmTransactionRouterData>::try_from(types::ResponseRouterData {
response: response_data,
data: data.clone(),
http_code: res.status_code,
})
}
riskified::RiskifiedTransactionResponse::SuccessResponse(response_data) => {
<frm_types::FrmTransactionRouterData>::try_from(types::ResponseRouterData {
response: response_data,
data: data.clone(),
http_code: res.status_code,
})
}
}
}
<file_sep path="hyperswitch/crates/router/src/connector/riskified.rs" role="context" start="309" end="334">
fn get_request_body(
&self,
req: &frm_types::FrmTransactionRouterData,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
match req.is_payment_successful() {
Some(false) => {
let req_obj = riskified::TransactionFailedRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(req_obj)))
}
_ => {
let amount = convert_amount(
self.amount_converter,
MinorUnit::new(req.request.amount),
req.request
.currency
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "currency",
})?,
)?;
let req_data = riskified::RiskifiedRouterData::from((amount, req));
let req_obj = riskified::TransactionSuccessRequest::try_from(&req_data)?;
Ok(RequestContent::Json(Box::new(req_obj)))
}
}
}
<file_sep path="hyperswitch/crates/router/src/connector/riskified.rs" role="context" start="294" end="307">
fn get_url(
&self,
req: &frm_types::FrmTransactionRouterData,
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
match req.is_payment_successful() {
Some(false) => Ok(format!(
"{}{}",
self.base_url(connectors),
"/checkout_denied"
)),
_ => Ok(format!("{}{}", self.base_url(connectors), "/decision")),
}
}
<file_sep path="hyperswitch/crates/router/src/connector/riskified.rs" role="context" start="426" end="433">
fn get_request_body(
&self,
req: &frm_types::FrmFulfillmentRouterData,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let req_obj = riskified::RiskifiedFulfillmentRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(req_obj)))
}
<file_sep path="hyperswitch/crates/router/src/connector/riskified.rs" role="context" start="406" end="412">
fn get_headers(
&self,
req: &frm_types::FrmFulfillmentRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
<file_sep path="hyperswitch/crates/router/src/core/relay.rs" role="context" start="97" end="97">
type Request = relay_api_models::RelayRefundRequestData;
<file_sep path="hyperswitch/crates/api_models/src/analytics/frm.rs" role="context" start="22" end="26">
pub enum FrmTransactionType {
#[default]
PreFrm,
PostFrm,
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/payone.rs<|crate|> router anchor=build_request kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/connector/payone.rs" role="context" start="321" end="338">
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/payone.rs" role="context" start="320" end="320">
use common_utils::request::RequestContent;
use common_utils::types::{AmountConvertor, MinorUnit, MinorUnitForConnector};
use self::transformers as payone;
use crate::services;
use crate::{
configs::settings,
connector::{
utils as connector_utils,
utils::{ConnectorErrorType, ConnectorErrorTypeMapping},
},
consts,
core::errors::{self, CustomResult},
events::connector_api_logs::ConnectorEvent,
headers,
services::{
request::{self, Mask},
ConnectorIntegration, ConnectorSpecifications, ConnectorValidation,
},
types::{
self,
api::{self, ConnectorCommon, ConnectorCommonExt},
ErrorResponse, Response,
},
utils::BytesExt,
};
<file_sep path="hyperswitch/crates/router/src/connector/payone.rs" role="context" start="362" end="368">
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/payone.rs" role="context" start="341" end="360">
fn handle_response(
&self,
data: &types::PayoutsRouterData<api::PoFulfill>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PayoutsRouterData<api::PoFulfill>, errors::ConnectorError> {
let response: payone::PayonePayoutFulfillResponse = res
.response
.parse_struct("PayonePayoutFulfillResponse")
.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/payone.rs" role="context" start="306" end="319">
fn get_request_body(
&self,
req: &types::PayoutsRouterData<api::PoFulfill>,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.destination_currency,
)?;
let connector_router_data = payone::PayoneRouterData::from((amount, req));
let connector_req = payone::PayonePayoutFulfillRequest::try_from(connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
<file_sep path="hyperswitch/crates/router/src/connector/payone.rs" role="context" start="298" end="304">
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/payone.rs" role="context" start="49" end="54">
pub fn new() -> &'static Self {
&Self {
#[cfg(feature = "payouts")]
amount_converter: &MinorUnitForConnector,
}
}
<file_sep path="hyperswitch/crates/router/src/connector/payone.rs" role="context" start="284" end="296">
fn get_url(
&self,
req: &types::PayoutsRouterData<api::PoFulfill>,
_connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let auth = payone::PayoneAuthType::try_from(&req.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(format!(
"{}v2/{}/payouts",
self.base_url(_connectors),
auth.merchant_account.peek()
))
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/stripe.rs<|crate|> router anchor=build_request kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="2523" end="2541">
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/stripe.rs" role="context" start="2522" end="2522">
use common_utils::{
request::RequestContent,
types::{AmountConvertor, MinorUnit, MinorUnitForConnector},
};
use self::transformers as stripe;
use super::utils::{self as connector_utils, PaymentMethodDataType, RefundsRequestData};
use crate::{
configs::settings,
consts,
core::{
errors::{self, CustomResult},
payments,
},
events::connector_api_logs::ConnectorEvent,
headers,
services::{
self,
request::{self, Mask},
ConnectorSpecifications, ConnectorValidation,
},
types::{
self,
api::{self, ConnectorCommon, ConnectorCommonExt},
domain,
},
utils::{crypto, ByteSliceExt, BytesExt, OptionExt},
};
type Verify = dyn services::ConnectorIntegration<
api::SetupMandate,
types::SetupMandateRequestData,
types::PaymentsResponseData,
>;
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="2561" end="2567">
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/stripe.rs" role="context" start="2543" end="2559">
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: stripe::StripeConnectPayoutFulfillResponse = res
.response
.parse_struct("StripeConnectPayoutFulfillResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_error_response_body(&response));
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="2514" end="2521">
fn get_request_body(
&self,
req: &types::PayoutsRouterData<api::PoFulfill>,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = stripe::StripeConnectPayoutFulfillRequest::try_from(req)?;
Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="2499" end="2512">
fn get_headers(
&self,
req: &types::PayoutsRouterData<api::PoFulfill>,
connectors: &settings::Connectors,
) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
let mut headers = self.build_headers(req, connectors)?;
let customer_account = req.get_connector_customer_id()?;
let mut customer_account_header = vec![(
headers::STRIPE_COMPATIBLE_CONNECT_ACCOUNT.to_string(),
customer_account.into_masked(),
)];
headers.append(&mut customer_account_header);
Ok(headers)
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="2663" end="2673">
fn get_url(
&self,
req: &types::PayoutsRouterData<api::PoRecipientAccount>,
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_customer_id = req.get_connector_customer_id()?;
Ok(format!(
"{}v1/accounts/{}/external_accounts",
connectors.stripe.base_url, connector_customer_id
))
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="2675" end="2681">
fn get_headers(
&self,
req: &types::PayoutsRouterData<api::PoRecipientAccount>,
connectors: &settings::Connectors,
) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/stripe.rs<|crate|> router anchor=build_request kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="2692" end="2712">
fn build_request(
&self,
req: &types::PayoutsRouterData<api::PoRecipientAccount>,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
let request = services::RequestBuilder::new()
.method(services::Method::Post)
.url(&types::PayoutRecipientAccountType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::PayoutRecipientAccountType::get_headers(
self, req, connectors,
)?)
.set_body(types::PayoutRecipientAccountType::get_request_body(
self, req, connectors,
)?)
.build();
Ok(Some(request))
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="2691" end="2691">
use common_utils::{
request::RequestContent,
types::{AmountConvertor, MinorUnit, MinorUnitForConnector},
};
use self::transformers as stripe;
use super::utils::{self as connector_utils, PaymentMethodDataType, RefundsRequestData};
use crate::{
configs::settings,
consts,
core::{
errors::{self, CustomResult},
payments,
},
events::connector_api_logs::ConnectorEvent,
headers,
services::{
self,
request::{self, Mask},
ConnectorSpecifications, ConnectorValidation,
},
types::{
self,
api::{self, ConnectorCommon, ConnectorCommonExt},
domain,
},
utils::{crypto, ByteSliceExt, BytesExt, OptionExt},
};
type Verify = dyn services::ConnectorIntegration<
api::SetupMandate,
types::SetupMandateRequestData,
types::PaymentsResponseData,
>;
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="2733" end="2739">
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/stripe.rs" role="context" start="2714" end="2731">
fn handle_response(
&self,
data: &types::PayoutsRouterData<api::PoRecipientAccount>,
event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PayoutsRouterData<api::PoRecipientAccount>, errors::ConnectorError>
{
let response: stripe::StripeConnectRecipientAccountCreateResponse = res
.response
.parse_struct("StripeConnectRecipientAccountCreateResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_error_response_body(&response));
types::RouterData::try_from(types::ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="2683" end="2690">
fn get_request_body(
&self,
req: &types::PayoutsRouterData<api::PoRecipientAccount>,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = stripe::StripeConnectRecipientAccountCreateRequest::try_from(req)?;
Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="2675" end="2681">
fn get_headers(
&self,
req: &types::PayoutsRouterData<api::PoRecipientAccount>,
connectors: &settings::Connectors,
) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="48" end="52">
pub const fn new() -> &'static Self {
&Self {
amount_converter: &MinorUnitForConnector,
}
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="2663" end="2673">
fn get_url(
&self,
req: &types::PayoutsRouterData<api::PoRecipientAccount>,
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_customer_id = req.get_connector_customer_id()?;
Ok(format!(
"{}v1/accounts/{}/external_accounts",
connectors.stripe.base_url, connector_customer_id
))
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/riskified.rs<|crate|> router anchor=build_request 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="435" end="455">
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/riskified.rs" role="context" start="434" end="434">
use super::utils::{self as connector_utils, FrmTransactionRouterDataRequest};
use crate::{
configs::settings,
core::errors::{self, CustomResult},
services::{self, ConnectorIntegration, ConnectorSpecifications, ConnectorValidation},
types::{
self,
api::{self, ConnectorCommon, ConnectorCommonExt},
},
};
use crate::{
consts,
events::connector_api_logs::ConnectorEvent,
headers,
services::request,
types::{api::fraud_check as frm_api, fraud_check as frm_types, ErrorResponse, Response},
utils::BytesExt,
};
<file_sep path="hyperswitch/crates/router/src/connector/riskified.rs" role="context" start="478" end="484">
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/riskified.rs" role="context" start="457" end="476">
fn handle_response(
&self,
data: &frm_types::FrmFulfillmentRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<frm_types::FrmFulfillmentRouterData, errors::ConnectorError> {
let response: riskified::RiskifiedFulfilmentResponse = res
.response
.parse_struct("RiskifiedFulfilmentResponse fulfilment")
.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/riskified.rs" role="context" start="426" end="433">
fn get_request_body(
&self,
req: &frm_types::FrmFulfillmentRouterData,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let req_obj = riskified::RiskifiedFulfillmentRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(req_obj)))
}
<file_sep path="hyperswitch/crates/router/src/connector/riskified.rs" role="context" start="418" end="424">
fn get_url(
&self,
_req: &frm_types::FrmFulfillmentRouterData,
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}{}", self.base_url(connectors), "/fulfill"))
}
<file_sep path="hyperswitch/crates/router/src/connector/riskified.rs" role="context" start="406" end="412">
fn get_headers(
&self,
req: &frm_types::FrmFulfillmentRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/utils/currency.rs<|crate|> router anchor=get_forex_rates kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<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="157" end="157">
use common_utils::{date_time, errors::CustomResult, events::ApiEventMetric, ext_traits::AsyncExt};
use crate::{
logger,
routes::app::settings::{Conversion, DefaultExchangeRates},
services, SessionState,
};
<file_sep path="hyperswitch/crates/router/src/utils/currency.rs" role="context" start="200" end="223">
async fn call_forex_api_and_save_data_to_cache_and_redis(
state: &SessionState,
stale_redis_data: Option<FxExchangeRatesCacheEntry>,
) -> CustomResult<FxExchangeRatesCacheEntry, ForexError> {
// spawn a new thread and do the api fetch and write operations on redis.
let forex_api_key = state.conf.forex_api.get_inner().api_key.peek();
if forex_api_key.is_empty() {
Err(ForexError::ConfigurationError("api_keys not provided".into()).into())
} else {
let state = state.clone();
tokio::spawn(
async move {
acquire_redis_lock_and_call_forex_api(&state)
.await
.map_err(|err| {
logger::error!(forex_error=?err);
})
.ok();
}
.in_current_span(),
);
stale_redis_data.ok_or(ForexError::EntryNotFound.into())
}
}
<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="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="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="516" end="544">
pub async fn convert_currency(
state: SessionState,
amount: i64,
to_currency: String,
from_currency: String,
) -> CustomResult<api_models::currency::CurrencyConversionResponse, ForexError> {
let forex_api = state.conf.forex_api.get_inner();
let rates = get_forex_rates(&state, forex_api.data_expiration_delay_in_seconds)
.await
.change_context(ForexError::ApiError)?;
let to_currency = enums::Currency::from_str(to_currency.as_str())
.change_context(ForexError::CurrencyNotAcceptable)
.attach_printable("The provided currency is not acceptable")?;
let from_currency = enums::Currency::from_str(from_currency.as_str())
.change_context(ForexError::CurrencyNotAcceptable)
.attach_printable("The provided currency is not acceptable")?;
let converted_amount =
currency_conversion::conversion::convert(&rates.data, from_currency, to_currency, amount)
.change_context(ForexError::ConversionError)
.attach_printable("Unable to perform currency conversion")?;
Ok(api_models::currency::CurrencyConversionResponse {
converted_amount: converted_amount.to_string(),
currency: to_currency.to_string(),
})
}
<file_sep path="hyperswitch/crates/router/src/utils/currency.rs" role="context" start="41" end="80">
pub enum ForexError {
#[error("API error")]
ApiError,
#[error("API timeout")]
ApiTimeout,
#[error("API unresponsive")]
ApiUnresponsive,
#[error("Conversion error")]
ConversionError,
#[error("Could not acquire the lock for cache entry")]
CouldNotAcquireLock,
#[error("Provided currency not acceptable")]
CurrencyNotAcceptable,
#[error("Forex configuration error: {0}")]
ConfigurationError(String),
#[error("Incorrect entries in default Currency response")]
DefaultCurrencyParsingError,
#[error("Entry not found in cache")]
EntryNotFound,
#[error("Forex data unavailable")]
ForexDataUnavailable,
#[error("Expiration time invalid")]
InvalidLogExpiry,
#[error("Error reading local")]
LocalReadError,
#[error("Error writing to local cache")]
LocalWriteError,
#[error("Json Parsing error")]
ParsingError,
#[error("Aws Kms decryption error")]
AwsKmsDecryptionFailed,
#[error("Error connecting to redis")]
RedisConnectionError,
#[error("Not able to release write lock")]
RedisLockReleaseFailed,
#[error("Error writing to redis")]
RedisWriteError,
#[error("Not able to acquire write lock")]
WriteLockNotAcquired,
}
<file_sep path="hyperswitch/crates/router/src/utils/currency.rs" role="context" start="30" end="33">
pub struct FxExchangeRatesCacheEntry {
pub data: Arc<ExchangeRates>,
timestamp: i64,
}
<file_sep path="hyperswitch/crates/router/src/routes/app.rs" role="context" start="787" end="787">
pub struct Forex;
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/utils/currency.rs<|crate|> router anchor=call_api_if_redis_forex_data_expired kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<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="177" end="177">
use common_utils::{date_time, errors::CustomResult, events::ApiEventMetric, ext_traits::AsyncExt};
use crate::{
logger,
routes::app::settings::{Conversion, DefaultExchangeRates},
services, SessionState,
};
<file_sep path="hyperswitch/crates/router/src/utils/currency.rs" role="context" start="225" end="250">
async fn acquire_redis_lock_and_call_forex_api(
state: &SessionState,
) -> CustomResult<(), ForexError> {
let lock_acquired = acquire_redis_lock(state).await?;
if !lock_acquired {
Err(ForexError::CouldNotAcquireLock.into())
} else {
logger::debug!("forex_log: redis lock acquired");
let api_rates = fetch_forex_rates_from_primary_api(state).await;
match api_rates {
Ok(rates) => save_forex_data_to_cache_and_redis(state, rates).await,
Err(error) => {
logger::error!(forex_error=?error,"primary_forex_error");
// API not able to fetch data call secondary service
let secondary_api_rates = fetch_forex_rates_from_fallback_api(state).await;
match secondary_api_rates {
Ok(rates) => save_forex_data_to_cache_and_redis(state, rates).await,
Err(error) => {
release_redis_lock(state).await?;
Err(error)
}
}
}
}
}
}
<file_sep path="hyperswitch/crates/router/src/utils/currency.rs" role="context" start="200" end="223">
async fn call_forex_api_and_save_data_to_cache_and_redis(
state: &SessionState,
stale_redis_data: Option<FxExchangeRatesCacheEntry>,
) -> CustomResult<FxExchangeRatesCacheEntry, ForexError> {
// spawn a new thread and do the api fetch and write operations on redis.
let forex_api_key = state.conf.forex_api.get_inner().api_key.peek();
if forex_api_key.is_empty() {
Err(ForexError::ConfigurationError("api_keys not provided".into()).into())
} else {
let state = state.clone();
tokio::spawn(
async move {
acquire_redis_lock_and_call_forex_api(&state)
.await
.map_err(|err| {
logger::error!(forex_error=?err);
})
.ok();
}
.in_current_span(),
);
stale_redis_data.ok_or(ForexError::EntryNotFound.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="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="264" end="282">
async fn call_forex_api_if_redis_data_expired(
state: &SessionState,
redis_data: FxExchangeRatesCacheEntry,
data_expiration_delay: u32,
) -> CustomResult<FxExchangeRatesCacheEntry, ForexError> {
match is_redis_expired(Some(redis_data.clone()).as_ref(), data_expiration_delay).await {
Some(redis_forex) => {
// Valid data present in redis
let exchange_rates = FxExchangeRatesCacheEntry::new(redis_forex.as_ref().clone());
logger::debug!("forex_log: forex response found in redis");
save_forex_data_to_local_cache(exchange_rates.clone()).await?;
Ok(exchange_rates)
}
None => {
// redis expired
call_forex_api_and_save_data_to_cache_and_redis(state, Some(redis_data)).await
}
}
}
<file_sep path="hyperswitch/crates/router/src/utils/currency.rs" role="context" start="129" end="129">
type Error = error_stack::Report<ForexError>;
<file_sep path="hyperswitch/crates/router/src/utils/currency.rs" role="context" start="41" end="80">
pub enum ForexError {
#[error("API error")]
ApiError,
#[error("API timeout")]
ApiTimeout,
#[error("API unresponsive")]
ApiUnresponsive,
#[error("Conversion error")]
ConversionError,
#[error("Could not acquire the lock for cache entry")]
CouldNotAcquireLock,
#[error("Provided currency not acceptable")]
CurrencyNotAcceptable,
#[error("Forex configuration error: {0}")]
ConfigurationError(String),
#[error("Incorrect entries in default Currency response")]
DefaultCurrencyParsingError,
#[error("Entry not found in cache")]
EntryNotFound,
#[error("Forex data unavailable")]
ForexDataUnavailable,
#[error("Expiration time invalid")]
InvalidLogExpiry,
#[error("Error reading local")]
LocalReadError,
#[error("Error writing to local cache")]
LocalWriteError,
#[error("Json Parsing error")]
ParsingError,
#[error("Aws Kms decryption error")]
AwsKmsDecryptionFailed,
#[error("Error connecting to redis")]
RedisConnectionError,
#[error("Not able to release write lock")]
RedisLockReleaseFailed,
#[error("Error writing to redis")]
RedisWriteError,
#[error("Not able to acquire write lock")]
WriteLockNotAcquired,
}
<file_sep path="hyperswitch/crates/router/src/routes/app.rs" role="context" start="104" end="125">
pub struct SessionState {
pub store: Box<dyn StorageInterface>,
/// Global store is used for global schema operations in tables like Users and Tenants
pub global_store: Box<dyn GlobalStorageInterface>,
pub accounts_store: Box<dyn AccountsStorageInterface>,
pub conf: Arc<settings::Settings<RawSecret>>,
pub api_client: Box<dyn crate::services::ApiClient>,
pub event_handler: EventsHandler,
#[cfg(feature = "email")]
pub email_client: Arc<Box<dyn EmailService>>,
#[cfg(feature = "olap")]
pub pool: AnalyticsProvider,
pub file_storage_client: Arc<dyn FileStorageInterface>,
pub request_id: Option<RequestId>,
pub base_url: String,
pub tenant: Tenant,
#[cfg(feature = "olap")]
pub opensearch_client: Option<Arc<OpenSearchClient>>,
pub grpc_client: Arc<GrpcClients>,
pub theme_storage_client: Arc<dyn FileStorageInterface>,
pub locale: String,
}
<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=call_forex_api_and_save_data_to_cache_and_redis kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/utils/currency.rs" role="context" start="200" end="223">
async fn call_forex_api_and_save_data_to_cache_and_redis(
state: &SessionState,
stale_redis_data: Option<FxExchangeRatesCacheEntry>,
) -> CustomResult<FxExchangeRatesCacheEntry, ForexError> {
// spawn a new thread and do the api fetch and write operations on redis.
let forex_api_key = state.conf.forex_api.get_inner().api_key.peek();
if forex_api_key.is_empty() {
Err(ForexError::ConfigurationError("api_keys not provided".into()).into())
} else {
let state = state.clone();
tokio::spawn(
async move {
acquire_redis_lock_and_call_forex_api(&state)
.await
.map_err(|err| {
logger::error!(forex_error=?err);
})
.ok();
}
.in_current_span(),
);
stale_redis_data.ok_or(ForexError::EntryNotFound.into())
}
}
<file_sep path="hyperswitch/crates/router/src/utils/currency.rs" role="context" start="199" end="199">
use common_utils::{date_time, errors::CustomResult, events::ApiEventMetric, ext_traits::AsyncExt};
use tokio::sync::RwLock;
use crate::{
logger,
routes::app::settings::{Conversion, DefaultExchangeRates},
services, SessionState,
};
<file_sep path="hyperswitch/crates/router/src/utils/currency.rs" role="context" start="252" end="262">
async fn save_forex_data_to_cache_and_redis(
state: &SessionState,
forex: FxExchangeRatesCacheEntry,
) -> CustomResult<(), ForexError> {
save_forex_data_to_redis(state, &forex)
.await
.async_and_then(|_rates| release_redis_lock(state))
.await
.async_and_then(|_val| save_forex_data_to_local_cache(forex.clone()))
.await
}
<file_sep path="hyperswitch/crates/router/src/utils/currency.rs" role="context" start="225" end="250">
async fn acquire_redis_lock_and_call_forex_api(
state: &SessionState,
) -> CustomResult<(), ForexError> {
let lock_acquired = acquire_redis_lock(state).await?;
if !lock_acquired {
Err(ForexError::CouldNotAcquireLock.into())
} else {
logger::debug!("forex_log: redis lock acquired");
let api_rates = fetch_forex_rates_from_primary_api(state).await;
match api_rates {
Ok(rates) => save_forex_data_to_cache_and_redis(state, rates).await,
Err(error) => {
logger::error!(forex_error=?error,"primary_forex_error");
// API not able to fetch data call secondary service
let secondary_api_rates = fetch_forex_rates_from_fallback_api(state).await;
match secondary_api_rates {
Ok(rates) => save_forex_data_to_cache_and_redis(state, rates).await,
Err(error) => {
release_redis_lock(state).await?;
Err(error)
}
}
}
}
}
}
<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="264" end="282">
async fn call_forex_api_if_redis_data_expired(
state: &SessionState,
redis_data: FxExchangeRatesCacheEntry,
data_expiration_delay: u32,
) -> CustomResult<FxExchangeRatesCacheEntry, ForexError> {
match is_redis_expired(Some(redis_data.clone()).as_ref(), data_expiration_delay).await {
Some(redis_forex) => {
// Valid data present in redis
let exchange_rates = FxExchangeRatesCacheEntry::new(redis_forex.as_ref().clone());
logger::debug!("forex_log: forex response found in redis");
save_forex_data_to_local_cache(exchange_rates.clone()).await?;
Ok(exchange_rates)
}
None => {
// redis expired
call_forex_api_and_save_data_to_cache_and_redis(state, Some(redis_data)).await
}
}
}
<file_sep path="hyperswitch/crates/router/src/utils/currency.rs" role="context" start="41" end="80">
pub enum ForexError {
#[error("API error")]
ApiError,
#[error("API timeout")]
ApiTimeout,
#[error("API unresponsive")]
ApiUnresponsive,
#[error("Conversion error")]
ConversionError,
#[error("Could not acquire the lock for cache entry")]
CouldNotAcquireLock,
#[error("Provided currency not acceptable")]
CurrencyNotAcceptable,
#[error("Forex configuration error: {0}")]
ConfigurationError(String),
#[error("Incorrect entries in default Currency response")]
DefaultCurrencyParsingError,
#[error("Entry not found in cache")]
EntryNotFound,
#[error("Forex data unavailable")]
ForexDataUnavailable,
#[error("Expiration time invalid")]
InvalidLogExpiry,
#[error("Error reading local")]
LocalReadError,
#[error("Error writing to local cache")]
LocalWriteError,
#[error("Json Parsing error")]
ParsingError,
#[error("Aws Kms decryption error")]
AwsKmsDecryptionFailed,
#[error("Error connecting to redis")]
RedisConnectionError,
#[error("Not able to release write lock")]
RedisLockReleaseFailed,
#[error("Error writing to redis")]
RedisWriteError,
#[error("Not able to acquire write lock")]
WriteLockNotAcquired,
}
<file_sep path="hyperswitch/crates/router/src/utils/currency.rs" role="context" start="30" end="33">
pub struct FxExchangeRatesCacheEntry {
pub data: Arc<ExchangeRates>,
timestamp: i64,
}
<file_sep path="hyperswitch/crates/router/src/routes/app.rs" role="context" start="104" end="125">
pub struct SessionState {
pub store: Box<dyn StorageInterface>,
/// Global store is used for global schema operations in tables like Users and Tenants
pub global_store: Box<dyn GlobalStorageInterface>,
pub accounts_store: Box<dyn AccountsStorageInterface>,
pub conf: Arc<settings::Settings<RawSecret>>,
pub api_client: Box<dyn crate::services::ApiClient>,
pub event_handler: EventsHandler,
#[cfg(feature = "email")]
pub email_client: Arc<Box<dyn EmailService>>,
#[cfg(feature = "olap")]
pub pool: AnalyticsProvider,
pub file_storage_client: Arc<dyn FileStorageInterface>,
pub request_id: Option<RequestId>,
pub base_url: String,
pub tenant: Tenant,
#[cfg(feature = "olap")]
pub opensearch_client: Option<Arc<OpenSearchClient>>,
pub grpc_client: Arc<GrpcClients>,
pub theme_storage_client: Arc<dyn FileStorageInterface>,
pub locale: String,
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/gpayments.rs<|crate|> router anchor=build_request 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="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/crates/router/src/connector/gpayments.rs" role="context" start="267" end="267">
use common_utils::{
request::RequestContent,
types::{AmountConvertor, MinorUnit, MinorUnitForConnector},
};
use transformers as gpayments;
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="321" end="327">
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/gpayments.rs" role="context" start="299" end="319">
fn handle_response(
&self,
data: &types::authentication::ConnectorAuthenticationRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<
types::authentication::ConnectorAuthenticationRouterData,
errors::ConnectorError,
> {
let response: gpayments_types::GpaymentsAuthenticationSuccessResponse = res
.response
.parse_struct("gpayments GpaymentsAuthenticationResponse")
.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/gpayments.rs" role="context" start="258" end="267">
fn get_request_body(
&self,
req: &types::authentication::ConnectorAuthenticationRouterData,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_router_data = gpayments::GpaymentsRouterData::from((MinorUnit::zero(), req));
let req_obj =
gpayments_types::GpaymentsAuthenticationRequest::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="244" end="256">
fn get_url(
&self,
req: &types::authentication::ConnectorAuthenticationRouterData,
_connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_metadata: GpaymentsConnectorMetaData = to_connector_meta(
req.request
.pre_authentication_data
.connector_metadata
.clone(),
)?;
Ok(connector_metadata.authentication_url)
}
<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="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/core/relay.rs" role="context" start="97" end="97">
type Request = relay_api_models::RelayRefundRequestData;
<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/services/api/client.rs<|crate|> router anchor=create_client kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/services/api/client.rs" role="context" start="71" end="99">
pub fn create_client(
proxy_config: &Proxy,
client_certificate: Option<masking::Secret<String>>,
client_certificate_key: Option<masking::Secret<String>>,
) -> CustomResult<reqwest::Client, ApiClientError> {
match (client_certificate, client_certificate_key) {
(Some(encoded_certificate), Some(encoded_certificate_key)) => {
let client_builder = get_client_builder(proxy_config)?;
let identity = create_identity_from_certificate_and_key(
encoded_certificate.clone(),
encoded_certificate_key,
)?;
let certificate_list = create_certificate(encoded_certificate)?;
let client_builder = certificate_list
.into_iter()
.fold(client_builder, |client_builder, certificate| {
client_builder.add_root_certificate(certificate)
});
client_builder
.identity(identity)
.use_rustls_tls()
.build()
.change_context(ApiClientError::ClientConstructionFailed)
.attach_printable("Failed to construct client with certificate and certificate key")
}
_ => get_base_client(proxy_config),
}
}
<file_sep path="hyperswitch/crates/router/src/services/api/client.rs" role="context" start="70" end="70">
use masking::{ExposeInterface, PeekInterface};
use reqwest::multipart::Form;
use crate::{
configs::settings::Proxy,
consts::BASE64_ENGINE,
core::errors::{ApiClientError, CustomResult},
routes::SessionState,
};
<file_sep path="hyperswitch/crates/router/src/services/api/client.rs" role="context" start="124" end="135">
pub fn create_certificate(
encoded_certificate: masking::Secret<String>,
) -> Result<Vec<reqwest::Certificate>, error_stack::Report<ApiClientError>> {
let decoded_certificate = BASE64_ENGINE
.decode(encoded_certificate.expose())
.change_context(ApiClientError::CertificateDecodeFailed)?;
let certificate = String::from_utf8(decoded_certificate)
.change_context(ApiClientError::CertificateDecodeFailed)?;
reqwest::Certificate::from_pem_bundle(certificate.as_bytes())
.change_context(ApiClientError::CertificateDecodeFailed)
}
<file_sep path="hyperswitch/crates/router/src/services/api/client.rs" role="context" start="101" end="122">
pub fn create_identity_from_certificate_and_key(
encoded_certificate: masking::Secret<String>,
encoded_certificate_key: masking::Secret<String>,
) -> Result<reqwest::Identity, error_stack::Report<ApiClientError>> {
let decoded_certificate = BASE64_ENGINE
.decode(encoded_certificate.expose())
.change_context(ApiClientError::CertificateDecodeFailed)?;
let decoded_certificate_key = BASE64_ENGINE
.decode(encoded_certificate_key.expose())
.change_context(ApiClientError::CertificateDecodeFailed)?;
let certificate = String::from_utf8(decoded_certificate)
.change_context(ApiClientError::CertificateDecodeFailed)?;
let certificate_key = String::from_utf8(decoded_certificate_key)
.change_context(ApiClientError::CertificateDecodeFailed)?;
let key_chain = format!("{}{}", certificate_key, certificate);
reqwest::Identity::from_pem(key_chain.as_bytes())
.change_context(ApiClientError::CertificateDecodeFailed)
}
<file_sep path="hyperswitch/crates/router/src/services/api/client.rs" role="context" start="58" end="67">
fn get_base_client(proxy_config: &Proxy) -> CustomResult<reqwest::Client, ApiClientError> {
Ok(DEFAULT_CLIENT
.get_or_try_init(|| {
get_client_builder(proxy_config)?
.build()
.change_context(ApiClientError::ClientConstructionFailed)
.attach_printable("Failed to construct base client")
})?
.clone())
}
<file_sep path="hyperswitch/crates/router/src/services/api/client.rs" role="context" start="21" end="56">
fn get_client_builder(
proxy_config: &Proxy,
) -> CustomResult<reqwest::ClientBuilder, ApiClientError> {
let mut client_builder = reqwest::Client::builder()
.redirect(reqwest::redirect::Policy::none())
.pool_idle_timeout(Duration::from_secs(
proxy_config
.idle_pool_connection_timeout
.unwrap_or_default(),
));
let proxy_exclusion_config =
reqwest::NoProxy::from_string(&proxy_config.bypass_proxy_hosts.clone().unwrap_or_default());
// Proxy all HTTPS traffic through the configured HTTPS proxy
if let Some(url) = proxy_config.https_url.as_ref() {
client_builder = client_builder.proxy(
reqwest::Proxy::https(url)
.change_context(ApiClientError::InvalidProxyConfiguration)
.attach_printable("HTTPS proxy configuration error")?
.no_proxy(proxy_exclusion_config.clone()),
);
}
// Proxy all HTTP traffic through the configured HTTP proxy
if let Some(url) = proxy_config.http_url.as_ref() {
client_builder = client_builder.proxy(
reqwest::Proxy::http(url)
.change_context(ApiClientError::InvalidProxyConfiguration)
.attach_printable("HTTP proxy configuration error")?
.no_proxy(proxy_exclusion_config),
);
}
Ok(client_builder)
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/gpayments.rs<|crate|> router anchor=build_request 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="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="462" end="462">
use common_utils::{
request::RequestContent,
types::{AmountConvertor, MinorUnit, MinorUnitForConnector},
};
use transformers as gpayments;
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="513" end="519">
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/gpayments.rs" role="context" start="494" end="511">
fn handle_response(
&self,
data: &types::authentication::PreAuthNRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::authentication::PreAuthNRouterData, errors::ConnectorError> {
let response: gpayments_types::GpaymentsPreAuthenticationResponse = res
.response
.parse_struct("gpayments GpaymentsPreAuthenticationResponse")
.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/gpayments.rs" role="context" start="452" end="461">
fn get_request_body(
&self,
req: &types::authentication::PreAuthNRouterData,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_router_data = gpayments::GpaymentsRouterData::from((MinorUnit::zero(), req));
let req_obj =
gpayments_types::GpaymentsPreAuthenticationRequest::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="443" end="450">
fn get_url(
&self,
req: &types::authentication::PreAuthNRouterData,
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/brw/init?mode=custom", base_url,))
}
<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="32" end="36">
pub fn new() -> &'static Self {
&Self {
_amount_converter: &MinorUnitForConnector,
}
}
<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/tests/connectors/opennode.rs<|crate|> router<|connector|> opennode 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/opennode.rs" role="context" start="40" end="66">
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/opennode.rs" role="context" start="39" end="39">
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/opennode.rs" role="context" start="110" end="124">
async fn should_only_authorize_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);
let resp = response.response.ok().unwrap();
let endpoint = match resp {
types::PaymentsResponseData::TransactionResponse {
redirection_data, ..
} => Some(redirection_data),
_ => None,
};
assert!(endpoint.is_some())
}
<file_sep path="hyperswitch/crates/router/tests/connectors/opennode.rs" role="context" start="68" end="106">
fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
Some(types::PaymentsAuthorizeData {
amount: 1,
currency: enums::Currency::USD,
payment_method_data: domain::PaymentMethodData::Crypto(domain::CryptoData {
pay_currency: None,
network: None,
}),
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("https://google.com/")),
webhook_url: Some(String::from("https://google.com/")),
complete_authorize_url: None,
capture_method: 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/opennode.rs" role="context" start="33" end="35">
fn get_name(&self) -> String {
"opennode".to_string()
}
<file_sep path="hyperswitch/crates/router/tests/connectors/opennode.rs" role="context" start="24" end="31">
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.opennode
.expect("Missing connector authentication configuration")
.into(),
)
}
<file_sep path="hyperswitch/crates/router/tests/connectors/opennode.rs" role="context" start="128" end="143">
async fn should_sync_authorized_payment() {
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
"5adebfb1-802e-432b-8b42-5db4b754b2eb".to_string(),
),
..Default::default()
}),
get_default_payment_info(),
)
.await
.expect("PSync response");
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
<file_sep path="hyperswitch/crates/router/tests/connectors/opennode.rs" role="context" start="166" end="181">
async fn should_sync_expired_payment() {
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
"c36a097a-5091-4317-8749-80343a71c1c4".to_string(),
),
..Default::default()
}),
get_default_payment_info(),
)
.await
.expect("PSync response");
assert_eq!(response.status, enums::AttemptStatus::Failure);
}
<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/connector/gpayments.rs<|crate|> router anchor=build_request 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="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="559" end="559">
use common_utils::{
request::RequestContent,
types::{AmountConvertor, MinorUnit, MinorUnitForConnector},
};
use transformers as gpayments;
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="611" end="617">
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/gpayments.rs" role="context" start="591" end="609">
fn handle_response(
&self,
data: &types::authentication::PreAuthNVersionCallRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::authentication::PreAuthNVersionCallRouterData, errors::ConnectorError>
{
let response: gpayments_types::GpaymentsPreAuthVersionCallResponse = res
.response
.parse_struct("gpayments GpaymentsPreAuthVersionCallResponse")
.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/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="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="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="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/core/relay.rs" role="context" start="97" end="97">
type Request = relay_api_models::RelayRefundRequestData;
<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=build_request kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|>
<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="559" end="559">
use common_utils::{
request::RequestContent,
types::{AmountConvertor, MinorUnit, MinorUnitForConnector},
};
use transformers as gpayments;
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="611" end="617">
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/gpayments.rs" role="context" start="591" end="609">
fn handle_response(
&self,
data: &types::authentication::PreAuthNVersionCallRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::authentication::PreAuthNVersionCallRouterData, errors::ConnectorError>
{
let response: gpayments_types::GpaymentsPreAuthVersionCallResponse = res
.response
.parse_struct("gpayments GpaymentsPreAuthVersionCallResponse")
.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/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="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="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="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)
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/configs/settings.rs<|crate|> router anchor=deserialize_hashset_inner 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="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/configs/settings.rs" role="context" start="1213" end="1213">
use std::{
collections::{HashMap, HashSet},
path::PathBuf,
sync::Arc,
};
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="1263" end="1280">
fn deserialize_optional_hashset<'a, D, T>(deserializer: D) -> Result<Option<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;
<Option<String>>::deserialize(deserializer).map(|value| {
value.map_or(Ok(None), |inner: String| {
let list = deserialize_hashset_inner(inner).map_err(D::Error::custom)?;
match list.len() {
0 => Ok(None),
_ => Ok(Some(list)),
}
})
})?
}
<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="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="1159" end="1199">
fn deserialize_hashmap_inner<K, V>(
value: HashMap<String, String>,
) -> Result<HashMap<K, HashSet<V>>, String>
where
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,
{
let (values, errors) = value
.into_iter()
.map(
|(k, v)| match (K::from_str(k.trim()), deserialize_hashset_inner(v)) {
(Err(error), _) => Err(format!(
"Unable to deserialize `{}` as `{}`: {error}",
k,
std::any::type_name::<K>()
)),
(_, Err(error)) => Err(error),
(Ok(key), Ok(value)) => Ok((key, value)),
},
)
.fold(
(HashMap::new(), Vec::new()),
|(mut values, mut errors), result| match result {
Ok((key, value)) => {
values.insert(key, value);
(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="907" end="909">
pub fn new() -> ApplicationResult<Self> {
Self::with_config_path(None)
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/services/openidconnect.rs<|crate|> router anchor=get_authorization_url kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/services/openidconnect.rs" role="context" start="16" end="44">
pub async fn get_authorization_url(
state: SessionState,
redirect_url: String,
redirect_state: Secret<String>,
base_url: Secret<String>,
client_id: Secret<String>,
) -> UserResult<url::Url> {
let discovery_document = get_discovery_document(base_url, &state).await?;
let (auth_url, csrf_token, nonce) =
get_oidc_core_client(discovery_document, client_id, None, redirect_url)?
.authorize_url(
oidc_core::CoreAuthenticationFlow::AuthorizationCode,
|| oidc::CsrfToken::new(redirect_state.expose()),
oidc::Nonce::new_random,
)
.add_scope(oidc::Scope::new("email".to_string()))
.url();
// Save csrf & nonce as key value respectively
let key = get_oidc_redis_key(csrf_token.secret());
get_redis_connection(&state)?
.set_key_with_expiry(&key.into(), nonce.secret(), consts::user::REDIS_SSO_TTL)
.await
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to save csrf-nonce in redis")?;
Ok(auth_url)
}
<file_sep path="hyperswitch/crates/router/src/services/openidconnect.rs" role="context" start="15" end="15">
use masking::{ExposeInterface, Secret};
use oidc::TokenResponse;
use openidconnect::{self as oidc, core as oidc_core};
use crate::{
consts,
core::errors::{UserErrors, UserResult},
routes::SessionState,
services::api::client,
types::domain::user::UserEmail,
};
<file_sep path="hyperswitch/crates/router/src/services/openidconnect.rs" role="context" start="106" end="117">
async fn get_discovery_document(
base_url: Secret<String>,
state: &SessionState,
) -> UserResult<oidc_core::CoreProviderMetadata> {
let issuer_url =
oidc::IssuerUrl::new(base_url.expose()).change_context(UserErrors::InternalServerError)?;
oidc_core::CoreProviderMetadata::discover_async(issuer_url, |req| {
get_oidc_reqwest_client(state, req)
})
.await
.change_context(UserErrors::InternalServerError)
}
<file_sep path="hyperswitch/crates/router/src/services/openidconnect.rs" role="context" start="46" end="103">
pub async fn get_user_email_from_oidc_provider(
state: &SessionState,
redirect_url: String,
redirect_state: Secret<String>,
base_url: Secret<String>,
client_id: Secret<String>,
authorization_code: Secret<String>,
client_secret: Secret<String>,
) -> UserResult<UserEmail> {
let nonce = get_nonce_from_redis(state, &redirect_state).await?;
let discovery_document = get_discovery_document(base_url, state).await?;
let client = get_oidc_core_client(
discovery_document,
client_id,
Some(client_secret),
redirect_url,
)?;
let nonce_clone = nonce.clone();
client
.authorize_url(
oidc_core::CoreAuthenticationFlow::AuthorizationCode,
|| oidc::CsrfToken::new(redirect_state.expose()),
|| nonce_clone,
)
.add_scope(oidc::Scope::new("email".to_string()));
// Send request to OpenId provider with authorization code
let token_response = client
.exchange_code(oidc::AuthorizationCode::new(authorization_code.expose()))
.request_async(|req| get_oidc_reqwest_client(state, req))
.await
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to exchange code and fetch oidc token")?;
// Fetch id token from response
let id_token = token_response
.id_token()
.ok_or(UserErrors::InternalServerError)
.attach_printable("Id Token not provided in token response")?;
// Verify id token
let id_token_claims = id_token
.claims(&client.id_token_verifier(), &nonce)
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to verify id token")?;
// Get email from token
let email_from_token = id_token_claims
.email()
.map(|email| email.to_string())
.ok_or(UserErrors::InternalServerError)
.attach_printable("OpenID Provider Didnt provide email")?;
UserEmail::new(Secret::new(email_from_token))
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to create email type")
}
<file_sep path="hyperswitch/crates/router/src/services/openidconnect.rs" role="context" start="187" end="189">
fn get_oidc_redis_key(csrf: &str) -> String {
format!("{}OIDC_{}", consts::user::REDIS_SSO_PREFIX, csrf)
}
<file_sep path="hyperswitch/crates/router/src/core/errors/user.rs" role="context" start="10" end="113">
pub enum UserErrors {
#[error("User InternalServerError")]
InternalServerError,
#[error("InvalidCredentials")]
InvalidCredentials,
#[error("UserNotFound")]
UserNotFound,
#[error("UserExists")]
UserExists,
#[error("LinkInvalid")]
LinkInvalid,
#[error("UnverifiedUser")]
UnverifiedUser,
#[error("InvalidOldPassword")]
InvalidOldPassword,
#[error("EmailParsingError")]
EmailParsingError,
#[error("NameParsingError")]
NameParsingError,
#[error("PasswordParsingError")]
PasswordParsingError,
#[error("UserAlreadyVerified")]
UserAlreadyVerified,
#[error("CompanyNameParsingError")]
CompanyNameParsingError,
#[error("MerchantAccountCreationError: {0}")]
MerchantAccountCreationError(String),
#[error("InvalidEmailError")]
InvalidEmailError,
#[error("DuplicateOrganizationId")]
DuplicateOrganizationId,
#[error("MerchantIdNotFound")]
MerchantIdNotFound,
#[error("MetadataAlreadySet")]
MetadataAlreadySet,
#[error("InvalidRoleId")]
InvalidRoleId,
#[error("InvalidRoleOperation")]
InvalidRoleOperation,
#[error("IpAddressParsingFailed")]
IpAddressParsingFailed,
#[error("InvalidMetadataRequest")]
InvalidMetadataRequest,
#[error("MerchantIdParsingError")]
MerchantIdParsingError,
#[error("ChangePasswordError")]
ChangePasswordError,
#[error("InvalidDeleteOperation")]
InvalidDeleteOperation,
#[error("MaxInvitationsError")]
MaxInvitationsError,
#[error("RoleNotFound")]
RoleNotFound,
#[error("InvalidRoleOperationWithMessage")]
InvalidRoleOperationWithMessage(String),
#[error("RoleNameParsingError")]
RoleNameParsingError,
#[error("RoleNameAlreadyExists")]
RoleNameAlreadyExists,
#[error("TotpNotSetup")]
TotpNotSetup,
#[error("InvalidTotp")]
InvalidTotp,
#[error("TotpRequired")]
TotpRequired,
#[error("InvalidRecoveryCode")]
InvalidRecoveryCode,
#[error("TwoFactorAuthRequired")]
TwoFactorAuthRequired,
#[error("TwoFactorAuthNotSetup")]
TwoFactorAuthNotSetup,
#[error("TOTP secret not found")]
TotpSecretNotFound,
#[error("User auth method already exists")]
UserAuthMethodAlreadyExists,
#[error("Invalid user auth method operation")]
InvalidUserAuthMethodOperation,
#[error("Auth config parsing error")]
AuthConfigParsingError,
#[error("Invalid SSO request")]
SSOFailed,
#[error("profile_id missing in JWT")]
JwtProfileIdMissing,
#[error("Maximum attempts reached for TOTP")]
MaxTotpAttemptsReached,
#[error("Maximum attempts reached for Recovery Code")]
MaxRecoveryCodeAttemptsReached,
#[error("Forbidden tenant id")]
ForbiddenTenantId,
#[error("Error Uploading file to Theme Storage")]
ErrorUploadingFile,
#[error("Error Retrieving file from Theme Storage")]
ErrorRetrievingFile,
#[error("Theme not found")]
ThemeNotFound,
#[error("Theme with lineage already exists")]
ThemeAlreadyExists,
#[error("Invalid field: {0} in lineage")]
InvalidThemeLineage(String),
#[error("Missing required field: email_config")]
MissingEmailConfig,
#[error("Invalid Auth Method Operation: {0}")]
InvalidAuthMethodOperationWithMessage(String),
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/services/email/types.rs<|crate|> router anchor=get_email_data 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="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="492" end="492">
use common_utils::{errors::CustomResult, pii, types::theme::EmailThemeConfig};
use external_services::email::{EmailContents, EmailData, EmailError};
use crate::{
core::errors::{UserErrors, UserResult},
services::jwt,
types::domain,
};
<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="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="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/router/src/services/email/types.rs" role="context" start="89" end="246">
pub fn get_html_body(email_body: EmailBody) -> String {
match email_body {
EmailBody::Verify {
link,
entity_name,
entity_logo_url,
primary_color,
background_color,
foreground_color,
} => {
format!(
include_str!("assets/verify.html"),
link = link,
entity_name = entity_name,
entity_logo_url = entity_logo_url,
primary_color = primary_color,
background_color = background_color,
foreground_color = foreground_color
)
}
EmailBody::Reset {
link,
user_name,
entity_name,
entity_logo_url,
primary_color,
background_color,
foreground_color,
} => {
format!(
include_str!("assets/reset.html"),
link = link,
username = user_name,
entity_name = entity_name,
entity_logo_url = entity_logo_url,
primary_color = primary_color,
background_color = background_color,
foreground_color = foreground_color
)
}
EmailBody::MagicLink {
link,
user_name,
entity_name,
entity_logo_url,
primary_color,
background_color,
foreground_color,
} => {
format!(
include_str!("assets/magic_link.html"),
username = user_name,
link = link,
entity_name = entity_name,
entity_logo_url = entity_logo_url,
primary_color = primary_color,
background_color = background_color,
foreground_color = foreground_color
)
}
EmailBody::InviteUser {
link,
user_name,
entity_name,
entity_logo_url,
primary_color,
background_color,
foreground_color,
} => {
format!(
include_str!("assets/invite.html"),
username = user_name,
link = link,
entity_name = entity_name,
entity_logo_url = entity_logo_url,
primary_color = primary_color,
background_color = background_color,
foreground_color = foreground_color
)
}
// TODO: Change the linked html for accept invite from email
EmailBody::AcceptInviteFromEmail {
link,
user_name,
entity_name,
entity_logo_url,
primary_color,
background_color,
foreground_color,
} => {
format!(
include_str!("assets/invite.html"),
username = user_name,
link = link,
entity_name = entity_name,
entity_logo_url = entity_logo_url,
primary_color = primary_color,
background_color = background_color,
foreground_color = foreground_color
)
}
EmailBody::ReconActivation { user_name } => {
format!(
include_str!("assets/recon_activation.html"),
username = user_name,
)
}
EmailBody::BizEmailProd {
user_name,
poc_email,
legal_business_name,
business_location,
business_website,
product_type,
} => {
format!(
include_str!("assets/bizemailprod.html"),
poc_email = poc_email,
legal_business_name = legal_business_name,
business_location = business_location,
business_website = business_website,
username = user_name,
product_type = product_type
)
}
EmailBody::ProFeatureRequest {
feature_name,
merchant_id,
user_name,
user_email,
} => format!(
"Dear Hyperswitch Support Team,
Dashboard Pro Feature Request,
Feature name : {feature_name}
Merchant ID : {}
Merchant Name : {user_name}
Email : {user_email}
(note: This is an auto generated email. Use merchant email for any further communications)",
merchant_id.get_string_repr()
),
EmailBody::ApiKeyExpiryReminder {
expires_in,
api_key_name,
prefix,
} => format!(
include_str!("assets/api_key_expiry_reminder.html"),
api_key_name = api_key_name,
prefix = prefix,
expires_in = expires_in,
),
EmailBody::WelcomeToCommunity => {
include_str!("assets/welcome_to_community.html").to_string()
}
}
}
<file_sep path="hyperswitch/crates/router/src/services/email/types.rs" role="context" start="250" end="255">
pub struct EmailToken {
email: String,
flow: domain::Origin,
exp: u64,
entity: Option<Entity>,
}
<file_sep path="hyperswitch/crates/router/src/services/email/types.rs" role="context" start="16" end="84">
pub enum EmailBody {
Verify {
link: String,
entity_name: String,
entity_logo_url: String,
primary_color: String,
background_color: String,
foreground_color: String,
},
Reset {
link: String,
user_name: String,
entity_name: String,
entity_logo_url: String,
primary_color: String,
background_color: String,
foreground_color: String,
},
MagicLink {
link: String,
user_name: String,
entity_name: String,
entity_logo_url: String,
primary_color: String,
background_color: String,
foreground_color: String,
},
InviteUser {
link: String,
user_name: String,
entity_name: String,
entity_logo_url: String,
primary_color: String,
background_color: String,
foreground_color: String,
},
AcceptInviteFromEmail {
link: String,
user_name: String,
entity_name: String,
entity_logo_url: String,
primary_color: String,
background_color: String,
foreground_color: String,
},
BizEmailProd {
user_name: String,
poc_email: String,
legal_business_name: String,
business_location: String,
business_website: String,
product_type: MerchantProductType,
},
ReconActivation {
user_name: String,
},
ProFeatureRequest {
feature_name: String,
merchant_id: common_utils::id_type::MerchantId,
user_name: String,
user_email: String,
},
ApiKeyExpiryReminder {
expires_in: u8,
api_key_name: String,
prefix: String,
},
WelcomeToCommunity,
}
<file_sep path="hyperswitch/crates/router/src/types/domain/user/decision_manager.rs" role="context" start="149" end="158">
pub enum Origin {
#[serde(rename = "sign_in_with_sso")]
SignInWithSSO,
SignIn,
SignUp,
MagicLink,
VerifyEmail,
AcceptInvitationFromEmail,
ResetPassword,
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/services/openidconnect.rs<|crate|> router anchor=get_user_email_from_oidc_provider kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/services/openidconnect.rs" role="context" start="46" end="103">
pub async fn get_user_email_from_oidc_provider(
state: &SessionState,
redirect_url: String,
redirect_state: Secret<String>,
base_url: Secret<String>,
client_id: Secret<String>,
authorization_code: Secret<String>,
client_secret: Secret<String>,
) -> UserResult<UserEmail> {
let nonce = get_nonce_from_redis(state, &redirect_state).await?;
let discovery_document = get_discovery_document(base_url, state).await?;
let client = get_oidc_core_client(
discovery_document,
client_id,
Some(client_secret),
redirect_url,
)?;
let nonce_clone = nonce.clone();
client
.authorize_url(
oidc_core::CoreAuthenticationFlow::AuthorizationCode,
|| oidc::CsrfToken::new(redirect_state.expose()),
|| nonce_clone,
)
.add_scope(oidc::Scope::new("email".to_string()));
// Send request to OpenId provider with authorization code
let token_response = client
.exchange_code(oidc::AuthorizationCode::new(authorization_code.expose()))
.request_async(|req| get_oidc_reqwest_client(state, req))
.await
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to exchange code and fetch oidc token")?;
// Fetch id token from response
let id_token = token_response
.id_token()
.ok_or(UserErrors::InternalServerError)
.attach_printable("Id Token not provided in token response")?;
// Verify id token
let id_token_claims = id_token
.claims(&client.id_token_verifier(), &nonce)
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to verify id token")?;
// Get email from token
let email_from_token = id_token_claims
.email()
.map(|email| email.to_string())
.ok_or(UserErrors::InternalServerError)
.attach_printable("OpenID Provider Didnt provide email")?;
UserEmail::new(Secret::new(email_from_token))
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to create email type")
}
<file_sep path="hyperswitch/crates/router/src/services/openidconnect.rs" role="context" start="45" end="45">
use masking::{ExposeInterface, Secret};
use oidc::TokenResponse;
use openidconnect::{self as oidc, core as oidc_core};
use crate::{
consts,
core::errors::{UserErrors, UserResult},
routes::SessionState,
services::api::client,
types::domain::user::UserEmail,
};
<file_sep path="hyperswitch/crates/router/src/services/openidconnect.rs" role="context" start="119" end="135">
fn get_oidc_core_client(
discovery_document: oidc_core::CoreProviderMetadata,
client_id: Secret<String>,
client_secret: Option<Secret<String>>,
redirect_url: String,
) -> UserResult<oidc_core::CoreClient> {
let client_id = oidc::ClientId::new(client_id.expose());
let client_secret = client_secret.map(|secret| oidc::ClientSecret::new(secret.expose()));
let redirect_url = oidc::RedirectUrl::new(redirect_url)
.change_context(UserErrors::InternalServerError)
.attach_printable("Error creating redirect URL type")?;
Ok(
oidc_core::CoreClient::from_provider_metadata(discovery_document, client_id, client_secret)
.set_redirect_uri(redirect_url),
)
}
<file_sep path="hyperswitch/crates/router/src/services/openidconnect.rs" role="context" start="106" end="117">
async fn get_discovery_document(
base_url: Secret<String>,
state: &SessionState,
) -> UserResult<oidc_core::CoreProviderMetadata> {
let issuer_url =
oidc::IssuerUrl::new(base_url.expose()).change_context(UserErrors::InternalServerError)?;
oidc_core::CoreProviderMetadata::discover_async(issuer_url, |req| {
get_oidc_reqwest_client(state, req)
})
.await
.change_context(UserErrors::InternalServerError)
}
<file_sep path="hyperswitch/crates/router/src/services/openidconnect.rs" role="context" start="16" end="44">
pub async fn get_authorization_url(
state: SessionState,
redirect_url: String,
redirect_state: Secret<String>,
base_url: Secret<String>,
client_id: Secret<String>,
) -> UserResult<url::Url> {
let discovery_document = get_discovery_document(base_url, &state).await?;
let (auth_url, csrf_token, nonce) =
get_oidc_core_client(discovery_document, client_id, None, redirect_url)?
.authorize_url(
oidc_core::CoreAuthenticationFlow::AuthorizationCode,
|| oidc::CsrfToken::new(redirect_state.expose()),
oidc::Nonce::new_random,
)
.add_scope(oidc::Scope::new("email".to_string()))
.url();
// Save csrf & nonce as key value respectively
let key = get_oidc_redis_key(csrf_token.secret());
get_redis_connection(&state)?
.set_key_with_expiry(&key.into(), nonce.secret(), consts::user::REDIS_SSO_TTL)
.await
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to save csrf-nonce in redis")?;
Ok(auth_url)
}
<file_sep path="hyperswitch/crates/router/src/services/openidconnect.rs" role="context" start="137" end="152">
async fn get_nonce_from_redis(
state: &SessionState,
redirect_state: &Secret<String>,
) -> UserResult<oidc::Nonce> {
let redis_connection = get_redis_connection(state)?;
let redirect_state = redirect_state.clone().expose();
let key = get_oidc_redis_key(&redirect_state);
redis_connection
.get_key::<Option<String>>(&key.into())
.await
.change_context(UserErrors::InternalServerError)
.attach_printable("Error Fetching CSRF from redis")?
.map(oidc::Nonce::new)
.ok_or(UserErrors::SSOFailed)
.attach_printable("Cannot find csrf in redis. Csrf invalid or expired")
}
<file_sep path="hyperswitch/crates/router/src/services/openidconnect.rs" role="context" start="154" end="185">
async fn get_oidc_reqwest_client(
state: &SessionState,
request: oidc::HttpRequest,
) -> Result<oidc::HttpResponse, ApiClientError> {
let client = client::create_client(&state.conf.proxy, None, None)
.map_err(|e| e.current_context().to_owned())?;
let mut request_builder = client
.request(request.method, request.url)
.body(request.body);
for (name, value) in &request.headers {
request_builder = request_builder.header(name.as_str(), value.as_bytes());
}
let request = request_builder
.build()
.map_err(|_| ApiClientError::ClientConstructionFailed)?;
let response = client
.execute(request)
.await
.map_err(|_| ApiClientError::RequestNotSent("OpenIDConnect".to_string()))?;
Ok(oidc::HttpResponse {
status_code: response.status(),
headers: response.headers().to_owned(),
body: response
.bytes()
.await
.map_err(|_| ApiClientError::ResponseDecodingFailed)?
.to_vec(),
})
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/services/api.rs<|crate|> router anchor=build_payment_link_template kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/services/api.rs" role="context" start="1998" end="2064">
fn build_payment_link_template(
payment_link_data: PaymentLinkFormData,
) -> CustomResult<(Tera, Context), errors::ApiErrorResponse> {
let mut tera = Tera::default();
// Add modification to css template with dynamic data
let css_template =
include_str!("../core/payment_link/payment_link_initiate/payment_link.css").to_string();
let _ = tera.add_raw_template("payment_link_css", &css_template);
let mut context = Context::new();
context.insert("css_color_scheme", &payment_link_data.css_script);
let rendered_css = match tera.render("payment_link_css", &context) {
Ok(rendered_css) => rendered_css,
Err(tera_error) => {
crate::logger::warn!("{tera_error}");
Err(errors::ApiErrorResponse::InternalServerError)?
}
};
// Add modification to js template with dynamic data
let js_template =
include_str!("../core/payment_link/payment_link_initiate/payment_link.js").to_string();
let _ = tera.add_raw_template("payment_link_js", &js_template);
context.insert("payment_details_js_script", &payment_link_data.js_script);
let rendered_js = match tera.render("payment_link_js", &context) {
Ok(rendered_js) => rendered_js,
Err(tera_error) => {
crate::logger::warn!("{tera_error}");
Err(errors::ApiErrorResponse::InternalServerError)?
}
};
// Logging template
let logging_template =
include_str!("redirection/assets/redirect_error_logs_push.js").to_string();
//Locale template
let locale_template = include_str!("../core/payment_link/locale.js").to_string();
// Modify Html template with rendered js and rendered css files
let html_template =
include_str!("../core/payment_link/payment_link_initiate/payment_link.html").to_string();
let _ = tera.add_raw_template("payment_link", &html_template);
context.insert("rendered_meta_tag_html", &payment_link_data.html_meta_tags);
context.insert(
"preload_link_tags",
&get_preload_link_html_template(&payment_link_data.sdk_url),
);
context.insert(
"hyperloader_sdk_link",
&get_hyper_loader_sdk(&payment_link_data.sdk_url),
);
context.insert("locale_template", &locale_template);
context.insert("rendered_css", &rendered_css);
context.insert("rendered_js", &rendered_js);
context.insert("logging_template", &logging_template);
Ok((tera, context))
}
<file_sep path="hyperswitch/crates/router/src/services/api.rs" role="context" start="1997" end="1997">
use common_utils::{
consts::{DEFAULT_TENANT, TENANT_HEADER, X_HS_LATENCY},
errors::{ErrorSwitch, ReportSwitchExt},
request::RequestContent,
};
pub use hyperswitch_domain_models::{
api::{
ApplicationResponse, GenericExpiredLinkData, GenericLinkFormData, GenericLinkStatusData,
GenericLinks, PaymentLinkAction, PaymentLinkFormData, PaymentLinkStatusData,
RedirectionFormData,
},
payment_method_data::PaymentMethodData,
router_response_types::RedirectForm,
};
use tera::{Context, Error as TeraError, Tera};
use crate::{
configs::Settings,
consts,
core::{
api_locking,
errors::{self, CustomResult},
payments,
},
events::{
api_logs::{ApiEvent, ApiEventMetric, ApiEventsType},
connector_api_logs::ConnectorEvent,
},
headers, logger,
routes::{
app::{AppStateInfo, ReqState, SessionStateInfo},
metrics, AppState, SessionState,
},
services::{
connector_integration_interface::RouterDataConversion,
generic_link_response::build_generic_link_html,
},
types::{self, api, ErrorResponse},
utils,
};
<file_sep path="hyperswitch/crates/router/src/services/api.rs" role="context" start="2084" end="2100">
pub fn build_secure_payment_link_html(
payment_link_data: PaymentLinkFormData,
) -> CustomResult<String, errors::ApiErrorResponse> {
let (tera, mut context) = build_payment_link_template(payment_link_data)
.attach_printable("Failed to build payment link's HTML template")?;
let payment_link_initiator =
include_str!("../core/payment_link/payment_link_initiate/secure_payment_link_initiator.js")
.to_string();
context.insert("payment_link_initiator", &payment_link_initiator);
tera.render("payment_link", &context)
.map_err(|tera_error: TeraError| {
crate::logger::warn!("{tera_error}");
report!(errors::ApiErrorResponse::InternalServerError)
})
.attach_printable("Error while rendering secure payment link's HTML template")
}
<file_sep path="hyperswitch/crates/router/src/services/api.rs" role="context" start="2066" end="2082">
pub fn build_payment_link_html(
payment_link_data: PaymentLinkFormData,
) -> CustomResult<String, errors::ApiErrorResponse> {
let (tera, mut context) = build_payment_link_template(payment_link_data)
.attach_printable("Failed to build payment link's HTML template")?;
let payment_link_initiator =
include_str!("../core/payment_link/payment_link_initiate/payment_link_initiator.js")
.to_string();
context.insert("payment_link_initiator", &payment_link_initiator);
tera.render("payment_link", &context)
.map_err(|tera_error: TeraError| {
crate::logger::warn!("{tera_error}");
report!(errors::ApiErrorResponse::InternalServerError)
})
.attach_printable("Error while rendering open payment link's HTML template")
}
<file_sep path="hyperswitch/crates/router/src/services/api.rs" role="context" start="1268" end="1270">
fn get_client_secret(&self) -> Option<&String> {
Some(self.client_secret.peek())
}
<file_sep path="hyperswitch/crates/router/src/services/api.rs" role="context" start="2106" end="2112">
fn get_preload_link_html_template(sdk_url: &str) -> String {
format!(
r#"<link rel="preload" href="https://fonts.googleapis.com/css2?family=Montserrat:wght@400;500;600;700;800" as="style">
<link rel="preload" href="{sdk_url}" as="script">"#,
sdk_url = sdk_url
)
}
<file_sep path="hyperswitch/crates/router/src/services/api.rs" role="context" start="2102" end="2104">
fn get_hyper_loader_sdk(sdk_url: &str) -> String {
format!("<script src=\"{sdk_url}\" onload=\"initializeSDK()\"></script>")
}
<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/authentication/transformers.rs<|crate|> router anchor=construct_router_data kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/authentication/transformers.rs" role="context" start="143" end="210">
pub fn construct_router_data<F: Clone, Req, Res>(
state: &SessionState,
authentication_connector_name: String,
payment_method: PaymentMethod,
merchant_id: common_utils::id_type::MerchantId,
address: types::PaymentAddress,
request_data: Req,
merchant_connector_account: &payments_helpers::MerchantConnectorAccountType,
psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>,
payment_id: common_utils::id_type::PaymentId,
) -> RouterResult<types::RouterData<F, Req, Res>> {
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)?;
Ok(types::RouterData {
flow: PhantomData,
merchant_id,
customer_id: None,
tenant_id: state.tenant.tenant_id.clone(),
connector_customer: None,
connector: authentication_connector_name,
payment_id: payment_id.get_string_repr().to_owned(),
attempt_id: IRRELEVANT_ATTEMPT_ID_IN_AUTHENTICATION_FLOW.to_owned(),
status: common_enums::AttemptStatus::default(),
payment_method,
connector_auth_type: auth_type,
description: None,
address,
auth_type: common_enums::AuthenticationType::NoThreeDs,
connector_meta_data: merchant_connector_account.get_metadata(),
connector_wallets_details: merchant_connector_account.get_connector_wallets_details(),
amount_captured: None,
minor_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: request_data,
response: Err(types::ErrorResponse::default()),
connector_request_reference_id:
IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_AUTHENTICATION_FLOW.to_owned(),
#[cfg(feature = "payouts")]
payout_method_data: None,
#[cfg(feature = "payouts")]
quote_id: None,
test_mode,
connector_http_status_code: None,
external_latency: None,
apple_pay_flow: None,
frm_metadata: None,
dispute_id: None,
refund_id: None,
payment_method_status: 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,
})
}
<file_sep path="hyperswitch/crates/router/src/core/authentication/transformers.rs" role="context" start="142" end="142">
use std::marker::PhantomData;
use common_enums::PaymentMethod;
use common_utils::ext_traits::ValueExt;
use crate::{
core::{
errors::{self, RouterResult},
payments::helpers as payments_helpers,
},
types::{
self, domain, storage,
transformers::{ForeignFrom, ForeignTryFrom},
},
utils::ext_traits::OptionExt,
SessionState,
};
<file_sep path="hyperswitch/crates/router/src/core/authentication/transformers.rs" role="context" start="213" end="224">
fn foreign_from(trans_status: common_enums::TransactionStatus) -> Self {
match trans_status {
common_enums::TransactionStatus::Success => Self::Success,
common_enums::TransactionStatus::Failure
| common_enums::TransactionStatus::Rejected
| common_enums::TransactionStatus::VerificationNotPerformed
| common_enums::TransactionStatus::NotVerified => Self::Failed,
common_enums::TransactionStatus::ChallengeRequired
| common_enums::TransactionStatus::ChallengeRequiredDecoupledAuthentication
| common_enums::TransactionStatus::InformationOnly => Self::Pending,
}
}
<file_sep path="hyperswitch/crates/router/src/core/authentication/transformers.rs" role="context" start="114" end="140">
pub fn construct_pre_authentication_router_data<F: Clone>(
state: &SessionState,
authentication_connector: String,
card: hyperswitch_domain_models::payment_method_data::Card,
merchant_connector_account: &payments_helpers::MerchantConnectorAccountType,
merchant_id: common_utils::id_type::MerchantId,
payment_id: common_utils::id_type::PaymentId,
) -> RouterResult<
types::RouterData<
F,
types::authentication::PreAuthNRequestData,
types::authentication::AuthenticationResponseData,
>,
> {
let router_request = types::authentication::PreAuthNRequestData { card };
construct_router_data(
state,
authentication_connector,
PaymentMethod::default(),
merchant_id,
types::PaymentAddress::default(),
router_request,
merchant_connector_account,
None,
payment_id,
)
}
<file_sep path="hyperswitch/crates/router/src/core/authentication/transformers.rs" role="context" start="85" end="112">
pub fn construct_post_authentication_router_data(
state: &SessionState,
authentication_connector: String,
business_profile: domain::Profile,
merchant_connector_account: payments_helpers::MerchantConnectorAccountType,
authentication_data: &storage::Authentication,
payment_id: &common_utils::id_type::PaymentId,
) -> RouterResult<types::authentication::ConnectorPostAuthenticationRouterData> {
let threeds_server_transaction_id = authentication_data
.threeds_server_transaction_id
.clone()
.get_required_value("threeds_server_transaction_id")
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let router_request = types::authentication::ConnectorPostAuthenticationRequestData {
threeds_server_transaction_id,
};
construct_router_data(
state,
authentication_connector,
PaymentMethod::default(),
business_profile.merchant_id.clone(),
types::PaymentAddress::default(),
router_request,
&merchant_connector_account,
None,
payment_id.clone(),
)
}
<file_sep path="hyperswitch/crates/router/src/core/authentication/transformers.rs" role="context" start="27" end="83">
pub fn construct_authentication_router_data(
state: &SessionState,
merchant_id: common_utils::id_type::MerchantId,
authentication_connector: String,
payment_method_data: domain::PaymentMethodData,
payment_method: PaymentMethod,
billing_address: hyperswitch_domain_models::address::Address,
shipping_address: Option<hyperswitch_domain_models::address::Address>,
browser_details: Option<types::BrowserInformation>,
amount: Option<common_utils::types::MinorUnit>,
currency: Option<common_enums::Currency>,
message_category: types::api::authentication::MessageCategory,
device_channel: payments::DeviceChannel,
merchant_connector_account: payments_helpers::MerchantConnectorAccountType,
authentication_data: storage::Authentication,
return_url: Option<String>,
sdk_information: Option<payments::SdkInformation>,
threeds_method_comp_ind: payments::ThreeDsCompletionIndicator,
email: Option<common_utils::pii::Email>,
webhook_url: String,
three_ds_requestor_url: String,
psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>,
payment_id: common_utils::id_type::PaymentId,
force_3ds_challenge: bool,
) -> RouterResult<types::authentication::ConnectorAuthenticationRouterData> {
let router_request = types::authentication::ConnectorAuthenticationRequestData {
payment_method_data,
billing_address,
shipping_address,
browser_details,
amount: amount.map(|amt| amt.get_amount_as_i64()),
currency,
message_category,
device_channel,
pre_authentication_data: super::types::PreAuthenticationData::foreign_try_from(
&authentication_data,
)?,
return_url,
sdk_information,
email,
three_ds_requestor_url,
threeds_method_comp_ind,
webhook_url,
force_3ds_challenge,
};
construct_router_data(
state,
authentication_connector,
payment_method,
merchant_id.clone(),
types::PaymentAddress::default(),
router_request,
&merchant_connector_account,
psd2_sca_exemption_type,
payment_id,
)
}
<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/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=is_shipping_address_required_to_be_collected_form_wallet 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="756" end="784">
fn is_shipping_address_required_to_be_collected_form_wallet(
state: &routes::SessionState,
connector: &api::ConnectorData,
business_profile: &domain::Profile,
payment_method_type: enums::PaymentMethodType,
) -> bool {
let always_collect_shipping_details_from_wallet_connector = business_profile
.always_collect_shipping_details_from_wallet_connector
.unwrap_or(false);
if always_collect_shipping_details_from_wallet_connector {
always_collect_shipping_details_from_wallet_connector
} else if business_profile
.collect_shipping_details_from_wallet_connector
.unwrap_or(false)
{
let shipping_variants = enums::FieldType::get_shipping_variants();
is_dynamic_fields_required(
&state.conf.required_fields,
enums::PaymentMethod::Wallet,
payment_method_type,
connector.connector_name,
shipping_variants,
)
} else {
false
}
}
<file_sep path="hyperswitch/crates/router/src/core/payments/flows/session_flow.rs" role="context" start="755" end="755">
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="798" end="813">
fn get_session_request_for_manual_apple_pay(
session_token_data: payment_types::SessionTokenInfo,
merchant_domain: Option<String>,
) -> RouterResult<payment_types::ApplepaySessionRequest> {
let initiative_context = merchant_domain
.or_else(|| session_token_data.initiative_context.clone())
.get_required_value("apple pay domain")
.attach_printable("Failed to get domain for apple pay session call")?;
Ok(payment_types::ApplepaySessionRequest {
merchant_identifier: session_token_data.merchant_identifier.clone(),
display_name: session_token_data.display_name.clone(),
initiative: session_token_data.initiative.to_string(),
initiative_context,
})
}
<file_sep path="hyperswitch/crates/router/src/core/payments/flows/session_flow.rs" role="context" start="786" end="796">
fn get_session_request_for_simplified_apple_pay(
apple_pay_merchant_identifier: String,
session_token_data: payment_types::SessionTokenForSimplifiedApplePay,
) -> payment_types::ApplepaySessionRequest {
payment_types::ApplepaySessionRequest {
merchant_identifier: apple_pay_merchant_identifier,
display_name: "Apple pay".to_string(),
initiative: "web".to_string(),
initiative_context: session_token_data.initiative_context,
}
}
<file_sep path="hyperswitch/crates/router/src/core/payments/flows/session_flow.rs" role="context" start="716" end="744">
fn is_billing_address_required_to_be_collected_from_wallet(
state: &routes::SessionState,
connector: &api::ConnectorData,
business_profile: &domain::Profile,
payment_method_type: enums::PaymentMethodType,
) -> bool {
let always_collect_billing_details_from_wallet_connector = business_profile
.always_collect_billing_details_from_wallet_connector
.unwrap_or(false);
if always_collect_billing_details_from_wallet_connector {
always_collect_billing_details_from_wallet_connector
} else if business_profile
.collect_billing_details_from_wallet_connector
.unwrap_or(false)
{
let billing_variants = enums::FieldType::get_billing_variants();
is_dynamic_fields_required(
&state.conf.required_fields,
enums::PaymentMethod::Wallet,
payment_method_type,
connector.connector_name,
billing_variants,
)
} else {
false
}
}
<file_sep path="hyperswitch/crates/router/src/core/payments/flows/session_flow.rs" role="context" start="612" end="704">
fn create_samsung_pay_session_token(
state: &routes::SessionState,
router_data: &types::PaymentsSessionRouterData,
header_payload: hyperswitch_domain_models::payments::HeaderPayload,
connector: &api::ConnectorData,
business_profile: &domain::Profile,
) -> RouterResult<types::PaymentsSessionRouterData> {
let samsung_pay_session_token_data = router_data
.connector_wallets_details
.clone()
.parse_value::<payment_types::SamsungPaySessionTokenData>("SamsungPaySessionTokenData")
.change_context(errors::ConnectorError::NoConnectorWalletDetails)
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "connector_wallets_details".to_string(),
expected_format: "samsung_pay_metadata_format".to_string(),
})?;
let required_amount_type = StringMajorUnitForConnector;
let samsung_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 Samsung Pay".to_string(),
})?;
let merchant_domain = match header_payload.x_client_platform {
Some(common_enums::ClientPlatform::Web) => Some(
header_payload
.x_merchant_domain
.get_required_value("samsung pay domain")
.attach_printable("Failed to get domain for samsung pay session call")?,
),
_ => None,
};
let samsung_pay_wallet_details = match samsung_pay_session_token_data.data {
payment_types::SamsungPayCombinedMetadata::MerchantCredentials(
samsung_pay_merchant_credentials,
) => samsung_pay_merchant_credentials,
payment_types::SamsungPayCombinedMetadata::ApplicationCredentials(
_samsung_pay_application_credentials,
) => Err(errors::ApiErrorResponse::NotSupported {
message: "Samsung Pay decryption flow with application credentials is not implemented"
.to_owned(),
})?,
};
let formatted_payment_id = router_data.payment_id.replace("_", "-");
let billing_address_required = is_billing_address_required_to_be_collected_from_wallet(
state,
connector,
business_profile,
enums::PaymentMethodType::SamsungPay,
);
let shipping_address_required = is_shipping_address_required_to_be_collected_form_wallet(
state,
connector,
business_profile,
enums::PaymentMethodType::SamsungPay,
);
Ok(types::PaymentsSessionRouterData {
response: Ok(types::PaymentsResponseData::SessionResponse {
session_token: payment_types::SessionToken::SamsungPay(Box::new(
payment_types::SamsungPaySessionTokenResponse {
version: "2".to_string(),
service_id: samsung_pay_wallet_details.service_id,
order_number: formatted_payment_id,
merchant_payment_information:
payment_types::SamsungPayMerchantPaymentInformation {
name: samsung_pay_wallet_details.merchant_display_name,
url: merchant_domain,
country_code: samsung_pay_wallet_details.merchant_business_country,
},
amount: payment_types::SamsungPayAmountDetails {
amount_format: payment_types::SamsungPayAmountFormat::FormatTotalPriceOnly,
currency_code: router_data.request.currency,
total_amount: samsung_pay_amount,
},
protocol: payment_types::SamsungPayProtocolType::Protocol3ds,
allowed_brands: samsung_pay_wallet_details.allowed_brands,
billing_address_required,
shipping_address_required,
},
)),
}),
..router_data.clone()
})
}
<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="195" end="227">
fn is_dynamic_fields_required(
required_fields: &settings::RequiredFields,
payment_method: enums::PaymentMethod,
payment_method_type: enums::PaymentMethodType,
connector: types::Connector,
required_field_type: Vec<enums::FieldType>,
) -> bool {
required_fields
.0
.get(&payment_method)
.and_then(|pm_type| pm_type.0.get(&payment_method_type))
.and_then(|required_fields_for_connector| {
required_fields_for_connector.fields.get(&connector)
})
.map(|required_fields_final| {
required_fields_final
.non_mandate
.iter()
.flatten()
.any(|field_info| required_field_type.contains(&field_info.field_type))
|| required_fields_final
.mandate
.iter()
.flatten()
.any(|field_info| required_field_type.contains(&field_info.field_type))
|| required_fields_final
.common
.iter()
.flatten()
.any(|field_info| required_field_type.contains(&field_info.field_type))
})
.unwrap_or(false)
}
<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/payouts.rs" role="context" start="364" end="367">
pub enum Wallet {
Paypal(Paypal),
Venmo(Venmo),
}
<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/flows/session_flow.rs<|crate|> router anchor=is_billing_address_required_to_be_collected_from_wallet 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="716" end="744">
fn is_billing_address_required_to_be_collected_from_wallet(
state: &routes::SessionState,
connector: &api::ConnectorData,
business_profile: &domain::Profile,
payment_method_type: enums::PaymentMethodType,
) -> bool {
let always_collect_billing_details_from_wallet_connector = business_profile
.always_collect_billing_details_from_wallet_connector
.unwrap_or(false);
if always_collect_billing_details_from_wallet_connector {
always_collect_billing_details_from_wallet_connector
} else if business_profile
.collect_billing_details_from_wallet_connector
.unwrap_or(false)
{
let billing_variants = enums::FieldType::get_billing_variants();
is_dynamic_fields_required(
&state.conf.required_fields,
enums::PaymentMethod::Wallet,
payment_method_type,
connector.connector_name,
billing_variants,
)
} else {
false
}
}
<file_sep path="hyperswitch/crates/router/src/core/payments/flows/session_flow.rs" role="context" start="715" end="715">
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="786" end="796">
fn get_session_request_for_simplified_apple_pay(
apple_pay_merchant_identifier: String,
session_token_data: payment_types::SessionTokenForSimplifiedApplePay,
) -> payment_types::ApplepaySessionRequest {
payment_types::ApplepaySessionRequest {
merchant_identifier: apple_pay_merchant_identifier,
display_name: "Apple pay".to_string(),
initiative: "web".to_string(),
initiative_context: session_token_data.initiative_context,
}
}
<file_sep path="hyperswitch/crates/router/src/core/payments/flows/session_flow.rs" role="context" start="756" end="784">
fn is_shipping_address_required_to_be_collected_form_wallet(
state: &routes::SessionState,
connector: &api::ConnectorData,
business_profile: &domain::Profile,
payment_method_type: enums::PaymentMethodType,
) -> bool {
let always_collect_shipping_details_from_wallet_connector = business_profile
.always_collect_shipping_details_from_wallet_connector
.unwrap_or(false);
if always_collect_shipping_details_from_wallet_connector {
always_collect_shipping_details_from_wallet_connector
} else if business_profile
.collect_shipping_details_from_wallet_connector
.unwrap_or(false)
{
let shipping_variants = enums::FieldType::get_shipping_variants();
is_dynamic_fields_required(
&state.conf.required_fields,
enums::PaymentMethod::Wallet,
payment_method_type,
connector.connector_name,
shipping_variants,
)
} else {
false
}
}
<file_sep path="hyperswitch/crates/router/src/core/payments/flows/session_flow.rs" role="context" start="612" end="704">
fn create_samsung_pay_session_token(
state: &routes::SessionState,
router_data: &types::PaymentsSessionRouterData,
header_payload: hyperswitch_domain_models::payments::HeaderPayload,
connector: &api::ConnectorData,
business_profile: &domain::Profile,
) -> RouterResult<types::PaymentsSessionRouterData> {
let samsung_pay_session_token_data = router_data
.connector_wallets_details
.clone()
.parse_value::<payment_types::SamsungPaySessionTokenData>("SamsungPaySessionTokenData")
.change_context(errors::ConnectorError::NoConnectorWalletDetails)
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "connector_wallets_details".to_string(),
expected_format: "samsung_pay_metadata_format".to_string(),
})?;
let required_amount_type = StringMajorUnitForConnector;
let samsung_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 Samsung Pay".to_string(),
})?;
let merchant_domain = match header_payload.x_client_platform {
Some(common_enums::ClientPlatform::Web) => Some(
header_payload
.x_merchant_domain
.get_required_value("samsung pay domain")
.attach_printable("Failed to get domain for samsung pay session call")?,
),
_ => None,
};
let samsung_pay_wallet_details = match samsung_pay_session_token_data.data {
payment_types::SamsungPayCombinedMetadata::MerchantCredentials(
samsung_pay_merchant_credentials,
) => samsung_pay_merchant_credentials,
payment_types::SamsungPayCombinedMetadata::ApplicationCredentials(
_samsung_pay_application_credentials,
) => Err(errors::ApiErrorResponse::NotSupported {
message: "Samsung Pay decryption flow with application credentials is not implemented"
.to_owned(),
})?,
};
let formatted_payment_id = router_data.payment_id.replace("_", "-");
let billing_address_required = is_billing_address_required_to_be_collected_from_wallet(
state,
connector,
business_profile,
enums::PaymentMethodType::SamsungPay,
);
let shipping_address_required = is_shipping_address_required_to_be_collected_form_wallet(
state,
connector,
business_profile,
enums::PaymentMethodType::SamsungPay,
);
Ok(types::PaymentsSessionRouterData {
response: Ok(types::PaymentsResponseData::SessionResponse {
session_token: payment_types::SessionToken::SamsungPay(Box::new(
payment_types::SamsungPaySessionTokenResponse {
version: "2".to_string(),
service_id: samsung_pay_wallet_details.service_id,
order_number: formatted_payment_id,
merchant_payment_information:
payment_types::SamsungPayMerchantPaymentInformation {
name: samsung_pay_wallet_details.merchant_display_name,
url: merchant_domain,
country_code: samsung_pay_wallet_details.merchant_business_country,
},
amount: payment_types::SamsungPayAmountDetails {
amount_format: payment_types::SamsungPayAmountFormat::FormatTotalPriceOnly,
currency_code: router_data.request.currency,
total_amount: samsung_pay_amount,
},
protocol: payment_types::SamsungPayProtocolType::Protocol3ds,
allowed_brands: samsung_pay_wallet_details.allowed_brands,
billing_address_required,
shipping_address_required,
},
)),
}),
..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/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="195" end="227">
fn is_dynamic_fields_required(
required_fields: &settings::RequiredFields,
payment_method: enums::PaymentMethod,
payment_method_type: enums::PaymentMethodType,
connector: types::Connector,
required_field_type: Vec<enums::FieldType>,
) -> bool {
required_fields
.0
.get(&payment_method)
.and_then(|pm_type| pm_type.0.get(&payment_method_type))
.and_then(|required_fields_for_connector| {
required_fields_for_connector.fields.get(&connector)
})
.map(|required_fields_final| {
required_fields_final
.non_mandate
.iter()
.flatten()
.any(|field_info| required_field_type.contains(&field_info.field_type))
|| required_fields_final
.mandate
.iter()
.flatten()
.any(|field_info| required_field_type.contains(&field_info.field_type))
|| required_fields_final
.common
.iter()
.flatten()
.any(|field_info| required_field_type.contains(&field_info.field_type))
})
.unwrap_or(false)
}
<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/payouts.rs" role="context" start="364" end="367">
pub enum Wallet {
Paypal(Paypal),
Venmo(Venmo),
}
| symbol_neighborhood |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.