text stringlengths 70 351k | source stringclasses 4 values |
|---|---|
<|meta_start|><|file|> hyperswitch/crates/router/src/core/user/dashboard_metadata.rs<|crate|> router anchor=set_metadata kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/user/dashboard_metadata.rs" role="context" start="27" end="39">
pub async fn set_metadata(
state: SessionState,
user: UserFromToken,
request: api::SetMetaDataRequest,
_req_state: ReqState,
) -> UserResponse<()> {
let metadata_value = parse_set_request(request)?;
let metadata_key = DBEnum::from(&metadata_value);
insert_metadata(&state, user, metadata_key, metadata_value).await?;
Ok(ApplicationResponse::StatusOk)
}
<file_sep path="hyperswitch/crates/router/src/core/user/dashboard_metadata.rs" role="context" start="26" end="26">
use api_models::user::dashboard_metadata::{self as api, GetMultipleMetaDataPayload};
use diesel_models::{
enums::DashboardMetadata as DBEnum, user::dashboard_metadata::DashboardMetadata,
};
use crate::{
core::errors::{UserErrors, UserResponse, UserResult},
routes::{app::ReqState, SessionState},
services::{authentication::UserFromToken, ApplicationResponse},
types::domain::{self, user::dashboard_metadata as types, MerchantKeyStore},
utils::user::dashboard_metadata as utils,
};
use crate::{services::email::types as email_types, utils::user::theme as theme_utils};
<file_sep path="hyperswitch/crates/router/src/core/user/dashboard_metadata.rs" role="context" start="67" end="126">
fn parse_set_request(data_enum: api::SetMetaDataRequest) -> UserResult<types::MetaData> {
match data_enum {
api::SetMetaDataRequest::ProductionAgreement(req) => {
let ip_address = req
.ip_address
.ok_or(report!(UserErrors::InternalServerError))
.attach_printable("Error Getting Ip Address")?;
Ok(types::MetaData::ProductionAgreement(
types::ProductionAgreementValue {
version: req.version,
ip_address,
timestamp: common_utils::date_time::now(),
},
))
}
api::SetMetaDataRequest::SetupProcessor(req) => Ok(types::MetaData::SetupProcessor(req)),
api::SetMetaDataRequest::ConfigureEndpoint => Ok(types::MetaData::ConfigureEndpoint(true)),
api::SetMetaDataRequest::SetupComplete => Ok(types::MetaData::SetupComplete(true)),
api::SetMetaDataRequest::FirstProcessorConnected(req) => {
Ok(types::MetaData::FirstProcessorConnected(req))
}
api::SetMetaDataRequest::SecondProcessorConnected(req) => {
Ok(types::MetaData::SecondProcessorConnected(req))
}
api::SetMetaDataRequest::ConfiguredRouting(req) => {
Ok(types::MetaData::ConfiguredRouting(req))
}
api::SetMetaDataRequest::TestPayment(req) => Ok(types::MetaData::TestPayment(req)),
api::SetMetaDataRequest::IntegrationMethod(req) => {
Ok(types::MetaData::IntegrationMethod(req))
}
api::SetMetaDataRequest::ConfigurationType(req) => {
Ok(types::MetaData::ConfigurationType(req))
}
api::SetMetaDataRequest::IntegrationCompleted => {
Ok(types::MetaData::IntegrationCompleted(true))
}
api::SetMetaDataRequest::SPRoutingConfigured(req) => {
Ok(types::MetaData::SPRoutingConfigured(req))
}
api::SetMetaDataRequest::Feedback(req) => Ok(types::MetaData::Feedback(req)),
api::SetMetaDataRequest::ProdIntent(req) => Ok(types::MetaData::ProdIntent(req)),
api::SetMetaDataRequest::SPTestPayment => Ok(types::MetaData::SPTestPayment(true)),
api::SetMetaDataRequest::DownloadWoocom => Ok(types::MetaData::DownloadWoocom(true)),
api::SetMetaDataRequest::ConfigureWoocom => Ok(types::MetaData::ConfigureWoocom(true)),
api::SetMetaDataRequest::SetupWoocomWebhook => {
Ok(types::MetaData::SetupWoocomWebhook(true))
}
api::SetMetaDataRequest::IsMultipleConfiguration => {
Ok(types::MetaData::IsMultipleConfiguration(true))
}
api::SetMetaDataRequest::IsChangePasswordRequired => {
Ok(types::MetaData::IsChangePasswordRequired(true))
}
api::SetMetaDataRequest::OnboardingSurvey(req) => {
Ok(types::MetaData::OnboardingSurvey(req))
}
api::SetMetaDataRequest::ReconStatus(req) => Ok(types::MetaData::ReconStatus(req)),
}
}
<file_sep path="hyperswitch/crates/router/src/core/user/dashboard_metadata.rs" role="context" start="41" end="65">
pub async fn get_multiple_metadata(
state: SessionState,
user: UserFromToken,
request: GetMultipleMetaDataPayload,
_req_state: ReqState,
) -> UserResponse<Vec<api::GetMetaDataResponse>> {
let metadata_keys: Vec<DBEnum> = request.results.into_iter().map(parse_get_request).collect();
let metadata = fetch_metadata(&state, &user, metadata_keys.clone()).await?;
let mut response = Vec::with_capacity(metadata_keys.len());
for key in metadata_keys {
let data = metadata.iter().find(|ele| ele.data_key == key);
let resp;
if data.is_none() && utils::is_backfill_required(key) {
let backfill_data = backfill_metadata(&state, &user, &key).await?;
resp = into_response(backfill_data.as_ref(), key)?;
} else {
resp = into_response(data, key)?;
}
response.push(resp);
}
Ok(ApplicationResponse::Json(response))
}
<file_sep path="hyperswitch/crates/router/src/core/user/dashboard_metadata.rs" role="context" start="244" end="626">
async fn insert_metadata(
state: &SessionState,
user: UserFromToken,
metadata_key: DBEnum,
metadata_value: types::MetaData,
) -> UserResult<DashboardMetadata> {
match metadata_value {
types::MetaData::ProductionAgreement(data) => {
utils::insert_merchant_scoped_metadata_to_db(
state,
user.user_id,
user.merchant_id,
user.org_id,
metadata_key,
data,
)
.await
}
types::MetaData::SetupProcessor(data) => {
utils::insert_merchant_scoped_metadata_to_db(
state,
user.user_id,
user.merchant_id,
user.org_id,
metadata_key,
data,
)
.await
}
types::MetaData::ConfigureEndpoint(data) => {
utils::insert_merchant_scoped_metadata_to_db(
state,
user.user_id,
user.merchant_id,
user.org_id,
metadata_key,
data,
)
.await
}
types::MetaData::SetupComplete(data) => {
utils::insert_merchant_scoped_metadata_to_db(
state,
user.user_id,
user.merchant_id,
user.org_id,
metadata_key,
data,
)
.await
}
types::MetaData::FirstProcessorConnected(data) => {
utils::insert_merchant_scoped_metadata_to_db(
state,
user.user_id,
user.merchant_id,
user.org_id,
metadata_key,
data,
)
.await
}
types::MetaData::SecondProcessorConnected(data) => {
utils::insert_merchant_scoped_metadata_to_db(
state,
user.user_id,
user.merchant_id,
user.org_id,
metadata_key,
data,
)
.await
}
types::MetaData::ConfiguredRouting(data) => {
utils::insert_merchant_scoped_metadata_to_db(
state,
user.user_id,
user.merchant_id,
user.org_id,
metadata_key,
data,
)
.await
}
types::MetaData::TestPayment(data) => {
utils::insert_merchant_scoped_metadata_to_db(
state,
user.user_id,
user.merchant_id,
user.org_id,
metadata_key,
data,
)
.await
}
types::MetaData::IntegrationMethod(data) => {
let mut metadata = utils::insert_merchant_scoped_metadata_to_db(
state,
user.user_id.clone(),
user.merchant_id.clone(),
user.org_id.clone(),
metadata_key,
data.clone(),
)
.await;
if utils::is_update_required(&metadata) {
metadata = utils::update_merchant_scoped_metadata(
state,
user.user_id,
user.merchant_id,
user.org_id,
metadata_key,
data,
)
.await
.change_context(UserErrors::InternalServerError);
}
metadata
}
types::MetaData::ConfigurationType(data) => {
let mut metadata = utils::insert_merchant_scoped_metadata_to_db(
state,
user.user_id.clone(),
user.merchant_id.clone(),
user.org_id.clone(),
metadata_key,
data.clone(),
)
.await;
if utils::is_update_required(&metadata) {
metadata = utils::update_merchant_scoped_metadata(
state,
user.user_id,
user.merchant_id,
user.org_id,
metadata_key,
data,
)
.await
.change_context(UserErrors::InternalServerError);
}
metadata
}
types::MetaData::IntegrationCompleted(data) => {
utils::insert_merchant_scoped_metadata_to_db(
state,
user.user_id,
user.merchant_id,
user.org_id,
metadata_key,
data,
)
.await
}
types::MetaData::StripeConnected(data) => {
utils::insert_merchant_scoped_metadata_to_db(
state,
user.user_id,
user.merchant_id,
user.org_id,
metadata_key,
data,
)
.await
}
types::MetaData::PaypalConnected(data) => {
utils::insert_merchant_scoped_metadata_to_db(
state,
user.user_id,
user.merchant_id,
user.org_id,
metadata_key,
data,
)
.await
}
types::MetaData::SPRoutingConfigured(data) => {
utils::insert_merchant_scoped_metadata_to_db(
state,
user.user_id,
user.merchant_id,
user.org_id,
metadata_key,
data,
)
.await
}
types::MetaData::Feedback(data) => {
let mut metadata = utils::insert_user_scoped_metadata_to_db(
state,
user.user_id.clone(),
user.merchant_id.clone(),
user.org_id.clone(),
metadata_key,
data.clone(),
)
.await;
if utils::is_update_required(&metadata) {
metadata = utils::update_user_scoped_metadata(
state,
user.user_id,
user.merchant_id,
user.org_id,
metadata_key,
data,
)
.await
.change_context(UserErrors::InternalServerError);
}
metadata
}
types::MetaData::ProdIntent(data) => {
if let Some(poc_email) = &data.poc_email {
let inner_poc_email = poc_email.peek().as_str();
pii::Email::from_str(inner_poc_email)
.change_context(UserErrors::EmailParsingError)?;
}
let mut metadata = utils::insert_merchant_scoped_metadata_to_db(
state,
user.user_id.clone(),
user.merchant_id.clone(),
user.org_id.clone(),
metadata_key,
data.clone(),
)
.await;
if utils::is_update_required(&metadata) {
metadata = utils::update_merchant_scoped_metadata(
state,
user.user_id.clone(),
user.merchant_id.clone(),
user.org_id.clone(),
metadata_key,
data.clone(),
)
.await
.change_context(UserErrors::InternalServerError);
}
#[cfg(feature = "email")]
{
let user_data = user.get_user_from_db(state).await?;
let user_email = domain::UserEmail::from_pii_email(user_data.get_email())
.change_context(UserErrors::InternalServerError)?
.get_secret()
.expose();
if utils::is_prod_email_required(&data, user_email) {
let theme = theme_utils::get_most_specific_theme_using_token_and_min_entity(
state,
&user,
EntityType::Merchant,
)
.await?;
let email_contents = email_types::BizEmailProd::new(
state,
data,
theme.as_ref().map(|theme| theme.theme_id.clone()),
theme
.map(|theme| theme.email_config())
.unwrap_or(state.conf.theme.email_config.clone()),
)?;
let send_email_result = state
.email_client
.compose_and_send_email(
email_types::get_base_url(state),
Box::new(email_contents),
state.conf.proxy.https_url.as_ref(),
)
.await;
logger::info!(prod_intent_email=?send_email_result);
}
}
metadata
}
types::MetaData::SPTestPayment(data) => {
utils::insert_merchant_scoped_metadata_to_db(
state,
user.user_id,
user.merchant_id,
user.org_id,
metadata_key,
data,
)
.await
}
types::MetaData::DownloadWoocom(data) => {
utils::insert_merchant_scoped_metadata_to_db(
state,
user.user_id,
user.merchant_id,
user.org_id,
metadata_key,
data,
)
.await
}
types::MetaData::ConfigureWoocom(data) => {
utils::insert_merchant_scoped_metadata_to_db(
state,
user.user_id,
user.merchant_id,
user.org_id,
metadata_key,
data,
)
.await
}
types::MetaData::SetupWoocomWebhook(data) => {
utils::insert_merchant_scoped_metadata_to_db(
state,
user.user_id,
user.merchant_id,
user.org_id,
metadata_key,
data,
)
.await
}
types::MetaData::IsMultipleConfiguration(data) => {
utils::insert_merchant_scoped_metadata_to_db(
state,
user.user_id,
user.merchant_id,
user.org_id,
metadata_key,
data,
)
.await
}
types::MetaData::IsChangePasswordRequired(data) => {
utils::insert_user_scoped_metadata_to_db(
state,
user.user_id,
user.merchant_id,
user.org_id,
metadata_key,
data,
)
.await
}
types::MetaData::OnboardingSurvey(data) => {
utils::insert_merchant_scoped_metadata_to_db(
state,
user.user_id,
user.merchant_id,
user.org_id,
metadata_key,
data,
)
.await
}
types::MetaData::ReconStatus(data) => {
let mut metadata = utils::insert_merchant_scoped_metadata_to_db(
state,
user.user_id.clone(),
user.merchant_id.clone(),
user.org_id.clone(),
metadata_key,
data.clone(),
)
.await;
if utils::is_update_required(&metadata) {
metadata = utils::update_merchant_scoped_metadata(
state,
user.user_id,
user.merchant_id,
user.org_id,
metadata_key,
data,
)
.await;
}
metadata
}
}
}
<file_sep path="hyperswitch/crates/router/src/routes/app.rs" role="context" start="99" end="101">
pub struct ReqState {
pub event_context: events::EventContext<crate::events::EventType, EventsHandler>,
}
<file_sep path="hyperswitch/crates/api_models/src/user/dashboard_metadata.rs" role="context" start="7" end="31">
pub enum SetMetaDataRequest {
ProductionAgreement(ProductionAgreementRequest),
SetupProcessor(SetupProcessor),
ConfigureEndpoint,
SetupComplete,
FirstProcessorConnected(ProcessorConnected),
SecondProcessorConnected(ProcessorConnected),
ConfiguredRouting(ConfiguredRouting),
TestPayment(TestPayment),
IntegrationMethod(IntegrationMethod),
ConfigurationType(ConfigurationType),
IntegrationCompleted,
SPRoutingConfigured(ConfiguredRouting),
Feedback(Feedback),
ProdIntent(ProdIntent),
SPTestPayment,
DownloadWoocom,
ConfigureWoocom,
SetupWoocomWebhook,
IsMultipleConfiguration,
#[serde(skip)]
IsChangePasswordRequired,
OnboardingSurvey(OnboardingSurvey),
ReconStatus(ReconStatus),
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/refunds.rs<|crate|> router anchor=refund_to_refund_core_workflow_model 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="1593" end="1603">
pub fn refund_to_refund_core_workflow_model(
refund: &storage::Refund,
) -> storage::RefundCoreWorkflow {
storage::RefundCoreWorkflow {
refund_internal_reference_id: refund.internal_reference_id.clone(),
connector_transaction_id: refund.connector_transaction_id.clone(),
merchant_id: refund.merchant_id.clone(),
payment_id: refund.payment_id.clone(),
processor_transaction_data: refund.processor_transaction_data.clone(),
}
}
<file_sep path="hyperswitch/crates/router/src/core/refunds.rs" role="context" start="1592" end="1592">
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="1645" end="1679">
pub async fn add_refund_execute_task(
db: &dyn db::StorageInterface,
refund: &storage::Refund,
runner: storage::ProcessTrackerRunner,
) -> RouterResult<storage::ProcessTracker> {
let task = "EXECUTE_REFUND";
let process_tracker_id = format!("{runner}_{task}_{}", refund.internal_reference_id);
let tag = ["REFUND"];
let schedule_time = common_utils::date_time::now();
let refund_workflow_tracking_data = refund_to_refund_core_workflow_model(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 execute 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
)
})?;
Ok(response)
}
<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="1472" end="1590">
pub async fn trigger_refund_execute_workflow(
state: &SessionState,
refund_tracker: &storage::ProcessTracker,
) -> Result<(), errors::ProcessTrackerError> {
let db = &*state.store;
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_manager_state = &state.into();
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 = db
.find_merchant_account_by_merchant_id(
key_manager_state,
&refund_core.merchant_id,
&key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
let refund = db
.find_refund_by_internal_reference_id_merchant_id(
&refund_core.refund_internal_reference_id,
&refund_core.merchant_id,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?;
match (&refund.sent_to_gateway, &refund.refund_status) {
(false, enums::RefundStatus::Pending) => {
let merchant_account = db
.find_merchant_account_by_merchant_id(
key_manager_state,
&refund.merchant_id,
&key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
let payment_attempt = db
.find_payment_attempt_by_connector_transaction_id_payment_id_merchant_id(
&refund.connector_transaction_id,
&refund_core.payment_id,
&refund.merchant_id,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
let payment_intent = db
.find_payment_intent_by_payment_id_merchant_id(
&(state.into()),
&payment_attempt.payment_id,
&refund.merchant_id,
&key_store,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
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: refund.split_refunds.clone(),
})?;
//trigger refund request to gateway
let updated_refund = Box::pin(trigger_refund_to_gateway(
state,
&refund,
&merchant_account,
&key_store,
&payment_attempt,
&payment_intent,
None,
split_refunds,
))
.await?;
add_refund_sync_task(
db,
&updated_refund,
storage::ProcessTrackerRunner::RefundWorkflowRouter,
)
.await?;
}
(true, enums::RefundStatus::Pending) => {
// create sync task
add_refund_sync_task(
db,
&refund,
storage::ProcessTrackerRunner::RefundWorkflowRouter,
)
.await?;
}
(_, _) => {
//mark task as finished
db.as_scheduler()
.finish_process_with_business_status(
refund_tracker.clone(),
business_status::COMPLETED_BY_PT,
)
.await?;
}
};
Ok(())
}
<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/configs/settings.rs" role="context" start="721" end="724">
pub struct Refund {
pub max_attempts: usize,
pub max_age: i64,
}
<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/payments/conditional_configs.rs<|crate|> router anchor=execute_dsl_and_get_conditional_config kind=fn pack=symbol_neighborhood lang=rust role_window=k2 hops=1<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/payments/conditional_configs.rs" role="context" start="80" end="89">
pub fn execute_dsl_and_get_conditional_config(
backend_input: dsl_inputs::BackendInput,
interpreter: &backend::VirInterpreterBackend<common_types::payments::ConditionalConfigs>,
) -> ConditionalConfigResult<common_types::payments::ConditionalConfigs> {
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/payments/conditional_configs.rs" role="context" start="79" end="79">
use euclid::backend::{self, inputs as dsl_inputs, EuclidBackend};
use crate::{
core::{errors, errors::ConditionalConfigError as ConfigError, routing as core_routing},
routes,
};
pub type ConditionalConfigResult<O> = errors::CustomResult<O, ConfigError>;
<file_sep path="hyperswitch/crates/router/src/core/payments/conditional_configs.rs" role="context" start="64" end="78">
pub fn perform_decision_management(
record: common_types::payments::DecisionManagerRecord,
payment_data: &core_routing::PaymentsDslInput<'_>,
) -> RouterResult<common_types::payments::ConditionalConfigs> {
let interpreter = backend::VirInterpreterBackend::with_program(record.program)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error initializing DSL interpreter backend")?;
let backend_input = make_dsl_input(payment_data)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error constructing DSL input")?;
execute_dsl_and_get_conditional_config(backend_input, &interpreter)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error executing DSL")
}
<file_sep path="hyperswitch/crates/router/src/core/payments/conditional_configs.rs" role="context" start="19" end="61">
pub async fn perform_decision_management(
state: &routes::SessionState,
algorithm_ref: routing::RoutingAlgorithmRef,
merchant_id: &common_utils::id_type::MerchantId,
payment_data: &core_routing::PaymentsDslInput<'_>,
) -> ConditionalConfigResult<common_types::payments::ConditionalConfigs> {
let algorithm_id = if let Some(id) = algorithm_ref.config_algo_id {
id
} else {
return Ok(common_types::payments::ConditionalConfigs::default());
};
let db = &*state.store;
let key = merchant_id.get_dsl_config();
let find_key_from_db = || async {
let config = db.find_config_by_key(&algorithm_id).await?;
let rec: DecisionManagerRecord = config
.config
.parse_struct("Program")
.change_context(errors::StorageError::DeserializationFailed)
.attach_printable("Error parsing routing algorithm from configs")?;
backend::VirInterpreterBackend::with_program(rec.program)
.change_context(errors::StorageError::ValueNotFound("Program".to_string()))
.attach_printable("Error initializing DSL interpreter backend")
};
let interpreter = cache::get_or_populate_in_memory(
db.get_cache_store().as_ref(),
&key,
find_key_from_db,
&DECISION_MANAGER_CACHE,
)
.await
.change_context(ConfigError::DslCachePoisoned)?;
let backend_input =
make_dsl_input(payment_data).change_context(ConfigError::InputConstructionError)?;
execute_dsl_and_get_conditional_config(backend_input, &interpreter)
}
<file_sep path="hyperswitch/crates/router/src/core/payments/conditional_configs.rs" role="context" start="15" end="15">
pub type ConditionalConfigResult<O> = errors::CustomResult<O, ConfigError>;
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payment_methods/migration.rs<|crate|> router anchor=parse_csv kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/migration.rs" role="context" start="74" end="85">
fn parse_csv(data: &[u8]) -> csv::Result<Vec<PaymentMethodRecord>> {
let mut csv_reader = Reader::from_reader(data);
let mut records = Vec::new();
let mut id_counter = 0;
for result in csv_reader.deserialize() {
let mut record: PaymentMethodRecord = result?;
id_counter += 1;
record.line_number = Some(id_counter);
records.push(record);
}
Ok(records)
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/migration.rs" role="context" start="73" end="73">
use api_models::payment_methods::{PaymentMethodMigrationResponse, PaymentMethodRecord};
use csv::Reader;
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/migration.rs" role="context" start="109" end="135">
pub fn validate_card_expiry(
card_exp_month: &masking::Secret<String>,
card_exp_year: &masking::Secret<String>,
) -> errors::CustomResult<(), errors::ApiErrorResponse> {
let exp_month = card_exp_month
.peek()
.to_string()
.parse::<u8>()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "card_exp_month",
})?;
::cards::CardExpirationMonth::try_from(exp_month).change_context(
errors::ApiErrorResponse::PreconditionFailed {
message: "Invalid Expiry Month".to_string(),
},
)?;
let year_str = card_exp_year.peek().to_string();
validate_card_exp_year(year_str).change_context(
errors::ApiErrorResponse::PreconditionFailed {
message: "Invalid Expiry Year".to_string(),
},
)?;
Ok(())
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/migration.rs" role="context" start="86" end="106">
pub fn get_payment_method_records(
form: PaymentMethodsMigrateForm,
) -> Result<
(
common_utils::id_type::MerchantId,
Vec<PaymentMethodRecord>,
Option<common_utils::id_type::MerchantConnectorAccountId>,
),
errors::ApiErrorResponse,
> {
match parse_csv(form.file.data.to_bytes()) {
Ok(records) => {
let merchant_id = form.merchant_id.clone();
let mca_id = form.merchant_connector_id.clone();
Ok((merchant_id.clone(), records, mca_id))
}
Err(e) => Err(errors::ApiErrorResponse::PreconditionFailed {
message: e.to_string(),
}),
}
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/migration.rs" role="context" start="15" end="62">
pub async fn migrate_payment_methods(
state: routes::SessionState,
payment_methods: Vec<PaymentMethodRecord>,
merchant_id: &common_utils::id_type::MerchantId,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
mca_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
) -> errors::RouterResponse<Vec<PaymentMethodMigrationResponse>> {
let mut result = Vec::new();
for record in payment_methods {
let req = api::PaymentMethodMigrate::try_from((
record.clone(),
merchant_id.clone(),
mca_id.clone(),
))
.map_err(|err| errors::ApiErrorResponse::InvalidRequestData {
message: format!("error: {:?}", err),
})
.attach_printable("record deserialization failed");
match req {
Ok(_) => (),
Err(e) => {
result.push(PaymentMethodMigrationResponse::from((
Err(e.to_string()),
record,
)));
continue;
}
};
let res = migrate_payment_method(
state.clone(),
req?,
merchant_id,
merchant_account,
key_store,
)
.await;
result.push(PaymentMethodMigrationResponse::from((
match res {
Ok(services::api::ApplicationResponse::Json(response)) => Ok(response),
Err(e) => Err(e.to_string()),
_ => Err("Failed to migrate payment method".to_string()),
},
record,
)));
}
Ok(services::api::ApplicationResponse::Json(result))
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/migration.rs" role="context" start="170" end="177">
pub fn new() -> Self {
Self {
card_migrated: None,
network_token_migrated: None,
connector_mandate_details_migrated: None,
network_transaction_migrated: None,
}
}
<file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="2370" end="2404">
pub struct PaymentMethodRecord {
pub customer_id: id_type::CustomerId,
pub name: Option<masking::Secret<String>>,
pub email: Option<pii::Email>,
pub phone: Option<masking::Secret<String>>,
pub phone_country_code: Option<String>,
pub merchant_id: Option<id_type::MerchantId>,
pub payment_method: Option<api_enums::PaymentMethod>,
pub payment_method_type: Option<api_enums::PaymentMethodType>,
pub nick_name: masking::Secret<String>,
pub payment_instrument_id: Option<masking::Secret<String>>,
pub card_number_masked: masking::Secret<String>,
pub card_expiry_month: masking::Secret<String>,
pub card_expiry_year: masking::Secret<String>,
pub card_scheme: Option<String>,
pub original_transaction_id: Option<String>,
pub billing_address_zip: masking::Secret<String>,
pub billing_address_state: masking::Secret<String>,
pub billing_address_first_name: masking::Secret<String>,
pub billing_address_last_name: masking::Secret<String>,
pub billing_address_city: String,
pub billing_address_country: Option<api_enums::CountryAlpha2>,
pub billing_address_line1: masking::Secret<String>,
pub billing_address_line2: Option<masking::Secret<String>>,
pub billing_address_line3: Option<masking::Secret<String>>,
pub raw_card_number: Option<masking::Secret<String>>,
pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
pub original_transaction_amount: Option<i64>,
pub original_transaction_currency: Option<common_enums::Currency>,
pub line_number: Option<i64>,
pub network_token_number: Option<CardNumber>,
pub network_token_expiry_month: Option<masking::Secret<String>>,
pub network_token_expiry_year: Option<masking::Secret<String>>,
pub network_token_requestor_ref_id: Option<String>,
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payments.rs<|crate|> router anchor=decide_apple_pay_flow kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="4787" end="4798">
fn decide_apple_pay_flow(
state: &SessionState,
payment_method_type: Option<enums::PaymentMethodType>,
merchant_connector_account: Option<&helpers::MerchantConnectorAccountType>,
) -> Option<domain::ApplePayFlow> {
payment_method_type.and_then(|pmt| match pmt {
enums::PaymentMethodType::ApplePay => {
check_apple_pay_metadata(state, merchant_connector_account)
}
_ => None,
})
}
<file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="4786" end="4786">
use api_models::{
self, enums,
mandates::RecurringDetails,
payments::{self as payments_api},
};
pub use common_enums::enums::CallConnectorAction;
use helpers::{decrypt_paze_token, ApplePayData};
use crate::core::routing::helpers as routing_helpers;
use crate::{
configs::settings::{ApplePayPreDecryptFlow, PaymentMethodTypeTokenFilter},
connector::utils::missing_field_err,
consts,
core::{
errors::{self, CustomResult, RouterResponse, RouterResult},
payment_methods::{cards, network_tokenization},
payouts,
routing::{self as core_routing},
utils::{self as core_utils},
},
db::StorageInterface,
logger,
routes::{app::ReqState, metrics, payment_methods::ParentPaymentMethodToken, SessionState},
services::{self, api::Authenticate, ConnectorRedirectResponse},
types::{
self as router_types,
api::{self, ConnectorCallType, ConnectorCommon},
domain,
storage::{self, enums as storage_enums, payment_attempt::PaymentAttemptExt},
transformers::ForeignTryInto,
},
utils::{
self, add_apple_pay_flow_metrics, add_connector_http_status_code_metrics, Encode,
OptionExt, ValueExt,
},
workflows::payment_sync,
};
<file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="4880" end="4939">
fn get_google_pay_connector_wallet_details(
state: &SessionState,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
) -> Option<GooglePayPaymentProcessingDetails> {
let google_pay_root_signing_keys = state
.conf
.google_pay_decrypt_keys
.as_ref()
.map(|google_pay_keys| google_pay_keys.google_pay_root_signing_keys.clone());
match merchant_connector_account.get_connector_wallets_details() {
Some(wallet_details) => {
let google_pay_wallet_details = wallet_details
.parse_value::<api_models::payments::GooglePayWalletDetails>(
"GooglePayWalletDetails",
)
.map_err(|error| {
logger::warn!(?error, "Failed to Parse Value to GooglePayWalletDetails")
});
google_pay_wallet_details
.ok()
.and_then(
|google_pay_wallet_details| {
match google_pay_wallet_details
.google_pay
.provider_details {
api_models::payments::GooglePayProviderDetails::GooglePayMerchantDetails(merchant_details) => {
match (
merchant_details
.merchant_info
.tokenization_specification
.parameters
.private_key,
google_pay_root_signing_keys,
merchant_details
.merchant_info
.tokenization_specification
.parameters
.recipient_id,
) {
(Some(google_pay_private_key), Some(google_pay_root_signing_keys), Some(google_pay_recipient_id)) => {
Some(GooglePayPaymentProcessingDetails {
google_pay_private_key,
google_pay_root_signing_keys,
google_pay_recipient_id
})
}
_ => {
logger::warn!("One or more of the following fields are missing in GooglePayMerchantDetails: google_pay_private_key, google_pay_root_signing_keys, google_pay_recipient_id");
None
}
}
}
}
}
)
}
None => None,
}
}
<file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="4800" end="4878">
fn check_apple_pay_metadata(
state: &SessionState,
merchant_connector_account: Option<&helpers::MerchantConnectorAccountType>,
) -> Option<domain::ApplePayFlow> {
merchant_connector_account.and_then(|mca| {
let metadata = mca.get_metadata();
metadata.and_then(|apple_pay_metadata| {
let parsed_metadata = apple_pay_metadata
.clone()
.parse_value::<api_models::payments::ApplepayCombinedSessionTokenData>(
"ApplepayCombinedSessionTokenData",
)
.map(|combined_metadata| {
api_models::payments::ApplepaySessionTokenMetadata::ApplePayCombined(
combined_metadata.apple_pay_combined,
)
})
.or_else(|_| {
apple_pay_metadata
.parse_value::<api_models::payments::ApplepaySessionTokenData>(
"ApplepaySessionTokenData",
)
.map(|old_metadata| {
api_models::payments::ApplepaySessionTokenMetadata::ApplePay(
old_metadata.apple_pay,
)
})
})
.map_err(|error| {
logger::warn!(?error, "Failed to Parse Value to ApplepaySessionTokenData")
});
parsed_metadata.ok().map(|metadata| match metadata {
api_models::payments::ApplepaySessionTokenMetadata::ApplePayCombined(
apple_pay_combined,
) => match apple_pay_combined {
api_models::payments::ApplePayCombinedMetadata::Simplified { .. } => {
domain::ApplePayFlow::Simplified(payments_api::PaymentProcessingDetails {
payment_processing_certificate: state
.conf
.applepay_decrypt_keys
.get_inner()
.apple_pay_ppc
.clone(),
payment_processing_certificate_key: state
.conf
.applepay_decrypt_keys
.get_inner()
.apple_pay_ppc_key
.clone(),
})
}
api_models::payments::ApplePayCombinedMetadata::Manual {
payment_request_data: _,
session_token_data,
} => {
if let Some(manual_payment_processing_details_at) =
session_token_data.payment_processing_details_at
{
match manual_payment_processing_details_at {
payments_api::PaymentProcessingDetailsAt::Hyperswitch(
payment_processing_details,
) => domain::ApplePayFlow::Simplified(payment_processing_details),
payments_api::PaymentProcessingDetailsAt::Connector => {
domain::ApplePayFlow::Manual
}
}
} else {
domain::ApplePayFlow::Manual
}
}
},
api_models::payments::ApplepaySessionTokenMetadata::ApplePay(_) => {
domain::ApplePayFlow::Manual
}
})
})
})
}
<file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="4770" end="4785">
fn is_apple_pay_pre_decrypt_type_connector_tokenization(
payment_method_type: Option<storage::enums::PaymentMethodType>,
apple_pay_flow: &Option<domain::ApplePayFlow>,
apple_pay_pre_decrypt_flow_filter: Option<ApplePayPreDecryptFlow>,
) -> bool {
match (payment_method_type, apple_pay_flow) {
(
Some(storage::enums::PaymentMethodType::ApplePay),
Some(domain::ApplePayFlow::Simplified(_)),
) => !matches!(
apple_pay_pre_decrypt_flow_filter,
Some(ApplePayPreDecryptFlow::NetworkTokenization)
),
_ => true,
}
}
<file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="4742" end="4768">
fn is_payment_method_tokenization_enabled_for_connector(
state: &SessionState,
connector_name: &str,
payment_method: storage::enums::PaymentMethod,
payment_method_type: Option<storage::enums::PaymentMethodType>,
apple_pay_flow: &Option<domain::ApplePayFlow>,
) -> RouterResult<bool> {
let connector_tokenization_filter = state.conf.tokenization.0.get(connector_name);
Ok(connector_tokenization_filter
.map(|connector_filter| {
connector_filter
.payment_method
.clone()
.contains(&payment_method)
&& is_payment_method_type_allowed_for_connector(
payment_method_type,
connector_filter.payment_method_type.clone(),
)
&& is_apple_pay_pre_decrypt_type_connector_tokenization(
payment_method_type,
apple_pay_flow,
connector_filter.apple_pay_pre_decrypt_flow.clone(),
)
})
.unwrap_or(false))
}
<file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="5102" end="5244">
pub async fn get_connector_tokenization_action_when_confirm_true<F, Req, D>(
state: &SessionState,
operation: &BoxedOperation<'_, F, Req, D>,
payment_data: &mut D,
validate_result: &operations::ValidateResult,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
merchant_key_store: &domain::MerchantKeyStore,
customer: &Option<domain::Customer>,
business_profile: &domain::Profile,
should_retry_with_pan: bool,
) -> RouterResult<(D, TokenizationAction)>
where
F: Send + Clone,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
{
let connector = payment_data.get_payment_attempt().connector.to_owned();
let is_mandate = payment_data
.get_mandate_id()
.as_ref()
.and_then(|inner| inner.mandate_reference_id.as_ref())
.map(|mandate_reference| match mandate_reference {
api_models::payments::MandateReferenceId::ConnectorMandateId(_) => true,
api_models::payments::MandateReferenceId::NetworkMandateId(_)
| api_models::payments::MandateReferenceId::NetworkTokenWithNTI(_) => false,
})
.unwrap_or(false);
let payment_data_and_tokenization_action = match connector {
Some(_) if is_mandate => (
payment_data.to_owned(),
TokenizationAction::SkipConnectorTokenization,
),
Some(connector) if is_operation_confirm(&operation) => {
let payment_method = payment_data
.get_payment_attempt()
.payment_method
.get_required_value("payment_method")?;
let payment_method_type = payment_data.get_payment_attempt().payment_method_type;
let apple_pay_flow =
decide_apple_pay_flow(state, payment_method_type, Some(merchant_connector_account));
let is_connector_tokenization_enabled =
is_payment_method_tokenization_enabled_for_connector(
state,
&connector,
payment_method,
payment_method_type,
&apple_pay_flow,
)?;
add_apple_pay_flow_metrics(
&apple_pay_flow,
payment_data.get_payment_attempt().connector.clone(),
payment_data.get_payment_attempt().merchant_id.clone(),
);
let payment_method_action = decide_payment_method_tokenize_action(
state,
&connector,
payment_method,
payment_data.get_token(),
is_connector_tokenization_enabled,
apple_pay_flow,
payment_method_type,
merchant_connector_account,
)
.await?;
let connector_tokenization_action = match payment_method_action {
TokenizationAction::TokenizeInRouter => {
let (_operation, payment_method_data, pm_id) = operation
.to_domain()?
.make_pm_data(
state,
payment_data,
validate_result.storage_scheme,
merchant_key_store,
customer,
business_profile,
should_retry_with_pan,
)
.await?;
payment_data.set_payment_method_data(payment_method_data);
payment_data.set_payment_method_id_in_attempt(pm_id);
TokenizationAction::SkipConnectorTokenization
}
TokenizationAction::TokenizeInConnector => TokenizationAction::TokenizeInConnector,
TokenizationAction::TokenizeInConnectorAndRouter => {
let (_operation, payment_method_data, pm_id) = operation
.to_domain()?
.make_pm_data(
state,
payment_data,
validate_result.storage_scheme,
merchant_key_store,
customer,
business_profile,
should_retry_with_pan,
)
.await?;
payment_data.set_payment_method_data(payment_method_data);
payment_data.set_payment_method_id_in_attempt(pm_id);
TokenizationAction::TokenizeInConnector
}
TokenizationAction::ConnectorToken(token) => {
payment_data.set_pm_token(token);
TokenizationAction::SkipConnectorTokenization
}
TokenizationAction::SkipConnectorTokenization => {
TokenizationAction::SkipConnectorTokenization
}
TokenizationAction::DecryptApplePayToken(payment_processing_details) => {
TokenizationAction::DecryptApplePayToken(payment_processing_details)
}
TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt(
payment_processing_details,
) => TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt(
payment_processing_details,
),
TokenizationAction::DecryptPazeToken(paze_payment_processing_details) => {
TokenizationAction::DecryptPazeToken(paze_payment_processing_details)
}
TokenizationAction::DecryptGooglePayToken(
google_pay_payment_processing_details,
) => {
TokenizationAction::DecryptGooglePayToken(google_pay_payment_processing_details)
}
};
(payment_data.to_owned(), connector_tokenization_action)
}
_ => (
payment_data.to_owned(),
TokenizationAction::SkipConnectorTokenization,
),
};
Ok(payment_data_and_tokenization_action)
}
<file_sep path="hyperswitch/crates/router/src/connector/utils.rs" role="context" start="1750" end="1752">
pub trait ApplePay {
fn get_applepay_decoded_payment_data(&self) -> Result<Secret<String>, Error>;
}
<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/retry.rs<|crate|> router anchor=get_retries kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/payments/retry.rs" role="context" start="250" end="262">
pub async fn get_retries(
state: &app::SessionState,
retries: Option<i32>,
merchant_id: &common_utils::id_type::MerchantId,
profile: &domain::Profile,
) -> Option<i32> {
match retries {
Some(retries) => Some(retries),
None => get_merchant_max_auto_retries_enabled(state.store.as_ref(), merchant_id)
.await
.or(profile.max_auto_retries_enabled.map(i32::from)),
}
}
<file_sep path="hyperswitch/crates/router/src/core/payments/retry.rs" role="context" start="249" end="249">
use common_utils::{ext_traits::Encode, types::MinorUnit};
use crate::{
core::{
errors::{self, RouterResult, StorageErrorExt},
payments::{
self,
flows::{ConstructFlowSpecificData, Feature},
operations,
},
},
db::StorageInterface,
routes::{
self,
app::{self, ReqState},
metrics,
},
services,
types::{self, api, domain, storage},
};
<file_sep path="hyperswitch/crates/router/src/core/payments/retry.rs" role="context" start="281" end="300">
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_RETRY_GSM_MATCH_COUNT.add(1, &[]);
}
option_gsm_decision.unwrap_or_default()
}
<file_sep path="hyperswitch/crates/router/src/core/payments/retry.rs" role="context" start="265" end="278">
pub async fn get_gsm<F, FData>(
state: &app::SessionState,
router_data: &types::RouterData<F, FData, types::PaymentsResponseData>,
) -> RouterResult<Option<storage::gsm::GatewayStatusMap>> {
let error_response = router_data.response.as_ref().err();
let error_code = error_response.map(|err| err.code.to_owned());
let error_message = error_response.map(|err| err.message.to_owned());
let connector_name = router_data.connector.to_string();
let flow = get_flow_name::<F>()?;
Ok(
payments::helpers::get_gsm_record(state, error_code, error_message, connector_name, flow)
.await,
)
}
<file_sep path="hyperswitch/crates/router/src/core/payments/retry.rs" role="context" start="225" end="246">
pub async fn get_merchant_max_auto_retries_enabled(
db: &dyn StorageInterface,
merchant_id: &common_utils::id_type::MerchantId,
) -> Option<i32> {
let key = merchant_id.get_max_auto_retries_enabled();
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/payments/retry.rs" role="context" start="201" end="222">
pub async fn is_step_up_enabled_for_merchant_connector(
state: &app::SessionState,
merchant_id: &common_utils::id_type::MerchantId,
connector_name: types::Connector,
) -> bool {
let key = merchant_id.get_step_up_enabled_key();
let db = &*state.store;
db.find_config_by_key_unwrap_or(key.as_str(), Some("[]".to_string()))
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.and_then(|step_up_config| {
serde_json::from_str::<Vec<types::Connector>>(&step_up_config.config)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Step-up config parsing failed")
})
.map_err(|err| {
logger::error!(step_up_config_error=?err);
})
.ok()
.map(|connectors_enabled| connectors_enabled.contains(&connector_name))
.unwrap_or(false)
}
<file_sep path="hyperswitch/crates/router/src/core/payments/retry.rs" role="context" start="33" end="198">
pub async fn do_gsm_actions<F, ApiRequest, FData, D>(
state: &app::SessionState,
req_state: ReqState,
payment_data: &mut D,
mut connectors: IntoIter<api::ConnectorData>,
original_connector_data: &api::ConnectorData,
mut router_data: types::RouterData<F, FData, types::PaymentsResponseData>,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
operation: &operations::BoxedOperation<'_, F, ApiRequest, D>,
customer: &Option<domain::Customer>,
validate_result: &operations::ValidateResult,
schedule_time: Option<time::PrimitiveDateTime>,
frm_suggestion: Option<storage_enums::FrmSuggestion>,
business_profile: &domain::Profile,
) -> RouterResult<types::RouterData<F, FData, types::PaymentsResponseData>>
where
F: Clone + Send + Sync,
FData: Send + Sync,
payments::PaymentResponse: operations::Operation<F, FData>,
D: payments::OperationSessionGetters<F>
+ payments::OperationSessionSetters<F>
+ Send
+ Sync
+ Clone,
D: ConstructFlowSpecificData<F, FData, types::PaymentsResponseData>,
types::RouterData<F, FData, types::PaymentsResponseData>: Feature<F, FData>,
dyn api::Connector: services::api::ConnectorIntegration<F, FData, types::PaymentsResponseData>,
{
let mut retries = None;
metrics::AUTO_RETRY_ELIGIBLE_REQUEST_COUNT.add(1, &[]);
let mut initial_gsm = get_gsm(state, &router_data).await?;
//Check if step-up to threeDS is possible and merchant has enabled
let step_up_possible = initial_gsm
.clone()
.map(|gsm| gsm.step_up_possible)
.unwrap_or(false);
#[cfg(feature = "v1")]
let is_no_three_ds_payment = matches!(
payment_data.get_payment_attempt().authentication_type,
Some(storage_enums::AuthenticationType::NoThreeDs)
);
#[cfg(feature = "v2")]
let is_no_three_ds_payment = matches!(
payment_data.get_payment_attempt().authentication_type,
storage_enums::AuthenticationType::NoThreeDs
);
let should_step_up = if step_up_possible && is_no_three_ds_payment {
is_step_up_enabled_for_merchant_connector(
state,
merchant_account.get_id(),
original_connector_data.connector_name,
)
.await
} else {
false
};
if should_step_up {
router_data = do_retry(
&state.clone(),
req_state.clone(),
original_connector_data,
operation,
customer,
merchant_account,
key_store,
payment_data,
router_data,
validate_result,
schedule_time,
true,
frm_suggestion,
business_profile,
false, //should_retry_with_pan is not applicable for step-up
)
.await?;
}
// Step up is not applicable so proceed with auto retries flow
else {
loop {
// Use initial_gsm for first time alone
let gsm = match initial_gsm.as_ref() {
Some(gsm) => Some(gsm.clone()),
None => get_gsm(state, &router_data).await?,
};
match get_gsm_decision(gsm) {
api_models::gsm::GsmDecision::Retry => {
retries =
get_retries(state, retries, merchant_account.get_id(), business_profile)
.await;
if retries.is_none() || retries == Some(0) {
metrics::AUTO_RETRY_EXHAUSTED_COUNT.add(1, &[]);
logger::info!("retries exhausted for auto_retry payment");
break;
}
if connectors.len() == 0 {
logger::info!("connectors exhausted for auto_retry payment");
metrics::AUTO_RETRY_EXHAUSTED_COUNT.add(1, &[]);
break;
}
let is_network_token = payment_data
.get_payment_method_data()
.map(|pmd| pmd.is_network_token_payment_method_data())
.unwrap_or(false);
let should_retry_with_pan = is_network_token
&& initial_gsm
.as_ref()
.map(|gsm| gsm.clear_pan_possible)
.unwrap_or(false)
&& business_profile.is_clear_pan_retries_enabled;
let connector = if should_retry_with_pan {
// If should_retry_with_pan is true, it indicates that we are retrying with PAN using the same connector.
original_connector_data.clone()
} else {
super::get_connector_data(&mut connectors)?
};
router_data = do_retry(
&state.clone(),
req_state.clone(),
&connector,
operation,
customer,
merchant_account,
key_store,
payment_data,
router_data,
validate_result,
schedule_time,
//this is an auto retry payment, but not step-up
false,
frm_suggestion,
business_profile,
should_retry_with_pan,
)
.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,
}
initial_gsm = None;
}
}
Ok(router_data)
}
<file_sep path="hyperswitch/crates/router/src/routes/app.rs" role="context" start="1906" end="1906">
pub struct Profile;
<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/cards_info.rs<|crate|> router anchor=parse_cards_bin_csv kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/cards_info.rs" role="context" start="111" end="124">
fn parse_cards_bin_csv(
data: &[u8],
) -> csv::Result<Vec<cards_info_api_types::CardInfoUpdateRequest>> {
let mut csv_reader = Reader::from_reader(data);
let mut records = Vec::new();
let mut id_counter = 0;
for result in csv_reader.deserialize() {
let mut record: cards_info_api_types::CardInfoUpdateRequest = result?;
id_counter += 1;
record.line_number = Some(id_counter);
records.push(record);
}
Ok(records)
}
<file_sep path="hyperswitch/crates/router/src/core/cards_info.rs" role="context" start="110" end="110">
use api_models::cards_info as cards_info_api_types;
use csv::Reader;
<file_sep path="hyperswitch/crates/router/src/core/cards_info.rs" role="context" start="138" end="155">
pub async fn migrate_cards_info(
state: routes::SessionState,
card_info_records: Vec<cards_info_api_types::CardInfoUpdateRequest>,
) -> RouterResponse<Vec<cards_info_api_types::CardInfoMigrationResponse>> {
let mut result = Vec::new();
for record in card_info_records {
let res = card_info_flow(record.clone(), state.clone()).await;
result.push(cards_info_api_types::CardInfoMigrationResponse::from((
match res {
Ok(ApplicationResponse::Json(response)) => Ok(response),
Err(e) => Err(e.to_string()),
_ => Err("Failed to migrate card info".to_string()),
},
record,
)));
}
Ok(ApplicationResponse::Json(result))
}
<file_sep path="hyperswitch/crates/router/src/core/cards_info.rs" role="context" start="126" end="135">
pub fn get_cards_bin_records(
form: CardsInfoUpdateForm,
) -> Result<Vec<cards_info_api_types::CardInfoUpdateRequest>, errors::ApiErrorResponse> {
match parse_cards_bin_csv(form.file.data.to_bytes()) {
Ok(records) => Ok(records),
Err(e) => Err(errors::ApiErrorResponse::PreconditionFailed {
message: e.to_string(),
}),
}
}
<file_sep path="hyperswitch/crates/router/src/core/cards_info.rs" role="context" start="76" end="103">
pub async fn update_card_info(
state: routes::SessionState,
card_info_request: cards_info_api_types::CardInfoUpdateRequest,
) -> RouterResponse<cards_info_api_types::CardInfoResponse> {
let db = state.store.as_ref();
CardsInfoInterface::update_card_info(
db,
card_info_request.card_iin,
card_info_models::UpdateCardInfo {
card_issuer: card_info_request.card_issuer,
card_network: card_info_request.card_network,
card_type: card_info_request.card_type,
card_subtype: card_info_request.card_subtype,
card_issuing_country: card_info_request.card_issuing_country,
bank_code_id: card_info_request.bank_code_id,
bank_code: card_info_request.bank_code,
country_code: card_info_request.country_code,
last_updated: Some(common_utils::date_time::now()),
last_updated_provider: card_info_request.last_updated_provider,
},
)
.await
.to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError {
message: "Card info with given key does not exist in our records".to_string(),
})
.attach_printable("Failed while updating card info")
.map(|card_info| ApplicationResponse::Json(card_info.foreign_into()))
}
<file_sep path="hyperswitch/crates/router/src/core/cards_info.rs" role="context" start="62" end="73">
pub async fn create_card_info(
state: routes::SessionState,
card_info_request: cards_info_api_types::CardInfoCreateRequest,
) -> RouterResponse<cards_info_api_types::CardInfoResponse> {
let db = state.store.as_ref();
CardsInfoInterface::add_card_info(db, card_info_request.foreign_into())
.await
.to_duplicate_response(errors::ApiErrorResponse::GenericDuplicateError {
message: "CardInfo with given key already exists in our records".to_string(),
})
.map(|card_info| ApplicationResponse::Json(card_info.foreign_into()))
}
<file_sep path="hyperswitch/crates/router/src/core/cards_info.rs" role="context" start="243" end="248">
fn new() -> Self {
Self {
state: std::marker::PhantomData,
card_info: None,
}
}
<file_sep path="hyperswitch/crates/api_models/src/cards_info.rs" role="context" start="63" end="75">
pub struct CardInfoUpdateRequest {
pub card_iin: String,
pub card_issuer: Option<String>,
pub card_network: Option<enums::CardNetwork>,
pub card_type: Option<String>,
pub card_subtype: Option<String>,
pub card_issuing_country: Option<String>,
pub bank_code_id: Option<String>,
pub bank_code: Option<String>,
pub country_code: Option<String>,
pub last_updated_provider: Option<String>,
pub line_number: Option<i64>,
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/refunds.rs<|crate|> router anchor=start_refund_workflow 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="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="1455" end="1455">
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="1593" end="1603">
pub fn refund_to_refund_core_workflow_model(
refund: &storage::Refund,
) -> storage::RefundCoreWorkflow {
storage::RefundCoreWorkflow {
refund_internal_reference_id: refund.internal_reference_id.clone(),
connector_transaction_id: refund.connector_transaction_id.clone(),
merchant_id: refund.merchant_id.clone(),
payment_id: refund.payment_id.clone(),
processor_transaction_data: refund.processor_transaction_data.clone(),
}
}
<file_sep path="hyperswitch/crates/router/src/core/refunds.rs" role="context" start="1472" end="1590">
pub async fn trigger_refund_execute_workflow(
state: &SessionState,
refund_tracker: &storage::ProcessTracker,
) -> Result<(), errors::ProcessTrackerError> {
let db = &*state.store;
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_manager_state = &state.into();
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 = db
.find_merchant_account_by_merchant_id(
key_manager_state,
&refund_core.merchant_id,
&key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
let refund = db
.find_refund_by_internal_reference_id_merchant_id(
&refund_core.refund_internal_reference_id,
&refund_core.merchant_id,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?;
match (&refund.sent_to_gateway, &refund.refund_status) {
(false, enums::RefundStatus::Pending) => {
let merchant_account = db
.find_merchant_account_by_merchant_id(
key_manager_state,
&refund.merchant_id,
&key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
let payment_attempt = db
.find_payment_attempt_by_connector_transaction_id_payment_id_merchant_id(
&refund.connector_transaction_id,
&refund_core.payment_id,
&refund.merchant_id,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
let payment_intent = db
.find_payment_intent_by_payment_id_merchant_id(
&(state.into()),
&payment_attempt.payment_id,
&refund.merchant_id,
&key_store,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
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: refund.split_refunds.clone(),
})?;
//trigger refund request to gateway
let updated_refund = Box::pin(trigger_refund_to_gateway(
state,
&refund,
&merchant_account,
&key_store,
&payment_attempt,
&payment_intent,
None,
split_refunds,
))
.await?;
add_refund_sync_task(
db,
&updated_refund,
storage::ProcessTrackerRunner::RefundWorkflowRouter,
)
.await?;
}
(true, enums::RefundStatus::Pending) => {
// create sync task
add_refund_sync_task(
db,
&refund,
storage::ProcessTrackerRunner::RefundWorkflowRouter,
)
.await?;
}
(_, _) => {
//mark task as finished
db.as_scheduler()
.finish_process_with_business_status(
refund_tracker.clone(),
business_status::COMPLETED_BY_PT,
)
.await?;
}
};
Ok(())
}
<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="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/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/2022-09-29-084920_create_initial_tables/up.sql" role="context" start="430" end="446">
created_at TIMESTAMP NOT NULL,
last_modified TIMESTAMP NOT NULL,
payment_method "PaymentMethodType" NOT NULL,
payment_method_type "PaymentMethodSubType",
payment_method_issuer VARCHAR(255),
payment_method_issuer_code "PaymentMethodIssuerCode"
);
CREATE TABLE process_tracker (
id VARCHAR(127) PRIMARY KEY,
NAME VARCHAR(255),
tag TEXT [ ] NOT NULL DEFAULT '{}'::TEXT [ ],
runner VARCHAR(255),
retry_count INTEGER NOT NULL,
schedule_time TIMESTAMP,
rule VARCHAR(255) NOT NULL,
tracking_data JSON NOT NULL,
<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/setup_mandate_flow.rs<|crate|> router anchor=add_payment_method_token kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/payments/flows/setup_mandate_flow.rs" role="context" start="169" end="186">
async fn add_payment_method_token<'a>(
&mut self,
state: &SessionState,
connector: &api::ConnectorData,
tokenization_action: &payments::TokenizationAction,
should_continue_payment: bool,
) -> RouterResult<types::PaymentMethodTokenResult> {
let request = self.request.clone();
tokenization::add_payment_method_token(
state,
connector,
tokenization_action,
self,
types::PaymentMethodTokenizationData::try_from(request)?,
should_continue_payment,
)
.await
}
<file_sep path="hyperswitch/crates/router/src/core/payments/flows/setup_mandate_flow.rs" role="context" start="168" end="168">
use crate::{
core::{
errors::{ConnectorErrorExt, RouterResult},
mandate,
payments::{
self, access_token, customers, helpers, tokenization, transformers, PaymentData,
},
},
routes::SessionState,
services,
types::{self, api, domain},
};
<file_sep path="hyperswitch/crates/router/src/core/payments/flows/setup_mandate_flow.rs" role="context" start="202" end="225">
async fn build_flow_specific_connector_request(
&mut self,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
) -> RouterResult<(Option<services::Request>, bool)> {
match call_connector_action {
payments::CallConnectorAction::Trigger => {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::SetupMandate,
types::SetupMandateRequestData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
Ok((
connector_integration
.build_request(self, &state.conf.connectors)
.to_payment_failed_response()?,
true,
))
}
_ => Ok((None, true)),
}
}
<file_sep path="hyperswitch/crates/router/src/core/payments/flows/setup_mandate_flow.rs" role="context" start="188" end="200">
async fn create_connector_customer<'a>(
&self,
state: &SessionState,
connector: &api::ConnectorData,
) -> RouterResult<Option<String>> {
customers::create_connector_customer(
state,
connector,
self,
types::ConnectorCustomerData::try_from(self.request.to_owned())?,
)
.await
}
<file_sep path="hyperswitch/crates/router/src/core/payments/flows/setup_mandate_flow.rs" role="context" start="158" end="167">
async fn add_access_token<'a>(
&self,
state: &SessionState,
connector: &api::ConnectorData,
merchant_account: &domain::MerchantAccount,
creds_identifier: Option<&str>,
) -> RouterResult<types::AddAccessTokenResult> {
access_token::add_access_token(state, connector, merchant_account, self, creds_identifier)
.await
}
<file_sep path="hyperswitch/crates/router/src/core/payments/flows/setup_mandate_flow.rs" role="context" start="117" end="156">
async fn decide_flows<'a>(
mut self,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
connector_request: Option<services::Request>,
_business_profile: &domain::Profile,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<Self> {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::SetupMandate,
types::SetupMandateRequestData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
// Change the authentication_type to ThreeDs, for google_pay wallet if card_holder_authenticated or account_verified in assurance_details is false
if let hyperswitch_domain_models::payment_method_data::PaymentMethodData::Wallet(
hyperswitch_domain_models::payment_method_data::WalletData::GooglePay(google_pay_data),
) = &self.request.payment_method_data
{
if let Some(assurance_details) = google_pay_data.info.assurance_details.as_ref() {
// Step up the transaction to 3DS when either assurance_details.card_holder_authenticated or assurance_details.account_verified is false
if !assurance_details.card_holder_authenticated
|| !assurance_details.account_verified
{
logger::info!("Googlepay transaction stepped up to 3DS");
self.auth_type = diesel_models::enums::AuthenticationType::ThreeDs;
}
}
}
let resp = services::execute_connector_processing_step(
state,
connector_integration,
&self,
call_connector_action.clone(),
connector_request,
)
.await
.to_setup_mandate_failed_response()?;
Ok(resp)
}
<file_sep path="hyperswitch/crates/router/src/core/errors.rs" role="context" start="31" end="31">
pub type RouterResult<T> = CustomResult<T, ApiErrorResponse>;
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payments/flows/authorize_flow.rs<|crate|> router anchor=add_payment_method_token kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/payments/flows/authorize_flow.rs" role="context" start="281" end="298">
async fn add_payment_method_token<'a>(
&mut self,
state: &SessionState,
connector: &api::ConnectorData,
tokenization_action: &payments::TokenizationAction,
should_continue_payment: bool,
) -> RouterResult<types::PaymentMethodTokenResult> {
let request = self.request.clone();
tokenization::add_payment_method_token(
state,
connector,
tokenization_action,
self,
types::PaymentMethodTokenizationData::try_from(request)?,
should_continue_payment,
)
.await
}
<file_sep path="hyperswitch/crates/router/src/core/payments/flows/authorize_flow.rs" role="context" start="280" end="280">
use hyperswitch_domain_models::payments::PaymentConfirmData;
use crate::{
core::{
errors::{ConnectorErrorExt, RouterResult},
mandate,
payments::{
self, access_token, customers, helpers, tokenization, transformers, PaymentData,
},
},
logger,
routes::{metrics, SessionState},
services::{self, api::ConnectorValidation},
types::{
self, api, domain,
transformers::{ForeignFrom, ForeignTryFrom},
},
utils::OptionExt,
};
<file_sep path="hyperswitch/crates/router/src/core/payments/flows/authorize_flow.rs" role="context" start="308" end="314">
async fn postprocessing_steps<'a>(
self,
state: &SessionState,
connector: &api::ConnectorData,
) -> RouterResult<Self> {
authorize_postprocessing_steps(state, &self, true, connector).await
}
<file_sep path="hyperswitch/crates/router/src/core/payments/flows/authorize_flow.rs" role="context" start="300" end="306">
async fn preprocessing_steps<'a>(
self,
state: &SessionState,
connector: &api::ConnectorData,
) -> RouterResult<Self> {
authorize_preprocessing_steps(state, &self, true, connector).await
}
<file_sep path="hyperswitch/crates/router/src/core/payments/flows/authorize_flow.rs" role="context" start="250" end="279">
async fn add_session_token<'a>(
self,
state: &SessionState,
connector: &api::ConnectorData,
) -> RouterResult<Self>
where
Self: Sized,
{
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::AuthorizeSessionToken,
types::AuthorizeSessionTokenData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
let authorize_data = &types::PaymentsAuthorizeSessionTokenRouterData::foreign_from((
&self,
types::AuthorizeSessionTokenData::foreign_from(&self),
));
let resp = services::execute_connector_processing_step(
state,
connector_integration,
authorize_data,
payments::CallConnectorAction::Trigger,
None,
)
.await
.to_payment_failed_response()?;
let mut router_data = self;
router_data.session_token = resp.session_token;
Ok(router_data)
}
<file_sep path="hyperswitch/crates/router/src/core/payments/flows/authorize_flow.rs" role="context" start="239" end="248">
async fn add_access_token<'a>(
&self,
state: &SessionState,
connector: &api::ConnectorData,
merchant_account: &domain::MerchantAccount,
creds_identifier: Option<&str>,
) -> RouterResult<types::AddAccessTokenResult> {
access_token::add_access_token(state, connector, merchant_account, self, creds_identifier)
.await
}
<file_sep path="hyperswitch/crates/router/src/core/errors.rs" role="context" start="31" end="31">
pub type RouterResult<T> = CustomResult<T, ApiErrorResponse>;
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payments/types.rs<|crate|> router anchor=get_surcharge_details_redis_hashset_key kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/payments/types.rs" role="context" start="283" end="299">
pub fn get_surcharge_details_redis_hashset_key(surcharge_key: &SurchargeKey) -> String {
match surcharge_key {
SurchargeKey::Token(token) => {
format!("token_{}", token)
}
SurchargeKey::PaymentMethodData(payment_method, payment_method_type, card_network) => {
if let Some(card_network) = card_network {
format!(
"{}_{}_{}",
payment_method, payment_method_type, card_network
)
} else {
format!("{}_{}", payment_method, payment_method_type)
}
}
}
}
<file_sep path="hyperswitch/crates/router/src/core/payments/types.rs" role="context" start="282" end="282">
pub use hyperswitch_domain_models::router_request_types::{
AuthenticationData, SplitRefundsRequest, StripeSplitRefund, SurchargeDetails,
};
<file_sep path="hyperswitch/crates/router/src/core/payments/types.rs" role="context" start="342" end="366">
pub async fn get_individual_surcharge_detail_from_redis(
state: &SessionState,
surcharge_key: SurchargeKey,
payment_attempt_id: &str,
) -> CustomResult<SurchargeDetails, RedisError> {
let redis_conn = state
.store
.get_redis_conn()
.attach_printable("Failed to get redis connection")?;
let redis_key = Self::get_surcharge_metadata_redis_key(payment_attempt_id);
let value_key = Self::get_surcharge_details_redis_hashset_key(&surcharge_key);
let result = redis_conn
.get_hash_field_and_deserialize(
&redis_key.as_str().into(),
&value_key,
"SurchargeDetails",
)
.await;
logger::debug!(
"Surcharge result fetched from redis with key = {} and {}",
redis_key,
value_key
);
result
}
<file_sep path="hyperswitch/crates/router/src/core/payments/types.rs" role="context" start="301" end="339">
pub async fn persist_individual_surcharge_details_in_redis(
&self,
state: &SessionState,
business_profile: &Profile,
) -> RouterResult<()> {
if !self.is_empty_result() {
let redis_conn = state
.store
.get_redis_conn()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get redis connection")?;
let redis_key = Self::get_surcharge_metadata_redis_key(&self.payment_attempt_id);
let mut value_list = Vec::with_capacity(self.get_surcharge_results_size());
for (key, value) in self.get_individual_surcharge_key_value_pairs().into_iter() {
value_list.push((
key,
value
.encode_to_string_of_json()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to encode to string of json")?,
));
}
let intent_fulfillment_time = business_profile
.get_order_fulfillment_time()
.unwrap_or(router_consts::DEFAULT_FULFILLMENT_TIME);
redis_conn
.set_hash_fields(
&redis_key.as_str().into(),
value_list,
Some(intent_fulfillment_time),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to write to redis")?;
logger::debug!("Surcharge results stored in redis with key = {}", redis_key);
}
Ok(())
}
<file_sep path="hyperswitch/crates/router/src/core/payments/types.rs" role="context" start="274" end="282">
pub fn get_individual_surcharge_key_value_pairs(&self) -> Vec<(String, SurchargeDetails)> {
self.surcharge_results
.iter()
.map(|(surcharge_key, surcharge_details)| {
let key = Self::get_surcharge_details_redis_hashset_key(surcharge_key);
(key, surcharge_details.to_owned())
})
.collect()
}
<file_sep path="hyperswitch/crates/router/src/core/payments/types.rs" role="context" start="271" end="273">
pub fn get_surcharge_metadata_redis_key(payment_attempt_id: &str) -> String {
format!("surcharge_metadata_{}", payment_attempt_id)
}
<file_sep path="hyperswitch/crates/router/src/core/payments/types.rs" role="context" start="232" end="239">
pub enum SurchargeKey {
Token(String),
PaymentMethodData(
common_enums::PaymentMethod,
common_enums::PaymentMethodType,
Option<common_enums::CardNetwork>,
),
}
<file_sep path="hyperswitch/crates/router/src/compatibility/stripe/customers/types.rs" role="context" start="202" end="207">
pub struct PaymentMethodData {
pub id: Option<String>,
pub object: &'static str,
pub card: Option<CardDetails>,
pub created: Option<time::PrimitiveDateTime>,
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payments/types.rs<|crate|> router anchor=get_surcharge_details_redis_hashset_key kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/payments/types.rs" role="context" start="283" end="299">
pub fn get_surcharge_details_redis_hashset_key(surcharge_key: &SurchargeKey) -> String {
match surcharge_key {
SurchargeKey::Token(token) => {
format!("token_{}", token)
}
SurchargeKey::PaymentMethodData(payment_method, payment_method_type, card_network) => {
if let Some(card_network) = card_network {
format!(
"{}_{}_{}",
payment_method, payment_method_type, card_network
)
} else {
format!("{}_{}", payment_method, payment_method_type)
}
}
}
}
<file_sep path="hyperswitch/crates/router/src/core/payments/types.rs" role="context" start="282" end="282">
pub use hyperswitch_domain_models::router_request_types::{
AuthenticationData, SplitRefundsRequest, StripeSplitRefund, SurchargeDetails,
};
<file_sep path="hyperswitch/crates/router/src/core/payments/types.rs" role="context" start="342" end="366">
pub async fn get_individual_surcharge_detail_from_redis(
state: &SessionState,
surcharge_key: SurchargeKey,
payment_attempt_id: &str,
) -> CustomResult<SurchargeDetails, RedisError> {
let redis_conn = state
.store
.get_redis_conn()
.attach_printable("Failed to get redis connection")?;
let redis_key = Self::get_surcharge_metadata_redis_key(payment_attempt_id);
let value_key = Self::get_surcharge_details_redis_hashset_key(&surcharge_key);
let result = redis_conn
.get_hash_field_and_deserialize(
&redis_key.as_str().into(),
&value_key,
"SurchargeDetails",
)
.await;
logger::debug!(
"Surcharge result fetched from redis with key = {} and {}",
redis_key,
value_key
);
result
}
<file_sep path="hyperswitch/crates/router/src/core/payments/types.rs" role="context" start="301" end="339">
pub async fn persist_individual_surcharge_details_in_redis(
&self,
state: &SessionState,
business_profile: &Profile,
) -> RouterResult<()> {
if !self.is_empty_result() {
let redis_conn = state
.store
.get_redis_conn()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get redis connection")?;
let redis_key = Self::get_surcharge_metadata_redis_key(&self.payment_attempt_id);
let mut value_list = Vec::with_capacity(self.get_surcharge_results_size());
for (key, value) in self.get_individual_surcharge_key_value_pairs().into_iter() {
value_list.push((
key,
value
.encode_to_string_of_json()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to encode to string of json")?,
));
}
let intent_fulfillment_time = business_profile
.get_order_fulfillment_time()
.unwrap_or(router_consts::DEFAULT_FULFILLMENT_TIME);
redis_conn
.set_hash_fields(
&redis_key.as_str().into(),
value_list,
Some(intent_fulfillment_time),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to write to redis")?;
logger::debug!("Surcharge results stored in redis with key = {}", redis_key);
}
Ok(())
}
<file_sep path="hyperswitch/crates/router/src/core/payments/types.rs" role="context" start="274" end="282">
pub fn get_individual_surcharge_key_value_pairs(&self) -> Vec<(String, SurchargeDetails)> {
self.surcharge_results
.iter()
.map(|(surcharge_key, surcharge_details)| {
let key = Self::get_surcharge_details_redis_hashset_key(surcharge_key);
(key, surcharge_details.to_owned())
})
.collect()
}
<file_sep path="hyperswitch/crates/router/src/core/payments/types.rs" role="context" start="271" end="273">
pub fn get_surcharge_metadata_redis_key(payment_attempt_id: &str) -> String {
format!("surcharge_metadata_{}", payment_attempt_id)
}
<file_sep path="hyperswitch/crates/router/src/core/payments/types.rs" role="context" start="232" end="239">
pub enum SurchargeKey {
Token(String),
PaymentMethodData(
common_enums::PaymentMethod,
common_enums::PaymentMethodType,
Option<common_enums::CardNetwork>,
),
}
<file_sep path="hyperswitch/crates/router/src/compatibility/stripe/customers/types.rs" role="context" start="202" end="207">
pub struct PaymentMethodData {
pub id: Option<String>,
pub object: &'static str,
pub card: Option<CardDetails>,
pub created: Option<time::PrimitiveDateTime>,
}
<file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="2504" end="2539">
pub enum PaymentMethodData {
#[schema(title = "Card")]
Card(Card),
#[schema(title = "CardRedirect")]
CardRedirect(CardRedirectData),
#[schema(title = "Wallet")]
Wallet(WalletData),
#[schema(title = "PayLater")]
PayLater(PayLaterData),
#[schema(title = "BankRedirect")]
BankRedirect(BankRedirectData),
#[schema(title = "BankDebit")]
BankDebit(BankDebitData),
#[schema(title = "BankTransfer")]
BankTransfer(Box<BankTransferData>),
#[schema(title = "RealTimePayment")]
RealTimePayment(Box<RealTimePaymentData>),
#[schema(title = "Crypto")]
Crypto(CryptoData),
#[schema(title = "MandatePayment")]
MandatePayment,
#[schema(title = "Reward")]
Reward,
#[schema(title = "Upi")]
Upi(UpiData),
#[schema(title = "Voucher")]
Voucher(VoucherData),
#[schema(title = "GiftCard")]
GiftCard(Box<GiftCardData>),
#[schema(title = "CardToken")]
CardToken(CardToken),
#[schema(title = "OpenBanking")]
OpenBanking(OpenBankingData),
#[schema(title = "MobilePayment")]
MobilePayment(MobilePaymentData),
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/webhooks/outgoing.rs<|crate|> router anchor=get_webhook_url_from_business_profile kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/webhooks/outgoing.rs" role="context" start="592" end="606">
fn get_webhook_url_from_business_profile(
business_profile: &domain::Profile,
) -> CustomResult<String, errors::WebhooksFlowError> {
let webhook_details = business_profile
.webhook_details
.clone()
.get_required_value("webhook_details")
.change_context(errors::WebhooksFlowError::MerchantWebhookDetailsNotFound)?;
webhook_details
.webhook_url
.get_required_value("webhook_url")
.change_context(errors::WebhooksFlowError::MerchantWebhookUrlNotConfigured)
.map(ExposeInterface::expose)
}
<file_sep path="hyperswitch/crates/router/src/core/webhooks/outgoing.rs" role="context" start="591" end="591">
use masking::{ExposeInterface, Mask, PeekInterface, Secret};
use crate::{
core::{
errors::{self, CustomResult},
metrics,
},
db::StorageInterface,
events::outgoing_webhook_logs::{
OutgoingWebhookEvent, OutgoingWebhookEventContent, OutgoingWebhookEventMetric,
},
logger,
routes::{app::SessionStateInfo, SessionState},
services,
types::{
api,
domain::{self},
storage::{self, enums},
transformers::ForeignFrom,
},
utils::{OptionExt, ValueExt},
workflows::outgoing_webhook_retry,
};
<file_sep path="hyperswitch/crates/router/src/core/webhooks/outgoing.rs" role="context" start="608" end="675">
pub(crate) fn get_outgoing_webhook_request(
merchant_account: &domain::MerchantAccount,
outgoing_webhook: api::OutgoingWebhook,
business_profile: &domain::Profile,
) -> CustomResult<OutgoingWebhookRequestContent, errors::WebhooksFlowError> {
#[inline]
fn get_outgoing_webhook_request_inner<WebhookType: types::OutgoingWebhookType>(
outgoing_webhook: api::OutgoingWebhook,
business_profile: &domain::Profile,
) -> CustomResult<OutgoingWebhookRequestContent, errors::WebhooksFlowError> {
let mut headers = vec![
(
reqwest::header::CONTENT_TYPE.to_string(),
mime::APPLICATION_JSON.essence_str().into(),
),
(
reqwest::header::USER_AGENT.to_string(),
consts::USER_AGENT.to_string().into(),
),
];
let transformed_outgoing_webhook = WebhookType::from(outgoing_webhook);
let payment_response_hash_key = business_profile.payment_response_hash_key.clone();
let custom_headers = business_profile
.outgoing_webhook_custom_http_headers
.clone()
.map(|headers| {
headers
.into_inner()
.expose()
.parse_value::<HashMap<String, String>>("HashMap<String,String>")
.change_context(errors::WebhooksFlowError::OutgoingWebhookEncodingFailed)
.attach_printable("Failed to deserialize outgoing webhook custom HTTP headers")
})
.transpose()?;
if let Some(ref map) = custom_headers {
headers.extend(
map.iter()
.map(|(key, value)| (key.clone(), value.clone().into_masked())),
);
};
let outgoing_webhooks_signature = transformed_outgoing_webhook
.get_outgoing_webhooks_signature(payment_response_hash_key)?;
if let Some(signature) = outgoing_webhooks_signature.signature {
WebhookType::add_webhook_header(&mut headers, signature)
}
Ok(OutgoingWebhookRequestContent {
body: outgoing_webhooks_signature.payload,
headers: headers
.into_iter()
.map(|(name, value)| (name, Secret::new(value.into_inner())))
.collect(),
})
}
match merchant_account.get_compatible_connector() {
#[cfg(feature = "stripe")]
Some(api_models::enums::Connector::Stripe) => get_outgoing_webhook_request_inner::<
stripe_webhooks::StripeOutgoingWebhook,
>(outgoing_webhook, business_profile),
_ => get_outgoing_webhook_request_inner::<webhooks::OutgoingWebhook>(
outgoing_webhook,
business_profile,
),
}
}
<file_sep path="hyperswitch/crates/router/src/core/webhooks/outgoing.rs" role="context" start="614" end="663">
fn get_outgoing_webhook_request_inner<WebhookType: types::OutgoingWebhookType>(
outgoing_webhook: api::OutgoingWebhook,
business_profile: &domain::Profile,
) -> CustomResult<OutgoingWebhookRequestContent, errors::WebhooksFlowError> {
let mut headers = vec![
(
reqwest::header::CONTENT_TYPE.to_string(),
mime::APPLICATION_JSON.essence_str().into(),
),
(
reqwest::header::USER_AGENT.to_string(),
consts::USER_AGENT.to_string().into(),
),
];
let transformed_outgoing_webhook = WebhookType::from(outgoing_webhook);
let payment_response_hash_key = business_profile.payment_response_hash_key.clone();
let custom_headers = business_profile
.outgoing_webhook_custom_http_headers
.clone()
.map(|headers| {
headers
.into_inner()
.expose()
.parse_value::<HashMap<String, String>>("HashMap<String,String>")
.change_context(errors::WebhooksFlowError::OutgoingWebhookEncodingFailed)
.attach_printable("Failed to deserialize outgoing webhook custom HTTP headers")
})
.transpose()?;
if let Some(ref map) = custom_headers {
headers.extend(
map.iter()
.map(|(key, value)| (key.clone(), value.clone().into_masked())),
);
};
let outgoing_webhooks_signature = transformed_outgoing_webhook
.get_outgoing_webhooks_signature(payment_response_hash_key)?;
if let Some(signature) = outgoing_webhooks_signature.signature {
WebhookType::add_webhook_header(&mut headers, signature)
}
Ok(OutgoingWebhookRequestContent {
body: outgoing_webhooks_signature.payload,
headers: headers
.into_iter()
.map(|(name, value)| (name, Secret::new(value.into_inner())))
.collect(),
})
}
<file_sep path="hyperswitch/crates/router/src/core/webhooks/outgoing.rs" role="context" start="532" end="590">
pub(crate) async fn add_outgoing_webhook_retry_task_to_process_tracker(
db: &dyn StorageInterface,
business_profile: &domain::Profile,
event: &domain::Event,
) -> CustomResult<storage::ProcessTracker, errors::StorageError> {
let schedule_time = outgoing_webhook_retry::get_webhook_delivery_retry_schedule_time(
db,
&business_profile.merchant_id,
0,
)
.await
.ok_or(errors::StorageError::ValueNotFound(
"Process tracker schedule time".into(), // Can raise a better error here
))
.attach_printable("Failed to obtain initial process tracker schedule time")?;
let tracking_data = types::OutgoingWebhookTrackingData {
merchant_id: business_profile.merchant_id.clone(),
business_profile_id: business_profile.get_id().to_owned(),
event_type: event.event_type,
event_class: event.event_class,
primary_object_id: event.primary_object_id.clone(),
primary_object_type: event.primary_object_type,
initial_attempt_id: event.initial_attempt_id.clone(),
};
let runner = storage::ProcessTrackerRunner::OutgoingWebhookRetryWorkflow;
let task = "OUTGOING_WEBHOOK_RETRY";
let tag = ["OUTGOING_WEBHOOKS"];
let process_tracker_id = scheduler::utils::get_process_tracker_id(
runner,
task,
&event.event_id,
&business_profile.merchant_id,
);
let process_tracker_entry = storage::ProcessTrackerNew::new(
process_tracker_id,
task,
runner,
tag,
tracking_data,
None,
schedule_time,
common_types::consts::API_VERSION,
)
.map_err(errors::StorageError::from)?;
let attributes = router_env::metric_attributes!(("flow", "OutgoingWebhookRetry"));
match db.insert_process(process_tracker_entry).await {
Ok(process_tracker) => {
crate::routes::metrics::TASKS_ADDED_COUNT.add(1, attributes);
Ok(process_tracker)
}
Err(error) => {
crate::routes::metrics::TASK_ADDITION_FAILURES_COUNT.add(1, attributes);
Err(error)
}
}
}
<file_sep path="hyperswitch/crates/router/src/core/webhooks/outgoing.rs" role="context" start="457" end="530">
async fn raise_webhooks_analytics_event(
state: SessionState,
trigger_webhook_result: CustomResult<(), errors::WebhooksFlowError>,
content: Option<api::OutgoingWebhookContent>,
merchant_id: common_utils::id_type::MerchantId,
event: domain::Event,
merchant_key_store: &domain::MerchantKeyStore,
) {
let key_manager_state: &KeyManagerState = &(&state).into();
let event_id = event.event_id;
let error = if let Err(error) = trigger_webhook_result {
logger::error!(?error, "Failed to send webhook to merchant");
serde_json::to_value(error.current_context())
.change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
.inspect_err(|error| {
logger::error!(?error, "Failed to serialize outgoing webhook error as JSON");
})
.ok()
} else {
None
};
let outgoing_webhook_event_content = content
.as_ref()
.and_then(api::OutgoingWebhookContent::get_outgoing_webhook_event_content)
.or_else(|| get_outgoing_webhook_event_content_from_event_metadata(event.metadata));
// Fetch updated_event from db
let updated_event = state
.store
.find_event_by_merchant_id_event_id(
key_manager_state,
&merchant_id,
&event_id,
merchant_key_store,
)
.await
.attach_printable_lazy(|| format!("event not found for id: {}", &event_id))
.map_err(|error| {
logger::error!(?error);
error
})
.ok();
// Get status_code from webhook response
let status_code = updated_event.and_then(|updated_event| {
let webhook_response: Option<OutgoingWebhookResponseContent> =
updated_event.response.and_then(|res| {
res.peek()
.parse_struct("OutgoingWebhookResponseContent")
.map_err(|error| {
logger::error!(?error, "Error deserializing webhook response");
error
})
.ok()
});
webhook_response.and_then(|res| res.status_code)
});
let webhook_event = OutgoingWebhookEvent::new(
state.tenant.tenant_id.clone(),
merchant_id,
event_id,
event.event_type,
outgoing_webhook_event_content,
error,
event.initial_attempt_id,
status_code,
event.delivery_attempt,
);
state.event_handler().log_event(&webhook_event);
}
<file_sep path="hyperswitch/crates/router/src/core/webhooks/outgoing.rs" role="context" start="238" end="455">
async fn trigger_webhook_to_merchant(
state: SessionState,
business_profile: domain::Profile,
merchant_key_store: &domain::MerchantKeyStore,
event: domain::Event,
request_content: OutgoingWebhookRequestContent,
delivery_attempt: enums::WebhookDeliveryAttempt,
process_tracker: Option<storage::ProcessTracker>,
) -> CustomResult<(), errors::WebhooksFlowError> {
let webhook_url = match (
get_webhook_url_from_business_profile(&business_profile),
process_tracker.clone(),
) {
(Ok(webhook_url), _) => Ok(webhook_url),
(Err(error), Some(process_tracker)) => {
if !error
.current_context()
.is_webhook_delivery_retryable_error()
{
logger::debug!("Failed to obtain merchant webhook URL, aborting retries");
state
.store
.as_scheduler()
.finish_process_with_business_status(process_tracker, business_status::FAILURE)
.await
.change_context(
errors::WebhooksFlowError::OutgoingWebhookProcessTrackerTaskUpdateFailed,
)?;
}
Err(error)
}
(Err(error), None) => Err(error),
}?;
let event_id = event.event_id;
let headers = request_content
.headers
.into_iter()
.map(|(name, value)| (name, value.into_masked()))
.collect();
let request = services::RequestBuilder::new()
.method(services::Method::Post)
.url(&webhook_url)
.attach_default_headers()
.headers(headers)
.set_body(RequestContent::RawBytes(
request_content.body.expose().into_bytes(),
))
.build();
let response = state
.api_client
.send_request(&state, request, Some(OUTGOING_WEBHOOK_TIMEOUT_SECS), false)
.await;
metrics::WEBHOOK_OUTGOING_COUNT.add(
1,
router_env::metric_attributes!((MERCHANT_ID, business_profile.merchant_id.clone())),
);
logger::debug!(outgoing_webhook_response=?response);
match delivery_attempt {
enums::WebhookDeliveryAttempt::InitialAttempt => match response {
Err(client_error) => {
api_client_error_handler(
state.clone(),
merchant_key_store.clone(),
&business_profile.merchant_id,
&event_id,
client_error,
delivery_attempt,
ScheduleWebhookRetry::NoSchedule,
)
.await?
}
Ok(response) => {
let status_code = response.status();
let updated_event = update_event_in_storage(
state.clone(),
merchant_key_store.clone(),
&business_profile.merchant_id,
&event_id,
response,
)
.await?;
if status_code.is_success() {
update_overall_delivery_status_in_storage(
state.clone(),
merchant_key_store.clone(),
&business_profile.merchant_id,
updated_event,
)
.await?;
success_response_handler(
state.clone(),
&business_profile.merchant_id,
process_tracker,
business_status::INITIAL_DELIVERY_ATTEMPT_SUCCESSFUL,
)
.await?;
} else {
error_response_handler(
state.clone(),
&business_profile.merchant_id,
delivery_attempt,
status_code.as_u16(),
"Ignoring error when sending webhook to merchant",
ScheduleWebhookRetry::NoSchedule,
)
.await?;
}
}
},
enums::WebhookDeliveryAttempt::AutomaticRetry => {
let process_tracker = process_tracker
.get_required_value("process_tracker")
.change_context(errors::WebhooksFlowError::OutgoingWebhookRetrySchedulingFailed)
.attach_printable("`process_tracker` is unavailable in automatic retry flow")?;
match response {
Err(client_error) => {
api_client_error_handler(
state.clone(),
merchant_key_store.clone(),
&business_profile.merchant_id,
&event_id,
client_error,
delivery_attempt,
ScheduleWebhookRetry::WithProcessTracker(Box::new(process_tracker)),
)
.await?;
}
Ok(response) => {
let status_code = response.status();
let updated_event = update_event_in_storage(
state.clone(),
merchant_key_store.clone(),
&business_profile.merchant_id,
&event_id,
response,
)
.await?;
if status_code.is_success() {
update_overall_delivery_status_in_storage(
state.clone(),
merchant_key_store.clone(),
&business_profile.merchant_id,
updated_event,
)
.await?;
success_response_handler(
state.clone(),
&business_profile.merchant_id,
Some(process_tracker),
"COMPLETED_BY_PT",
)
.await?;
} else {
error_response_handler(
state.clone(),
&business_profile.merchant_id,
delivery_attempt,
status_code.as_u16(),
"An error occurred when sending webhook to merchant",
ScheduleWebhookRetry::WithProcessTracker(Box::new(process_tracker)),
)
.await?;
}
}
}
}
enums::WebhookDeliveryAttempt::ManualRetry => match response {
Err(client_error) => {
api_client_error_handler(
state.clone(),
merchant_key_store.clone(),
&business_profile.merchant_id,
&event_id,
client_error,
delivery_attempt,
ScheduleWebhookRetry::NoSchedule,
)
.await?
}
Ok(response) => {
let status_code = response.status();
let _updated_event = update_event_in_storage(
state.clone(),
merchant_key_store.clone(),
&business_profile.merchant_id,
&event_id,
response,
)
.await?;
if status_code.is_success() {
increment_webhook_outgoing_received_count(&business_profile.merchant_id);
} else {
error_response_handler(
state,
&business_profile.merchant_id,
delivery_attempt,
status_code.as_u16(),
"Ignoring error when sending webhook to merchant",
ScheduleWebhookRetry::NoSchedule,
)
.await?;
}
}
},
}
Ok(())
}
<file_sep path="hyperswitch/crates/router/src/core/webhooks/outgoing.rs" role="context" start="52" end="194">
pub(crate) async fn create_event_and_trigger_outgoing_webhook(
state: SessionState,
merchant_account: domain::MerchantAccount,
business_profile: domain::Profile,
merchant_key_store: &domain::MerchantKeyStore,
event_type: enums::EventType,
event_class: enums::EventClass,
primary_object_id: String,
primary_object_type: enums::EventObjectType,
content: api::OutgoingWebhookContent,
primary_object_created_at: Option<time::PrimitiveDateTime>,
) -> CustomResult<(), errors::ApiErrorResponse> {
let delivery_attempt = enums::WebhookDeliveryAttempt::InitialAttempt;
let idempotent_event_id =
utils::get_idempotent_event_id(&primary_object_id, event_type, delivery_attempt);
let webhook_url_result = get_webhook_url_from_business_profile(&business_profile);
if !state.conf.webhooks.outgoing_enabled
|| webhook_url_result.is_err()
|| webhook_url_result.as_ref().is_ok_and(String::is_empty)
{
logger::debug!(
business_profile_id=?business_profile.get_id(),
%idempotent_event_id,
"Outgoing webhooks are disabled in application configuration, or merchant webhook URL \
could not be obtained; skipping outgoing webhooks for event"
);
return Ok(());
}
let event_id = utils::generate_event_id();
let merchant_id = business_profile.merchant_id.clone();
let now = common_utils::date_time::now();
let outgoing_webhook = api::OutgoingWebhook {
merchant_id: merchant_id.clone(),
event_id: event_id.clone(),
event_type,
content: content.clone(),
timestamp: now,
};
let request_content =
get_outgoing_webhook_request(&merchant_account, outgoing_webhook, &business_profile)
.change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
.attach_printable("Failed to construct outgoing webhook request content")?;
let event_metadata = storage::EventMetadata::foreign_from(&content);
let key_manager_state = &(&state).into();
let new_event = domain::Event {
event_id: event_id.clone(),
event_type,
event_class,
is_webhook_notified: false,
primary_object_id,
primary_object_type,
created_at: now,
merchant_id: Some(business_profile.merchant_id.clone()),
business_profile_id: Some(business_profile.get_id().to_owned()),
primary_object_created_at,
idempotent_event_id: Some(idempotent_event_id.clone()),
initial_attempt_id: Some(event_id.clone()),
request: Some(
crypto_operation(
key_manager_state,
type_name!(domain::Event),
CryptoOperation::Encrypt(
request_content
.encode_to_string_of_json()
.change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
.attach_printable("Failed to encode outgoing webhook request content")
.map(Secret::new)?,
),
Identifier::Merchant(merchant_key_store.merchant_id.clone()),
merchant_key_store.key.get_inner().peek(),
)
.await
.and_then(|val| val.try_into_operation())
.change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
.attach_printable("Failed to encrypt outgoing webhook request content")?,
),
response: None,
delivery_attempt: Some(delivery_attempt),
metadata: Some(event_metadata),
is_overall_delivery_successful: Some(false),
};
let event_insert_result = state
.store
.insert_event(key_manager_state, new_event, merchant_key_store)
.await;
let event = match event_insert_result {
Ok(event) => Ok(event),
Err(error) => {
if error.current_context().is_db_unique_violation() {
logger::debug!("Event with idempotent ID `{idempotent_event_id}` already exists in the database");
return Ok(());
} else {
logger::error!(event_insertion_failure=?error);
Err(error
.change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
.attach_printable("Failed to insert event in events table"))
}
}
}?;
let process_tracker = add_outgoing_webhook_retry_task_to_process_tracker(
&*state.store,
&business_profile,
&event,
)
.await
.inspect_err(|error| {
logger::error!(
?error,
"Failed to add outgoing webhook retry task to process tracker"
);
})
.ok();
let cloned_key_store = merchant_key_store.clone();
// Using a tokio spawn here and not arbiter because not all caller of this function
// may have an actix arbiter
tokio::spawn(
async move {
Box::pin(trigger_webhook_and_raise_event(
state,
business_profile,
&cloned_key_store,
event,
request_content,
delivery_attempt,
Some(content),
process_tracker,
))
.await;
}
.in_current_span(),
);
Ok(())
}
<file_sep path="hyperswitch/crates/router/src/routes/app.rs" role="context" start="1906" end="1906">
pub struct Profile;
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payment_methods/cards.rs<|crate|> router anchor=get_lookup_key_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="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="5366" end="5366">
use std::{
collections::{HashMap, HashSet},
fmt::Debug,
str::FromStr,
};
use crate::routes::app::SessionStateInfo;
use crate::types::domain::types::AsyncLift;
use crate::{
configs::{
defaults::{get_billing_required_fields, get_shipping_required_fields},
settings,
},
consts as router_consts,
core::{
errors::{self, StorageErrorExt},
payment_methods::{network_tokenization, transformers as payment_methods, vault},
payments::{
helpers,
routing::{self, SessionFlowRoutingInput},
},
utils as core_utils,
},
db, logger,
pii::prelude::*,
routes::{self, metrics, payment_methods::ParentPaymentMethodToken},
services,
types::{
api::{self, routing as routing_types, PaymentMethodCreateExt},
domain::{self, Profile},
storage::{self, enums, PaymentMethodListContext, PaymentTokenData},
transformers::{ForeignFrom, ForeignTryFrom},
},
utils,
utils::OptionExt,
};
<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/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="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="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="5661" end="5738">
async fn create_payment_method_data_in_temp_locker(
state: &routes::SessionState,
payment_token: &str,
card: api::CardDetailFromLocker,
pm: &domain::PaymentMethod,
merchant_key_store: &domain::MerchantKeyStore,
) -> errors::RouterResult<api::CardDetailFromLocker> {
let card_number = card.card_number.clone().get_required_value("card_number")?;
let card_exp_month = card
.expiry_month
.clone()
.expose_option()
.get_required_value("expiry_month")?;
let card_exp_year = card
.expiry_year
.clone()
.expose_option()
.get_required_value("expiry_year")?;
let card_holder_name = card
.card_holder_name
.clone()
.expose_option()
.unwrap_or_default();
let value1 = payment_methods::mk_card_value1(
card_number,
card_exp_year,
card_exp_month,
Some(card_holder_name),
None,
None,
None,
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error getting Value1 for locker")?;
let value2 = payment_methods::mk_card_value2(
None,
None,
None,
Some(pm.customer_id.clone()),
Some(pm.get_id().to_string()),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error getting Value2 for locker")?;
let value1 = vault::VaultPaymentMethod::Card(value1);
let value2 = vault::VaultPaymentMethod::Card(value2);
let value1 = value1
.encode_to_string_of_json()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Wrapped value1 construction failed when saving card to locker")?;
let value2 = value2
.encode_to_string_of_json()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Wrapped value2 construction failed when saving card to locker")?;
let lookup_key = vault::create_tokenize(
state,
value1,
Some(value2),
payment_token.to_string(),
merchant_key_store.key.get_inner(),
)
.await?;
vault::add_delete_tokenized_data_task(
&*state.store,
&lookup_key,
enums::PaymentMethod::Card,
)
.await?;
metrics::TOKENIZED_DATA_COUNT.add(1, &[]);
metrics::TASKS_ADDED_COUNT.add(
1,
router_env::metric_attributes!(("flow", "DeleteTokenizeData")),
);
Ok(card)
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="5653" end="5653">
pub struct TempLockerCardSupport;
<file_sep path="hyperswitch/crates/router/src/connector/nmi/transformers.rs" role="context" start="454" end="459">
pub enum PaymentMethod {
CardNonThreeDs(Box<CardData>),
CardThreeDs(Box<CardThreeDsData>),
GPay(Box<GooglePayData>),
ApplePay(Box<ApplePayData>),
}
<file_sep path="hyperswitch/v2_compatible_migrations/2024-08-28-081721_add_v2_columns/up.sql" role="context" start="54" end="70">
ADD COLUMN redirection_data JSONB,
ADD COLUMN connector_payment_data TEXT,
ADD COLUMN connector_token_details JSONB;
-- Change the type of the column from JSON to JSONB
ALTER TABLE merchant_connector_account
ADD COLUMN IF NOT EXISTS feature_metadata JSONB;
ALTER TABLE payment_methods
ADD COLUMN IF NOT EXISTS locker_fingerprint_id VARCHAR(64),
ADD COLUMN IF NOT EXISTS payment_method_type_v2 VARCHAR(64),
ADD COLUMN IF NOT EXISTS payment_method_subtype VARCHAR(64);
ALTER TABLE refund
ADD COLUMN IF NOT EXISTS id VARCHAR(64),
ADD COLUMN IF NOT EXISTS merchant_reference_id VARCHAR(64),
ADD COLUMN IF NOT EXISTS connector_id VARCHAR(64);
<file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="1090" end="1123">
pub struct CardDetailFromLocker {
pub scheme: Option<String>,
pub issuer_country: Option<String>,
pub last4_digits: Option<String>,
#[serde(skip)]
#[schema(value_type=Option<String>)]
pub card_number: Option<CardNumber>,
#[schema(value_type=Option<String>)]
pub expiry_month: Option<masking::Secret<String>>,
#[schema(value_type=Option<String>)]
pub expiry_year: Option<masking::Secret<String>>,
#[schema(value_type=Option<String>)]
pub card_token: Option<masking::Secret<String>>,
#[schema(value_type=Option<String>)]
pub card_holder_name: Option<masking::Secret<String>>,
#[schema(value_type=Option<String>)]
pub card_fingerprint: Option<masking::Secret<String>>,
#[schema(value_type=Option<String>)]
pub nick_name: Option<masking::Secret<String>>,
#[schema(value_type = Option<CardNetwork>)]
pub card_network: Option<api_enums::CardNetwork>,
pub card_isin: Option<String>,
pub card_issuer: Option<String>,
pub card_type: Option<String>,
pub saved_to_locker: bool,
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payouts/retry.rs<|crate|> router anchor=get_gsm 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="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="184" end="184">
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="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/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="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="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/migrations/2024-11-24-104438_add_error_category_col_to_gsm/up.sql" role="context" start="1" end="2">
-- Your SQL goes here
ALTER TABLE gateway_status_map ADD COLUMN error_category 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/webhooks/outgoing.rs<|crate|> router anchor=success_response_handler kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/webhooks/outgoing.rs" role="context" start="902" end="921">
async fn success_response_handler(
state: SessionState,
merchant_id: &common_utils::id_type::MerchantId,
process_tracker: Option<storage::ProcessTracker>,
business_status: &'static str,
) -> CustomResult<(), errors::WebhooksFlowError> {
increment_webhook_outgoing_received_count(merchant_id);
match process_tracker {
Some(process_tracker) => state
.store
.as_scheduler()
.finish_process_with_business_status(process_tracker, business_status)
.await
.change_context(
errors::WebhooksFlowError::OutgoingWebhookProcessTrackerTaskUpdateFailed,
),
None => Ok(()),
}
}
<file_sep path="hyperswitch/crates/router/src/core/webhooks/outgoing.rs" role="context" start="901" end="901">
use common_utils::{
ext_traits::{Encode, StringExt},
request::RequestContent,
type_name,
types::keymanager::{Identifier, KeyManagerState},
};
use diesel_models::process_tracker::business_status;
use crate::{
core::{
errors::{self, CustomResult},
metrics,
},
db::StorageInterface,
events::outgoing_webhook_logs::{
OutgoingWebhookEvent, OutgoingWebhookEventContent, OutgoingWebhookEventMetric,
},
logger,
routes::{app::SessionStateInfo, SessionState},
services,
types::{
api,
domain::{self},
storage::{self, enums},
transformers::ForeignFrom,
},
utils::{OptionExt, ValueExt},
workflows::outgoing_webhook_retry,
};
<file_sep path="hyperswitch/crates/router/src/core/webhooks/outgoing.rs" role="context" start="954" end="977">
fn foreign_from(content: &api::OutgoingWebhookContent) -> Self {
match content {
webhooks::OutgoingWebhookContent::PaymentDetails(payments_response) => Self::Payment {
payment_id: payments_response.payment_id.clone(),
},
webhooks::OutgoingWebhookContent::RefundDetails(refund_response) => Self::Refund {
payment_id: refund_response.payment_id.clone(),
refund_id: refund_response.refund_id.clone(),
},
webhooks::OutgoingWebhookContent::DisputeDetails(dispute_response) => Self::Dispute {
payment_id: dispute_response.payment_id.clone(),
attempt_id: dispute_response.attempt_id.clone(),
dispute_id: dispute_response.dispute_id.clone(),
},
webhooks::OutgoingWebhookContent::MandateDetails(mandate_response) => Self::Mandate {
payment_method_id: mandate_response.payment_method_id.clone(),
mandate_id: mandate_response.mandate_id.clone(),
},
#[cfg(feature = "payouts")]
webhooks::OutgoingWebhookContent::PayoutDetails(payout_response) => Self::Payout {
payout_id: payout_response.payout_id.clone(),
},
}
}
<file_sep path="hyperswitch/crates/router/src/core/webhooks/outgoing.rs" role="context" start="923" end="951">
async fn error_response_handler(
state: SessionState,
merchant_id: &common_utils::id_type::MerchantId,
delivery_attempt: enums::WebhookDeliveryAttempt,
status_code: u16,
log_message: &'static str,
schedule_webhook_retry: ScheduleWebhookRetry,
) -> CustomResult<(), errors::WebhooksFlowError> {
metrics::WEBHOOK_OUTGOING_NOT_RECEIVED_COUNT.add(
1,
router_env::metric_attributes!((MERCHANT_ID, merchant_id.clone())),
);
let error = report!(errors::WebhooksFlowError::NotReceivedByMerchant);
logger::warn!(?error, ?delivery_attempt, status_code, %log_message);
if let ScheduleWebhookRetry::WithProcessTracker(process_tracker) = schedule_webhook_retry {
// Schedule a retry attempt for webhook delivery
outgoing_webhook_retry::retry_webhook_delivery_task(
&*state.store,
merchant_id,
*process_tracker,
)
.await
.change_context(errors::WebhooksFlowError::OutgoingWebhookRetrySchedulingFailed)?;
}
Err(error)
}
<file_sep path="hyperswitch/crates/router/src/core/webhooks/outgoing.rs" role="context" start="895" end="900">
fn increment_webhook_outgoing_received_count(merchant_id: &common_utils::id_type::MerchantId) {
metrics::WEBHOOK_OUTGOING_RECEIVED_COUNT.add(
1,
router_env::metric_attributes!((MERCHANT_ID, merchant_id.clone())),
)
}
<file_sep path="hyperswitch/crates/router/src/core/webhooks/outgoing.rs" role="context" start="857" end="893">
async fn update_overall_delivery_status_in_storage(
state: SessionState,
merchant_key_store: domain::MerchantKeyStore,
merchant_id: &common_utils::id_type::MerchantId,
updated_event: domain::Event,
) -> CustomResult<(), errors::WebhooksFlowError> {
let key_manager_state = &(&state).into();
let update_overall_delivery_status = domain::EventUpdate::OverallDeliveryStatusUpdate {
is_overall_delivery_successful: true,
};
let initial_attempt_id = updated_event.initial_attempt_id.as_ref();
let delivery_attempt = updated_event.delivery_attempt;
if let Some((
initial_attempt_id,
enums::WebhookDeliveryAttempt::InitialAttempt
| enums::WebhookDeliveryAttempt::AutomaticRetry,
)) = initial_attempt_id.zip(delivery_attempt)
{
state
.store
.update_event_by_merchant_id_event_id(
key_manager_state,
merchant_id,
initial_attempt_id.as_str(),
update_overall_delivery_status,
&merchant_key_store,
)
.await
.change_context(errors::WebhooksFlowError::WebhookEventUpdationFailed)
.attach_printable("Failed to update initial delivery attempt")?;
}
Ok(())
}
<file_sep path="hyperswitch/crates/router/src/core/webhooks/outgoing.rs" role="context" start="238" end="455">
async fn trigger_webhook_to_merchant(
state: SessionState,
business_profile: domain::Profile,
merchant_key_store: &domain::MerchantKeyStore,
event: domain::Event,
request_content: OutgoingWebhookRequestContent,
delivery_attempt: enums::WebhookDeliveryAttempt,
process_tracker: Option<storage::ProcessTracker>,
) -> CustomResult<(), errors::WebhooksFlowError> {
let webhook_url = match (
get_webhook_url_from_business_profile(&business_profile),
process_tracker.clone(),
) {
(Ok(webhook_url), _) => Ok(webhook_url),
(Err(error), Some(process_tracker)) => {
if !error
.current_context()
.is_webhook_delivery_retryable_error()
{
logger::debug!("Failed to obtain merchant webhook URL, aborting retries");
state
.store
.as_scheduler()
.finish_process_with_business_status(process_tracker, business_status::FAILURE)
.await
.change_context(
errors::WebhooksFlowError::OutgoingWebhookProcessTrackerTaskUpdateFailed,
)?;
}
Err(error)
}
(Err(error), None) => Err(error),
}?;
let event_id = event.event_id;
let headers = request_content
.headers
.into_iter()
.map(|(name, value)| (name, value.into_masked()))
.collect();
let request = services::RequestBuilder::new()
.method(services::Method::Post)
.url(&webhook_url)
.attach_default_headers()
.headers(headers)
.set_body(RequestContent::RawBytes(
request_content.body.expose().into_bytes(),
))
.build();
let response = state
.api_client
.send_request(&state, request, Some(OUTGOING_WEBHOOK_TIMEOUT_SECS), false)
.await;
metrics::WEBHOOK_OUTGOING_COUNT.add(
1,
router_env::metric_attributes!((MERCHANT_ID, business_profile.merchant_id.clone())),
);
logger::debug!(outgoing_webhook_response=?response);
match delivery_attempt {
enums::WebhookDeliveryAttempt::InitialAttempt => match response {
Err(client_error) => {
api_client_error_handler(
state.clone(),
merchant_key_store.clone(),
&business_profile.merchant_id,
&event_id,
client_error,
delivery_attempt,
ScheduleWebhookRetry::NoSchedule,
)
.await?
}
Ok(response) => {
let status_code = response.status();
let updated_event = update_event_in_storage(
state.clone(),
merchant_key_store.clone(),
&business_profile.merchant_id,
&event_id,
response,
)
.await?;
if status_code.is_success() {
update_overall_delivery_status_in_storage(
state.clone(),
merchant_key_store.clone(),
&business_profile.merchant_id,
updated_event,
)
.await?;
success_response_handler(
state.clone(),
&business_profile.merchant_id,
process_tracker,
business_status::INITIAL_DELIVERY_ATTEMPT_SUCCESSFUL,
)
.await?;
} else {
error_response_handler(
state.clone(),
&business_profile.merchant_id,
delivery_attempt,
status_code.as_u16(),
"Ignoring error when sending webhook to merchant",
ScheduleWebhookRetry::NoSchedule,
)
.await?;
}
}
},
enums::WebhookDeliveryAttempt::AutomaticRetry => {
let process_tracker = process_tracker
.get_required_value("process_tracker")
.change_context(errors::WebhooksFlowError::OutgoingWebhookRetrySchedulingFailed)
.attach_printable("`process_tracker` is unavailable in automatic retry flow")?;
match response {
Err(client_error) => {
api_client_error_handler(
state.clone(),
merchant_key_store.clone(),
&business_profile.merchant_id,
&event_id,
client_error,
delivery_attempt,
ScheduleWebhookRetry::WithProcessTracker(Box::new(process_tracker)),
)
.await?;
}
Ok(response) => {
let status_code = response.status();
let updated_event = update_event_in_storage(
state.clone(),
merchant_key_store.clone(),
&business_profile.merchant_id,
&event_id,
response,
)
.await?;
if status_code.is_success() {
update_overall_delivery_status_in_storage(
state.clone(),
merchant_key_store.clone(),
&business_profile.merchant_id,
updated_event,
)
.await?;
success_response_handler(
state.clone(),
&business_profile.merchant_id,
Some(process_tracker),
"COMPLETED_BY_PT",
)
.await?;
} else {
error_response_handler(
state.clone(),
&business_profile.merchant_id,
delivery_attempt,
status_code.as_u16(),
"An error occurred when sending webhook to merchant",
ScheduleWebhookRetry::WithProcessTracker(Box::new(process_tracker)),
)
.await?;
}
}
}
}
enums::WebhookDeliveryAttempt::ManualRetry => match response {
Err(client_error) => {
api_client_error_handler(
state.clone(),
merchant_key_store.clone(),
&business_profile.merchant_id,
&event_id,
client_error,
delivery_attempt,
ScheduleWebhookRetry::NoSchedule,
)
.await?
}
Ok(response) => {
let status_code = response.status();
let _updated_event = update_event_in_storage(
state.clone(),
merchant_key_store.clone(),
&business_profile.merchant_id,
&event_id,
response,
)
.await?;
if status_code.is_success() {
increment_webhook_outgoing_received_count(&business_profile.merchant_id);
} else {
error_response_handler(
state,
&business_profile.merchant_id,
delivery_attempt,
status_code.as_u16(),
"Ignoring error when sending webhook to merchant",
ScheduleWebhookRetry::NoSchedule,
)
.await?;
}
}
},
}
Ok(())
}
<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/2022-09-29-084920_create_initial_tables/up.sql" role="context" start="430" end="446">
created_at TIMESTAMP NOT NULL,
last_modified TIMESTAMP NOT NULL,
payment_method "PaymentMethodType" NOT NULL,
payment_method_type "PaymentMethodSubType",
payment_method_issuer VARCHAR(255),
payment_method_issuer_code "PaymentMethodIssuerCode"
);
CREATE TABLE process_tracker (
id VARCHAR(127) PRIMARY KEY,
NAME VARCHAR(255),
tag TEXT [ ] NOT NULL DEFAULT '{}'::TEXT [ ],
runner VARCHAR(255),
retry_count INTEGER NOT NULL,
schedule_time TIMESTAMP,
rule VARCHAR(255) NOT NULL,
tracking_data JSON 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/relay.rs<|crate|> router anchor=relay_flow_decider kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/relay.rs" role="context" start="200" end="220">
pub async fn relay_flow_decider(
state: SessionState,
merchant_account: domain::MerchantAccount,
profile_id_optional: Option<id_type::ProfileId>,
key_store: domain::MerchantKeyStore,
request: relay_api_models::RelayRequest,
) -> RouterResponse<relay_api_models::RelayResponse> {
let relay_flow_request = match request.relay_type {
common_enums::RelayType::Refund => {
RelayRequestInner::<RelayRefund>::from_relay_request(request)?
}
};
relay(
state,
merchant_account,
profile_id_optional,
key_store,
relay_flow_request,
)
.await
}
<file_sep path="hyperswitch/crates/router/src/core/relay.rs" role="context" start="199" end="199">
use api_models::relay as relay_api_models;
use common_enums::RelayStatus;
use common_utils::{
self, fp_utils,
id_type::{self, GenerateId},
};
use hyperswitch_domain_models::relay;
use super::errors::{self, ConnectorErrorExt, RouterResponse, RouterResult, StorageErrorExt};
use crate::{
core::payments,
routes::SessionState,
services,
types::{
api::{self},
domain,
},
utils::OptionExt,
};
<file_sep path="hyperswitch/crates/router/src/core/relay.rs" role="context" start="297" end="392">
pub async fn relay_retrieve(
state: SessionState,
merchant_account: domain::MerchantAccount,
profile_id_optional: Option<id_type::ProfileId>,
key_store: domain::MerchantKeyStore,
req: relay_api_models::RelayRetrieveRequest,
) -> RouterResponse<relay_api_models::RelayResponse> {
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
let merchant_id = merchant_account.get_id();
let relay_id = &req.id;
let profile_id_from_auth_layer = profile_id_optional.get_required_value("ProfileId")?;
db.find_business_profile_by_merchant_id_profile_id(
key_manager_state,
&key_store,
merchant_id,
&profile_id_from_auth_layer,
)
.await
.change_context(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id_from_auth_layer.get_string_repr().to_owned(),
})?;
let relay_record_result = db
.find_relay_by_id(key_manager_state, &key_store, relay_id)
.await;
let relay_record = match relay_record_result {
Err(error) => {
if error.current_context().is_db_not_found() {
Err(error).change_context(errors::ApiErrorResponse::GenericNotFoundError {
message: "relay not found".to_string(),
})?
} else {
Err(error)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("error while fetch relay record")?
}
}
Ok(relay) => relay,
};
#[cfg(feature = "v1")]
let connector_account = db
.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
key_manager_state,
merchant_id,
&relay_record.connector_id,
&key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: relay_record.connector_id.get_string_repr().to_string(),
})?;
#[cfg(feature = "v2")]
let connector_account = db
.find_merchant_connector_account_by_id(
key_manager_state,
&relay_record.connector_id,
&key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: relay_record.connector_id.get_string_repr().to_string(),
})?;
let relay_response = match relay_record.relay_type {
common_enums::RelayType::Refund => {
if should_call_connector_for_relay_refund_status(&relay_record, req.force_sync) {
let relay_response = sync_relay_refund_with_gateway(
&state,
&merchant_account,
&relay_record,
connector_account,
)
.await?;
db.update_relay(key_manager_state, &key_store, relay_record, relay_response)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update the relay record")?
} else {
relay_record
}
}
};
let response = relay_api_models::RelayResponse::from(relay_response);
Ok(hyperswitch_domain_models::api::ApplicationResponse::Json(
response,
))
}
<file_sep path="hyperswitch/crates/router/src/core/relay.rs" role="context" start="222" end="295">
pub async fn relay<T: RelayInterface>(
state: SessionState,
merchant_account: domain::MerchantAccount,
profile_id_optional: Option<id_type::ProfileId>,
key_store: domain::MerchantKeyStore,
req: RelayRequestInner<T>,
) -> RouterResponse<relay_api_models::RelayResponse> {
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
let merchant_id = merchant_account.get_id();
let connector_id = &req.connector_id;
let profile_id_from_auth_layer = profile_id_optional.get_required_value("ProfileId")?;
let profile = db
.find_business_profile_by_merchant_id_profile_id(
key_manager_state,
&key_store,
merchant_id,
&profile_id_from_auth_layer,
)
.await
.change_context(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id_from_auth_layer.get_string_repr().to_owned(),
})?;
#[cfg(feature = "v1")]
let connector_account = db
.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
key_manager_state,
merchant_id,
connector_id,
&key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: connector_id.get_string_repr().to_string(),
})?;
#[cfg(feature = "v2")]
let connector_account = db
.find_merchant_connector_account_by_id(key_manager_state, connector_id, &key_store)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: connector_id.get_string_repr().to_string(),
})?;
T::validate_relay_request(&req.data)?;
let relay_domain = T::get_domain_models(req, merchant_id, profile.get_id());
let relay_record = db
.insert_relay(key_manager_state, &key_store, relay_domain)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to insert a relay record in db")?;
let relay_response =
T::process_relay(&state, merchant_account, connector_account, &relay_record)
.await
.attach_printable("Failed to process relay")?;
let relay_update_record = db
.update_relay(key_manager_state, &key_store, relay_record, relay_response)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let response = T::generate_response(relay_update_record)
.attach_printable("Failed to generate relay response")?;
Ok(hyperswitch_domain_models::api::ApplicationResponse::Json(
response,
))
}
<file_sep path="hyperswitch/crates/router/src/core/relay.rs" role="context" start="172" end="197">
fn generate_response(value: relay::Relay) -> RouterResult<api_models::relay::RelayResponse> {
let error = value
.error_code
.zip(value.error_message)
.map(
|(error_code, error_message)| api_models::relay::RelayError {
code: error_code,
message: error_message,
},
);
let data =
api_models::relay::RelayData::from(value.request_data.get_required_value("RelayData")?);
Ok(api_models::relay::RelayResponse {
id: value.id,
status: value.status,
error,
connector_resource_id: value.connector_resource_id,
connector_id: value.connector_id,
profile_id: value.profile_id,
relay_type: value.relay_type,
data: Some(data),
connector_reference_id: value.connector_reference_id,
})
}
<file_sep path="hyperswitch/crates/router/src/core/relay.rs" role="context" start="124" end="170">
async fn process_relay(
state: &SessionState,
merchant_account: domain::MerchantAccount,
connector_account: domain::MerchantConnectorAccount,
relay_record: &relay::Relay,
) -> RouterResult<relay::RelayUpdate> {
let connector_id = &relay_record.connector_id;
let merchant_id = merchant_account.get_id();
let connector_name = &connector_account.get_connector_name_as_string();
let connector_data = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
connector_name,
api::GetToken::Connector,
Some(connector_id.clone()),
)?;
let connector_integration: services::BoxedRefundConnectorIntegrationInterface<
api::Execute,
hyperswitch_domain_models::router_request_types::RefundsData,
hyperswitch_domain_models::router_response_types::RefundsResponseData,
> = connector_data.connector.get_connector_integration();
let router_data = utils::construct_relay_refund_router_data(
state,
merchant_id,
&connector_account,
relay_record,
)
.await?;
let router_data_res = services::execute_connector_processing_step(
state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
)
.await
.to_refund_failed_response()?;
let relay_update = relay::RelayUpdate::from(router_data_res.response);
Ok(relay_update)
}
<file_sep path="hyperswitch/crates/router/src/core/relay.rs" role="context" start="78" end="90">
pub fn from_relay_request(relay_request: relay_api_models::RelayRequest) -> RouterResult<Self> {
match relay_request.data {
Some(relay_api_models::RelayData::Refund(ref_data)) => Ok(Self {
connector_resource_id: relay_request.connector_resource_id,
connector_id: relay_request.connector_id,
relay_type: PhantomData,
data: ref_data,
}),
None => Err(errors::ApiErrorResponse::InvalidRequestData {
message: "Relay data is required for relay type refund".to_string(),
})?,
}
}
<file_sep path="hyperswitch/crates/router/src/core/relay.rs" role="context" start="93" end="93">
pub struct RelayRefund;
<file_sep path="hyperswitch/crates/router/src/core/relay.rs" role="context" start="70" end="75">
pub struct RelayRequestInner<T: RelayInterface + ?Sized> {
pub connector_resource_id: String,
pub connector_id: id_type::MerchantConnectorAccountId,
pub relay_type: PhantomData<T>,
pub data: T::Request,
}
<file_sep path="hyperswitch/crates/router/src/configs/settings.rs" role="context" start="721" end="724">
pub struct Refund {
pub max_attempts: usize,
pub max_age: i64,
}
<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/relay.rs" role="context" start="8" end="21">
pub struct RelayRequest {
/// The identifier that is associated to a resource at the connector reference to which the relay request is being made
#[schema(example = "7256228702616471803954")]
pub connector_resource_id: String,
/// Identifier of the connector ( merchant connector account ) which was chosen to make the payment
#[schema(example = "mca_5apGeP94tMts6rg3U3kR", value_type = String)]
pub connector_id: common_utils::id_type::MerchantConnectorAccountId,
/// The type of relay request
#[serde(rename = "type")]
#[schema(value_type = RelayType)]
pub relay_type: api_enums::RelayType,
/// The data that is associated with the relay request
pub data: Option<RelayData>,
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payment_methods/vault.rs<|crate|> router anchor=get_payment_method_data_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/vault.rs" role="context" start="887" end="900">
pub async fn get_payment_method_data_from_locker(
state: &routes::SessionState,
lookup_key: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> RouterResult<(Option<domain::PaymentMethodData>, SupplementaryVaultData)> {
let de_tokenize =
get_tokenized_data(state, lookup_key, true, merchant_key_store.key.get_inner()).await?;
let (payment_method, customer_id) =
domain::PaymentMethodData::from_values(de_tokenize.value1, de_tokenize.value2)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error parsing Payment Method from Values")?;
Ok((Some(payment_method), customer_id))
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/vault.rs" role="context" start="886" end="886">
use crate::{
consts,
core::errors::{self, CustomResult, RouterResult},
db, logger, routes,
routes::metrics,
types::{
api, domain,
storage::{self, enums},
},
utils::StringExt,
};
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/vault.rs" role="context" start="938" end="951">
pub async fn get_payout_method_data_from_temporary_locker(
state: &routes::SessionState,
lookup_key: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> RouterResult<(Option<api::PayoutMethodData>, SupplementaryVaultData)> {
let de_tokenize =
get_tokenized_data(state, lookup_key, true, merchant_key_store.key.get_inner()).await?;
let (payout_method, supp_data) =
api::PayoutMethodData::from_values(de_tokenize.value1, de_tokenize.value2)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error parsing Payout Method from Values")?;
Ok((Some(payout_method), supp_data))
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/vault.rs" role="context" start="903" end="934">
pub async fn store_payment_method_data_in_locker(
state: &routes::SessionState,
token_id: Option<String>,
payment_method: &domain::PaymentMethodData,
customer_id: Option<id_type::CustomerId>,
pm: enums::PaymentMethod,
merchant_key_store: &domain::MerchantKeyStore,
) -> RouterResult<String> {
let value1 = payment_method
.get_value1(customer_id.clone())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error getting Value1 for locker")?;
let value2 = payment_method
.get_value2(customer_id)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error getting Value12 for locker")?;
let lookup_key = token_id.unwrap_or_else(|| generate_id_with_default_len("token"));
let lookup_key = create_tokenize(
state,
value1,
Some(value2),
lookup_key,
merchant_key_store.key.get_inner(),
)
.await?;
add_delete_tokenized_data_task(&*state.store, &lookup_key, pm).await?;
metrics::TOKENIZED_DATA_COUNT.add(1, &[]);
Ok(lookup_key)
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/vault.rs" role="context" start="844" end="874">
fn from_values(
value1: String,
value2: String,
) -> CustomResult<(Self, SupplementaryVaultData), errors::VaultError> {
let value1: VaultPayoutMethod = value1
.parse_struct("VaultMethodValue1")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Could not deserialize into vault method value 1")?;
let value2: VaultPayoutMethod = value2
.parse_struct("VaultMethodValue2")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Could not deserialize into vault method value 2")?;
match (value1, value2) {
(VaultPayoutMethod::Card(mvalue1), VaultPayoutMethod::Card(mvalue2)) => {
let (card, supp_data) = api::CardPayout::from_values(mvalue1, mvalue2)?;
Ok((Self::Card(card), supp_data))
}
(VaultPayoutMethod::Bank(mvalue1), VaultPayoutMethod::Bank(mvalue2)) => {
let (bank, supp_data) = api::BankPayout::from_values(mvalue1, mvalue2)?;
Ok((Self::Bank(bank), supp_data))
}
(VaultPayoutMethod::Wallet(mvalue1), VaultPayoutMethod::Wallet(mvalue2)) => {
let (wallet, supp_data) = api::WalletPayout::from_values(mvalue1, mvalue2)?;
Ok((Self::Wallet(wallet), supp_data))
}
_ => Err(errors::VaultError::PayoutMethodNotSupported)
.attach_printable("Payout method not supported"),
}
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/vault.rs" role="context" start="828" end="842">
fn get_value2(
&self,
customer_id: Option<id_type::CustomerId>,
) -> CustomResult<String, errors::VaultError> {
let value2 = match self {
Self::Card(card) => VaultPayoutMethod::Card(card.get_value2(customer_id)?),
Self::Bank(bank) => VaultPayoutMethod::Bank(bank.get_value2(customer_id)?),
Self::Wallet(wallet) => VaultPayoutMethod::Wallet(wallet.get_value2(customer_id)?),
};
value2
.encode_to_string_of_json()
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode payout method value2")
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/vault.rs" role="context" start="1076" end="1138">
pub async fn get_tokenized_data(
state: &routes::SessionState,
lookup_key: &str,
_should_get_value2: bool,
encryption_key: &masking::Secret<Vec<u8>>,
) -> RouterResult<api::TokenizePayloadRequest> {
let redis_key = get_redis_locker_key(lookup_key);
let func = || async {
metrics::GET_TOKENIZED_CARD.add(1, &[]);
let redis_conn = state
.store
.get_redis_conn()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get redis connection")?;
let response = redis_conn
.get_key::<bytes::Bytes>(&redis_key.as_str().into())
.await;
match response {
Ok(resp) => {
let decrypted_payload = GcmAes256
.decode_message(
encryption_key.peek().as_ref(),
masking::Secret::new(resp.into()),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to decode redis temp locker data")?;
let get_response: api::TokenizePayloadRequest =
bytes::Bytes::from(decrypted_payload)
.parse_struct("TokenizePayloadRequest")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Error getting TokenizePayloadRequest from tokenize response",
)?;
Ok(get_response)
}
Err(err) => {
metrics::TEMP_LOCKER_FAILURES.add(1, &[]);
Err(err).change_context(errors::ApiErrorResponse::UnprocessableEntity {
message: "Token is invalid or expired".into(),
})
}
}
};
match func().await {
Ok(s) => {
logger::info!(
"Fetch payload in redis locker successful with lookup key: {:?}",
redis_key
);
Ok(s)
}
Err(err) => {
logger::error!("Redis Temp locker Failed: {:?}", err);
Err(err)
}
}
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/vault.rs" role="context" start="35" end="38">
pub struct SupplementaryVaultData {
pub customer_id: Option<id_type::CustomerId>,
pub payment_method_id: Option<String>,
}
<file_sep path="hyperswitch/crates/router/src/compatibility/stripe/customers/types.rs" role="context" start="202" end="207">
pub struct PaymentMethodData {
pub id: Option<String>,
pub object: &'static str,
pub card: Option<CardDetails>,
pub created: Option<time::PrimitiveDateTime>,
}
<file_sep path="hyperswitch/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/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/cards_info.rs<|crate|> router anchor=migrate_cards_info kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/cards_info.rs" role="context" start="138" end="155">
pub async fn migrate_cards_info(
state: routes::SessionState,
card_info_records: Vec<cards_info_api_types::CardInfoUpdateRequest>,
) -> RouterResponse<Vec<cards_info_api_types::CardInfoMigrationResponse>> {
let mut result = Vec::new();
for record in card_info_records {
let res = card_info_flow(record.clone(), state.clone()).await;
result.push(cards_info_api_types::CardInfoMigrationResponse::from((
match res {
Ok(ApplicationResponse::Json(response)) => Ok(response),
Err(e) => Err(e.to_string()),
_ => Err("Failed to migrate card info".to_string()),
},
record,
)));
}
Ok(ApplicationResponse::Json(result))
}
<file_sep path="hyperswitch/crates/router/src/core/cards_info.rs" role="context" start="137" end="137">
use api_models::cards_info as cards_info_api_types;
use crate::{
core::{
errors::{self, RouterResponse, RouterResult, StorageErrorExt},
payments::helpers,
},
db::cards_info::CardsInfoInterface,
routes,
services::ApplicationResponse,
types::{
domain,
transformers::{ForeignFrom, ForeignInto},
},
};
<file_sep path="hyperswitch/crates/router/src/core/cards_info.rs" role="context" start="190" end="197">
async fn fetch_card_info(&self) -> RouterResult<Option<card_info_models::CardInfo>> {
let db = self.state.store.as_ref();
let maybe_card_info = db
.get_card_info(&self.record.card_iin)
.await
.change_context(errors::ApiErrorResponse::InvalidCardIin)?;
Ok(maybe_card_info)
}
<file_sep path="hyperswitch/crates/router/src/core/cards_info.rs" role="context" start="183" end="188">
fn new(
state: &'a routes::SessionState,
record: &'a cards_info_api_types::CardInfoUpdateRequest,
) -> Self {
Self { state, record }
}
<file_sep path="hyperswitch/crates/router/src/core/cards_info.rs" role="context" start="126" end="135">
pub fn get_cards_bin_records(
form: CardsInfoUpdateForm,
) -> Result<Vec<cards_info_api_types::CardInfoUpdateRequest>, errors::ApiErrorResponse> {
match parse_cards_bin_csv(form.file.data.to_bytes()) {
Ok(records) => Ok(records),
Err(e) => Err(errors::ApiErrorResponse::PreconditionFailed {
message: e.to_string(),
}),
}
}
<file_sep path="hyperswitch/crates/router/src/core/cards_info.rs" role="context" start="111" end="124">
fn parse_cards_bin_csv(
data: &[u8],
) -> csv::Result<Vec<cards_info_api_types::CardInfoUpdateRequest>> {
let mut csv_reader = Reader::from_reader(data);
let mut records = Vec::new();
let mut id_counter = 0;
for result in csv_reader.deserialize() {
let mut record: cards_info_api_types::CardInfoUpdateRequest = result?;
id_counter += 1;
record.line_number = Some(id_counter);
records.push(record);
}
Ok(records)
}
<file_sep path="hyperswitch/crates/router/src/core/cards_info.rs" role="context" start="243" end="248">
fn new() -> Self {
Self {
state: std::marker::PhantomData,
card_info: None,
}
}
<file_sep path="hyperswitch/crates/router/src/core/cards_info.rs" role="context" start="317" end="339">
async fn card_info_flow(
record: cards_info_api_types::CardInfoUpdateRequest,
state: routes::SessionState,
) -> RouterResponse<cards_info_api_types::CardInfoMigrateResponseRecord> {
let builder = CardInfoBuilder::new();
let executor = CardInfoMigrateExecutor::new(&state, &record);
let fetched_card_info_details = executor.fetch_card_info().await?;
let builder = match fetched_card_info_details {
Some(card_info) => {
let builder = builder.set_card_info(card_info);
let updated_card_info = executor.update_card_info().await?;
builder.set_updated_card_info(updated_card_info)
}
None => {
let builder = builder.transition();
let added_card_info = executor.add_card_info().await?;
builder.set_added_card_info(added_card_info)
}
};
Ok(ApplicationResponse::Json(builder.build()))
}
<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/cards_info.rs" role="context" start="63" end="75">
pub struct CardInfoUpdateRequest {
pub card_iin: String,
pub card_issuer: Option<String>,
pub card_network: Option<enums::CardNetwork>,
pub card_type: Option<String>,
pub card_subtype: Option<String>,
pub card_issuing_country: Option<String>,
pub bank_code_id: Option<String>,
pub bank_code: Option<String>,
pub country_code: Option<String>,
pub last_updated_provider: Option<String>,
pub line_number: Option<i64>,
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payments/retry.rs<|crate|> router anchor=get_gsm kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/payments/retry.rs" role="context" start="265" end="278">
pub async fn get_gsm<F, FData>(
state: &app::SessionState,
router_data: &types::RouterData<F, FData, types::PaymentsResponseData>,
) -> RouterResult<Option<storage::gsm::GatewayStatusMap>> {
let error_response = router_data.response.as_ref().err();
let error_code = error_response.map(|err| err.code.to_owned());
let error_message = error_response.map(|err| err.message.to_owned());
let connector_name = router_data.connector.to_string();
let flow = get_flow_name::<F>()?;
Ok(
payments::helpers::get_gsm_record(state, error_code, error_message, connector_name, flow)
.await,
)
}
<file_sep path="hyperswitch/crates/router/src/core/payments/retry.rs" role="context" start="264" end="264">
use common_utils::{ext_traits::Encode, types::MinorUnit};
use crate::{
core::{
errors::{self, RouterResult, StorageErrorExt},
payments::{
self,
flows::{ConstructFlowSpecificData, Feature},
operations,
},
},
db::StorageInterface,
routes::{
self,
app::{self, ReqState},
metrics,
},
services,
types::{self, api, domain, storage},
};
<file_sep path="hyperswitch/crates/router/src/core/payments/retry.rs" role="context" start="303" end="311">
fn get_flow_name<F>() -> RouterResult<String> {
Ok(std::any::type_name::<F>()
.to_string()
.rsplit("::")
.next()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Flow stringify failed")?
.to_string())
}
<file_sep path="hyperswitch/crates/router/src/core/payments/retry.rs" role="context" start="281" end="300">
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_RETRY_GSM_MATCH_COUNT.add(1, &[]);
}
option_gsm_decision.unwrap_or_default()
}
<file_sep path="hyperswitch/crates/router/src/core/payments/retry.rs" role="context" start="250" end="262">
pub async fn get_retries(
state: &app::SessionState,
retries: Option<i32>,
merchant_id: &common_utils::id_type::MerchantId,
profile: &domain::Profile,
) -> Option<i32> {
match retries {
Some(retries) => Some(retries),
None => get_merchant_max_auto_retries_enabled(state.store.as_ref(), merchant_id)
.await
.or(profile.max_auto_retries_enabled.map(i32::from)),
}
}
<file_sep path="hyperswitch/crates/router/src/core/payments/retry.rs" role="context" start="225" end="246">
pub async fn get_merchant_max_auto_retries_enabled(
db: &dyn StorageInterface,
merchant_id: &common_utils::id_type::MerchantId,
) -> Option<i32> {
let key = merchant_id.get_max_auto_retries_enabled();
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/payments/retry.rs" role="context" start="403" end="608">
pub async fn modify_trackers<F, FData, D>(
state: &routes::SessionState,
connector: String,
payment_data: &mut D,
key_store: &domain::MerchantKeyStore,
storage_scheme: storage_enums::MerchantStorageScheme,
router_data: types::RouterData<F, FData, types::PaymentsResponseData>,
is_step_up: bool,
) -> RouterResult<()>
where
F: Clone + Send,
FData: Send,
D: payments::OperationSessionGetters<F> + payments::OperationSessionSetters<F> + Send + Sync,
{
let new_attempt_count = payment_data.get_payment_intent().attempt_count + 1;
let new_payment_attempt = make_new_payment_attempt(
connector,
payment_data.get_payment_attempt().clone(),
new_attempt_count,
is_step_up,
);
let db = &*state.store;
let key_manager_state = &state.into();
let additional_payment_method_data =
payments::helpers::update_additional_payment_data_with_connector_response_pm_data(
payment_data
.get_payment_attempt()
.payment_method_data
.clone(),
router_data
.connector_response
.clone()
.and_then(|connector_response| connector_response.additional_payment_method_data),
)?;
match router_data.response {
Ok(types::PaymentsResponseData::TransactionResponse {
resource_id,
connector_metadata,
redirection_data,
charges,
..
}) => {
let encoded_data = payment_data.get_payment_attempt().encoded_data.clone();
let authentication_data = (*redirection_data)
.as_ref()
.map(Encode::encode_to_value)
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Could not parse the connector response")?;
let payment_attempt_update = storage::PaymentAttemptUpdate::ResponseUpdate {
status: router_data.status,
connector: None,
connector_transaction_id: match resource_id {
types::ResponseId::NoResponseId => None,
types::ResponseId::ConnectorTransactionId(id)
| types::ResponseId::EncodedData(id) => Some(id),
},
connector_response_reference_id: payment_data
.get_payment_attempt()
.connector_response_reference_id
.clone(),
authentication_type: None,
payment_method_id: payment_data.get_payment_attempt().payment_method_id.clone(),
mandate_id: payment_data
.get_mandate_id()
.and_then(|mandate| mandate.mandate_id.clone()),
connector_metadata,
payment_token: None,
error_code: None,
error_message: None,
error_reason: None,
amount_capturable: if router_data.status.is_terminal_status() {
Some(MinorUnit::new(0))
} else {
None
},
updated_by: storage_scheme.to_string(),
authentication_data,
encoded_data,
unified_code: None,
unified_message: None,
capture_before: None,
extended_authorization_applied: None,
payment_method_data: additional_payment_method_data,
connector_mandate_detail: None,
charges,
};
#[cfg(feature = "v1")]
db.update_payment_attempt_with_attempt_id(
payment_data.get_payment_attempt().clone(),
payment_attempt_update,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
#[cfg(feature = "v2")]
db.update_payment_attempt_with_attempt_id(
key_manager_state,
key_store,
payment_data.get_payment_attempt().clone(),
payment_attempt_update,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
}
Ok(_) => {
logger::error!("unexpected response: this response was not expected in Retry flow");
return Ok(());
}
Err(ref error_response) => {
let option_gsm = get_gsm(state, &router_data).await?;
let auth_update = if Some(router_data.auth_type)
!= payment_data.get_payment_attempt().authentication_type
{
Some(router_data.auth_type)
} else {
None
};
let payment_attempt_update = storage::PaymentAttemptUpdate::ErrorUpdate {
connector: None,
error_code: Some(Some(error_response.code.clone())),
error_message: Some(Some(error_response.message.clone())),
status: storage_enums::AttemptStatus::Failure,
error_reason: Some(error_response.reason.clone()),
amount_capturable: Some(MinorUnit::new(0)),
updated_by: storage_scheme.to_string(),
unified_code: option_gsm.clone().map(|gsm| gsm.unified_code),
unified_message: option_gsm.map(|gsm| gsm.unified_message),
connector_transaction_id: error_response.connector_transaction_id.clone(),
payment_method_data: additional_payment_method_data,
authentication_type: auth_update,
issuer_error_code: error_response.network_decline_code.clone(),
issuer_error_message: error_response.network_error_message.clone(),
};
#[cfg(feature = "v1")]
db.update_payment_attempt_with_attempt_id(
payment_data.get_payment_attempt().clone(),
payment_attempt_update,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
#[cfg(feature = "v2")]
db.update_payment_attempt_with_attempt_id(
key_manager_state,
key_store,
payment_data.get_payment_attempt().clone(),
payment_attempt_update,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
}
}
#[cfg(feature = "v1")]
let payment_attempt = db
.insert_payment_attempt(new_payment_attempt, storage_scheme)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error inserting payment attempt")?;
#[cfg(feature = "v2")]
let payment_attempt = db
.insert_payment_attempt(
key_manager_state,
key_store,
new_payment_attempt,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error inserting payment attempt")?;
// update payment_attempt, connector_response and payment_intent in payment_data
payment_data.set_payment_attempt(payment_attempt);
let payment_intent = db
.update_payment_intent(
key_manager_state,
payment_data.get_payment_intent().clone(),
storage::PaymentIntentUpdate::PaymentAttemptAndAttemptCountUpdate {
active_attempt_id: payment_data.get_payment_attempt().get_id().to_owned(),
attempt_count: new_attempt_count,
updated_by: storage_scheme.to_string(),
},
key_store,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
payment_data.set_payment_intent(payment_intent);
Ok(())
}
<file_sep path="hyperswitch/crates/router/src/core/payments/retry.rs" role="context" start="33" end="198">
pub async fn do_gsm_actions<F, ApiRequest, FData, D>(
state: &app::SessionState,
req_state: ReqState,
payment_data: &mut D,
mut connectors: IntoIter<api::ConnectorData>,
original_connector_data: &api::ConnectorData,
mut router_data: types::RouterData<F, FData, types::PaymentsResponseData>,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
operation: &operations::BoxedOperation<'_, F, ApiRequest, D>,
customer: &Option<domain::Customer>,
validate_result: &operations::ValidateResult,
schedule_time: Option<time::PrimitiveDateTime>,
frm_suggestion: Option<storage_enums::FrmSuggestion>,
business_profile: &domain::Profile,
) -> RouterResult<types::RouterData<F, FData, types::PaymentsResponseData>>
where
F: Clone + Send + Sync,
FData: Send + Sync,
payments::PaymentResponse: operations::Operation<F, FData>,
D: payments::OperationSessionGetters<F>
+ payments::OperationSessionSetters<F>
+ Send
+ Sync
+ Clone,
D: ConstructFlowSpecificData<F, FData, types::PaymentsResponseData>,
types::RouterData<F, FData, types::PaymentsResponseData>: Feature<F, FData>,
dyn api::Connector: services::api::ConnectorIntegration<F, FData, types::PaymentsResponseData>,
{
let mut retries = None;
metrics::AUTO_RETRY_ELIGIBLE_REQUEST_COUNT.add(1, &[]);
let mut initial_gsm = get_gsm(state, &router_data).await?;
//Check if step-up to threeDS is possible and merchant has enabled
let step_up_possible = initial_gsm
.clone()
.map(|gsm| gsm.step_up_possible)
.unwrap_or(false);
#[cfg(feature = "v1")]
let is_no_three_ds_payment = matches!(
payment_data.get_payment_attempt().authentication_type,
Some(storage_enums::AuthenticationType::NoThreeDs)
);
#[cfg(feature = "v2")]
let is_no_three_ds_payment = matches!(
payment_data.get_payment_attempt().authentication_type,
storage_enums::AuthenticationType::NoThreeDs
);
let should_step_up = if step_up_possible && is_no_three_ds_payment {
is_step_up_enabled_for_merchant_connector(
state,
merchant_account.get_id(),
original_connector_data.connector_name,
)
.await
} else {
false
};
if should_step_up {
router_data = do_retry(
&state.clone(),
req_state.clone(),
original_connector_data,
operation,
customer,
merchant_account,
key_store,
payment_data,
router_data,
validate_result,
schedule_time,
true,
frm_suggestion,
business_profile,
false, //should_retry_with_pan is not applicable for step-up
)
.await?;
}
// Step up is not applicable so proceed with auto retries flow
else {
loop {
// Use initial_gsm for first time alone
let gsm = match initial_gsm.as_ref() {
Some(gsm) => Some(gsm.clone()),
None => get_gsm(state, &router_data).await?,
};
match get_gsm_decision(gsm) {
api_models::gsm::GsmDecision::Retry => {
retries =
get_retries(state, retries, merchant_account.get_id(), business_profile)
.await;
if retries.is_none() || retries == Some(0) {
metrics::AUTO_RETRY_EXHAUSTED_COUNT.add(1, &[]);
logger::info!("retries exhausted for auto_retry payment");
break;
}
if connectors.len() == 0 {
logger::info!("connectors exhausted for auto_retry payment");
metrics::AUTO_RETRY_EXHAUSTED_COUNT.add(1, &[]);
break;
}
let is_network_token = payment_data
.get_payment_method_data()
.map(|pmd| pmd.is_network_token_payment_method_data())
.unwrap_or(false);
let should_retry_with_pan = is_network_token
&& initial_gsm
.as_ref()
.map(|gsm| gsm.clear_pan_possible)
.unwrap_or(false)
&& business_profile.is_clear_pan_retries_enabled;
let connector = if should_retry_with_pan {
// If should_retry_with_pan is true, it indicates that we are retrying with PAN using the same connector.
original_connector_data.clone()
} else {
super::get_connector_data(&mut connectors)?
};
router_data = do_retry(
&state.clone(),
req_state.clone(),
&connector,
operation,
customer,
merchant_account,
key_store,
payment_data,
router_data,
validate_result,
schedule_time,
//this is an auto retry payment, but not step-up
false,
frm_suggestion,
business_profile,
should_retry_with_pan,
)
.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,
}
initial_gsm = None;
}
}
Ok(router_data)
}
<file_sep path="hyperswitch/crates/router/src/connector/utils.rs" role="context" start="82" end="146">
pub trait RouterData {
fn get_billing(&self) -> Result<&hyperswitch_domain_models::address::Address, Error>;
fn get_billing_country(&self) -> Result<api_models::enums::CountryAlpha2, Error>;
fn get_billing_phone(&self)
-> Result<&hyperswitch_domain_models::address::PhoneDetails, Error>;
fn get_description(&self) -> Result<String, Error>;
fn get_billing_address(
&self,
) -> Result<&hyperswitch_domain_models::address::AddressDetails, Error>;
fn get_shipping_address(
&self,
) -> Result<&hyperswitch_domain_models::address::AddressDetails, Error>;
fn get_shipping_address_with_phone_number(
&self,
) -> Result<&hyperswitch_domain_models::address::Address, Error>;
fn get_connector_meta(&self) -> Result<pii::SecretSerdeValue, Error>;
fn get_session_token(&self) -> Result<String, Error>;
fn get_billing_first_name(&self) -> Result<Secret<String>, Error>;
fn get_billing_full_name(&self) -> Result<Secret<String>, Error>;
fn get_billing_last_name(&self) -> Result<Secret<String>, Error>;
fn get_billing_line1(&self) -> Result<Secret<String>, Error>;
fn get_billing_city(&self) -> Result<String, Error>;
fn get_billing_email(&self) -> Result<Email, Error>;
fn get_billing_phone_number(&self) -> Result<Secret<String>, Error>;
fn to_connector_meta<T>(&self) -> Result<T, Error>
where
T: serde::de::DeserializeOwned;
fn is_three_ds(&self) -> bool;
fn get_payment_method_token(&self) -> Result<types::PaymentMethodToken, Error>;
fn get_customer_id(&self) -> Result<id_type::CustomerId, Error>;
fn get_connector_customer_id(&self) -> Result<String, Error>;
fn get_preprocessing_id(&self) -> Result<String, Error>;
fn get_recurring_mandate_payment_data(
&self,
) -> Result<types::RecurringMandatePaymentData, Error>;
#[cfg(feature = "payouts")]
fn get_payout_method_data(&self) -> Result<api::PayoutMethodData, Error>;
#[cfg(feature = "payouts")]
fn get_quote_id(&self) -> Result<String, Error>;
fn get_optional_billing(&self) -> Option<&hyperswitch_domain_models::address::Address>;
fn get_optional_shipping(&self) -> Option<&hyperswitch_domain_models::address::Address>;
fn get_optional_shipping_line1(&self) -> Option<Secret<String>>;
fn get_optional_shipping_line2(&self) -> Option<Secret<String>>;
fn get_optional_shipping_city(&self) -> Option<String>;
fn get_optional_shipping_country(&self) -> Option<enums::CountryAlpha2>;
fn get_optional_shipping_zip(&self) -> Option<Secret<String>>;
fn get_optional_shipping_state(&self) -> Option<Secret<String>>;
fn get_optional_shipping_first_name(&self) -> Option<Secret<String>>;
fn get_optional_shipping_last_name(&self) -> Option<Secret<String>>;
fn get_optional_shipping_phone_number(&self) -> Option<Secret<String>>;
fn get_optional_shipping_email(&self) -> Option<Email>;
fn get_optional_billing_full_name(&self) -> Option<Secret<String>>;
fn get_optional_billing_line1(&self) -> Option<Secret<String>>;
fn get_optional_billing_line2(&self) -> Option<Secret<String>>;
fn get_optional_billing_city(&self) -> Option<String>;
fn get_optional_billing_country(&self) -> Option<enums::CountryAlpha2>;
fn get_optional_billing_zip(&self) -> Option<Secret<String>>;
fn get_optional_billing_state(&self) -> Option<Secret<String>>;
fn get_optional_billing_first_name(&self) -> Option<Secret<String>>;
fn get_optional_billing_last_name(&self) -> Option<Secret<String>>;
fn get_optional_billing_phone_number(&self) -> Option<Secret<String>>;
fn get_optional_billing_email(&self) -> Option<Email>;
}
<file_sep path="hyperswitch/migrations/2024-11-24-104438_add_error_category_col_to_gsm/up.sql" role="context" start="1" end="2">
-- Your SQL goes here
ALTER TABLE gateway_status_map ADD COLUMN error_category 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/vault.rs<|crate|> router anchor=get_payout_method_data_from_temporary_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/vault.rs" role="context" start="938" end="951">
pub async fn get_payout_method_data_from_temporary_locker(
state: &routes::SessionState,
lookup_key: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> RouterResult<(Option<api::PayoutMethodData>, SupplementaryVaultData)> {
let de_tokenize =
get_tokenized_data(state, lookup_key, true, merchant_key_store.key.get_inner()).await?;
let (payout_method, supp_data) =
api::PayoutMethodData::from_values(de_tokenize.value1, de_tokenize.value2)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error parsing Payout Method from Values")?;
Ok((Some(payout_method), supp_data))
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/vault.rs" role="context" start="937" end="937">
use crate::types::api::payouts;
use crate::{
consts,
core::errors::{self, CustomResult, RouterResult},
db, logger, routes,
routes::metrics,
types::{
api, domain,
storage::{self, enums},
},
utils::StringExt,
};
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/vault.rs" role="context" start="989" end="1000">
pub async fn delete_locker_payment_method_by_lookup_key(
state: &routes::SessionState,
lookup_key: &Option<String>,
) {
if let Some(lookup_key) = lookup_key {
delete_tokenized_data(state, lookup_key)
.await
.map(|_| logger::info!("Card From locker deleted Successfully"))
.map_err(|err| logger::error!("Error: Deleting Card From Redis Locker : {:?}", err))
.ok();
}
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/vault.rs" role="context" start="955" end="986">
pub async fn store_payout_method_data_in_locker(
state: &routes::SessionState,
token_id: Option<String>,
payout_method: &api::PayoutMethodData,
customer_id: Option<id_type::CustomerId>,
merchant_key_store: &domain::MerchantKeyStore,
) -> RouterResult<String> {
let value1 = payout_method
.get_value1(customer_id.clone())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error getting Value1 for locker")?;
let value2 = payout_method
.get_value2(customer_id)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error getting Value2 for locker")?;
let lookup_key =
token_id.unwrap_or_else(|| generate_id_with_default_len("temporary_token"));
let lookup_key = create_tokenize(
state,
value1,
Some(value2),
lookup_key,
merchant_key_store.key.get_inner(),
)
.await?;
// add_delete_tokenized_data_task(&*state.store, &lookup_key, pm).await?;
// scheduler_metrics::TOKENIZED_DATA_COUNT.add(1, &[]);
Ok(lookup_key)
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/vault.rs" role="context" start="903" end="934">
pub async fn store_payment_method_data_in_locker(
state: &routes::SessionState,
token_id: Option<String>,
payment_method: &domain::PaymentMethodData,
customer_id: Option<id_type::CustomerId>,
pm: enums::PaymentMethod,
merchant_key_store: &domain::MerchantKeyStore,
) -> RouterResult<String> {
let value1 = payment_method
.get_value1(customer_id.clone())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error getting Value1 for locker")?;
let value2 = payment_method
.get_value2(customer_id)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error getting Value12 for locker")?;
let lookup_key = token_id.unwrap_or_else(|| generate_id_with_default_len("token"));
let lookup_key = create_tokenize(
state,
value1,
Some(value2),
lookup_key,
merchant_key_store.key.get_inner(),
)
.await?;
add_delete_tokenized_data_task(&*state.store, &lookup_key, pm).await?;
metrics::TOKENIZED_DATA_COUNT.add(1, &[]);
Ok(lookup_key)
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/vault.rs" role="context" start="887" end="900">
pub async fn get_payment_method_data_from_locker(
state: &routes::SessionState,
lookup_key: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> RouterResult<(Option<domain::PaymentMethodData>, SupplementaryVaultData)> {
let de_tokenize =
get_tokenized_data(state, lookup_key, true, merchant_key_store.key.get_inner()).await?;
let (payment_method, customer_id) =
domain::PaymentMethodData::from_values(de_tokenize.value1, de_tokenize.value2)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error parsing Payment Method from Values")?;
Ok((Some(payment_method), customer_id))
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/vault.rs" role="context" start="844" end="874">
fn from_values(
value1: String,
value2: String,
) -> CustomResult<(Self, SupplementaryVaultData), errors::VaultError> {
let value1: VaultPayoutMethod = value1
.parse_struct("VaultMethodValue1")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Could not deserialize into vault method value 1")?;
let value2: VaultPayoutMethod = value2
.parse_struct("VaultMethodValue2")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Could not deserialize into vault method value 2")?;
match (value1, value2) {
(VaultPayoutMethod::Card(mvalue1), VaultPayoutMethod::Card(mvalue2)) => {
let (card, supp_data) = api::CardPayout::from_values(mvalue1, mvalue2)?;
Ok((Self::Card(card), supp_data))
}
(VaultPayoutMethod::Bank(mvalue1), VaultPayoutMethod::Bank(mvalue2)) => {
let (bank, supp_data) = api::BankPayout::from_values(mvalue1, mvalue2)?;
Ok((Self::Bank(bank), supp_data))
}
(VaultPayoutMethod::Wallet(mvalue1), VaultPayoutMethod::Wallet(mvalue2)) => {
let (wallet, supp_data) = api::WalletPayout::from_values(mvalue1, mvalue2)?;
Ok((Self::Wallet(wallet), supp_data))
}
_ => Err(errors::VaultError::PayoutMethodNotSupported)
.attach_printable("Payout method not supported"),
}
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/vault.rs" role="context" start="1076" end="1138">
pub async fn get_tokenized_data(
state: &routes::SessionState,
lookup_key: &str,
_should_get_value2: bool,
encryption_key: &masking::Secret<Vec<u8>>,
) -> RouterResult<api::TokenizePayloadRequest> {
let redis_key = get_redis_locker_key(lookup_key);
let func = || async {
metrics::GET_TOKENIZED_CARD.add(1, &[]);
let redis_conn = state
.store
.get_redis_conn()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get redis connection")?;
let response = redis_conn
.get_key::<bytes::Bytes>(&redis_key.as_str().into())
.await;
match response {
Ok(resp) => {
let decrypted_payload = GcmAes256
.decode_message(
encryption_key.peek().as_ref(),
masking::Secret::new(resp.into()),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to decode redis temp locker data")?;
let get_response: api::TokenizePayloadRequest =
bytes::Bytes::from(decrypted_payload)
.parse_struct("TokenizePayloadRequest")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Error getting TokenizePayloadRequest from tokenize response",
)?;
Ok(get_response)
}
Err(err) => {
metrics::TEMP_LOCKER_FAILURES.add(1, &[]);
Err(err).change_context(errors::ApiErrorResponse::UnprocessableEntity {
message: "Token is invalid or expired".into(),
})
}
}
};
match func().await {
Ok(s) => {
logger::info!(
"Fetch payload in redis locker successful with lookup key: {:?}",
redis_key
);
Ok(s)
}
Err(err) => {
logger::error!("Redis Temp locker Failed: {:?}", err);
Err(err)
}
}
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/vault.rs" role="context" start="35" end="38">
pub struct SupplementaryVaultData {
pub customer_id: Option<id_type::CustomerId>,
pub payment_method_id: Option<String>,
}
<file_sep path="hyperswitch/crates/router/tests/utils.rs" role="context" start="399" end="401">
pub struct Error {
pub message: Message,
}
<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/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/helpers.rs<|crate|> router anchor=decide_payment_method_retrieval_action kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="1993" end="2014">
pub fn decide_payment_method_retrieval_action(
is_network_tokenization_enabled: bool,
mandate_id: Option<api_models::payments::MandateIds>,
connector: Option<api_enums::Connector>,
network_tokenization_supported_connectors: &HashSet<api_enums::Connector>,
should_retry_with_pan: bool,
network_token_requestor_ref_id: Option<String>,
) -> VaultFetchAction {
let standard_flow = || {
determine_standard_vault_action(
is_network_tokenization_enabled,
mandate_id,
connector,
network_tokenization_supported_connectors,
network_token_requestor_ref_id,
)
};
should_retry_with_pan
.then_some(VaultFetchAction::FetchCardDetailsFromLocker)
.unwrap_or_else(standard_flow)
}
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="1992" end="1992">
) -> RouterResult<domain::PaymentMethodData> {
todo!()
}
pub enum VaultFetchAction {
FetchCardDetailsFromLocker,
FetchCardDetailsForNetworkTransactionIdFlowFromLocker,
FetchNetworkTokenDataFromTokenizationService(String),
FetchNetworkTokenDetailsFromLocker(api_models::payments::NetworkTokenWithNTIRef),
NoFetchAction,
}
pub fn decide_payment_method_retrieval_action(
is_network_tokenization_enabled: bool,
mandate_id: Option<api_models::payments::MandateIds>,
connector: Option<api_enums::Connector>,
network_tokenization_supported_connectors: &HashSet<api_enums::Connector>,
should_retry_with_pan: bool,
network_token_requestor_ref_id: Option<String>,
) -> VaultFetchAction {
let standard_flow = || {
determine_standard_vault_action(
is_network_tokenization_enabled,
mandate_id,
connector,
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="2074" end="2220">
pub async fn retrieve_payment_method_data_with_permanent_token(
state: &SessionState,
locker_id: &str,
_payment_method_id: &str,
payment_intent: &PaymentIntent,
card_token_data: Option<&domain::CardToken>,
_merchant_key_store: &domain::MerchantKeyStore,
_storage_scheme: enums::MerchantStorageScheme,
mandate_id: Option<api_models::payments::MandateIds>,
payment_method_info: domain::PaymentMethod,
business_profile: &domain::Profile,
connector: Option<String>,
should_retry_with_pan: bool,
vault_data: Option<&domain_payments::VaultData>,
) -> RouterResult<domain::PaymentMethodData> {
let customer_id = payment_intent
.customer_id
.as_ref()
.get_required_value("customer_id")
.change_context(errors::ApiErrorResponse::UnprocessableEntity {
message: "no customer id provided for the payment".to_string(),
})?;
let network_tokenization_supported_connectors = &state
.conf
.network_tokenization_supported_connectors
.connector_list;
let connector_variant = connector
.as_ref()
.map(|conn| {
api_enums::Connector::from_str(conn.as_str())
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "connector",
})
.attach_printable_lazy(|| format!("unable to parse connector name {connector:?}"))
})
.transpose()?;
let vault_fetch_action = decide_payment_method_retrieval_action(
business_profile.is_network_tokenization_enabled,
mandate_id,
connector_variant,
network_tokenization_supported_connectors,
should_retry_with_pan,
payment_method_info
.network_token_requestor_reference_id
.clone(),
);
match vault_fetch_action {
VaultFetchAction::FetchCardDetailsFromLocker => {
let card = vault_data
.and_then(|vault_data| vault_data.get_card_vault_data())
.map(Ok)
.async_unwrap_or_else(|| async {
fetch_card_details_from_locker(
state,
customer_id,
&payment_intent.merchant_id,
locker_id,
card_token_data,
)
.await
})
.await?;
Ok(domain::PaymentMethodData::Card(card))
}
VaultFetchAction::FetchCardDetailsForNetworkTransactionIdFlowFromLocker => {
fetch_card_details_for_network_transaction_flow_from_locker(
state,
customer_id,
&payment_intent.merchant_id,
locker_id,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed to fetch card information from the permanent locker")
}
VaultFetchAction::FetchNetworkTokenDataFromTokenizationService(
network_token_requestor_ref_id,
) => {
logger::info!("Fetching network token data from tokenization service");
match network_tokenization::get_token_from_tokenization_service(
state,
network_token_requestor_ref_id,
&payment_method_info,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed to fetch network token data from tokenization service")
{
Ok(network_token_data) => {
Ok(domain::PaymentMethodData::NetworkToken(network_token_data))
}
Err(err) => {
logger::info!(
"Failed to fetch network token data from tokenization service {err:?}"
);
logger::info!("Falling back to fetch card details from locker");
Ok(domain::PaymentMethodData::Card(
vault_data
.and_then(|vault_data| vault_data.get_card_vault_data())
.map(Ok)
.async_unwrap_or_else(|| async {
fetch_card_details_from_locker(
state,
customer_id,
&payment_intent.merchant_id,
locker_id,
card_token_data,
)
.await
})
.await?,
))
}
}
}
VaultFetchAction::FetchNetworkTokenDetailsFromLocker(nt_data) => {
if let Some(network_token_locker_id) =
payment_method_info.network_token_locker_id.as_ref()
{
let network_token_data = vault_data
.and_then(|vault_data| vault_data.get_network_token_data())
.map(Ok)
.async_unwrap_or_else(|| async {
fetch_network_token_details_from_locker(
state,
customer_id,
&payment_intent.merchant_id,
network_token_locker_id,
nt_data,
)
.await
})
.await?;
Ok(domain::PaymentMethodData::NetworkToken(network_token_data))
} else {
Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Network token locker id is not present")
}
}
VaultFetchAction::NoFetchAction => Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Payment method data is not present"),
}
}
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="2016" end="2067">
pub fn determine_standard_vault_action(
is_network_tokenization_enabled: bool,
mandate_id: Option<api_models::payments::MandateIds>,
connector: Option<api_enums::Connector>,
network_tokenization_supported_connectors: &HashSet<api_enums::Connector>,
network_token_requestor_ref_id: Option<String>,
) -> VaultFetchAction {
let is_network_transaction_id_flow = mandate_id
.as_ref()
.map(|mandate_ids| mandate_ids.is_network_transaction_id_flow())
.unwrap_or(false);
if !is_network_tokenization_enabled {
if is_network_transaction_id_flow {
VaultFetchAction::FetchCardDetailsForNetworkTransactionIdFlowFromLocker
} else {
VaultFetchAction::FetchCardDetailsFromLocker
}
} else {
match mandate_id {
Some(mandate_ids) => match mandate_ids.mandate_reference_id {
Some(api_models::payments::MandateReferenceId::NetworkTokenWithNTI(nt_data)) => {
VaultFetchAction::FetchNetworkTokenDetailsFromLocker(nt_data)
}
Some(api_models::payments::MandateReferenceId::NetworkMandateId(_)) => {
VaultFetchAction::FetchCardDetailsForNetworkTransactionIdFlowFromLocker
}
Some(api_models::payments::MandateReferenceId::ConnectorMandateId(_)) | None => {
VaultFetchAction::NoFetchAction
}
},
None => {
//saved card flow
let is_network_token_supported_connector = connector
.map(|conn| network_tokenization_supported_connectors.contains(&conn))
.unwrap_or(false);
match (
is_network_token_supported_connector,
network_token_requestor_ref_id,
) {
(true, Some(ref_id)) => {
VaultFetchAction::FetchNetworkTokenDataFromTokenizationService(ref_id)
}
(false, Some(_)) | (true, None) | (false, None) => {
VaultFetchAction::FetchCardDetailsFromLocker
}
}
}
}
}
}
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="1973" end="1983">
pub async fn retrieve_card_with_permanent_token(
state: &SessionState,
locker_id: &str,
_payment_method_id: &id_type::GlobalPaymentMethodId,
payment_intent: &PaymentIntent,
card_token_data: Option<&domain::CardToken>,
_merchant_key_store: &domain::MerchantKeyStore,
_storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<domain::PaymentMethodData> {
todo!()
}
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="1848" end="1970">
pub async fn retrieve_payment_method_with_temporary_token(
state: &SessionState,
token: &str,
payment_intent: &PaymentIntent,
payment_attempt: &PaymentAttempt,
merchant_key_store: &domain::MerchantKeyStore,
card_token_data: Option<&domain::CardToken>,
) -> RouterResult<Option<(domain::PaymentMethodData, enums::PaymentMethod)>> {
let (pm, supplementary_data) =
vault::Vault::get_payment_method_data_from_locker(state, token, merchant_key_store)
.await
.attach_printable(
"Payment method for given token not found or there was a problem fetching it",
)?;
utils::when(
supplementary_data
.customer_id
.ne(&payment_intent.customer_id),
|| {
Err(errors::ApiErrorResponse::PreconditionFailed { message: "customer associated with payment method and customer passed in payment are not same".into() })
},
)?;
Ok::<_, error_stack::Report<errors::ApiErrorResponse>>(match pm {
Some(domain::PaymentMethodData::Card(card)) => {
let mut updated_card = card.clone();
let mut is_card_updated = false;
// The card_holder_name from locker retrieved card is considered if it is a non-empty string or else card_holder_name is picked
// from payment_method_data.card_token object
let name_on_card =
card_token_data.and_then(|token_data| token_data.card_holder_name.clone());
if let Some(name) = name_on_card.clone() {
if !name.peek().is_empty() {
is_card_updated = true;
updated_card.nick_name = name_on_card;
}
}
if let Some(token_data) = card_token_data {
if let Some(cvc) = token_data.card_cvc.clone() {
is_card_updated = true;
updated_card.card_cvc = cvc;
}
}
// populate additional card details from payment_attempt.payment_method_data (additional_payment_data) if not present in the locker
if updated_card.card_issuer.is_none()
|| updated_card.card_network.is_none()
|| updated_card.card_type.is_none()
|| updated_card.card_issuing_country.is_none()
{
let additional_payment_method_data: Option<
api_models::payments::AdditionalPaymentData,
> = payment_attempt
.payment_method_data
.clone()
.and_then(|data| match data {
serde_json::Value::Null => None, // This is to handle the case when the payment_method_data is null
_ => Some(data.parse_value("AdditionalPaymentData")),
})
.transpose()
.map_err(|err| logger::error!("Failed to parse AdditionalPaymentData {err:?}"))
.ok()
.flatten();
if let Some(api_models::payments::AdditionalPaymentData::Card(card)) =
additional_payment_method_data
{
is_card_updated = true;
updated_card.card_issuer = updated_card.card_issuer.or(card.card_issuer);
updated_card.card_network = updated_card.card_network.or(card.card_network);
updated_card.card_type = updated_card.card_type.or(card.card_type);
updated_card.card_issuing_country = updated_card
.card_issuing_country
.or(card.card_issuing_country);
};
};
if is_card_updated {
let updated_pm = domain::PaymentMethodData::Card(updated_card);
vault::Vault::store_payment_method_data_in_locker(
state,
Some(token.to_owned()),
&updated_pm,
payment_intent.customer_id.to_owned(),
enums::PaymentMethod::Card,
merchant_key_store,
)
.await?;
Some((updated_pm, enums::PaymentMethod::Card))
} else {
Some((
domain::PaymentMethodData::Card(card),
enums::PaymentMethod::Card,
))
}
}
Some(the_pm @ domain::PaymentMethodData::Wallet(_)) => {
Some((the_pm, enums::PaymentMethod::Wallet))
}
Some(the_pm @ domain::PaymentMethodData::BankTransfer(_)) => {
Some((the_pm, enums::PaymentMethod::BankTransfer))
}
Some(the_pm @ domain::PaymentMethodData::BankRedirect(_)) => {
Some((the_pm, enums::PaymentMethod::BankRedirect))
}
Some(the_pm @ domain::PaymentMethodData::BankDebit(_)) => {
Some((the_pm, enums::PaymentMethod::BankDebit))
}
Some(_) => Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Payment method received from locker is unsupported by locker")?,
None => None,
})
}
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="1985" end="1991">
pub enum VaultFetchAction {
FetchCardDetailsFromLocker,
FetchCardDetailsForNetworkTransactionIdFlowFromLocker,
FetchNetworkTokenDataFromTokenizationService(String),
FetchNetworkTokenDetailsFromLocker(api_models::payments::NetworkTokenWithNTIRef),
NoFetchAction,
}
<file_sep path="hyperswitch/crates/router/tests/connectors/utils.rs" role="context" start="24" end="44">
pub trait Connector {
fn get_data(&self) -> types::api::ConnectorData;
fn get_auth_token(&self) -> types::ConnectorAuthType;
fn get_name(&self) -> String;
fn get_connector_meta(&self) -> Option<serde_json::Value> {
None
}
/// interval in seconds to be followed when making the subsequent request whenever needed
fn get_request_interval(&self) -> u64 {
5
}
#[cfg(feature = "payouts")]
fn get_payout_data(&self) -> Option<types::api::ConnectorData> {
None
}
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payments/operations/payment_create.rs<|crate|> router anchor=make_pm_data kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_create.rs" role="context" start="776" end="801">
async fn make_pm_data<'a>(
&'a self,
state: &'a SessionState,
payment_data: &mut PaymentData<F>,
storage_scheme: enums::MerchantStorageScheme,
merchant_key_store: &domain::MerchantKeyStore,
customer: &Option<domain::Customer>,
business_profile: &domain::Profile,
should_retry_with_pan: bool,
) -> RouterResult<(
PaymentCreateOperation<'a, F>,
Option<domain::PaymentMethodData>,
Option<String>,
)> {
Box::pin(helpers::make_pm_data(
Box::new(self),
state,
payment_data,
merchant_key_store,
customer,
storage_scheme,
business_profile,
should_retry_with_pan,
))
.await
}
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_create.rs" role="context" start="775" end="775">
use api_models::{
enums::FrmSuggestion, mandates::RecurringDetails, payment_methods::PaymentMethodsData,
payments::GetAddressFromPaymentMethodData,
};
use error_stack::{self, ResultExt};
use crate::{
consts,
core::{
errors::{self, CustomResult, RouterResult, StorageErrorExt},
mandate::helpers as m_helpers,
payment_link,
payment_methods::cards::create_encrypted_data,
payments::{self, helpers, operations, CustomerDetails, PaymentAddress, PaymentData},
utils as core_utils,
},
db::StorageInterface,
events::audit_events::{AuditEvent, AuditEventType},
routes::{app::ReqState, SessionState},
services,
types::{
self,
api::{self, ConnectorCallType, PaymentIdTypeExt},
domain,
storage::{
self,
enums::{self, IntentStatus},
},
transformers::{ForeignFrom, ForeignTryFrom},
},
utils::{self, OptionExt},
};
type PaymentCreateOperation<'a, F> = BoxedOperation<'a, F, api::PaymentsRequest, PaymentData<F>>;
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_create.rs" role="context" start="814" end="823">
async fn get_connector<'a>(
&'a self,
_merchant_account: &domain::MerchantAccount,
state: &SessionState,
request: &api::PaymentsRequest,
_payment_intent: &storage::PaymentIntent,
_merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> {
helpers::get_connector_default(state, request.routing.clone()).await
}
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_create.rs" role="context" start="804" end="812">
async fn add_task_to_process_tracker<'a>(
&'a self,
_state: &'a SessionState,
_payment_attempt: &PaymentAttempt,
_requeue: bool,
_schedule_time: Option<PrimitiveDateTime>,
) -> CustomResult<(), errors::ApiErrorResponse> {
Ok(())
}
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_create.rs" role="context" start="671" end="773">
async fn payments_dynamic_tax_calculation<'a>(
&'a self,
state: &SessionState,
payment_data: &mut PaymentData<F>,
_connector_call_type: &ConnectorCallType,
business_profile: &domain::Profile,
key_store: &domain::MerchantKeyStore,
merchant_account: &domain::MerchantAccount,
) -> CustomResult<(), errors::ApiErrorResponse> {
let is_tax_connector_enabled = business_profile.get_is_tax_connector_enabled();
let skip_external_tax_calculation = payment_data
.payment_intent
.skip_external_tax_calculation
.unwrap_or(false);
if is_tax_connector_enabled && !skip_external_tax_calculation {
let db = state.store.as_ref();
let key_manager_state: &KeyManagerState = &state.into();
let merchant_connector_id = business_profile
.tax_connector_id
.as_ref()
.get_required_value("business_profile.tax_connector_id")?;
#[cfg(feature = "v1")]
let mca = db
.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
key_manager_state,
&business_profile.merchant_id,
merchant_connector_id,
key_store,
)
.await
.to_not_found_response(
errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: merchant_connector_id.get_string_repr().to_string(),
},
)?;
#[cfg(feature = "v2")]
let mca = db
.find_merchant_connector_account_by_id(
key_manager_state,
merchant_connector_id,
key_store,
)
.await
.to_not_found_response(
errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: merchant_connector_id.get_string_repr().to_string(),
},
)?;
let connector_data =
api::TaxCalculateConnectorData::get_connector_by_name(&mca.connector_name)?;
let router_data = core_utils::construct_payments_dynamic_tax_calculation_router_data(
state,
merchant_account,
key_store,
payment_data,
&mca,
)
.await?;
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::CalculateTax,
types::PaymentsTaxCalculationData,
types::TaxCalculationResponseData,
> = connector_data.connector.get_connector_integration();
let response = services::execute_connector_processing_step(
state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Tax connector Response Failed")?;
let tax_response = response.response.map_err(|err| {
errors::ApiErrorResponse::ExternalConnectorError {
code: err.code,
message: err.message,
connector: connector_data.connector_name.clone().to_string(),
status_code: err.status_code,
reason: err.reason,
}
})?;
payment_data.payment_intent.tax_details = Some(diesel_models::TaxDetails {
default: Some(diesel_models::DefaultTax {
order_tax_amount: tax_response.order_tax_amount,
}),
payment_method_type: None,
});
Ok(())
} else {
Ok(())
}
}
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_create.rs" role="context" start="650" end="669">
async fn get_or_create_customer_details<'a>(
&'a self,
state: &SessionState,
payment_data: &mut PaymentData<F>,
request: Option<CustomerDetails>,
key_store: &domain::MerchantKeyStore,
storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<(PaymentCreateOperation<'a, F>, Option<domain::Customer>), errors::StorageError>
{
helpers::create_customer_if_not_exist(
state,
Box::new(self),
payment_data,
request,
&key_store.merchant_id,
key_store,
storage_scheme,
)
.await
}
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_create.rs" role="context" start="65" end="65">
type PaymentCreateOperation<'a, F> = BoxedOperation<'a, F, api::PaymentsRequest, PaymentData<F>>;
<file_sep path="hyperswitch/crates/router/src/compatibility/stripe/customers/types.rs" role="context" start="202" end="207">
pub struct PaymentMethodData {
pub id: Option<String>,
pub object: &'static str,
pub card: Option<CardDetails>,
pub created: Option<time::PrimitiveDateTime>,
}
<file_sep path="hyperswitch/v2_compatible_migrations/2024-08-28-081721_add_v2_columns/up.sql" role="context" start="1" end="11">
-- This file contains all new columns being added as part of v2 refactoring.
-- The new columns added should work with both v1 and v2 applications.
ALTER TABLE customers
ADD COLUMN IF NOT EXISTS merchant_reference_id VARCHAR(64),
ADD COLUMN IF NOT EXISTS default_billing_address BYTEA DEFAULT NULL,
ADD COLUMN IF NOT EXISTS default_shipping_address BYTEA DEFAULT NULL,
ADD COLUMN IF NOT EXISTS status "DeleteStatus";
CREATE TYPE "OrderFulfillmentTimeOrigin" AS ENUM ('create', 'confirm');
ALTER TABLE business_profile
<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/operations/payment_create.rs<|crate|> router anchor=make_pm_data kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_create.rs" role="context" start="776" end="801">
async fn make_pm_data<'a>(
&'a self,
state: &'a SessionState,
payment_data: &mut PaymentData<F>,
storage_scheme: enums::MerchantStorageScheme,
merchant_key_store: &domain::MerchantKeyStore,
customer: &Option<domain::Customer>,
business_profile: &domain::Profile,
should_retry_with_pan: bool,
) -> RouterResult<(
PaymentCreateOperation<'a, F>,
Option<domain::PaymentMethodData>,
Option<String>,
)> {
Box::pin(helpers::make_pm_data(
Box::new(self),
state,
payment_data,
merchant_key_store,
customer,
storage_scheme,
business_profile,
should_retry_with_pan,
))
.await
}
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_create.rs" role="context" start="775" end="775">
use api_models::{
enums::FrmSuggestion, mandates::RecurringDetails, payment_methods::PaymentMethodsData,
payments::GetAddressFromPaymentMethodData,
};
use error_stack::{self, ResultExt};
use crate::{
consts,
core::{
errors::{self, CustomResult, RouterResult, StorageErrorExt},
mandate::helpers as m_helpers,
payment_link,
payment_methods::cards::create_encrypted_data,
payments::{self, helpers, operations, CustomerDetails, PaymentAddress, PaymentData},
utils as core_utils,
},
db::StorageInterface,
events::audit_events::{AuditEvent, AuditEventType},
routes::{app::ReqState, SessionState},
services,
types::{
self,
api::{self, ConnectorCallType, PaymentIdTypeExt},
domain,
storage::{
self,
enums::{self, IntentStatus},
},
transformers::{ForeignFrom, ForeignTryFrom},
},
utils::{self, OptionExt},
};
type PaymentCreateOperation<'a, F> = BoxedOperation<'a, F, api::PaymentsRequest, PaymentData<F>>;
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_create.rs" role="context" start="814" end="823">
async fn get_connector<'a>(
&'a self,
_merchant_account: &domain::MerchantAccount,
state: &SessionState,
request: &api::PaymentsRequest,
_payment_intent: &storage::PaymentIntent,
_merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> {
helpers::get_connector_default(state, request.routing.clone()).await
}
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_create.rs" role="context" start="804" end="812">
async fn add_task_to_process_tracker<'a>(
&'a self,
_state: &'a SessionState,
_payment_attempt: &PaymentAttempt,
_requeue: bool,
_schedule_time: Option<PrimitiveDateTime>,
) -> CustomResult<(), errors::ApiErrorResponse> {
Ok(())
}
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_create.rs" role="context" start="671" end="773">
async fn payments_dynamic_tax_calculation<'a>(
&'a self,
state: &SessionState,
payment_data: &mut PaymentData<F>,
_connector_call_type: &ConnectorCallType,
business_profile: &domain::Profile,
key_store: &domain::MerchantKeyStore,
merchant_account: &domain::MerchantAccount,
) -> CustomResult<(), errors::ApiErrorResponse> {
let is_tax_connector_enabled = business_profile.get_is_tax_connector_enabled();
let skip_external_tax_calculation = payment_data
.payment_intent
.skip_external_tax_calculation
.unwrap_or(false);
if is_tax_connector_enabled && !skip_external_tax_calculation {
let db = state.store.as_ref();
let key_manager_state: &KeyManagerState = &state.into();
let merchant_connector_id = business_profile
.tax_connector_id
.as_ref()
.get_required_value("business_profile.tax_connector_id")?;
#[cfg(feature = "v1")]
let mca = db
.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
key_manager_state,
&business_profile.merchant_id,
merchant_connector_id,
key_store,
)
.await
.to_not_found_response(
errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: merchant_connector_id.get_string_repr().to_string(),
},
)?;
#[cfg(feature = "v2")]
let mca = db
.find_merchant_connector_account_by_id(
key_manager_state,
merchant_connector_id,
key_store,
)
.await
.to_not_found_response(
errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: merchant_connector_id.get_string_repr().to_string(),
},
)?;
let connector_data =
api::TaxCalculateConnectorData::get_connector_by_name(&mca.connector_name)?;
let router_data = core_utils::construct_payments_dynamic_tax_calculation_router_data(
state,
merchant_account,
key_store,
payment_data,
&mca,
)
.await?;
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::CalculateTax,
types::PaymentsTaxCalculationData,
types::TaxCalculationResponseData,
> = connector_data.connector.get_connector_integration();
let response = services::execute_connector_processing_step(
state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Tax connector Response Failed")?;
let tax_response = response.response.map_err(|err| {
errors::ApiErrorResponse::ExternalConnectorError {
code: err.code,
message: err.message,
connector: connector_data.connector_name.clone().to_string(),
status_code: err.status_code,
reason: err.reason,
}
})?;
payment_data.payment_intent.tax_details = Some(diesel_models::TaxDetails {
default: Some(diesel_models::DefaultTax {
order_tax_amount: tax_response.order_tax_amount,
}),
payment_method_type: None,
});
Ok(())
} else {
Ok(())
}
}
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_create.rs" role="context" start="650" end="669">
async fn get_or_create_customer_details<'a>(
&'a self,
state: &SessionState,
payment_data: &mut PaymentData<F>,
request: Option<CustomerDetails>,
key_store: &domain::MerchantKeyStore,
storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<(PaymentCreateOperation<'a, F>, Option<domain::Customer>), errors::StorageError>
{
helpers::create_customer_if_not_exist(
state,
Box::new(self),
payment_data,
request,
&key_store.merchant_id,
key_store,
storage_scheme,
)
.await
}
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_create.rs" role="context" start="65" end="65">
type PaymentCreateOperation<'a, F> = BoxedOperation<'a, F, api::PaymentsRequest, PaymentData<F>>;
<file_sep path="hyperswitch/crates/router/src/compatibility/stripe/customers/types.rs" role="context" start="202" end="207">
pub struct PaymentMethodData {
pub id: Option<String>,
pub object: &'static str,
pub card: Option<CardDetails>,
pub created: Option<time::PrimitiveDateTime>,
}
<file_sep path="hyperswitch/v2_compatible_migrations/2024-08-28-081721_add_v2_columns/up.sql" role="context" start="1" end="11">
-- This file contains all new columns being added as part of v2 refactoring.
-- The new columns added should work with both v1 and v2 applications.
ALTER TABLE customers
ADD COLUMN IF NOT EXISTS merchant_reference_id VARCHAR(64),
ADD COLUMN IF NOT EXISTS default_billing_address BYTEA DEFAULT NULL,
ADD COLUMN IF NOT EXISTS default_shipping_address BYTEA DEFAULT NULL,
ADD COLUMN IF NOT EXISTS status "DeleteStatus";
CREATE TYPE "OrderFulfillmentTimeOrigin" AS ENUM ('create', 'confirm');
ALTER TABLE business_profile
<file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="2504" end="2539">
pub enum PaymentMethodData {
#[schema(title = "Card")]
Card(Card),
#[schema(title = "CardRedirect")]
CardRedirect(CardRedirectData),
#[schema(title = "Wallet")]
Wallet(WalletData),
#[schema(title = "PayLater")]
PayLater(PayLaterData),
#[schema(title = "BankRedirect")]
BankRedirect(BankRedirectData),
#[schema(title = "BankDebit")]
BankDebit(BankDebitData),
#[schema(title = "BankTransfer")]
BankTransfer(Box<BankTransferData>),
#[schema(title = "RealTimePayment")]
RealTimePayment(Box<RealTimePaymentData>),
#[schema(title = "Crypto")]
Crypto(CryptoData),
#[schema(title = "MandatePayment")]
MandatePayment,
#[schema(title = "Reward")]
Reward,
#[schema(title = "Upi")]
Upi(UpiData),
#[schema(title = "Voucher")]
Voucher(VoucherData),
#[schema(title = "GiftCard")]
GiftCard(Box<GiftCardData>),
#[schema(title = "CardToken")]
CardToken(CardToken),
#[schema(title = "OpenBanking")]
OpenBanking(OpenBankingData),
#[schema(title = "MobilePayment")]
MobilePayment(MobilePaymentData),
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payments/operations/payment_update.rs<|crate|> router anchor=make_pm_data kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_update.rs" role="context" start="647" end="672">
async fn make_pm_data<'a>(
&'a self,
state: &'a SessionState,
payment_data: &mut PaymentData<F>,
storage_scheme: storage_enums::MerchantStorageScheme,
merchant_key_store: &domain::MerchantKeyStore,
customer: &Option<domain::Customer>,
business_profile: &domain::Profile,
should_retry_with_pan: bool,
) -> RouterResult<(
PaymentUpdateOperation<'a, F>,
Option<domain::PaymentMethodData>,
Option<String>,
)> {
Box::pin(helpers::make_pm_data(
Box::new(self),
state,
payment_data,
merchant_key_store,
customer,
storage_scheme,
business_profile,
should_retry_with_pan,
))
.await
}
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_update.rs" role="context" start="646" end="646">
use crate::{
core::{
errors::{self, CustomResult, RouterResult, StorageErrorExt},
mandate::helpers as m_helpers,
payment_methods::cards::create_encrypted_data,
payments::{self, helpers, operations, CustomerDetails, PaymentAddress, PaymentData},
utils as core_utils,
},
events::audit_events::{AuditEvent, AuditEventType},
routes::{app::ReqState, SessionState},
services,
types::{
self,
api::{self, ConnectorCallType, PaymentIdTypeExt},
domain,
storage::{self, enums as storage_enums, payment_attempt::PaymentAttemptExt},
transformers::ForeignTryFrom,
},
utils::OptionExt,
};
type PaymentUpdateOperation<'a, F> = BoxedOperation<'a, F, api::PaymentsRequest, PaymentData<F>>;
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_update.rs" role="context" start="685" end="694">
async fn get_connector<'a>(
&'a self,
_merchant_account: &domain::MerchantAccount,
state: &SessionState,
request: &api::PaymentsRequest,
_payment_intent: &storage::PaymentIntent,
_key_store: &domain::MerchantKeyStore,
) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> {
helpers::get_connector_default(state, request.routing.clone()).await
}
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_update.rs" role="context" start="675" end="683">
async fn add_task_to_process_tracker<'a>(
&'a self,
_state: &'a SessionState,
_payment_attempt: &storage::PaymentAttempt,
_requeue: bool,
_schedule_time: Option<time::PrimitiveDateTime>,
) -> CustomResult<(), errors::ApiErrorResponse> {
Ok(())
}
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_update.rs" role="context" start="543" end="644">
async fn payments_dynamic_tax_calculation<'a>(
&'a self,
state: &SessionState,
payment_data: &mut PaymentData<F>,
_connector_call_type: &ConnectorCallType,
business_profile: &domain::Profile,
key_store: &domain::MerchantKeyStore,
merchant_account: &domain::MerchantAccount,
) -> CustomResult<(), errors::ApiErrorResponse> {
let is_tax_connector_enabled = business_profile.get_is_tax_connector_enabled();
let skip_external_tax_calculation = payment_data
.payment_intent
.skip_external_tax_calculation
.unwrap_or(false);
if is_tax_connector_enabled && !skip_external_tax_calculation {
let db = state.store.as_ref();
let key_manager_state: &KeyManagerState = &state.into();
let merchant_connector_id = business_profile
.tax_connector_id
.as_ref()
.get_required_value("business_profile.tax_connector_id")?;
#[cfg(feature = "v1")]
let mca = db
.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
key_manager_state,
&business_profile.merchant_id,
merchant_connector_id,
key_store,
)
.await
.to_not_found_response(
errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: merchant_connector_id.get_string_repr().to_string(),
},
)?;
#[cfg(feature = "v2")]
let mca = db
.find_merchant_connector_account_by_id(
key_manager_state,
merchant_connector_id,
key_store,
)
.await
.to_not_found_response(
errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: merchant_connector_id.get_string_repr().to_string(),
},
)?;
let connector_data =
api::TaxCalculateConnectorData::get_connector_by_name(&mca.connector_name)?;
let router_data = core_utils::construct_payments_dynamic_tax_calculation_router_data(
state,
merchant_account,
key_store,
payment_data,
&mca,
)
.await?;
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::CalculateTax,
types::PaymentsTaxCalculationData,
types::TaxCalculationResponseData,
> = connector_data.connector.get_connector_integration();
let response = services::execute_connector_processing_step(
state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Tax connector Response Failed")?;
let tax_response = response.response.map_err(|err| {
errors::ApiErrorResponse::ExternalConnectorError {
code: err.code,
message: err.message,
connector: connector_data.connector_name.clone().to_string(),
status_code: err.status_code,
reason: err.reason,
}
})?;
payment_data.payment_intent.tax_details = Some(diesel_models::TaxDetails {
default: Some(diesel_models::DefaultTax {
order_tax_amount: tax_response.order_tax_amount,
}),
payment_method_type: None,
});
Ok(())
} else {
Ok(())
}
}
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_update.rs" role="context" start="522" end="541">
async fn get_or_create_customer_details<'a>(
&'a self,
state: &SessionState,
payment_data: &mut PaymentData<F>,
request: Option<CustomerDetails>,
key_store: &domain::MerchantKeyStore,
storage_scheme: common_enums::enums::MerchantStorageScheme,
) -> CustomResult<(PaymentUpdateOperation<'a, F>, Option<domain::Customer>), errors::StorageError>
{
helpers::create_customer_if_not_exist(
state,
Box::new(self),
payment_data,
request,
&key_store.merchant_id,
key_store,
storage_scheme,
)
.await
}
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_update.rs" role="context" start="45" end="45">
type PaymentUpdateOperation<'a, F> = BoxedOperation<'a, F, api::PaymentsRequest, PaymentData<F>>;
<file_sep path="hyperswitch/crates/router/src/compatibility/stripe/customers/types.rs" role="context" start="202" end="207">
pub struct PaymentMethodData {
pub id: Option<String>,
pub object: &'static str,
pub card: Option<CardDetails>,
pub created: Option<time::PrimitiveDateTime>,
}
<file_sep path="hyperswitch/v2_compatible_migrations/2024-08-28-081721_add_v2_columns/up.sql" role="context" start="1" end="11">
-- This file contains all new columns being added as part of v2 refactoring.
-- The new columns added should work with both v1 and v2 applications.
ALTER TABLE customers
ADD COLUMN IF NOT EXISTS merchant_reference_id VARCHAR(64),
ADD COLUMN IF NOT EXISTS default_billing_address BYTEA DEFAULT NULL,
ADD COLUMN IF NOT EXISTS default_shipping_address BYTEA DEFAULT NULL,
ADD COLUMN IF NOT EXISTS status "DeleteStatus";
CREATE TYPE "OrderFulfillmentTimeOrigin" AS ENUM ('create', 'confirm');
ALTER TABLE business_profile
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payments/operations/payment_update.rs<|crate|> router anchor=make_pm_data kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_update.rs" role="context" start="647" end="672">
async fn make_pm_data<'a>(
&'a self,
state: &'a SessionState,
payment_data: &mut PaymentData<F>,
storage_scheme: storage_enums::MerchantStorageScheme,
merchant_key_store: &domain::MerchantKeyStore,
customer: &Option<domain::Customer>,
business_profile: &domain::Profile,
should_retry_with_pan: bool,
) -> RouterResult<(
PaymentUpdateOperation<'a, F>,
Option<domain::PaymentMethodData>,
Option<String>,
)> {
Box::pin(helpers::make_pm_data(
Box::new(self),
state,
payment_data,
merchant_key_store,
customer,
storage_scheme,
business_profile,
should_retry_with_pan,
))
.await
}
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_update.rs" role="context" start="646" end="646">
use crate::{
core::{
errors::{self, CustomResult, RouterResult, StorageErrorExt},
mandate::helpers as m_helpers,
payment_methods::cards::create_encrypted_data,
payments::{self, helpers, operations, CustomerDetails, PaymentAddress, PaymentData},
utils as core_utils,
},
events::audit_events::{AuditEvent, AuditEventType},
routes::{app::ReqState, SessionState},
services,
types::{
self,
api::{self, ConnectorCallType, PaymentIdTypeExt},
domain,
storage::{self, enums as storage_enums, payment_attempt::PaymentAttemptExt},
transformers::ForeignTryFrom,
},
utils::OptionExt,
};
type PaymentUpdateOperation<'a, F> = BoxedOperation<'a, F, api::PaymentsRequest, PaymentData<F>>;
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_update.rs" role="context" start="685" end="694">
async fn get_connector<'a>(
&'a self,
_merchant_account: &domain::MerchantAccount,
state: &SessionState,
request: &api::PaymentsRequest,
_payment_intent: &storage::PaymentIntent,
_key_store: &domain::MerchantKeyStore,
) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> {
helpers::get_connector_default(state, request.routing.clone()).await
}
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_update.rs" role="context" start="675" end="683">
async fn add_task_to_process_tracker<'a>(
&'a self,
_state: &'a SessionState,
_payment_attempt: &storage::PaymentAttempt,
_requeue: bool,
_schedule_time: Option<time::PrimitiveDateTime>,
) -> CustomResult<(), errors::ApiErrorResponse> {
Ok(())
}
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_update.rs" role="context" start="543" end="644">
async fn payments_dynamic_tax_calculation<'a>(
&'a self,
state: &SessionState,
payment_data: &mut PaymentData<F>,
_connector_call_type: &ConnectorCallType,
business_profile: &domain::Profile,
key_store: &domain::MerchantKeyStore,
merchant_account: &domain::MerchantAccount,
) -> CustomResult<(), errors::ApiErrorResponse> {
let is_tax_connector_enabled = business_profile.get_is_tax_connector_enabled();
let skip_external_tax_calculation = payment_data
.payment_intent
.skip_external_tax_calculation
.unwrap_or(false);
if is_tax_connector_enabled && !skip_external_tax_calculation {
let db = state.store.as_ref();
let key_manager_state: &KeyManagerState = &state.into();
let merchant_connector_id = business_profile
.tax_connector_id
.as_ref()
.get_required_value("business_profile.tax_connector_id")?;
#[cfg(feature = "v1")]
let mca = db
.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
key_manager_state,
&business_profile.merchant_id,
merchant_connector_id,
key_store,
)
.await
.to_not_found_response(
errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: merchant_connector_id.get_string_repr().to_string(),
},
)?;
#[cfg(feature = "v2")]
let mca = db
.find_merchant_connector_account_by_id(
key_manager_state,
merchant_connector_id,
key_store,
)
.await
.to_not_found_response(
errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: merchant_connector_id.get_string_repr().to_string(),
},
)?;
let connector_data =
api::TaxCalculateConnectorData::get_connector_by_name(&mca.connector_name)?;
let router_data = core_utils::construct_payments_dynamic_tax_calculation_router_data(
state,
merchant_account,
key_store,
payment_data,
&mca,
)
.await?;
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::CalculateTax,
types::PaymentsTaxCalculationData,
types::TaxCalculationResponseData,
> = connector_data.connector.get_connector_integration();
let response = services::execute_connector_processing_step(
state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Tax connector Response Failed")?;
let tax_response = response.response.map_err(|err| {
errors::ApiErrorResponse::ExternalConnectorError {
code: err.code,
message: err.message,
connector: connector_data.connector_name.clone().to_string(),
status_code: err.status_code,
reason: err.reason,
}
})?;
payment_data.payment_intent.tax_details = Some(diesel_models::TaxDetails {
default: Some(diesel_models::DefaultTax {
order_tax_amount: tax_response.order_tax_amount,
}),
payment_method_type: None,
});
Ok(())
} else {
Ok(())
}
}
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_update.rs" role="context" start="522" end="541">
async fn get_or_create_customer_details<'a>(
&'a self,
state: &SessionState,
payment_data: &mut PaymentData<F>,
request: Option<CustomerDetails>,
key_store: &domain::MerchantKeyStore,
storage_scheme: common_enums::enums::MerchantStorageScheme,
) -> CustomResult<(PaymentUpdateOperation<'a, F>, Option<domain::Customer>), errors::StorageError>
{
helpers::create_customer_if_not_exist(
state,
Box::new(self),
payment_data,
request,
&key_store.merchant_id,
key_store,
storage_scheme,
)
.await
}
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_update.rs" role="context" start="45" end="45">
type PaymentUpdateOperation<'a, F> = BoxedOperation<'a, F, api::PaymentsRequest, PaymentData<F>>;
<file_sep path="hyperswitch/crates/router/src/compatibility/stripe/customers/types.rs" role="context" start="202" end="207">
pub struct PaymentMethodData {
pub id: Option<String>,
pub object: &'static str,
pub card: Option<CardDetails>,
pub created: Option<time::PrimitiveDateTime>,
}
<file_sep path="hyperswitch/v2_compatible_migrations/2024-08-28-081721_add_v2_columns/up.sql" role="context" start="1" end="11">
-- This file contains all new columns being added as part of v2 refactoring.
-- The new columns added should work with both v1 and v2 applications.
ALTER TABLE customers
ADD COLUMN IF NOT EXISTS merchant_reference_id VARCHAR(64),
ADD COLUMN IF NOT EXISTS default_billing_address BYTEA DEFAULT NULL,
ADD COLUMN IF NOT EXISTS default_shipping_address BYTEA DEFAULT NULL,
ADD COLUMN IF NOT EXISTS status "DeleteStatus";
CREATE TYPE "OrderFulfillmentTimeOrigin" AS ENUM ('create', 'confirm');
ALTER TABLE business_profile
<file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="2504" end="2539">
pub enum PaymentMethodData {
#[schema(title = "Card")]
Card(Card),
#[schema(title = "CardRedirect")]
CardRedirect(CardRedirectData),
#[schema(title = "Wallet")]
Wallet(WalletData),
#[schema(title = "PayLater")]
PayLater(PayLaterData),
#[schema(title = "BankRedirect")]
BankRedirect(BankRedirectData),
#[schema(title = "BankDebit")]
BankDebit(BankDebitData),
#[schema(title = "BankTransfer")]
BankTransfer(Box<BankTransferData>),
#[schema(title = "RealTimePayment")]
RealTimePayment(Box<RealTimePaymentData>),
#[schema(title = "Crypto")]
Crypto(CryptoData),
#[schema(title = "MandatePayment")]
MandatePayment,
#[schema(title = "Reward")]
Reward,
#[schema(title = "Upi")]
Upi(UpiData),
#[schema(title = "Voucher")]
Voucher(VoucherData),
#[schema(title = "GiftCard")]
GiftCard(Box<GiftCardData>),
#[schema(title = "CardToken")]
CardToken(CardToken),
#[schema(title = "OpenBanking")]
OpenBanking(OpenBankingData),
#[schema(title = "MobilePayment")]
MobilePayment(MobilePaymentData),
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payment_methods/vault.rs<|crate|> router anchor=get_delete_tokenize_schedule_time kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/vault.rs" role="context" start="1455" end="1476">
pub async fn get_delete_tokenize_schedule_time(
db: &dyn db::StorageInterface,
pm: enums::PaymentMethod,
retry_count: i32,
) -> Option<time::PrimitiveDateTime> {
let redis_mapping = db::get_and_deserialize_key(
db,
&format!("pt_mapping_delete_{pm}_tokenize_data"),
"PaymentMethodsPTMapping",
)
.await;
let mapping = match redis_mapping {
Ok(x) => x,
Err(error) => {
logger::info!(?error, "Redis Mapping Error");
process_data::PaymentMethodsPTMapping::default()
}
};
let time_delta = process_tracker_utils::get_pm_schedule_time(mapping, pm, retry_count + 1);
process_tracker_utils::get_time_from_delta(time_delta)
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/vault.rs" role="context" start="1454" end="1454">
use scheduler::{types::process_data, utils as process_tracker_utils};
use crate::{
consts,
core::errors::{self, CustomResult, RouterResult},
db, logger, routes,
routes::metrics,
types::{
api, domain,
storage::{self, enums},
},
utils::StringExt,
};
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/vault.rs" role="context" start="1478" end="1507">
pub async fn retry_delete_tokenize(
db: &dyn db::StorageInterface,
pm: enums::PaymentMethod,
pt: storage::ProcessTracker,
) -> Result<(), errors::ProcessTrackerError> {
let schedule_time = get_delete_tokenize_schedule_time(db, pm, pt.retry_count).await;
match schedule_time {
Some(s_time) => {
let retry_schedule = db
.as_scheduler()
.retry_process(pt, s_time)
.await
.map_err(Into::into);
metrics::TASKS_RESET_COUNT.add(
1,
router_env::metric_attributes!(("flow", "DeleteTokenizeData")),
);
retry_schedule
}
None => db
.as_scheduler()
.finish_process_with_business_status(
pt,
diesel_models::process_tracker::business_status::RETRIES_EXCEEDED,
)
.await
.map_err(Into::into),
}
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/vault.rs" role="context" start="1419" end="1453">
pub async fn start_tokenize_data_workflow(
state: &routes::SessionState,
tokenize_tracker: &storage::ProcessTracker,
) -> Result<(), errors::ProcessTrackerError> {
let db = &*state.store;
let delete_tokenize_data = serde_json::from_value::<storage::TokenizeCoreWorkflow>(
tokenize_tracker.tracking_data.clone(),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| {
format!(
"unable to convert into DeleteTokenizeByTokenRequest {:?}",
tokenize_tracker.tracking_data
)
})?;
match delete_tokenized_data(state, &delete_tokenize_data.lookup_key).await {
Ok(()) => {
logger::info!("Card From locker deleted Successfully");
//mark task as finished
db.as_scheduler()
.finish_process_with_business_status(
tokenize_tracker.clone(),
diesel_models::process_tracker::business_status::COMPLETED_BY_PT,
)
.await?;
}
Err(err) => {
logger::error!("Err: Deleting Card From Locker : {:?}", err);
retry_delete_tokenize(db, delete_tokenize_data.pm, tokenize_tracker.to_owned()).await?;
metrics::RETRIED_DELETE_DATA_COUNT.add(1, &[]);
}
}
Ok(())
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/vault.rs" role="context" start="1378" end="1417">
pub async fn add_delete_tokenized_data_task(
db: &dyn db::StorageInterface,
lookup_key: &str,
pm: enums::PaymentMethod,
) -> RouterResult<()> {
let runner = storage::ProcessTrackerRunner::DeleteTokenizeDataWorkflow;
let process_tracker_id = format!("{runner}_{lookup_key}");
let task = runner.to_string();
let tag = ["BASILISK-V3"];
let tracking_data = storage::TokenizeCoreWorkflow {
lookup_key: lookup_key.to_owned(),
pm,
};
let schedule_time = get_delete_tokenize_schedule_time(db, pm, 0)
.await
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to obtain initial process tracker schedule time")?;
let process_tracker_entry = storage::ProcessTrackerNew::new(
process_tracker_id,
&task,
runner,
tag,
tracking_data,
None,
schedule_time,
common_types::consts::API_VERSION,
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to construct delete tokenized data process tracker task")?;
let response = db.insert_process(process_tracker_entry).await;
response.map(|_| ()).or_else(|err| {
if err.current_context().is_db_unique_violation() {
Ok(())
} else {
Err(report!(errors::ApiErrorResponse::InternalServerError))
}
})
}
<file_sep path="hyperswitch/crates/router/src/connector/nmi/transformers.rs" role="context" start="454" end="459">
pub enum PaymentMethod {
CardNonThreeDs(Box<CardData>),
CardThreeDs(Box<CardThreeDsData>),
GPay(Box<GooglePayData>),
ApplePay(Box<ApplePayData>),
}
<file_sep path="hyperswitch/v2_compatible_migrations/2024-08-28-081721_add_v2_columns/up.sql" role="context" start="54" end="70">
ADD COLUMN redirection_data JSONB,
ADD COLUMN connector_payment_data TEXT,
ADD COLUMN connector_token_details JSONB;
-- Change the type of the column from JSON to JSONB
ALTER TABLE merchant_connector_account
ADD COLUMN IF NOT EXISTS feature_metadata JSONB;
ALTER TABLE payment_methods
ADD COLUMN IF NOT EXISTS locker_fingerprint_id VARCHAR(64),
ADD COLUMN IF NOT EXISTS payment_method_type_v2 VARCHAR(64),
ADD COLUMN IF NOT EXISTS payment_method_subtype VARCHAR(64);
ALTER TABLE refund
ADD COLUMN IF NOT EXISTS id VARCHAR(64),
ADD COLUMN IF NOT EXISTS merchant_reference_id VARCHAR(64),
ADD COLUMN IF NOT EXISTS connector_id VARCHAR(64);
<file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="2478" end="2478">
type Error = error_stack::Report<errors::ValidationError>;
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payments/helpers.rs<|crate|> router anchor=is_apple_pay_simplified_flow kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="5210" end="5233">
pub fn is_apple_pay_simplified_flow(
connector_metadata: Option<pii::SecretSerdeValue>,
connector_name: Option<&String>,
) -> CustomResult<bool, errors::ApiErrorResponse> {
let option_apple_pay_metadata = get_applepay_metadata(connector_metadata)
.map_err(|error| {
logger::info!(
"Apple pay metadata parsing for {:?} in is_apple_pay_simplified_flow {:?}",
connector_name,
error
)
})
.ok();
// return true only if the apple flow type is simplified
Ok(matches!(
option_apple_pay_metadata,
Some(
api_models::payments::ApplepaySessionTokenMetadata::ApplePayCombined(
api_models::payments::ApplePayCombinedMetadata::Simplified { .. }
)
)
))
}
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="5209" end="5209">
) -> Result<(), errors::ApiErrorResponse> {
if auth_flow == services::AuthFlow::Client && request.get_customer_id().is_some() {
let is_same_customer = request.get_customer_id() == payment_intent.customer_id.as_ref();
if !is_same_customer {
Err(errors::ApiErrorResponse::GenericUnauthorized {
message: "Unauthorised access to update customer".to_string(),
})?;
}
}
Ok(())
}
pub fn is_apple_pay_simplified_flow(
connector_metadata: Option<pii::SecretSerdeValue>,
connector_name: Option<&String>,
) -> CustomResult<bool, errors::ApiErrorResponse> {
let option_apple_pay_metadata = get_applepay_metadata(connector_metadata)
.map_err(|error| {
logger::info!(
"Apple pay metadata parsing for {:?} in is_apple_pay_simplified_flow {:?}",
connector_name,
error
)
})
.ok();
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="5261" end="5281">
async fn get_apple_pay_metadata_if_needed(
connector_metadata: &Option<masking::Secret<tera::Value>>,
connector_wallets_details_optional: &Option<api_models::admin::ConnectorWalletDetails>,
) -> RouterResult<Option<api_models::admin::ConnectorWalletDetails>> {
if let Some(connector_wallets_details) = connector_wallets_details_optional {
if connector_wallets_details.apple_pay_combined.is_some()
|| connector_wallets_details.apple_pay.is_some()
{
return Ok(Some(connector_wallets_details.clone()));
}
// Otherwise, merge Apple Pay metadata
return get_and_merge_apple_pay_metadata(
connector_metadata.clone(),
Some(connector_wallets_details.clone()),
)
.await;
}
// If connector_wallets_details_optional is None, attempt to get Apple Pay metadata
get_and_merge_apple_pay_metadata(connector_metadata.clone(), None).await
}
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="5241" end="5259">
pub async fn get_connector_wallets_details_with_apple_pay_certificates(
connector_metadata: &Option<masking::Secret<tera::Value>>,
connector_wallets_details_optional: &Option<api_models::admin::ConnectorWalletDetails>,
) -> RouterResult<Option<masking::Secret<serde_json::Value>>> {
let connector_wallet_details_with_apple_pay_metadata_optional =
get_apple_pay_metadata_if_needed(connector_metadata, connector_wallets_details_optional)
.await?;
let connector_wallets_details = connector_wallet_details_with_apple_pay_metadata_optional
.map(|details| {
serde_json::to_value(details)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to serialize Apple Pay metadata as JSON")
})
.transpose()?
.map(masking::Secret::new);
Ok(connector_wallets_details)
}
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="5194" end="5208">
pub fn validate_customer_access(
payment_intent: &PaymentIntent,
auth_flow: services::AuthFlow,
request: &api::PaymentsRequest,
) -> Result<(), errors::ApiErrorResponse> {
if auth_flow == services::AuthFlow::Client && request.get_customer_id().is_some() {
let is_same_customer = request.get_customer_id() == payment_intent.customer_id.as_ref();
if !is_same_customer {
Err(errors::ApiErrorResponse::GenericUnauthorized {
message: "Unauthorised access to update customer".to_string(),
})?;
}
}
Ok(())
}
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="5186" end="5191">
pub async fn populate_bin_details_for_payment_method_create(
_card_details: api_models::payment_methods::CardDetail,
_db: &dyn StorageInterface,
) -> api_models::payment_methods::CardDetail {
todo!()
}
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="5382" end="5510">
pub async fn get_apple_pay_retryable_connectors<F, D>(
state: &SessionState,
merchant_account: &domain::MerchantAccount,
payment_data: &D,
key_store: &domain::MerchantKeyStore,
pre_routing_connector_data_list: &[api::ConnectorData],
merchant_connector_id: Option<&id_type::MerchantConnectorAccountId>,
business_profile: domain::Profile,
) -> CustomResult<Option<Vec<api::ConnectorData>>, errors::ApiErrorResponse>
where
F: Send + Clone,
D: payments::OperationSessionGetters<F> + Send,
{
let profile_id = business_profile.get_id();
let pre_decided_connector_data_first = pre_routing_connector_data_list
.first()
.ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)?;
let merchant_connector_account_type = get_merchant_connector_account(
state,
merchant_account.get_id(),
payment_data.get_creds_identifier(),
key_store,
profile_id,
&pre_decided_connector_data_first.connector_name.to_string(),
merchant_connector_id,
)
.await?;
let connector_data_list = if is_apple_pay_simplified_flow(
merchant_connector_account_type.get_metadata(),
merchant_connector_account_type
.get_connector_name()
.as_ref(),
)? {
let merchant_connector_account_list = state
.store
.find_merchant_connector_account_by_merchant_id_and_disabled_list(
&state.into(),
merchant_account.get_id(),
false,
key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::InternalServerError)?;
let profile_specific_merchant_connector_account_list = merchant_connector_account_list
.filter_based_on_profile_and_connector_type(
profile_id,
ConnectorType::PaymentProcessor,
);
let mut connector_data_list = vec![pre_decided_connector_data_first.clone()];
for merchant_connector_account in profile_specific_merchant_connector_account_list {
if is_apple_pay_simplified_flow(
merchant_connector_account.metadata.clone(),
Some(&merchant_connector_account.connector_name),
)? {
let connector_data = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
&merchant_connector_account.connector_name.to_string(),
api::GetToken::Connector,
Some(merchant_connector_account.get_id()),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Invalid connector name received")?;
if !connector_data_list.iter().any(|connector_details| {
connector_details.merchant_connector_id == connector_data.merchant_connector_id
}) {
connector_data_list.push(connector_data)
}
}
}
#[cfg(feature = "v1")]
let fallback_connetors_list = crate::core::routing::helpers::get_merchant_default_config(
&*state.clone().store,
profile_id.get_string_repr(),
&api_enums::TransactionType::Payment,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get merchant default fallback connectors config")?;
#[cfg(feature = "v2")]
let fallback_connetors_list = core_admin::ProfileWrapper::new(business_profile)
.get_default_fallback_list_of_connector_under_profile()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get merchant default fallback connectors config")?;
let mut routing_connector_data_list = Vec::new();
pre_routing_connector_data_list.iter().for_each(|pre_val| {
routing_connector_data_list.push(pre_val.merchant_connector_id.clone())
});
fallback_connetors_list.iter().for_each(|fallback_val| {
routing_connector_data_list
.iter()
.all(|val| *val != fallback_val.merchant_connector_id)
.then(|| {
routing_connector_data_list.push(fallback_val.merchant_connector_id.clone())
});
});
// connector_data_list is the list of connectors for which Apple Pay simplified flow is configured.
// This list is arranged in the same order as the merchant's connectors routingconfiguration.
let mut ordered_connector_data_list = Vec::new();
routing_connector_data_list
.iter()
.for_each(|merchant_connector_id| {
let connector_data = connector_data_list.iter().find(|connector_data| {
*merchant_connector_id == connector_data.merchant_connector_id
});
if let Some(connector_data_details) = connector_data {
ordered_connector_data_list.push(connector_data_details.clone());
}
});
Some(ordered_connector_data_list)
} else {
None
};
Ok(connector_data_list)
}
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="5351" end="5379">
pub fn get_applepay_metadata(
connector_metadata: Option<pii::SecretSerdeValue>,
) -> RouterResult<api_models::payments::ApplepaySessionTokenMetadata> {
connector_metadata
.clone()
.parse_value::<api_models::payments::ApplepayCombinedSessionTokenData>(
"ApplepayCombinedSessionTokenData",
)
.map(|combined_metadata| {
api_models::payments::ApplepaySessionTokenMetadata::ApplePayCombined(
combined_metadata.apple_pay_combined,
)
})
.or_else(|_| {
connector_metadata
.parse_value::<api_models::payments::ApplepaySessionTokenData>(
"ApplepaySessionTokenData",
)
.map(|old_metadata| {
api_models::payments::ApplepaySessionTokenMetadata::ApplePay(
old_metadata.apple_pay,
)
})
})
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "connector_metadata".to_string(),
expected_format: "applepay_metadata_format".to_string(),
})
}
<file_sep path="hyperswitch/crates/api_models/src/errors/types.rs" role="context" start="86" end="100">
pub enum ApiErrorResponse {
Unauthorized(ApiError),
ForbiddenCommonResource(ApiError),
ForbiddenPrivateResource(ApiError),
Conflict(ApiError),
Gone(ApiError),
Unprocessable(ApiError),
InternalServerError(ApiError),
NotImplemented(ApiError),
ConnectorError(ApiError, #[serde(skip_serializing)] StatusCode),
NotFound(ApiError),
MethodNotAllowed(ApiError),
BadRequest(ApiError),
DomainError(ApiError),
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payouts.rs<|crate|> router anchor=payouts_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="274" end="305">
pub async fn payouts_core(
state: &SessionState,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
payout_data: &mut PayoutData,
routing_algorithm: Option<serde_json::Value>,
eligible_connectors: Option<Vec<api_enums::PayoutConnectors>>,
) -> RouterResult<()> {
let payout_attempt = &payout_data.payout_attempt;
// Form connector data
let connector_call_type = get_connector_choice(
state,
merchant_account,
key_store,
payout_attempt.connector.clone(),
routing_algorithm,
payout_data,
eligible_connectors,
)
.await?;
// Call connector steps
Box::pin(make_connector_decision(
state,
merchant_account,
key_store,
connector_call_type,
payout_data,
))
.await
}
<file_sep path="hyperswitch/crates/router/src/core/payouts.rs" role="context" start="273" end="273">
use api_models::{self, enums as api_enums, payouts::PayoutLinkResponse};
use serde_json;
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="321" end="383">
pub async fn payouts_create_core(
state: SessionState,
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
req: payouts::PayoutCreateRequest,
) -> RouterResponse<payouts::PayoutCreateResponse> {
// Validate create request
let (payout_id, payout_method_data, profile_id, customer, payment_method) =
validator::validate_create_request(&state, &merchant_account, &req, &key_store).await?;
// Create DB entries
let mut payout_data = payout_create_db_entries(
&state,
&merchant_account,
&key_store,
&req,
&payout_id,
&profile_id,
payout_method_data.as_ref(),
&state.locale,
customer.as_ref(),
payment_method.clone(),
)
.await?;
let payout_attempt = payout_data.payout_attempt.to_owned();
let payout_type = payout_data.payouts.payout_type.to_owned();
// Persist 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_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="309" end="318">
pub async fn payouts_core(
state: &SessionState,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
payout_data: &mut PayoutData,
routing_algorithm: Option<serde_json::Value>,
eligible_connectors: Option<Vec<api_enums::PayoutConnectors>>,
) -> RouterResult<()> {
todo!()
}
<file_sep path="hyperswitch/crates/router/src/core/payouts.rs" role="context" start="169" end="270">
pub async fn make_connector_decision(
state: &SessionState,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
connector_call_type: api::ConnectorCallType,
payout_data: &mut PayoutData,
) -> RouterResult<()> {
match connector_call_type {
api::ConnectorCallType::PreDetermined(connector_data) => {
Box::pin(call_connector_payout(
state,
merchant_account,
key_store,
&connector_data,
payout_data,
))
.await?;
#[cfg(feature = "payout_retry")]
{
let config_bool = retry::config_should_call_gsm_payout(
&*state.store,
merchant_account.get_id(),
PayoutRetryType::SingleConnector,
)
.await;
if config_bool && payout_data.should_call_gsm() {
Box::pin(retry::do_gsm_single_connector_actions(
state,
connector_data,
payout_data,
merchant_account,
key_store,
))
.await?;
}
}
Ok(())
}
api::ConnectorCallType::Retryable(connectors) => {
let mut connectors = connectors.into_iter();
let connector_data = get_next_connector(&mut connectors)?;
Box::pin(call_connector_payout(
state,
merchant_account,
key_store,
&connector_data,
payout_data,
))
.await?;
#[cfg(feature = "payout_retry")]
{
let config_multiple_connector_bool = retry::config_should_call_gsm_payout(
&*state.store,
merchant_account.get_id(),
PayoutRetryType::MultiConnector,
)
.await;
if config_multiple_connector_bool && payout_data.should_call_gsm() {
Box::pin(retry::do_gsm_multiple_connector_actions(
state,
connectors,
connector_data.clone(),
payout_data,
merchant_account,
key_store,
))
.await?;
}
let config_single_connector_bool = retry::config_should_call_gsm_payout(
&*state.store,
merchant_account.get_id(),
PayoutRetryType::SingleConnector,
)
.await;
if config_single_connector_bool && payout_data.should_call_gsm() {
Box::pin(retry::do_gsm_single_connector_actions(
state,
connector_data,
payout_data,
merchant_account,
key_store,
))
.await?;
}
}
Ok(())
}
_ => Err(errors::ApiErrorResponse::InternalServerError).attach_printable({
"only PreDetermined and Retryable ConnectorCallTypes are supported".to_string()
})?,
}
}
<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/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/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/payment_methods.rs" role="context" start="1670" end="1670">
type Value = PaymentMethodListRequest;
<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/helpers.rs<|crate|> router anchor=get_apple_pay_metadata_if_needed kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="5261" end="5281">
async fn get_apple_pay_metadata_if_needed(
connector_metadata: &Option<masking::Secret<tera::Value>>,
connector_wallets_details_optional: &Option<api_models::admin::ConnectorWalletDetails>,
) -> RouterResult<Option<api_models::admin::ConnectorWalletDetails>> {
if let Some(connector_wallets_details) = connector_wallets_details_optional {
if connector_wallets_details.apple_pay_combined.is_some()
|| connector_wallets_details.apple_pay.is_some()
{
return Ok(Some(connector_wallets_details.clone()));
}
// Otherwise, merge Apple Pay metadata
return get_and_merge_apple_pay_metadata(
connector_metadata.clone(),
Some(connector_wallets_details.clone()),
)
.await;
}
// If connector_wallets_details_optional is None, attempt to get Apple Pay metadata
get_and_merge_apple_pay_metadata(connector_metadata.clone(), None).await
}
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="5260" end="5260">
let connector_wallets_details = connector_wallet_details_with_apple_pay_metadata_optional
.map(|details| {
serde_json::to_value(details)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to serialize Apple Pay metadata as JSON")
})
.transpose()?
.map(masking::Secret::new);
Ok(connector_wallets_details)
}
async fn get_apple_pay_metadata_if_needed(
connector_metadata: &Option<masking::Secret<tera::Value>>,
connector_wallets_details_optional: &Option<api_models::admin::ConnectorWalletDetails>,
) -> RouterResult<Option<api_models::admin::ConnectorWalletDetails>> {
if let Some(connector_wallets_details) = connector_wallets_details_optional {
if connector_wallets_details.apple_pay_combined.is_some()
|| connector_wallets_details.apple_pay.is_some()
{
return Ok(Some(connector_wallets_details.clone()));
}
// Otherwise, merge Apple Pay metadata
return get_and_merge_apple_pay_metadata(
connector_metadata.clone(),
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="5351" end="5379">
pub fn get_applepay_metadata(
connector_metadata: Option<pii::SecretSerdeValue>,
) -> RouterResult<api_models::payments::ApplepaySessionTokenMetadata> {
connector_metadata
.clone()
.parse_value::<api_models::payments::ApplepayCombinedSessionTokenData>(
"ApplepayCombinedSessionTokenData",
)
.map(|combined_metadata| {
api_models::payments::ApplepaySessionTokenMetadata::ApplePayCombined(
combined_metadata.apple_pay_combined,
)
})
.or_else(|_| {
connector_metadata
.parse_value::<api_models::payments::ApplepaySessionTokenData>(
"ApplepaySessionTokenData",
)
.map(|old_metadata| {
api_models::payments::ApplepaySessionTokenMetadata::ApplePay(
old_metadata.apple_pay,
)
})
})
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "connector_metadata".to_string(),
expected_format: "applepay_metadata_format".to_string(),
})
}
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="5283" end="5349">
async fn get_and_merge_apple_pay_metadata(
connector_metadata: Option<masking::Secret<tera::Value>>,
connector_wallets_details_optional: Option<api_models::admin::ConnectorWalletDetails>,
) -> RouterResult<Option<api_models::admin::ConnectorWalletDetails>> {
let apple_pay_metadata_optional = get_applepay_metadata(connector_metadata)
.map_err(|error| {
logger::error!(
"Apple Pay metadata parsing failed in get_encrypted_connector_wallets_details_with_apple_pay_certificates {:?}",
error
);
})
.ok();
if let Some(apple_pay_metadata) = apple_pay_metadata_optional {
let updated_wallet_details = match apple_pay_metadata {
api_models::payments::ApplepaySessionTokenMetadata::ApplePayCombined(
apple_pay_combined_metadata,
) => {
let combined_metadata_json = serde_json::to_value(apple_pay_combined_metadata)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to serialize Apple Pay combined metadata as JSON")?;
api_models::admin::ConnectorWalletDetails {
apple_pay_combined: Some(masking::Secret::new(combined_metadata_json)),
apple_pay: connector_wallets_details_optional
.as_ref()
.and_then(|d| d.apple_pay.clone()),
samsung_pay: connector_wallets_details_optional
.as_ref()
.and_then(|d| d.samsung_pay.clone()),
paze: connector_wallets_details_optional
.as_ref()
.and_then(|d| d.paze.clone()),
google_pay: connector_wallets_details_optional
.as_ref()
.and_then(|d| d.google_pay.clone()),
}
}
api_models::payments::ApplepaySessionTokenMetadata::ApplePay(apple_pay_metadata) => {
let metadata_json = serde_json::to_value(apple_pay_metadata)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to serialize Apple Pay metadata as JSON")?;
api_models::admin::ConnectorWalletDetails {
apple_pay: Some(masking::Secret::new(metadata_json)),
apple_pay_combined: connector_wallets_details_optional
.as_ref()
.and_then(|d| d.apple_pay_combined.clone()),
samsung_pay: connector_wallets_details_optional
.as_ref()
.and_then(|d| d.samsung_pay.clone()),
paze: connector_wallets_details_optional
.as_ref()
.and_then(|d| d.paze.clone()),
google_pay: connector_wallets_details_optional
.as_ref()
.and_then(|d| d.google_pay.clone()),
}
}
};
return Ok(Some(updated_wallet_details));
}
// Return connector_wallets_details if no Apple Pay metadata was found
Ok(connector_wallets_details_optional)
}
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="5241" end="5259">
pub async fn get_connector_wallets_details_with_apple_pay_certificates(
connector_metadata: &Option<masking::Secret<tera::Value>>,
connector_wallets_details_optional: &Option<api_models::admin::ConnectorWalletDetails>,
) -> RouterResult<Option<masking::Secret<serde_json::Value>>> {
let connector_wallet_details_with_apple_pay_metadata_optional =
get_apple_pay_metadata_if_needed(connector_metadata, connector_wallets_details_optional)
.await?;
let connector_wallets_details = connector_wallet_details_with_apple_pay_metadata_optional
.map(|details| {
serde_json::to_value(details)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to serialize Apple Pay metadata as JSON")
})
.transpose()?
.map(masking::Secret::new);
Ok(connector_wallets_details)
}
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="5210" end="5233">
pub fn is_apple_pay_simplified_flow(
connector_metadata: Option<pii::SecretSerdeValue>,
connector_name: Option<&String>,
) -> CustomResult<bool, errors::ApiErrorResponse> {
let option_apple_pay_metadata = get_applepay_metadata(connector_metadata)
.map_err(|error| {
logger::info!(
"Apple pay metadata parsing for {:?} in is_apple_pay_simplified_flow {:?}",
connector_name,
error
)
})
.ok();
// return true only if the apple flow type is simplified
Ok(matches!(
option_apple_pay_metadata,
Some(
api_models::payments::ApplepaySessionTokenMetadata::ApplePayCombined(
api_models::payments::ApplePayCombinedMetadata::Simplified { .. }
)
)
))
}
<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-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/payment_methods.rs" role="context" start="1670" end="1670">
type Value = PaymentMethodListRequest;
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payments/types.rs<|crate|> router anchor=get_individual_surcharge_detail_from_redis kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/payments/types.rs" role="context" start="342" end="366">
pub async fn get_individual_surcharge_detail_from_redis(
state: &SessionState,
surcharge_key: SurchargeKey,
payment_attempt_id: &str,
) -> CustomResult<SurchargeDetails, RedisError> {
let redis_conn = state
.store
.get_redis_conn()
.attach_printable("Failed to get redis connection")?;
let redis_key = Self::get_surcharge_metadata_redis_key(payment_attempt_id);
let value_key = Self::get_surcharge_details_redis_hashset_key(&surcharge_key);
let result = redis_conn
.get_hash_field_and_deserialize(
&redis_key.as_str().into(),
&value_key,
"SurchargeDetails",
)
.await;
logger::debug!(
"Surcharge result fetched from redis with key = {} and {}",
redis_key,
value_key
);
result
}
<file_sep path="hyperswitch/crates/router/src/core/payments/types.rs" role="context" start="341" end="341">
use common_utils::{
errors::CustomResult,
ext_traits::{Encode, OptionExt},
types::{self as common_types, ConnectorTransactionIdTrait},
};
pub use hyperswitch_domain_models::router_request_types::{
AuthenticationData, SplitRefundsRequest, StripeSplitRefund, SurchargeDetails,
};
use redis_interface::errors::RedisError;
use router_env::{instrument, logger, tracing};
use crate::{
consts as router_consts,
core::errors::{self, RouterResult},
routes::SessionState,
types::{
domain::Profile,
storage::{self, enums as storage_enums},
transformers::ForeignTryFrom,
},
};
<file_sep path="hyperswitch/crates/router/src/core/payments/types.rs" role="context" start="371" end="392">
fn foreign_try_from(authentication: &storage::Authentication) -> Result<Self, Self::Error> {
if authentication.authentication_status == common_enums::AuthenticationStatus::Success {
let threeds_server_transaction_id =
authentication.threeds_server_transaction_id.clone();
let message_version = authentication.message_version.clone();
let cavv = authentication
.cavv
.clone()
.get_required_value("cavv")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("cavv must not be null when authentication_status is success")?;
Ok(Self {
eci: authentication.eci.clone(),
cavv,
threeds_server_transaction_id,
message_version,
ds_trans_id: authentication.ds_trans_id.clone(),
})
} else {
Err(errors::ApiErrorResponse::PaymentAuthenticationFailed { data: None }.into())
}
}
<file_sep path="hyperswitch/crates/router/src/core/payments/types.rs" role="context" start="301" end="339">
pub async fn persist_individual_surcharge_details_in_redis(
&self,
state: &SessionState,
business_profile: &Profile,
) -> RouterResult<()> {
if !self.is_empty_result() {
let redis_conn = state
.store
.get_redis_conn()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get redis connection")?;
let redis_key = Self::get_surcharge_metadata_redis_key(&self.payment_attempt_id);
let mut value_list = Vec::with_capacity(self.get_surcharge_results_size());
for (key, value) in self.get_individual_surcharge_key_value_pairs().into_iter() {
value_list.push((
key,
value
.encode_to_string_of_json()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to encode to string of json")?,
));
}
let intent_fulfillment_time = business_profile
.get_order_fulfillment_time()
.unwrap_or(router_consts::DEFAULT_FULFILLMENT_TIME);
redis_conn
.set_hash_fields(
&redis_key.as_str().into(),
value_list,
Some(intent_fulfillment_time),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to write to redis")?;
logger::debug!("Surcharge results stored in redis with key = {}", redis_key);
}
Ok(())
}
<file_sep path="hyperswitch/crates/router/src/core/payments/types.rs" role="context" start="283" end="299">
pub fn get_surcharge_details_redis_hashset_key(surcharge_key: &SurchargeKey) -> String {
match surcharge_key {
SurchargeKey::Token(token) => {
format!("token_{}", token)
}
SurchargeKey::PaymentMethodData(payment_method, payment_method_type, card_network) => {
if let Some(card_network) = card_network {
format!(
"{}_{}_{}",
payment_method, payment_method_type, card_network
)
} else {
format!("{}_{}", payment_method, payment_method_type)
}
}
}
}
<file_sep path="hyperswitch/crates/router/src/core/payments/types.rs" role="context" start="271" end="273">
pub fn get_surcharge_metadata_redis_key(payment_attempt_id: &str) -> String {
format!("surcharge_metadata_{}", payment_attempt_id)
}
<file_sep path="hyperswitch/crates/router/src/core/payments/types.rs" role="context" start="232" end="239">
pub enum SurchargeKey {
Token(String),
PaymentMethodData(
common_enums::PaymentMethod,
common_enums::PaymentMethodType,
Option<common_enums::CardNetwork>,
),
}
<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/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/operations/payment_complete_authorize.rs<|crate|> router anchor=make_pm_data kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_complete_authorize.rs" role="context" start="417" end="443">
async fn make_pm_data<'a>(
&'a self,
state: &'a SessionState,
payment_data: &mut PaymentData<F>,
storage_scheme: storage_enums::MerchantStorageScheme,
merchant_key_store: &domain::MerchantKeyStore,
customer: &Option<domain::Customer>,
business_profile: &domain::Profile,
should_retry_with_pan: bool,
) -> RouterResult<(
CompleteAuthorizeOperation<'a, F>,
Option<domain::PaymentMethodData>,
Option<String>,
)> {
let (op, payment_method_data, pm_id) = Box::pin(helpers::make_pm_data(
Box::new(self),
state,
payment_data,
merchant_key_store,
customer,
storage_scheme,
business_profile,
should_retry_with_pan,
))
.await?;
Ok((op, payment_method_data, pm_id))
}
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_complete_authorize.rs" role="context" start="416" end="416">
use crate::{
core::{
errors::{self, CustomResult, RouterResult, StorageErrorExt},
mandate::helpers as m_helpers,
payments::{
self, helpers, operations, CustomerAcceptance, CustomerDetails, PaymentAddress,
PaymentData,
},
},
events::audit_events::{AuditEvent, AuditEventType},
routes::{app::ReqState, SessionState},
services,
types::{
api::{self, PaymentIdTypeExt},
domain,
storage::{self, enums as storage_enums},
},
utils::{self, OptionExt},
};
type CompleteAuthorizeOperation<'b, F> =
BoxedOperation<'b, F, api::PaymentsRequest, PaymentData<F>>;
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_complete_authorize.rs" role="context" start="456" end="467">
async fn get_connector<'a>(
&'a self,
_merchant_account: &domain::MerchantAccount,
state: &SessionState,
request: &api::PaymentsRequest,
_payment_intent: &storage::PaymentIntent,
_key_store: &domain::MerchantKeyStore,
) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> {
// Use a new connector in the confirm call or use the same one which was passed when
// creating the payment or if none is passed then use the routing algorithm
helpers::get_connector_default(state, request.routing.clone()).await
}
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_complete_authorize.rs" role="context" start="446" end="454">
async fn add_task_to_process_tracker<'a>(
&'a self,
_state: &'a SessionState,
_payment_attempt: &storage::PaymentAttempt,
_requeue: bool,
_schedule_time: Option<time::PrimitiveDateTime>,
) -> CustomResult<(), errors::ApiErrorResponse> {
Ok(())
}
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_complete_authorize.rs" role="context" start="393" end="414">
async fn get_or_create_customer_details<'a>(
&'a self,
state: &SessionState,
payment_data: &mut PaymentData<F>,
request: Option<CustomerDetails>,
key_store: &domain::MerchantKeyStore,
storage_scheme: common_enums::enums::MerchantStorageScheme,
) -> CustomResult<
(CompleteAuthorizeOperation<'a, F>, Option<domain::Customer>),
errors::StorageError,
> {
helpers::create_customer_if_not_exist(
state,
Box::new(self),
payment_data,
request,
&key_store.merchant_id,
key_store,
storage_scheme,
)
.await
}
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_complete_authorize.rs" role="context" start="42" end="387">
async fn get_trackers<'a>(
&'a self,
state: &'a SessionState,
payment_id: &api::PaymentIdType,
request: &api::PaymentsRequest,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
_auth_flow: services::AuthFlow,
_header_payload: &hyperswitch_domain_models::payments::HeaderPayload,
_platform_merchant_account: Option<&domain::MerchantAccount>,
) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsRequest, PaymentData<F>>>
{
let db = &*state.store;
let key_manager_state = &state.into();
let merchant_id = merchant_account.get_id();
let storage_scheme = merchant_account.storage_scheme;
let (mut payment_intent, mut payment_attempt, currency, amount);
let payment_id = payment_id
.get_payment_intent_id()
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
payment_intent = db
.find_payment_intent_by_payment_id_merchant_id(
key_manager_state,
&payment_id,
merchant_id,
key_store,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
// TODO (#7195): Add platform merchant account validation once client_secret auth is solved
payment_intent.setup_future_usage = request
.setup_future_usage
.or(payment_intent.setup_future_usage);
helpers::authenticate_client_secret(request.client_secret.as_ref(), &payment_intent)?;
helpers::validate_payment_status_against_not_allowed_statuses(
payment_intent.status,
&[
storage_enums::IntentStatus::Failed,
storage_enums::IntentStatus::Succeeded,
],
"confirm",
)?;
let browser_info = request
.browser_info
.clone()
.as_ref()
.map(utils::Encode::encode_to_value)
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "browser_info",
})?;
let recurring_details = request.recurring_details.clone();
payment_attempt = db
.find_payment_attempt_by_payment_id_merchant_id_attempt_id(
&payment_intent.payment_id,
merchant_id,
&payment_intent.active_attempt.get_id(),
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
let mandate_type = m_helpers::get_mandate_type(
request.mandate_data.clone(),
request.off_session,
payment_intent.setup_future_usage,
request.customer_acceptance.clone(),
request.payment_token.clone(),
payment_attempt.payment_method,
)
.change_context(errors::ApiErrorResponse::MandateValidationFailed {
reason: "Expected one out of recurring_details and mandate_data but got both".into(),
})?;
let m_helpers::MandateGenericData {
token,
payment_method,
payment_method_type,
mandate_data,
recurring_mandate_payment_data,
mandate_connector,
payment_method_info,
} = Box::pin(helpers::get_token_pm_type_mandate_details(
state,
request,
mandate_type.to_owned(),
merchant_account,
key_store,
payment_attempt.payment_method_id.clone(),
payment_intent.customer_id.as_ref(),
))
.await?;
let customer_acceptance: Option<CustomerAcceptance> = request
.customer_acceptance
.clone()
.map(From::from)
.or(payment_method_info
.clone()
.map(|pm| {
pm.customer_acceptance
.parse_value::<CustomerAcceptance>("CustomerAcceptance")
})
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to deserialize to CustomerAcceptance")?);
let token = token.or_else(|| payment_attempt.payment_token.clone());
if let Some(payment_method) = payment_method {
let should_validate_pm_or_token_given =
//this validation should happen if data was stored in the vault
helpers::should_store_payment_method_data_in_vault(
&state.conf.temp_locker_enable_config,
payment_attempt.connector.clone(),
payment_method,
);
if should_validate_pm_or_token_given {
helpers::validate_pm_or_token_given(
&request.payment_method,
&request
.payment_method_data
.as_ref()
.and_then(|pmd| pmd.payment_method_data.clone()),
&request.payment_method_type,
&mandate_type,
&token,
&request.ctp_service_details,
)?;
}
}
let token_data = if let Some((token, payment_method)) = token
.as_ref()
.zip(payment_method.or(payment_attempt.payment_method))
{
Some(
helpers::retrieve_payment_token_data(state, token.clone(), Some(payment_method))
.await?,
)
} else {
None
};
payment_attempt.payment_method = payment_method.or(payment_attempt.payment_method);
payment_attempt.browser_info = browser_info.or(payment_attempt.browser_info);
payment_attempt.payment_method_type =
payment_method_type.or(payment_attempt.payment_method_type);
payment_attempt.payment_experience = request
.payment_experience
.or(payment_attempt.payment_experience);
currency = payment_attempt.currency.get_required_value("currency")?;
amount = payment_attempt.get_total_amount().into();
let customer_id = payment_intent
.customer_id
.as_ref()
.or(request.customer_id.as_ref())
.cloned();
helpers::validate_customer_id_mandatory_cases(
request.setup_future_usage.is_some(),
customer_id.as_ref(),
)?;
let shipping_address = helpers::create_or_update_address_for_payment_by_request(
state,
request.shipping.as_ref(),
payment_intent.shipping_address_id.clone().as_deref(),
merchant_id,
payment_intent.customer_id.as_ref(),
key_store,
&payment_id,
storage_scheme,
)
.await?;
payment_intent.shipping_address_id = shipping_address
.as_ref()
.map(|shipping_address| shipping_address.address_id.clone());
let billing_address = helpers::get_address_by_id(
state,
payment_intent.billing_address_id.clone(),
key_store,
&payment_intent.payment_id,
merchant_id,
merchant_account.storage_scheme,
)
.await?;
let payment_method_billing = helpers::get_address_by_id(
state,
payment_attempt.payment_method_billing_address_id.clone(),
key_store,
&payment_intent.payment_id,
merchant_id,
merchant_account.storage_scheme,
)
.await?;
let redirect_response = request
.feature_metadata
.as_ref()
.and_then(|fm| fm.redirect_response.clone());
payment_intent.shipping_address_id = shipping_address.clone().map(|i| i.address_id);
payment_intent.billing_address_id = billing_address.clone().map(|i| i.address_id);
payment_intent.return_url = request
.return_url
.as_ref()
.map(|a| a.to_string())
.or(payment_intent.return_url);
payment_intent.allowed_payment_method_types = request
.get_allowed_payment_method_types_as_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error converting allowed_payment_types to Value")?
.or(payment_intent.allowed_payment_method_types);
payment_intent.connector_metadata = request
.get_connector_metadata_as_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error converting connector_metadata to Value")?
.or(payment_intent.connector_metadata);
payment_intent.feature_metadata = request
.get_feature_metadata_as_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error converting feature_metadata to Value")?
.or(payment_intent.feature_metadata);
payment_intent.metadata = request.metadata.clone().or(payment_intent.metadata);
// The operation merges mandate data from both request and payment_attempt
let setup_mandate = mandate_data;
let mandate_details_present =
payment_attempt.mandate_details.is_some() || request.mandate_data.is_some();
helpers::validate_mandate_data_and_future_usage(
payment_intent.setup_future_usage,
mandate_details_present,
)?;
let profile_id = payment_intent
.profile_id
.as_ref()
.get_required_value("profile_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("'profile_id' not set in 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 creds_identifier =
request
.merchant_connector_details
.as_ref()
.map(|merchant_connector_details| {
merchant_connector_details.creds_identifier.to_owned()
});
let payment_data = PaymentData {
flow: PhantomData,
payment_intent,
payment_attempt,
currency,
amount,
email: request.email.clone(),
mandate_id: None,
mandate_connector,
setup_mandate,
customer_acceptance,
token,
token_data,
address: PaymentAddress::new(
shipping_address.as_ref().map(From::from),
billing_address.as_ref().map(From::from),
payment_method_billing.as_ref().map(From::from),
business_profile.use_billing_as_payment_method_billing,
),
confirm: request.confirm,
payment_method_data: request
.payment_method_data
.as_ref()
.and_then(|pmd| pmd.payment_method_data.clone().map(Into::into)),
payment_method_info,
force_sync: None,
refunds: vec![],
disputes: vec![],
attempts: None,
sessions_token: vec![],
card_cvc: request.card_cvc.clone(),
creds_identifier,
pm_token: None,
connector_customer_id: None,
recurring_mandate_payment_data,
ephemeral_key: None,
multiple_capture_data: None,
redirect_response,
surcharge_details: None,
frm_message: None,
payment_link_data: None,
incremental_authorization_details: None,
authorizations: vec![],
authentication: None,
recurring_details,
poll_config: None,
tax_data: None,
session_id: None,
service_details: None,
card_testing_guard_data: None,
vault_operation: None,
threeds_method_comp_ind: request.threeds_method_comp_ind.clone(),
};
let customer_details = Some(CustomerDetails {
customer_id,
name: request.name.clone(),
email: request.email.clone(),
phone: request.phone.clone(),
phone_country_code: request.phone_country_code.clone(),
});
let get_trackers_response = operations::GetTrackerResponse {
operation: Box::new(self),
customer_details,
payment_data,
business_profile,
mandate_type,
};
Ok(get_trackers_response)
}
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_complete_authorize.rs" role="context" start="34" end="35">
type CompleteAuthorizeOperation<'b, F> =
BoxedOperation<'b, F, api::PaymentsRequest, PaymentData<F>>;
<file_sep path="hyperswitch/crates/router/src/compatibility/stripe/customers/types.rs" role="context" start="202" end="207">
pub struct PaymentMethodData {
pub id: Option<String>,
pub object: &'static str,
pub card: Option<CardDetails>,
pub created: Option<time::PrimitiveDateTime>,
}
<file_sep path="hyperswitch/v2_compatible_migrations/2024-08-28-081721_add_v2_columns/up.sql" role="context" start="1" end="11">
-- This file contains all new columns being added as part of v2 refactoring.
-- The new columns added should work with both v1 and v2 applications.
ALTER TABLE customers
ADD COLUMN IF NOT EXISTS merchant_reference_id VARCHAR(64),
ADD COLUMN IF NOT EXISTS default_billing_address BYTEA DEFAULT NULL,
ADD COLUMN IF NOT EXISTS default_shipping_address BYTEA DEFAULT NULL,
ADD COLUMN IF NOT EXISTS status "DeleteStatus";
CREATE TYPE "OrderFulfillmentTimeOrigin" AS ENUM ('create', 'confirm');
ALTER TABLE business_profile
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/connector_onboarding/paypal.rs<|crate|> router anchor=find_paypal_merchant_by_tracking_id kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/connector_onboarding/paypal.rs" role="context" start="115" end="139">
async fn find_paypal_merchant_by_tracking_id(
state: SessionState,
tracking_id: String,
access_token: &oss_types::AccessToken,
) -> RouterResult<Option<types::paypal::SellerStatusResponse>> {
let seller_status_request = utils::paypal::build_paypal_get_request(
merchant_onboarding_status_url(state.clone(), tracking_id),
access_token.token.peek().to_string(),
)?;
let seller_status_response = send_request(&state, seller_status_request, None)
.await
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to send request to paypal onboarding status")?;
if seller_status_response.status().is_success() {
return Ok(Some(
seller_status_response
.json()
.await
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to parse paypal onboarding status response")?,
));
}
Ok(None)
}
<file_sep path="hyperswitch/crates/router/src/core/connector_onboarding/paypal.rs" role="context" start="114" end="114">
use crate::{
core::{
admin,
errors::{ApiErrorResponse, RouterResult},
},
services::{send_request, ApplicationResponse, Request},
types::{self as oss_types, api as oss_api_types, api::connector_onboarding as types},
utils::connector_onboarding as utils,
SessionState,
};
<file_sep path="hyperswitch/crates/router/src/core/connector_onboarding/paypal.rs" role="context" start="141" end="191">
pub async fn update_mca(
state: &SessionState,
merchant_id: common_utils::id_type::MerchantId,
connector_id: common_utils::id_type::MerchantConnectorAccountId,
auth_details: oss_types::ConnectorAuthType,
) -> RouterResult<oss_api_types::MerchantConnectorResponse> {
let connector_auth_json = auth_details
.encode_to_value()
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Error while deserializing connector_account_details")?;
#[cfg(feature = "v1")]
let request = MerchantConnectorUpdate {
connector_type: common_enums::ConnectorType::PaymentProcessor,
connector_account_details: Some(Secret::new(connector_auth_json)),
disabled: Some(false),
status: Some(common_enums::ConnectorStatus::Active),
connector_label: None,
payment_methods_enabled: None,
metadata: None,
frm_configs: None,
connector_webhook_details: None,
pm_auth_config: None,
test_mode: None,
additional_merchant_data: None,
connector_wallets_details: None,
};
#[cfg(feature = "v2")]
let request = MerchantConnectorUpdate {
connector_type: common_enums::ConnectorType::PaymentProcessor,
connector_account_details: Some(Secret::new(connector_auth_json)),
disabled: Some(false),
status: Some(common_enums::ConnectorStatus::Active),
connector_label: None,
payment_methods_enabled: None,
metadata: None,
frm_configs: None,
connector_webhook_details: None,
pm_auth_config: None,
merchant_id: merchant_id.clone(),
additional_merchant_data: None,
connector_wallets_details: None,
feature_metadata: None,
};
let mca_response =
admin::update_connector(state.clone(), &merchant_id, None, &connector_id, request).await?;
match mca_response {
ApplicationResponse::Json(mca_data) => Ok(mca_data),
_ => Err(ApiErrorResponse::InternalServerError.into()),
}
}
<file_sep path="hyperswitch/crates/router/src/core/connector_onboarding/paypal.rs" role="context" start="80" end="113">
pub async fn sync_merchant_onboarding_status(
state: SessionState,
tracking_id: String,
) -> RouterResult<api::OnboardingStatus> {
let access_token = utils::paypal::generate_access_token(state.clone()).await?;
let Some(seller_status_response) =
find_paypal_merchant_by_tracking_id(state.clone(), tracking_id, &access_token).await?
else {
return Ok(api::OnboardingStatus::PayPal(
api::PayPalOnboardingStatus::AccountNotFound,
));
};
let merchant_details_url = seller_status_response
.extract_merchant_details_url(&state.conf.connectors.paypal.base_url)?;
let merchant_details_request =
utils::paypal::build_paypal_get_request(merchant_details_url, access_token.token.expose())?;
let merchant_details_response = send_request(&state, merchant_details_request, None)
.await
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to send request to paypal merchant details")?;
let parsed_response: types::paypal::SellerStatusDetailsResponse = merchant_details_response
.json()
.await
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to parse paypal merchant details response")?;
let eligibity = parsed_response.get_eligibility_status().await?;
Ok(api::OnboardingStatus::PayPal(eligibity))
}
<file_sep path="hyperswitch/crates/router/src/core/connector_onboarding/paypal.rs" role="context" start="64" end="78">
fn merchant_onboarding_status_url(state: SessionState, tracking_id: String) -> String {
let partner_id = state
.conf
.connector_onboarding
.get_inner()
.paypal
.partner_id
.to_owned();
format!(
"{}v1/customer/partners/{}/merchant-integrations?tracking_id={}",
state.conf.connectors.paypal.base_url,
partner_id.expose(),
tracking_id
)
}
<file_sep path="hyperswitch/crates/router/src/core/connector_onboarding.rs" role="context" start="16" end="18">
pub trait AccessToken {
async fn access_token(state: &SessionState) -> RouterResult<oss_types::AccessToken>;
}
<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/helpers.rs<|crate|> router anchor=store_payment_method_data_in_vault kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="2739" end="2769">
pub async fn store_payment_method_data_in_vault(
state: &SessionState,
payment_attempt: &PaymentAttempt,
payment_intent: &PaymentIntent,
payment_method: enums::PaymentMethod,
payment_method_data: &domain::PaymentMethodData,
merchant_key_store: &domain::MerchantKeyStore,
business_profile: Option<&domain::Profile>,
) -> RouterResult<Option<String>> {
if should_store_payment_method_data_in_vault(
&state.conf.temp_locker_enable_config,
payment_attempt.connector.clone(),
payment_method,
) || payment_intent.request_external_three_ds_authentication == Some(true)
{
let parent_payment_method_token = store_in_vault_and_generate_ppmt(
state,
payment_method_data,
payment_intent,
payment_attempt,
payment_method,
merchant_key_store,
business_profile,
)
.await?;
return Ok(Some(parent_payment_method_token));
}
Ok(None)
}
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="2738" end="2738">
state: &SessionState,
payment_attempt: &PaymentAttempt,
payment_intent: &PaymentIntent,
payment_method: enums::PaymentMethod,
payment_method_data: &domain::PaymentMethodData,
merchant_key_store: &domain::MerchantKeyStore,
business_profile: Option<&domain::Profile>,
) -> RouterResult<Option<String>> {
todo!()
}
#[cfg(feature = "v1")]
pub async fn store_payment_method_data_in_vault(
state: &SessionState,
payment_attempt: &PaymentAttempt,
payment_intent: &PaymentIntent,
payment_method: enums::PaymentMethod,
payment_method_data: &domain::PaymentMethodData,
merchant_key_store: &domain::MerchantKeyStore,
business_profile: Option<&domain::Profile>,
) -> RouterResult<Option<String>> {
if should_store_payment_method_data_in_vault(
&state.conf.temp_locker_enable_config,
payment_attempt.connector.clone(),
payment_method,
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="2787" end="2801">
pub(crate) fn validate_capture_method(
capture_method: storage_enums::CaptureMethod,
) -> RouterResult<()> {
utils::when(
capture_method == storage_enums::CaptureMethod::Automatic,
|| {
Err(report!(errors::ApiErrorResponse::PaymentUnexpectedState {
field_name: "capture_method".to_string(),
current_flow: "captured".to_string(),
current_value: capture_method.to_string(),
states: "manual, manual_multiple, scheduled".to_string()
}))
},
)
}
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="2770" end="2784">
pub fn should_store_payment_method_data_in_vault(
temp_locker_enable_config: &TempLockerEnableConfig,
option_connector: Option<String>,
payment_method: enums::PaymentMethod,
) -> bool {
option_connector
.map(|connector| {
temp_locker_enable_config
.0
.get(&connector)
.map(|config| config.payment_method.contains(&payment_method))
.unwrap_or(false)
})
.unwrap_or(true)
}
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="2726" end="2736">
pub async fn store_payment_method_data_in_vault(
state: &SessionState,
payment_attempt: &PaymentAttempt,
payment_intent: &PaymentIntent,
payment_method: enums::PaymentMethod,
payment_method_data: &domain::PaymentMethodData,
merchant_key_store: &domain::MerchantKeyStore,
business_profile: Option<&domain::Profile>,
) -> RouterResult<Option<String>> {
todo!()
}
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="2683" end="2723">
pub async fn store_in_vault_and_generate_ppmt(
state: &SessionState,
payment_method_data: &domain::PaymentMethodData,
payment_intent: &PaymentIntent,
payment_attempt: &PaymentAttempt,
payment_method: enums::PaymentMethod,
merchant_key_store: &domain::MerchantKeyStore,
business_profile: Option<&domain::Profile>,
) -> RouterResult<String> {
let router_token = vault::Vault::store_payment_method_data_in_locker(
state,
None,
payment_method_data,
payment_intent.customer_id.to_owned(),
payment_method,
merchant_key_store,
)
.await?;
let parent_payment_method_token = generate_id(consts::ID_LENGTH, "token");
let key_for_hyperswitch_token = payment_attempt.get_payment_method().map(|payment_method| {
payment_methods_handler::ParentPaymentMethodToken::create_key_for_token((
&parent_payment_method_token,
payment_method,
))
});
let intent_fulfillment_time = business_profile
.and_then(|b_profile| b_profile.get_order_fulfillment_time())
.unwrap_or(consts::DEFAULT_FULFILLMENT_TIME);
if let Some(key_for_hyperswitch_token) = key_for_hyperswitch_token {
key_for_hyperswitch_token
.insert(
intent_fulfillment_time,
storage::PaymentTokenData::temporary_generic(router_token),
state,
)
.await?;
};
Ok(parent_payment_method_token)
}
<file_sep path="hyperswitch/crates/router/src/connector/nmi/transformers.rs" role="context" start="454" end="459">
pub enum PaymentMethod {
CardNonThreeDs(Box<CardData>),
CardThreeDs(Box<CardThreeDsData>),
GPay(Box<GooglePayData>),
ApplePay(Box<ApplePayData>),
}
<file_sep path="hyperswitch/v2_compatible_migrations/2024-08-28-081721_add_v2_columns/up.sql" role="context" start="19" end="35">
-- Intentionally not adding a default value here since we would have to
-- check if any merchants have enabled this from configs table,
-- before filling data for this column.
-- If no merchants have enabled this, then we can use `false` as the default value
-- when adding the column, later we can drop the default added for the column
-- so that we ensure new records inserted always have a value for the column.
ADD COLUMN should_collect_cvv_during_payment BOOLEAN;
ALTER TABLE payment_intent
ADD COLUMN merchant_reference_id VARCHAR(64),
ADD COLUMN billing_address BYTEA DEFAULT NULL,
ADD COLUMN shipping_address BYTEA DEFAULT NULL,
ADD COLUMN capture_method "CaptureMethod",
ADD COLUMN authentication_type "AuthenticationType",
ADD COLUMN amount_to_capture bigint,
ADD COLUMN prerouting_algorithm JSONB,
ADD COLUMN surcharge_amount bigint,
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payments/helpers.rs<|crate|> router anchor=store_payment_method_data_in_vault kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="2739" end="2769">
pub async fn store_payment_method_data_in_vault(
state: &SessionState,
payment_attempt: &PaymentAttempt,
payment_intent: &PaymentIntent,
payment_method: enums::PaymentMethod,
payment_method_data: &domain::PaymentMethodData,
merchant_key_store: &domain::MerchantKeyStore,
business_profile: Option<&domain::Profile>,
) -> RouterResult<Option<String>> {
if should_store_payment_method_data_in_vault(
&state.conf.temp_locker_enable_config,
payment_attempt.connector.clone(),
payment_method,
) || payment_intent.request_external_three_ds_authentication == Some(true)
{
let parent_payment_method_token = store_in_vault_and_generate_ppmt(
state,
payment_method_data,
payment_intent,
payment_attempt,
payment_method,
merchant_key_store,
business_profile,
)
.await?;
return Ok(Some(parent_payment_method_token));
}
Ok(None)
}
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="2738" end="2738">
state: &SessionState,
payment_attempt: &PaymentAttempt,
payment_intent: &PaymentIntent,
payment_method: enums::PaymentMethod,
payment_method_data: &domain::PaymentMethodData,
merchant_key_store: &domain::MerchantKeyStore,
business_profile: Option<&domain::Profile>,
) -> RouterResult<Option<String>> {
todo!()
}
#[cfg(feature = "v1")]
pub async fn store_payment_method_data_in_vault(
state: &SessionState,
payment_attempt: &PaymentAttempt,
payment_intent: &PaymentIntent,
payment_method: enums::PaymentMethod,
payment_method_data: &domain::PaymentMethodData,
merchant_key_store: &domain::MerchantKeyStore,
business_profile: Option<&domain::Profile>,
) -> RouterResult<Option<String>> {
if should_store_payment_method_data_in_vault(
&state.conf.temp_locker_enable_config,
payment_attempt.connector.clone(),
payment_method,
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="2787" end="2801">
pub(crate) fn validate_capture_method(
capture_method: storage_enums::CaptureMethod,
) -> RouterResult<()> {
utils::when(
capture_method == storage_enums::CaptureMethod::Automatic,
|| {
Err(report!(errors::ApiErrorResponse::PaymentUnexpectedState {
field_name: "capture_method".to_string(),
current_flow: "captured".to_string(),
current_value: capture_method.to_string(),
states: "manual, manual_multiple, scheduled".to_string()
}))
},
)
}
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="2770" end="2784">
pub fn should_store_payment_method_data_in_vault(
temp_locker_enable_config: &TempLockerEnableConfig,
option_connector: Option<String>,
payment_method: enums::PaymentMethod,
) -> bool {
option_connector
.map(|connector| {
temp_locker_enable_config
.0
.get(&connector)
.map(|config| config.payment_method.contains(&payment_method))
.unwrap_or(false)
})
.unwrap_or(true)
}
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="2726" end="2736">
pub async fn store_payment_method_data_in_vault(
state: &SessionState,
payment_attempt: &PaymentAttempt,
payment_intent: &PaymentIntent,
payment_method: enums::PaymentMethod,
payment_method_data: &domain::PaymentMethodData,
merchant_key_store: &domain::MerchantKeyStore,
business_profile: Option<&domain::Profile>,
) -> RouterResult<Option<String>> {
todo!()
}
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="2683" end="2723">
pub async fn store_in_vault_and_generate_ppmt(
state: &SessionState,
payment_method_data: &domain::PaymentMethodData,
payment_intent: &PaymentIntent,
payment_attempt: &PaymentAttempt,
payment_method: enums::PaymentMethod,
merchant_key_store: &domain::MerchantKeyStore,
business_profile: Option<&domain::Profile>,
) -> RouterResult<String> {
let router_token = vault::Vault::store_payment_method_data_in_locker(
state,
None,
payment_method_data,
payment_intent.customer_id.to_owned(),
payment_method,
merchant_key_store,
)
.await?;
let parent_payment_method_token = generate_id(consts::ID_LENGTH, "token");
let key_for_hyperswitch_token = payment_attempt.get_payment_method().map(|payment_method| {
payment_methods_handler::ParentPaymentMethodToken::create_key_for_token((
&parent_payment_method_token,
payment_method,
))
});
let intent_fulfillment_time = business_profile
.and_then(|b_profile| b_profile.get_order_fulfillment_time())
.unwrap_or(consts::DEFAULT_FULFILLMENT_TIME);
if let Some(key_for_hyperswitch_token) = key_for_hyperswitch_token {
key_for_hyperswitch_token
.insert(
intent_fulfillment_time,
storage::PaymentTokenData::temporary_generic(router_token),
state,
)
.await?;
};
Ok(parent_payment_method_token)
}
<file_sep path="hyperswitch/crates/router/src/connector/nmi/transformers.rs" role="context" start="454" end="459">
pub enum PaymentMethod {
CardNonThreeDs(Box<CardData>),
CardThreeDs(Box<CardThreeDsData>),
GPay(Box<GooglePayData>),
ApplePay(Box<ApplePayData>),
}
<file_sep path="hyperswitch/v2_compatible_migrations/2024-08-28-081721_add_v2_columns/up.sql" role="context" start="19" end="35">
-- Intentionally not adding a default value here since we would have to
-- check if any merchants have enabled this from configs table,
-- before filling data for this column.
-- If no merchants have enabled this, then we can use `false` as the default value
-- when adding the column, later we can drop the default added for the column
-- so that we ensure new records inserted always have a value for the column.
ADD COLUMN should_collect_cvv_during_payment BOOLEAN;
ALTER TABLE payment_intent
ADD COLUMN merchant_reference_id VARCHAR(64),
ADD COLUMN billing_address BYTEA DEFAULT NULL,
ADD COLUMN shipping_address BYTEA DEFAULT NULL,
ADD COLUMN capture_method "CaptureMethod",
ADD COLUMN authentication_type "AuthenticationType",
ADD COLUMN amount_to_capture bigint,
ADD COLUMN prerouting_algorithm JSONB,
ADD COLUMN surcharge_amount bigint,
<file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="2504" end="2539">
pub enum PaymentMethodData {
#[schema(title = "Card")]
Card(Card),
#[schema(title = "CardRedirect")]
CardRedirect(CardRedirectData),
#[schema(title = "Wallet")]
Wallet(WalletData),
#[schema(title = "PayLater")]
PayLater(PayLaterData),
#[schema(title = "BankRedirect")]
BankRedirect(BankRedirectData),
#[schema(title = "BankDebit")]
BankDebit(BankDebitData),
#[schema(title = "BankTransfer")]
BankTransfer(Box<BankTransferData>),
#[schema(title = "RealTimePayment")]
RealTimePayment(Box<RealTimePaymentData>),
#[schema(title = "Crypto")]
Crypto(CryptoData),
#[schema(title = "MandatePayment")]
MandatePayment,
#[schema(title = "Reward")]
Reward,
#[schema(title = "Upi")]
Upi(UpiData),
#[schema(title = "Voucher")]
Voucher(VoucherData),
#[schema(title = "GiftCard")]
GiftCard(Box<GiftCardData>),
#[schema(title = "CardToken")]
CardToken(CardToken),
#[schema(title = "OpenBanking")]
OpenBanking(OpenBankingData),
#[schema(title = "MobilePayment")]
MobilePayment(MobilePaymentData),
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payment_methods/vault.rs<|crate|> router anchor=retry_delete_tokenize kind=fn pack=symbol_neighborhood lang=rust role_window=k2 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/vault.rs" role="context" start="1478" end="1507">
pub async fn retry_delete_tokenize(
db: &dyn db::StorageInterface,
pm: enums::PaymentMethod,
pt: storage::ProcessTracker,
) -> Result<(), errors::ProcessTrackerError> {
let schedule_time = get_delete_tokenize_schedule_time(db, pm, pt.retry_count).await;
match schedule_time {
Some(s_time) => {
let retry_schedule = db
.as_scheduler()
.retry_process(pt, s_time)
.await
.map_err(Into::into);
metrics::TASKS_RESET_COUNT.add(
1,
router_env::metric_attributes!(("flow", "DeleteTokenizeData")),
);
retry_schedule
}
None => db
.as_scheduler()
.finish_process_with_business_status(
pt,
diesel_models::process_tracker::business_status::RETRIES_EXCEEDED,
)
.await
.map_err(Into::into),
}
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/vault.rs" role="context" start="1477" end="1477">
use router_env::{instrument, tracing};
use crate::{
consts,
core::errors::{self, CustomResult, RouterResult},
db, logger, routes,
routes::metrics,
types::{
api, domain,
storage::{self, enums},
},
utils::StringExt,
};
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/vault.rs" role="context" start="1455" end="1476">
pub async fn get_delete_tokenize_schedule_time(
db: &dyn db::StorageInterface,
pm: enums::PaymentMethod,
retry_count: i32,
) -> Option<time::PrimitiveDateTime> {
let redis_mapping = db::get_and_deserialize_key(
db,
&format!("pt_mapping_delete_{pm}_tokenize_data"),
"PaymentMethodsPTMapping",
)
.await;
let mapping = match redis_mapping {
Ok(x) => x,
Err(error) => {
logger::info!(?error, "Redis Mapping Error");
process_data::PaymentMethodsPTMapping::default()
}
};
let time_delta = process_tracker_utils::get_pm_schedule_time(mapping, pm, retry_count + 1);
process_tracker_utils::get_time_from_delta(time_delta)
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/vault.rs" role="context" start="1419" end="1453">
pub async fn start_tokenize_data_workflow(
state: &routes::SessionState,
tokenize_tracker: &storage::ProcessTracker,
) -> Result<(), errors::ProcessTrackerError> {
let db = &*state.store;
let delete_tokenize_data = serde_json::from_value::<storage::TokenizeCoreWorkflow>(
tokenize_tracker.tracking_data.clone(),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| {
format!(
"unable to convert into DeleteTokenizeByTokenRequest {:?}",
tokenize_tracker.tracking_data
)
})?;
match delete_tokenized_data(state, &delete_tokenize_data.lookup_key).await {
Ok(()) => {
logger::info!("Card From locker deleted Successfully");
//mark task as finished
db.as_scheduler()
.finish_process_with_business_status(
tokenize_tracker.clone(),
diesel_models::process_tracker::business_status::COMPLETED_BY_PT,
)
.await?;
}
Err(err) => {
logger::error!("Err: Deleting Card From Locker : {:?}", err);
retry_delete_tokenize(db, delete_tokenize_data.pm, tokenize_tracker.to_owned()).await?;
metrics::RETRIED_DELETE_DATA_COUNT.add(1, &[]);
}
}
Ok(())
}
<file_sep path="hyperswitch/crates/router/src/connector/nmi/transformers.rs" role="context" start="454" end="459">
pub enum PaymentMethod {
CardNonThreeDs(Box<CardData>),
CardThreeDs(Box<CardThreeDsData>),
GPay(Box<GooglePayData>),
ApplePay(Box<ApplePayData>),
}
<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/payments/flows/complete_authorize_flow.rs<|crate|> router anchor=add_payment_method_token kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/payments/flows/complete_authorize_flow.rs" role="context" start="161" end="187">
async fn add_payment_method_token<'a>(
&mut self,
state: &SessionState,
connector: &api::ConnectorData,
_tokenization_action: &payments::TokenizationAction,
should_continue_payment: bool,
) -> RouterResult<types::PaymentMethodTokenResult> {
// TODO: remove this and handle it in core
if matches!(connector.connector_name, types::Connector::Payme) {
let request = self.request.clone();
payments::tokenization::add_payment_method_token(
state,
connector,
&payments::TokenizationAction::TokenizeInConnector,
self,
types::PaymentMethodTokenizationData::try_from(request)?,
should_continue_payment,
)
.await
} else {
Ok(types::PaymentMethodTokenResult {
payment_method_token_result: Ok(None),
is_payment_method_tokenization_performed: false,
connector_response: None,
})
}
}
<file_sep path="hyperswitch/crates/router/src/core/payments/flows/complete_authorize_flow.rs" role="context" start="160" end="160">
use crate::{
core::{
errors::{ApiErrorResponse, ConnectorErrorExt, RouterResult},
payments::{self, access_token, helpers, transformers, PaymentData},
},
routes::{metrics, SessionState},
services,
types::{self, api, domain, transformers::ForeignTryFrom},
};
<file_sep path="hyperswitch/crates/router/src/core/payments/flows/complete_authorize_flow.rs" role="context" start="213" end="219">
async fn preprocessing_steps<'a>(
self,
state: &SessionState,
connector: &api::ConnectorData,
) -> RouterResult<Self> {
complete_authorize_preprocessing_steps(state, &self, true, connector).await
}
<file_sep path="hyperswitch/crates/router/src/core/payments/flows/complete_authorize_flow.rs" role="context" start="189" end="211">
async fn build_flow_specific_connector_request(
&mut self,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
) -> RouterResult<(Option<services::Request>, bool)> {
let request = match call_connector_action {
payments::CallConnectorAction::Trigger => {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::CompleteAuthorize,
types::CompleteAuthorizeData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
connector_integration
.build_request(self, &state.conf.connectors)
.to_payment_failed_response()?
}
_ => None,
};
Ok((request, true))
}
<file_sep path="hyperswitch/crates/router/src/core/payments/flows/complete_authorize_flow.rs" role="context" start="150" end="159">
async fn add_access_token<'a>(
&self,
state: &SessionState,
connector: &api::ConnectorData,
merchant_account: &domain::MerchantAccount,
creds_identifier: Option<&str>,
) -> RouterResult<types::AddAccessTokenResult> {
access_token::add_access_token(state, connector, merchant_account, self, creds_identifier)
.await
}
<file_sep path="hyperswitch/crates/router/src/core/payments/flows/complete_authorize_flow.rs" role="context" start="99" end="148">
async fn decide_flows<'a>(
mut self,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
connector_request: Option<services::Request>,
business_profile: &domain::Profile,
header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<Self> {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::CompleteAuthorize,
types::CompleteAuthorizeData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
let mut complete_authorize_router_data = services::execute_connector_processing_step(
state,
connector_integration,
&self,
call_connector_action.clone(),
connector_request,
)
.await
.to_payment_failed_response()?;
match complete_authorize_router_data.response.clone() {
Err(_) => Ok(complete_authorize_router_data),
Ok(complete_authorize_response) => {
// Check if the Capture API should be called based on the connector and other parameters
if super::should_initiate_capture_flow(
&connector.connector_name,
self.request.customer_acceptance,
self.request.capture_method,
self.request.setup_future_usage,
complete_authorize_router_data.status,
) {
complete_authorize_router_data = Box::pin(process_capture_flow(
complete_authorize_router_data,
complete_authorize_response,
state,
connector,
call_connector_action.clone(),
business_profile,
header_payload,
))
.await?;
}
Ok(complete_authorize_router_data)
}
}
}
<file_sep path="hyperswitch/crates/router/tests/connectors/utils.rs" role="context" start="24" end="44">
pub trait Connector {
fn get_data(&self) -> types::api::ConnectorData;
fn get_auth_token(&self) -> types::ConnectorAuthType;
fn get_name(&self) -> String;
fn get_connector_meta(&self) -> Option<serde_json::Value> {
None
}
/// interval in seconds to be followed when making the subsequent request whenever needed
fn get_request_interval(&self) -> u64 {
5
}
#[cfg(feature = "payouts")]
fn get_payout_data(&self) -> Option<types::api::ConnectorData> {
None
}
}
<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.rs<|crate|> router anchor=complete_create_recipient 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="1170" end="1200">
pub async fn complete_create_recipient(
state: &SessionState,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
connector_data: &api::ConnectorData,
payout_data: &mut PayoutData,
) -> RouterResult<()> {
if !payout_data.should_terminate
&& matches!(
payout_data.payout_attempt.status,
common_enums::PayoutStatus::RequiresCreation
| common_enums::PayoutStatus::RequiresConfirmation
| common_enums::PayoutStatus::RequiresPayoutMethodData
)
&& connector_data
.connector_name
.supports_create_recipient(payout_data.payouts.payout_type)
{
Box::pin(create_recipient(
state,
merchant_account,
key_store,
connector_data,
payout_data,
))
.await
.attach_printable("Creation of customer failed")?;
}
Ok(())
}
<file_sep path="hyperswitch/crates/router/src/core/payouts.rs" role="context" start="1169" end="1169">
use api_models::{self, enums as api_enums, payouts::PayoutLinkResponse};
use common_enums::PayoutRetryType;
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="1403" end="1411">
pub async fn create_recipient(
state: &SessionState,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
connector_data: &api::ConnectorData,
payout_data: &mut PayoutData,
) -> RouterResult<()> {
todo!()
}
<file_sep path="hyperswitch/crates/router/src/core/payouts.rs" role="context" start="1203" end="1400">
pub async fn create_recipient(
state: &SessionState,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
connector_data: &api::ConnectorData,
payout_data: &mut PayoutData,
) -> RouterResult<()> {
let customer_details = payout_data.customer_details.to_owned();
let connector_name = connector_data.connector_name.to_string();
// Create the connector label using {profile_id}_{connector_name}
let connector_label = format!(
"{}_{}",
payout_data.profile_id.get_string_repr(),
connector_name
);
let (should_call_connector, _connector_customer_id) =
helpers::should_call_payout_connector_create_customer(
state,
connector_data,
&customer_details,
&connector_label,
);
if should_call_connector {
// 1. Form router data
let router_data = core_utils::construct_payout_router_data(
state,
connector_data,
merchant_account,
payout_data,
)
.await?;
// 2. Fetch connector integration details
let connector_integration: services::BoxedPayoutConnectorIntegrationInterface<
api::PoRecipient,
types::PayoutsData,
types::PayoutsResponseData,
> = connector_data.connector.get_connector_integration();
// 3. Call connector service
let router_resp = services::execute_connector_processing_step(
state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
)
.await
.to_payout_failed_response()?;
match router_resp.response {
Ok(recipient_create_data) => {
let db = &*state.store;
if let Some(customer) = customer_details {
if let Some(updated_customer) =
customers::update_connector_customer_in_customers(
&connector_label,
Some(&customer),
recipient_create_data.connector_payout_id.clone(),
)
.await
{
#[cfg(all(
any(feature = "v1", feature = "v2"),
not(feature = "customer_v2")
))]
{
let customer_id = customer.customer_id.to_owned();
payout_data.customer_details = Some(
db.update_customer_by_customer_id_merchant_id(
&state.into(),
customer_id,
merchant_account.get_id().to_owned(),
customer,
updated_customer,
key_store,
merchant_account.storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating customers in db")?,
);
}
#[cfg(all(feature = "v2", feature = "customer_v2"))]
{
let customer_id = customer.get_id().clone();
payout_data.customer_details = Some(
db.update_customer_by_global_id(
&state.into(),
&customer_id,
customer,
merchant_account.get_id(),
updated_customer,
key_store,
merchant_account.storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating customers in db")?,
);
}
}
}
// Add next step to ProcessTracker
if recipient_create_data.should_add_next_step_to_process_tracker {
add_external_account_addition_task(
&*state.store,
payout_data,
common_utils::date_time::now().saturating_add(Duration::seconds(consts::STRIPE_ACCOUNT_ONBOARDING_DELAY_IN_SECONDS)),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while adding attach_payout_account_workflow workflow to process tracker")?;
// Update payout status in DB
let status = recipient_create_data
.status
.unwrap_or(api_enums::PayoutStatus::RequiresVendorAccountCreation);
let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate {
connector_payout_id: payout_data
.payout_attempt
.connector_payout_id
.to_owned(),
status,
error_code: None,
error_message: None,
is_eligible: recipient_create_data.payout_eligible,
unified_code: None,
unified_message: None,
};
payout_data.payout_attempt = db
.update_payout_attempt(
&payout_data.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 = db
.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")?;
// Helps callee functions skip the execution
payout_data.should_terminate = true;
} else if let Some(status) = recipient_create_data.status {
let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate {
connector_payout_id: payout_data
.payout_attempt
.connector_payout_id
.to_owned(),
status,
error_code: None,
error_message: None,
is_eligible: recipient_create_data.payout_eligible,
unified_code: None,
unified_message: None,
};
payout_data.payout_attempt = db
.update_payout_attempt(
&payout_data.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 = db
.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")?;
}
}
Err(err) => Err(errors::ApiErrorResponse::PayoutFailed {
data: serde_json::to_value(err).ok(),
})?,
}
}
Ok(())
}
<file_sep path="hyperswitch/crates/router/src/core/payouts.rs" role="context" start="1048" end="1168">
pub async fn call_connector_payout(
state: &SessionState,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
connector_data: &api::ConnectorData,
payout_data: &mut PayoutData,
) -> RouterResult<()> {
let payout_attempt = &payout_data.payout_attempt.to_owned();
let payouts = &payout_data.payouts.to_owned();
// fetch merchant connector account if not present
if payout_data.merchant_connector_account.is_none()
|| payout_data.payout_attempt.merchant_connector_id.is_none()
{
let merchant_connector_account = get_mca_from_profile_id(
state,
merchant_account,
&payout_data.profile_id,
&connector_data.connector_name.to_string(),
payout_attempt
.merchant_connector_id
.clone()
.or(connector_data.merchant_connector_id.clone())
.as_ref(),
key_store,
)
.await?;
payout_data.payout_attempt.merchant_connector_id = merchant_connector_account.get_mca_id();
payout_data.merchant_connector_account = Some(merchant_connector_account);
}
// update connector_name
if payout_data.payout_attempt.connector.is_none()
|| payout_data.payout_attempt.connector != Some(connector_data.connector_name.to_string())
{
payout_data.payout_attempt.connector = Some(connector_data.connector_name.to_string());
let updated_payout_attempt = storage::PayoutAttemptUpdate::UpdateRouting {
connector: connector_data.connector_name.to_string(),
routing_info: payout_data.payout_attempt.routing_info.clone(),
merchant_connector_id: payout_data.payout_attempt.merchant_connector_id.clone(),
};
let db = &*state.store;
payout_data.payout_attempt = db
.update_payout_attempt(
&payout_data.payout_attempt,
updated_payout_attempt,
payouts,
merchant_account.storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating routing info in payout_attempt")?;
};
// Fetch / store payout_method_data
if payout_data.payout_method_data.is_none() || payout_attempt.payout_token.is_none() {
let customer_id = payouts
.customer_id
.clone()
.get_required_value("customer_id")?;
payout_data.payout_method_data = Some(
helpers::make_payout_method_data(
state,
payout_data.payout_method_data.to_owned().as_ref(),
payout_attempt.payout_token.as_deref(),
&customer_id,
&payout_attempt.merchant_id,
payouts.payout_type,
key_store,
Some(payout_data),
merchant_account.storage_scheme,
)
.await?
.get_required_value("payout_method_data")?,
);
}
// Eligibility flow
complete_payout_eligibility(state, merchant_account, connector_data, payout_data).await?;
// Create customer flow
Box::pin(complete_create_recipient(
state,
merchant_account,
key_store,
connector_data,
payout_data,
))
.await?;
// Create customer's disbursement account flow
Box::pin(complete_create_recipient_disburse_account(
state,
merchant_account,
connector_data,
payout_data,
key_store,
))
.await?;
// Payout creation flow
Box::pin(complete_create_payout(
state,
merchant_account,
connector_data,
payout_data,
))
.await?;
// Auto fulfillment flow
let status = payout_data.payout_attempt.status;
if payouts.auto_fulfill && status == storage_enums::PayoutStatus::RequiresFulfillment {
Box::pin(fulfill_payout(
state,
merchant_account,
key_store,
connector_data,
payout_data,
))
.await
.attach_printable("Payout fulfillment failed for given Payout request")?;
}
Ok(())
}
<file_sep path="hyperswitch/crates/router/src/core/payouts.rs" role="context" start="1010" end="1045">
pub async fn payouts_list_available_filters_core(
state: SessionState,
merchant_account: domain::MerchantAccount,
profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
time_range: common_utils::types::TimeRange,
) -> RouterResponse<api::PayoutListFilters> {
let db = state.store.as_ref();
let payouts = db
.filter_payouts_by_time_range_constraints(
merchant_account.get_id(),
&time_range,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
let payouts = core_utils::filter_objects_based_on_profile_id_list(profile_id_list, payouts);
let filters = db
.get_filters_for_payouts(
payouts.as_slice(),
merchant_account.get_id(),
storage_enums::MerchantStorageScheme::PostgresOnly,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
Ok(services::ApplicationResponse::Json(
api::PayoutListFilters {
connector: filters.connector,
currency: filters.currency,
status: filters.status,
payout_method: filters.payout_method,
},
))
}
<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/crates/router/src/core/errors.rs" role="context" start="31" end="31">
pub type RouterResult<T> = CustomResult<T, ApiErrorResponse>;
<file_sep path="hyperswitch/v2_compatible_migrations/2024-08-28-081757_drop_not_null_constraints_on_v1_columns/up.sql" role="context" start="5" end="21">
ALTER COLUMN org_id DROP NOT NULL;
-- Create index on org_id in organization table
-- This is done to mullify the effects of droping primary key for v1
CREATE INDEX idx_organization_org_id ON organization (org_id);
------------------------ Merchant Account -------------------
-- Drop not null in merchant_account table for v1 columns that are dropped in v2
ALTER TABLE merchant_account
DROP CONSTRAINT merchant_account_pkey,
ALTER COLUMN merchant_id DROP NOT NULL,
ALTER COLUMN primary_business_details DROP NOT NULL,
ALTER COLUMN is_recon_enabled DROP NOT NULL;
-- This is done to mullify the effects of droping primary key for v1
CREATE INDEX idx_merchant_account_merchant_id ON merchant_account (merchant_id);
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payment_methods/cards.rs<|crate|> router anchor=get_card_details_with_locker_fallback 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="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="5285" end="5285">
decrypted_data
.map(|decrypted_data| decrypted_data.into_inner().expose())
.map(|decrypted_value| decrypted_value.parse_value("generic_data"))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to parse generic data value")
}
#[cfg(all(
any(feature = "v2", feature = "v1"),
not(feature = "payment_methods_v2")
))]
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,
});
<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="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="5251" end="5280">
pub async fn decrypt_generic_data<T>(
state: &routes::SessionState,
data: Option<Encryption>,
key_store: &domain::MerchantKeyStore,
) -> errors::RouterResult<Option<T>>
where
T: serde::de::DeserializeOwned,
{
let key = key_store.key.get_inner().peek();
let identifier = Identifier::Merchant(key_store.merchant_id.clone());
let decrypted_data = domain::types::crypto_operation::<serde_json::Value, masking::WithType>(
&state.into(),
type_name!(T),
domain::types::CryptoOperation::DecryptOptional(data),
identifier,
key,
)
.await
.and_then(|val| val.try_into_optionaloperation())
.change_context(errors::StorageError::DecryptionError)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to decrypt data")?;
decrypted_data
.map(|decrypted_data| decrypted_data.into_inner().expose())
.map(|decrypted_value| decrypted_value.parse_value("generic_data"))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to parse generic data value")
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="5228" end="5249">
pub async fn get_mca_status(
state: &routes::SessionState,
key_store: &domain::MerchantKeyStore,
profile_id: Option<id_type::ProfileId>,
merchant_id: &id_type::MerchantId,
is_connector_agnostic_mit_enabled: bool,
connector_mandate_details: Option<&CommonMandateReference>,
network_transaction_id: Option<&String>,
merchant_connector_accounts: &domain::MerchantConnectorAccounts,
) -> bool {
if is_connector_agnostic_mit_enabled && network_transaction_id.is_some() {
return true;
}
match connector_mandate_details {
Some(connector_mandate_details) => merchant_connector_accounts
.is_merchant_connector_account_id_in_connector_mandate_details(
profile_id.as_ref(),
connector_mandate_details,
),
None => false,
}
}
<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/connector/nmi/transformers.rs" role="context" start="454" end="459">
pub enum PaymentMethod {
CardNonThreeDs(Box<CardData>),
CardThreeDs(Box<CardThreeDsData>),
GPay(Box<GooglePayData>),
ApplePay(Box<ApplePayData>),
}
<file_sep path="hyperswitch/v2_compatible_migrations/2024-08-28-081721_add_v2_columns/up.sql" role="context" start="54" end="70">
ADD COLUMN redirection_data JSONB,
ADD COLUMN connector_payment_data TEXT,
ADD COLUMN connector_token_details JSONB;
-- Change the type of the column from JSON to JSONB
ALTER TABLE merchant_connector_account
ADD COLUMN IF NOT EXISTS feature_metadata JSONB;
ALTER TABLE payment_methods
ADD COLUMN IF NOT EXISTS locker_fingerprint_id VARCHAR(64),
ADD COLUMN IF NOT EXISTS payment_method_type_v2 VARCHAR(64),
ADD COLUMN IF NOT EXISTS payment_method_subtype VARCHAR(64);
ALTER TABLE refund
ADD COLUMN IF NOT EXISTS id VARCHAR(64),
ADD COLUMN IF NOT EXISTS merchant_reference_id VARCHAR(64),
ADD COLUMN IF NOT EXISTS connector_id VARCHAR(64);
<file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="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/payouts/retry.rs<|crate|> router anchor=get_retries 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="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="153" end="153">
use common_enums::PayoutRetryType;
use router_env::{
logger,
tracing::{self, instrument},
};
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="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="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="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="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/tests/utils.rs" role="context" start="389" end="391">
pub struct MerchantId {
merchant_id: common_utils::id_type::MerchantId,
}
<file_sep path="hyperswitch/crates/api_models/src/errors/types.rs" role="context" start="86" end="100">
pub enum ApiErrorResponse {
Unauthorized(ApiError),
ForbiddenCommonResource(ApiError),
ForbiddenPrivateResource(ApiError),
Conflict(ApiError),
Gone(ApiError),
Unprocessable(ApiError),
InternalServerError(ApiError),
NotImplemented(ApiError),
ConnectorError(ApiError, #[serde(skip_serializing)] StatusCode),
NotFound(ApiError),
MethodNotAllowed(ApiError),
BadRequest(ApiError),
DomainError(ApiError),
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payouts.rs<|crate|> router anchor=complete_create_recipient_disburse_account 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="2009" end="2039">
pub async fn complete_create_recipient_disburse_account(
state: &SessionState,
merchant_account: &domain::MerchantAccount,
connector_data: &api::ConnectorData,
payout_data: &mut PayoutData,
key_store: &domain::MerchantKeyStore,
) -> RouterResult<()> {
if !payout_data.should_terminate
&& matches!(
payout_data.payout_attempt.status,
storage_enums::PayoutStatus::RequiresVendorAccountCreation
| storage_enums::PayoutStatus::RequiresCreation
)
&& connector_data
.connector_name
.supports_vendor_disburse_account_create_for_payout()
&& helpers::should_create_connector_transfer_method(&*payout_data, connector_data)?
.is_none()
{
Box::pin(create_recipient_disburse_account(
state,
merchant_account,
connector_data,
payout_data,
key_store,
))
.await
.attach_printable("Creation of customer failed")?;
}
Ok(())
}
<file_sep path="hyperswitch/crates/router/src/core/payouts.rs" role="context" start="2008" end="2008">
use diesel_models::{
enums as storage_enums,
generic_link::{GenericLinkNew, PayoutLink},
CommonMandateReference, PayoutsMandateReference, PayoutsMandateReferenceRecord,
};
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="2232" end="2357">
pub async fn cancel_payout(
state: &SessionState,
merchant_account: &domain::MerchantAccount,
connector_data: &api::ConnectorData,
payout_data: &mut PayoutData,
) -> RouterResult<()> {
// 1. Form Router data
let router_data = core_utils::construct_payout_router_data(
state,
connector_data,
merchant_account,
payout_data,
)
.await?;
// 2. Fetch connector integration details
let connector_integration: services::BoxedPayoutConnectorIntegrationInterface<
api::PoCancel,
types::PayoutsData,
types::PayoutsResponseData,
> = connector_data.connector.get_connector_integration();
// 3. Call connector service
let router_data_resp = services::execute_connector_processing_step(
state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
)
.await
.to_payout_failed_response()?;
// 4. Process data returned by the connector
let db = &*state.store;
match router_data_resp.response {
Ok(payout_response_data) => {
let status = payout_response_data
.status
.unwrap_or(payout_data.payout_attempt.status.to_owned());
let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate {
connector_payout_id: payout_response_data.connector_payout_id,
status,
error_code: None,
error_message: None,
is_eligible: payout_response_data.payout_eligible,
unified_code: None,
unified_message: None,
};
payout_data.payout_attempt = db
.update_payout_attempt(
&payout_data.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 = db
.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")?;
}
Err(err) => {
let status = storage_enums::PayoutStatus::Failed;
let (error_code, error_message) = (Some(err.code), Some(err.message));
let (unified_code, unified_message) = helpers::get_gsm_record(
state,
error_code.clone(),
error_message.clone(),
payout_data.payout_attempt.connector.clone(),
consts::PAYOUT_FLOW_STR,
)
.await
.map_or((None, None), |gsm| (gsm.unified_code, gsm.unified_message));
let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate {
connector_payout_id: payout_data.payout_attempt.connector_payout_id.to_owned(),
status,
error_code,
error_message,
is_eligible: None,
unified_code: unified_code
.map(UnifiedCode::try_from)
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "unified_code",
})?,
unified_message: unified_message
.map(UnifiedMessage::try_from)
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "unified_message",
})?,
};
payout_data.payout_attempt = db
.update_payout_attempt(
&payout_data.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 = db
.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")?;
}
};
Ok(())
}
<file_sep path="hyperswitch/crates/router/src/core/payouts.rs" role="context" start="2041" end="2230">
pub async fn create_recipient_disburse_account(
state: &SessionState,
merchant_account: &domain::MerchantAccount,
connector_data: &api::ConnectorData,
payout_data: &mut PayoutData,
key_store: &domain::MerchantKeyStore,
) -> RouterResult<()> {
// 1. Form Router data
let router_data = core_utils::construct_payout_router_data(
state,
connector_data,
merchant_account,
payout_data,
)
.await?;
// 2. Fetch connector integration details
let connector_integration: services::BoxedPayoutConnectorIntegrationInterface<
api::PoRecipientAccount,
types::PayoutsData,
types::PayoutsResponseData,
> = connector_data.connector.get_connector_integration();
// 3. Call connector service
let router_data_resp = services::execute_connector_processing_step(
state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
)
.await
.to_payout_failed_response()?;
// 4. Process data returned by the connector
let db = &*state.store;
match router_data_resp.response {
Ok(payout_response_data) => {
let payout_attempt = &payout_data.payout_attempt;
let status = payout_response_data
.status
.unwrap_or(payout_attempt.status.to_owned());
let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate {
connector_payout_id: payout_response_data.connector_payout_id.clone(),
status,
error_code: None,
error_message: None,
is_eligible: payout_response_data.payout_eligible,
unified_code: None,
unified_message: None,
};
payout_data.payout_attempt = db
.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")?;
if let (
true,
Some(ref payout_method_data),
Some(connector_payout_id),
Some(customer_details),
Some(merchant_connector_id),
) = (
payout_data.payouts.recurring,
payout_data.payout_method_data.clone(),
payout_response_data.connector_payout_id.clone(),
payout_data.customer_details.clone(),
connector_data.merchant_connector_id.clone(),
) {
let connector_mandate_details = HashMap::from([(
merchant_connector_id.clone(),
PayoutsMandateReferenceRecord {
transfer_method_id: Some(connector_payout_id),
},
)]);
let common_connector_mandate = CommonMandateReference {
payments: None,
payouts: Some(PayoutsMandateReference(connector_mandate_details)),
};
let connector_mandate_details_value = common_connector_mandate
.get_mandate_details_value()
.map_err(|err| {
router_env::logger::error!(
"Failed to get get_mandate_details_value : {:?}",
err
);
errors::ApiErrorResponse::MandateUpdateFailed
})?;
if let Some(pm_method) = payout_data.payment_method.clone() {
let pm_update =
diesel_models::PaymentMethodUpdate::ConnectorMandateDetailsUpdate {
#[cfg(all(
any(feature = "v1", feature = "v2"),
not(feature = "payment_methods_v2")
))]
connector_mandate_details: Some(connector_mandate_details_value),
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
connector_mandate_details: Some(common_connector_mandate),
};
payout_data.payment_method = Some(
db.update_payment_method(
&(state.into()),
key_store,
pm_method,
pm_update,
merchant_account.storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::PaymentMethodNotFound)
.attach_printable("Unable to find payment method")?,
);
} else {
#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
let customer_id = Some(customer_details.customer_id);
#[cfg(all(feature = "v2", feature = "customer_v2"))]
let customer_id = customer_details.merchant_reference_id;
if let Some(customer_id) = customer_id {
helpers::save_payout_data_to_locker(
state,
payout_data,
&customer_id,
payout_method_data,
Some(connector_mandate_details_value),
merchant_account,
key_store,
)
.await
.attach_printable("Failed to save payout data to locker")?;
}
};
}
}
Err(err) => {
let (error_code, error_message) = (Some(err.code), Some(err.message));
let (unified_code, unified_message) = helpers::get_gsm_record(
state,
error_code.clone(),
error_message.clone(),
payout_data.payout_attempt.connector.clone(),
consts::PAYOUT_FLOW_STR,
)
.await
.map_or((None, None), |gsm| (gsm.unified_code, gsm.unified_message));
let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate {
connector_payout_id: payout_data.payout_attempt.connector_payout_id.to_owned(),
status: storage_enums::PayoutStatus::Failed,
error_code,
error_message,
is_eligible: None,
unified_code: unified_code
.map(UnifiedCode::try_from)
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "unified_code",
})?,
unified_message: unified_message
.map(UnifiedMessage::try_from)
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "unified_message",
})?,
};
payout_data.payout_attempt = db
.update_payout_attempt(
&payout_data.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")?;
}
};
Ok(())
}
<file_sep path="hyperswitch/crates/router/src/core/payouts.rs" role="context" start="1918" end="2007">
pub async fn update_retrieve_payout_tracker<F, T>(
state: &SessionState,
merchant_account: &domain::MerchantAccount,
payout_data: &mut PayoutData,
payout_router_data: &types::RouterData<F, T, types::PayoutsResponseData>,
) -> RouterResult<()> {
let db = &*state.store;
match payout_router_data.response.as_ref() {
Ok(payout_response_data) => {
let payout_attempt = &payout_data.payout_attempt;
let status = payout_response_data
.status
.unwrap_or(payout_attempt.status.to_owned());
let updated_payout_attempt = if helpers::is_payout_err_state(status) {
let (error_code, error_message) = (
payout_response_data.error_code.clone(),
payout_response_data.error_message.clone(),
);
let (unified_code, unified_message) = helpers::get_gsm_record(
state,
error_code.clone(),
error_message.clone(),
payout_data.payout_attempt.connector.clone(),
consts::PAYOUT_FLOW_STR,
)
.await
.map_or((None, None), |gsm| (gsm.unified_code, gsm.unified_message));
storage::PayoutAttemptUpdate::StatusUpdate {
connector_payout_id: payout_response_data.connector_payout_id.clone(),
status,
error_code,
error_message,
is_eligible: payout_response_data.payout_eligible,
unified_code: unified_code
.map(UnifiedCode::try_from)
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "unified_code",
})?,
unified_message: unified_message
.map(UnifiedMessage::try_from)
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "unified_message",
})?,
}
} else {
storage::PayoutAttemptUpdate::StatusUpdate {
connector_payout_id: payout_response_data.connector_payout_id.clone(),
status,
error_code: None,
error_message: None,
is_eligible: payout_response_data.payout_eligible,
unified_code: None,
unified_message: None,
}
};
payout_data.payout_attempt = db
.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 = db
.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")?;
}
Err(err) => {
// log in case of error in retrieval
logger::error!("Error in payout retrieval");
// show error in the response of sync
payout_data.payout_attempt.error_code = Some(err.code.to_owned());
payout_data.payout_attempt.error_message = Some(err.message.to_owned());
}
};
Ok(())
}
<file_sep path="hyperswitch/crates/router/src/core/payouts.rs" role="context" start="1869" end="1916">
pub async fn create_payout_retrieve(
state: &SessionState,
merchant_account: &domain::MerchantAccount,
connector_data: &api::ConnectorData,
payout_data: &mut PayoutData,
) -> RouterResult<()> {
// 1. Form Router data
let mut router_data = core_utils::construct_payout_router_data(
state,
connector_data,
merchant_account,
payout_data,
)
.await?;
// 2. Get/Create access token
access_token::create_access_token(
state,
connector_data,
merchant_account,
&mut router_data,
payout_data.payouts.payout_type.to_owned(),
)
.await?;
// 3. Fetch connector integration details
let connector_integration: services::BoxedPayoutConnectorIntegrationInterface<
api::PoSync,
types::PayoutsData,
types::PayoutsResponseData,
> = connector_data.connector.get_connector_integration();
// 4. Call connector service
let router_data_resp = services::execute_connector_processing_step(
state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
)
.await
.to_payout_failed_response()?;
// 5. Process data returned by the connector
update_retrieve_payout_tracker(state, merchant_account, payout_data, &router_data_resp).await?;
Ok(())
}
<file_sep path="hyperswitch/crates/router/src/core/payouts.rs" role="context" start="1048" end="1168">
pub async fn call_connector_payout(
state: &SessionState,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
connector_data: &api::ConnectorData,
payout_data: &mut PayoutData,
) -> RouterResult<()> {
let payout_attempt = &payout_data.payout_attempt.to_owned();
let payouts = &payout_data.payouts.to_owned();
// fetch merchant connector account if not present
if payout_data.merchant_connector_account.is_none()
|| payout_data.payout_attempt.merchant_connector_id.is_none()
{
let merchant_connector_account = get_mca_from_profile_id(
state,
merchant_account,
&payout_data.profile_id,
&connector_data.connector_name.to_string(),
payout_attempt
.merchant_connector_id
.clone()
.or(connector_data.merchant_connector_id.clone())
.as_ref(),
key_store,
)
.await?;
payout_data.payout_attempt.merchant_connector_id = merchant_connector_account.get_mca_id();
payout_data.merchant_connector_account = Some(merchant_connector_account);
}
// update connector_name
if payout_data.payout_attempt.connector.is_none()
|| payout_data.payout_attempt.connector != Some(connector_data.connector_name.to_string())
{
payout_data.payout_attempt.connector = Some(connector_data.connector_name.to_string());
let updated_payout_attempt = storage::PayoutAttemptUpdate::UpdateRouting {
connector: connector_data.connector_name.to_string(),
routing_info: payout_data.payout_attempt.routing_info.clone(),
merchant_connector_id: payout_data.payout_attempt.merchant_connector_id.clone(),
};
let db = &*state.store;
payout_data.payout_attempt = db
.update_payout_attempt(
&payout_data.payout_attempt,
updated_payout_attempt,
payouts,
merchant_account.storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating routing info in payout_attempt")?;
};
// Fetch / store payout_method_data
if payout_data.payout_method_data.is_none() || payout_attempt.payout_token.is_none() {
let customer_id = payouts
.customer_id
.clone()
.get_required_value("customer_id")?;
payout_data.payout_method_data = Some(
helpers::make_payout_method_data(
state,
payout_data.payout_method_data.to_owned().as_ref(),
payout_attempt.payout_token.as_deref(),
&customer_id,
&payout_attempt.merchant_id,
payouts.payout_type,
key_store,
Some(payout_data),
merchant_account.storage_scheme,
)
.await?
.get_required_value("payout_method_data")?,
);
}
// Eligibility flow
complete_payout_eligibility(state, merchant_account, connector_data, payout_data).await?;
// Create customer flow
Box::pin(complete_create_recipient(
state,
merchant_account,
key_store,
connector_data,
payout_data,
))
.await?;
// Create customer's disbursement account flow
Box::pin(complete_create_recipient_disburse_account(
state,
merchant_account,
connector_data,
payout_data,
key_store,
))
.await?;
// Payout creation flow
Box::pin(complete_create_payout(
state,
merchant_account,
connector_data,
payout_data,
))
.await?;
// Auto fulfillment flow
let status = payout_data.payout_attempt.status;
if payouts.auto_fulfill && status == storage_enums::PayoutStatus::RequiresFulfillment {
Box::pin(fulfill_payout(
state,
merchant_account,
key_store,
connector_data,
payout_data,
))
.await
.attach_printable("Payout fulfillment failed for given Payout request")?;
}
Ok(())
}
<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/crates/router/src/core/errors.rs" role="context" start="31" end="31">
pub type RouterResult<T> = CustomResult<T, ApiErrorResponse>;
<file_sep path="hyperswitch/v2_compatible_migrations/2024-08-28-081757_drop_not_null_constraints_on_v1_columns/up.sql" role="context" start="5" end="21">
ALTER COLUMN org_id DROP NOT NULL;
-- Create index on org_id in organization table
-- This is done to mullify the effects of droping primary key for v1
CREATE INDEX idx_organization_org_id ON organization (org_id);
------------------------ Merchant Account -------------------
-- Drop not null in merchant_account table for v1 columns that are dropped in v2
ALTER TABLE merchant_account
DROP CONSTRAINT merchant_account_pkey,
ALTER COLUMN merchant_id DROP NOT NULL,
ALTER COLUMN primary_business_details DROP NOT NULL,
ALTER COLUMN is_recon_enabled DROP NOT NULL;
-- This is done to mullify the effects of droping primary key for v1
CREATE INDEX idx_merchant_account_merchant_id ON merchant_account (merchant_id);
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payments/operations/payment_confirm.rs<|crate|> router anchor=make_pm_data kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_confirm.rs" role="context" start="905" end="935">
async fn make_pm_data<'a>(
&'a self,
state: &'a SessionState,
payment_data: &mut PaymentData<F>,
storage_scheme: storage_enums::MerchantStorageScheme,
key_store: &domain::MerchantKeyStore,
customer: &Option<domain::Customer>,
business_profile: &domain::Profile,
should_retry_with_pan: bool,
) -> RouterResult<(
PaymentConfirmOperation<'a, F>,
Option<domain::PaymentMethodData>,
Option<String>,
)> {
let (op, payment_method_data, pm_id) = Box::pin(helpers::make_pm_data(
Box::new(self),
state,
payment_data,
key_store,
customer,
storage_scheme,
business_profile,
should_retry_with_pan,
))
.await?;
utils::when(payment_method_data.is_none(), || {
Err(errors::ApiErrorResponse::PaymentMethodNotFound)
})?;
Ok((op, payment_method_data, pm_id))
}
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_confirm.rs" role="context" start="904" end="904">
use crate::{
core::{
authentication,
blocklist::utils as blocklist_utils,
card_testing_guard::utils as card_testing_guard_utils,
errors::{self, CustomResult, RouterResult, StorageErrorExt},
mandate::helpers as m_helpers,
payments::{
self, helpers, operations, populate_surcharge_details, CustomerDetails, PaymentAddress,
PaymentData,
},
unified_authentication_service::{
self as uas_utils,
types::{ClickToPay, UnifiedAuthenticationService},
},
utils as core_utils,
},
routes::{app::ReqState, SessionState},
services,
types::{
self,
api::{self, ConnectorCallType, PaymentIdTypeExt},
domain::{self},
storage::{self, enums as storage_enums},
transformers::ForeignFrom,
},
utils::{self, OptionExt},
};
type PaymentConfirmOperation<'b, F> = BoxedOperation<'b, F, api::PaymentsRequest, PaymentData<F>>;
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_confirm.rs" role="context" start="968" end="979">
async fn get_connector<'a>(
&'a self,
_merchant_account: &domain::MerchantAccount,
state: &SessionState,
request: &api::PaymentsRequest,
_payment_intent: &storage::PaymentIntent,
_key_store: &domain::MerchantKeyStore,
) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> {
// Use a new connector in the confirm call or use the same one which was passed when
// creating the payment or if none is passed then use the routing algorithm
helpers::get_connector_default(state, request.routing.clone()).await
}
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_confirm.rs" role="context" start="938" end="966">
async fn add_task_to_process_tracker<'a>(
&'a self,
state: &'a SessionState,
payment_attempt: &storage::PaymentAttempt,
requeue: bool,
schedule_time: Option<time::PrimitiveDateTime>,
) -> CustomResult<(), errors::ApiErrorResponse> {
// This spawns this futures in a background thread, the exception inside this future won't affect
// the current thread and the lifecycle of spawn thread is not handled by runtime.
// So when server shutdown won't wait for this thread's completion.
let m_payment_attempt = payment_attempt.clone();
let m_state = state.clone();
let m_self = *self;
tokio::spawn(
async move {
helpers::add_domain_task_to_pt(
&m_self,
&m_state,
&m_payment_attempt,
requeue,
schedule_time,
)
.await
}
.in_current_span(),
);
Ok(())
}
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_confirm.rs" role="context" start="881" end="902">
async fn get_or_create_customer_details<'a>(
&'a self,
state: &SessionState,
payment_data: &mut PaymentData<F>,
request: Option<CustomerDetails>,
key_store: &domain::MerchantKeyStore,
storage_scheme: common_enums::enums::MerchantStorageScheme,
) -> CustomResult<
(PaymentConfirmOperation<'a, F>, Option<domain::Customer>),
errors::StorageError,
> {
helpers::create_customer_if_not_exist(
state,
Box::new(self),
payment_data,
request,
&key_store.merchant_id,
key_store,
storage_scheme,
)
.await
}
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_confirm.rs" role="context" start="844" end="875">
async fn validate_request_with_state(
&self,
state: &SessionState,
request: &api::PaymentsRequest,
payment_data: &mut PaymentData<F>,
business_profile: &domain::Profile,
) -> RouterResult<()> {
let payment_method_data: Option<&api_models::payments::PaymentMethodData> = request
.payment_method_data
.as_ref()
.and_then(|request_payment_method_data| {
request_payment_method_data.payment_method_data.as_ref()
});
let customer_id = &payment_data.payment_intent.customer_id;
match payment_method_data {
Some(api_models::payments::PaymentMethodData::Card(_card)) => {
payment_data.card_testing_guard_data =
card_testing_guard_utils::validate_card_testing_guard_checks(
state,
request,
payment_method_data,
customer_id,
business_profile,
)
.await?;
Ok(())
}
_ => Ok(()),
}
}
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_confirm.rs" role="context" start="65" end="65">
type PaymentConfirmOperation<'b, F> = BoxedOperation<'b, F, api::PaymentsRequest, PaymentData<F>>;
<file_sep path="hyperswitch/crates/router/src/compatibility/stripe/customers/types.rs" role="context" start="202" end="207">
pub struct PaymentMethodData {
pub id: Option<String>,
pub object: &'static str,
pub card: Option<CardDetails>,
pub created: Option<time::PrimitiveDateTime>,
}
<file_sep path="hyperswitch/v2_compatible_migrations/2024-08-28-081721_add_v2_columns/up.sql" role="context" start="1" end="11">
-- This file contains all new columns being added as part of v2 refactoring.
-- The new columns added should work with both v1 and v2 applications.
ALTER TABLE customers
ADD COLUMN IF NOT EXISTS merchant_reference_id VARCHAR(64),
ADD COLUMN IF NOT EXISTS default_billing_address BYTEA DEFAULT NULL,
ADD COLUMN IF NOT EXISTS default_shipping_address BYTEA DEFAULT NULL,
ADD COLUMN IF NOT EXISTS status "DeleteStatus";
CREATE TYPE "OrderFulfillmentTimeOrigin" AS ENUM ('create', 'confirm');
ALTER TABLE business_profile
<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/payments/operations/payment_confirm.rs<|crate|> router anchor=make_pm_data kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_confirm.rs" role="context" start="905" end="935">
async fn make_pm_data<'a>(
&'a self,
state: &'a SessionState,
payment_data: &mut PaymentData<F>,
storage_scheme: storage_enums::MerchantStorageScheme,
key_store: &domain::MerchantKeyStore,
customer: &Option<domain::Customer>,
business_profile: &domain::Profile,
should_retry_with_pan: bool,
) -> RouterResult<(
PaymentConfirmOperation<'a, F>,
Option<domain::PaymentMethodData>,
Option<String>,
)> {
let (op, payment_method_data, pm_id) = Box::pin(helpers::make_pm_data(
Box::new(self),
state,
payment_data,
key_store,
customer,
storage_scheme,
business_profile,
should_retry_with_pan,
))
.await?;
utils::when(payment_method_data.is_none(), || {
Err(errors::ApiErrorResponse::PaymentMethodNotFound)
})?;
Ok((op, payment_method_data, pm_id))
}
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_confirm.rs" role="context" start="904" end="904">
use crate::{
core::{
authentication,
blocklist::utils as blocklist_utils,
card_testing_guard::utils as card_testing_guard_utils,
errors::{self, CustomResult, RouterResult, StorageErrorExt},
mandate::helpers as m_helpers,
payments::{
self, helpers, operations, populate_surcharge_details, CustomerDetails, PaymentAddress,
PaymentData,
},
unified_authentication_service::{
self as uas_utils,
types::{ClickToPay, UnifiedAuthenticationService},
},
utils as core_utils,
},
routes::{app::ReqState, SessionState},
services,
types::{
self,
api::{self, ConnectorCallType, PaymentIdTypeExt},
domain::{self},
storage::{self, enums as storage_enums},
transformers::ForeignFrom,
},
utils::{self, OptionExt},
};
type PaymentConfirmOperation<'b, F> = BoxedOperation<'b, F, api::PaymentsRequest, PaymentData<F>>;
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_confirm.rs" role="context" start="968" end="979">
async fn get_connector<'a>(
&'a self,
_merchant_account: &domain::MerchantAccount,
state: &SessionState,
request: &api::PaymentsRequest,
_payment_intent: &storage::PaymentIntent,
_key_store: &domain::MerchantKeyStore,
) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> {
// Use a new connector in the confirm call or use the same one which was passed when
// creating the payment or if none is passed then use the routing algorithm
helpers::get_connector_default(state, request.routing.clone()).await
}
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_confirm.rs" role="context" start="938" end="966">
async fn add_task_to_process_tracker<'a>(
&'a self,
state: &'a SessionState,
payment_attempt: &storage::PaymentAttempt,
requeue: bool,
schedule_time: Option<time::PrimitiveDateTime>,
) -> CustomResult<(), errors::ApiErrorResponse> {
// This spawns this futures in a background thread, the exception inside this future won't affect
// the current thread and the lifecycle of spawn thread is not handled by runtime.
// So when server shutdown won't wait for this thread's completion.
let m_payment_attempt = payment_attempt.clone();
let m_state = state.clone();
let m_self = *self;
tokio::spawn(
async move {
helpers::add_domain_task_to_pt(
&m_self,
&m_state,
&m_payment_attempt,
requeue,
schedule_time,
)
.await
}
.in_current_span(),
);
Ok(())
}
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_confirm.rs" role="context" start="881" end="902">
async fn get_or_create_customer_details<'a>(
&'a self,
state: &SessionState,
payment_data: &mut PaymentData<F>,
request: Option<CustomerDetails>,
key_store: &domain::MerchantKeyStore,
storage_scheme: common_enums::enums::MerchantStorageScheme,
) -> CustomResult<
(PaymentConfirmOperation<'a, F>, Option<domain::Customer>),
errors::StorageError,
> {
helpers::create_customer_if_not_exist(
state,
Box::new(self),
payment_data,
request,
&key_store.merchant_id,
key_store,
storage_scheme,
)
.await
}
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_confirm.rs" role="context" start="844" end="875">
async fn validate_request_with_state(
&self,
state: &SessionState,
request: &api::PaymentsRequest,
payment_data: &mut PaymentData<F>,
business_profile: &domain::Profile,
) -> RouterResult<()> {
let payment_method_data: Option<&api_models::payments::PaymentMethodData> = request
.payment_method_data
.as_ref()
.and_then(|request_payment_method_data| {
request_payment_method_data.payment_method_data.as_ref()
});
let customer_id = &payment_data.payment_intent.customer_id;
match payment_method_data {
Some(api_models::payments::PaymentMethodData::Card(_card)) => {
payment_data.card_testing_guard_data =
card_testing_guard_utils::validate_card_testing_guard_checks(
state,
request,
payment_method_data,
customer_id,
business_profile,
)
.await?;
Ok(())
}
_ => Ok(()),
}
}
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_confirm.rs" role="context" start="65" end="65">
type PaymentConfirmOperation<'b, F> = BoxedOperation<'b, F, api::PaymentsRequest, PaymentData<F>>;
<file_sep path="hyperswitch/crates/router/src/compatibility/stripe/customers/types.rs" role="context" start="202" end="207">
pub struct PaymentMethodData {
pub id: Option<String>,
pub object: &'static str,
pub card: Option<CardDetails>,
pub created: Option<time::PrimitiveDateTime>,
}
<file_sep path="hyperswitch/v2_compatible_migrations/2024-08-28-081721_add_v2_columns/up.sql" role="context" start="1" end="11">
-- This file contains all new columns being added as part of v2 refactoring.
-- The new columns added should work with both v1 and v2 applications.
ALTER TABLE customers
ADD COLUMN IF NOT EXISTS merchant_reference_id VARCHAR(64),
ADD COLUMN IF NOT EXISTS default_billing_address BYTEA DEFAULT NULL,
ADD COLUMN IF NOT EXISTS default_shipping_address BYTEA DEFAULT NULL,
ADD COLUMN IF NOT EXISTS status "DeleteStatus";
CREATE TYPE "OrderFulfillmentTimeOrigin" AS ENUM ('create', 'confirm');
ALTER TABLE business_profile
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payments/helpers.rs<|crate|> router anchor=get_applepay_metadata kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="5351" end="5379">
pub fn get_applepay_metadata(
connector_metadata: Option<pii::SecretSerdeValue>,
) -> RouterResult<api_models::payments::ApplepaySessionTokenMetadata> {
connector_metadata
.clone()
.parse_value::<api_models::payments::ApplepayCombinedSessionTokenData>(
"ApplepayCombinedSessionTokenData",
)
.map(|combined_metadata| {
api_models::payments::ApplepaySessionTokenMetadata::ApplePayCombined(
combined_metadata.apple_pay_combined,
)
})
.or_else(|_| {
connector_metadata
.parse_value::<api_models::payments::ApplepaySessionTokenData>(
"ApplepaySessionTokenData",
)
.map(|old_metadata| {
api_models::payments::ApplepaySessionTokenMetadata::ApplePay(
old_metadata.apple_pay,
)
})
})
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "connector_metadata".to_string(),
expected_format: "applepay_metadata_format".to_string(),
})
}
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="5350" end="5350">
.and_then(|d| d.google_pay.clone()),
}
}
};
return Ok(Some(updated_wallet_details));
}
// Return connector_wallets_details if no Apple Pay metadata was found
Ok(connector_wallets_details_optional)
}
pub fn get_applepay_metadata(
connector_metadata: Option<pii::SecretSerdeValue>,
) -> RouterResult<api_models::payments::ApplepaySessionTokenMetadata> {
connector_metadata
.clone()
.parse_value::<api_models::payments::ApplepayCombinedSessionTokenData>(
"ApplepayCombinedSessionTokenData",
)
.map(|combined_metadata| {
api_models::payments::ApplepaySessionTokenMetadata::ApplePayCombined(
combined_metadata.apple_pay_combined,
)
})
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="5529" end="5537">
pub fn token_json(
wallet_data: domain::WalletData,
) -> CustomResult<Self, errors::ConnectorError> {
let json_wallet_data: Self = connector::utils::WalletData::get_wallet_token_as_json(
&wallet_data,
"Apple Pay".to_string(),
)?;
Ok(json_wallet_data)
}
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="5382" end="5510">
pub async fn get_apple_pay_retryable_connectors<F, D>(
state: &SessionState,
merchant_account: &domain::MerchantAccount,
payment_data: &D,
key_store: &domain::MerchantKeyStore,
pre_routing_connector_data_list: &[api::ConnectorData],
merchant_connector_id: Option<&id_type::MerchantConnectorAccountId>,
business_profile: domain::Profile,
) -> CustomResult<Option<Vec<api::ConnectorData>>, errors::ApiErrorResponse>
where
F: Send + Clone,
D: payments::OperationSessionGetters<F> + Send,
{
let profile_id = business_profile.get_id();
let pre_decided_connector_data_first = pre_routing_connector_data_list
.first()
.ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)?;
let merchant_connector_account_type = get_merchant_connector_account(
state,
merchant_account.get_id(),
payment_data.get_creds_identifier(),
key_store,
profile_id,
&pre_decided_connector_data_first.connector_name.to_string(),
merchant_connector_id,
)
.await?;
let connector_data_list = if is_apple_pay_simplified_flow(
merchant_connector_account_type.get_metadata(),
merchant_connector_account_type
.get_connector_name()
.as_ref(),
)? {
let merchant_connector_account_list = state
.store
.find_merchant_connector_account_by_merchant_id_and_disabled_list(
&state.into(),
merchant_account.get_id(),
false,
key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::InternalServerError)?;
let profile_specific_merchant_connector_account_list = merchant_connector_account_list
.filter_based_on_profile_and_connector_type(
profile_id,
ConnectorType::PaymentProcessor,
);
let mut connector_data_list = vec![pre_decided_connector_data_first.clone()];
for merchant_connector_account in profile_specific_merchant_connector_account_list {
if is_apple_pay_simplified_flow(
merchant_connector_account.metadata.clone(),
Some(&merchant_connector_account.connector_name),
)? {
let connector_data = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
&merchant_connector_account.connector_name.to_string(),
api::GetToken::Connector,
Some(merchant_connector_account.get_id()),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Invalid connector name received")?;
if !connector_data_list.iter().any(|connector_details| {
connector_details.merchant_connector_id == connector_data.merchant_connector_id
}) {
connector_data_list.push(connector_data)
}
}
}
#[cfg(feature = "v1")]
let fallback_connetors_list = crate::core::routing::helpers::get_merchant_default_config(
&*state.clone().store,
profile_id.get_string_repr(),
&api_enums::TransactionType::Payment,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get merchant default fallback connectors config")?;
#[cfg(feature = "v2")]
let fallback_connetors_list = core_admin::ProfileWrapper::new(business_profile)
.get_default_fallback_list_of_connector_under_profile()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get merchant default fallback connectors config")?;
let mut routing_connector_data_list = Vec::new();
pre_routing_connector_data_list.iter().for_each(|pre_val| {
routing_connector_data_list.push(pre_val.merchant_connector_id.clone())
});
fallback_connetors_list.iter().for_each(|fallback_val| {
routing_connector_data_list
.iter()
.all(|val| *val != fallback_val.merchant_connector_id)
.then(|| {
routing_connector_data_list.push(fallback_val.merchant_connector_id.clone())
});
});
// connector_data_list is the list of connectors for which Apple Pay simplified flow is configured.
// This list is arranged in the same order as the merchant's connectors routingconfiguration.
let mut ordered_connector_data_list = Vec::new();
routing_connector_data_list
.iter()
.for_each(|merchant_connector_id| {
let connector_data = connector_data_list.iter().find(|connector_data| {
*merchant_connector_id == connector_data.merchant_connector_id
});
if let Some(connector_data_details) = connector_data {
ordered_connector_data_list.push(connector_data_details.clone());
}
});
Some(ordered_connector_data_list)
} else {
None
};
Ok(connector_data_list)
}
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="5283" end="5349">
async fn get_and_merge_apple_pay_metadata(
connector_metadata: Option<masking::Secret<tera::Value>>,
connector_wallets_details_optional: Option<api_models::admin::ConnectorWalletDetails>,
) -> RouterResult<Option<api_models::admin::ConnectorWalletDetails>> {
let apple_pay_metadata_optional = get_applepay_metadata(connector_metadata)
.map_err(|error| {
logger::error!(
"Apple Pay metadata parsing failed in get_encrypted_connector_wallets_details_with_apple_pay_certificates {:?}",
error
);
})
.ok();
if let Some(apple_pay_metadata) = apple_pay_metadata_optional {
let updated_wallet_details = match apple_pay_metadata {
api_models::payments::ApplepaySessionTokenMetadata::ApplePayCombined(
apple_pay_combined_metadata,
) => {
let combined_metadata_json = serde_json::to_value(apple_pay_combined_metadata)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to serialize Apple Pay combined metadata as JSON")?;
api_models::admin::ConnectorWalletDetails {
apple_pay_combined: Some(masking::Secret::new(combined_metadata_json)),
apple_pay: connector_wallets_details_optional
.as_ref()
.and_then(|d| d.apple_pay.clone()),
samsung_pay: connector_wallets_details_optional
.as_ref()
.and_then(|d| d.samsung_pay.clone()),
paze: connector_wallets_details_optional
.as_ref()
.and_then(|d| d.paze.clone()),
google_pay: connector_wallets_details_optional
.as_ref()
.and_then(|d| d.google_pay.clone()),
}
}
api_models::payments::ApplepaySessionTokenMetadata::ApplePay(apple_pay_metadata) => {
let metadata_json = serde_json::to_value(apple_pay_metadata)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to serialize Apple Pay metadata as JSON")?;
api_models::admin::ConnectorWalletDetails {
apple_pay: Some(masking::Secret::new(metadata_json)),
apple_pay_combined: connector_wallets_details_optional
.as_ref()
.and_then(|d| d.apple_pay_combined.clone()),
samsung_pay: connector_wallets_details_optional
.as_ref()
.and_then(|d| d.samsung_pay.clone()),
paze: connector_wallets_details_optional
.as_ref()
.and_then(|d| d.paze.clone()),
google_pay: connector_wallets_details_optional
.as_ref()
.and_then(|d| d.google_pay.clone()),
}
}
};
return Ok(Some(updated_wallet_details));
}
// Return connector_wallets_details if no Apple Pay metadata was found
Ok(connector_wallets_details_optional)
}
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="5261" end="5281">
async fn get_apple_pay_metadata_if_needed(
connector_metadata: &Option<masking::Secret<tera::Value>>,
connector_wallets_details_optional: &Option<api_models::admin::ConnectorWalletDetails>,
) -> RouterResult<Option<api_models::admin::ConnectorWalletDetails>> {
if let Some(connector_wallets_details) = connector_wallets_details_optional {
if connector_wallets_details.apple_pay_combined.is_some()
|| connector_wallets_details.apple_pay.is_some()
{
return Ok(Some(connector_wallets_details.clone()));
}
// Otherwise, merge Apple Pay metadata
return get_and_merge_apple_pay_metadata(
connector_metadata.clone(),
Some(connector_wallets_details.clone()),
)
.await;
}
// If connector_wallets_details_optional is None, attempt to get Apple Pay metadata
get_and_merge_apple_pay_metadata(connector_metadata.clone(), None).await
}
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="5210" end="5233">
pub fn is_apple_pay_simplified_flow(
connector_metadata: Option<pii::SecretSerdeValue>,
connector_name: Option<&String>,
) -> CustomResult<bool, errors::ApiErrorResponse> {
let option_apple_pay_metadata = get_applepay_metadata(connector_metadata)
.map_err(|error| {
logger::info!(
"Apple pay metadata parsing for {:?} in is_apple_pay_simplified_flow {:?}",
connector_name,
error
)
})
.ok();
// return true only if the apple flow type is simplified
Ok(matches!(
option_apple_pay_metadata,
Some(
api_models::payments::ApplepaySessionTokenMetadata::ApplePayCombined(
api_models::payments::ApplePayCombinedMetadata::Simplified { .. }
)
)
))
}
<file_sep path="hyperswitch/crates/router/src/connector/utils.rs" role="context" start="1750" end="1752">
pub trait ApplePay {
fn get_applepay_decoded_payment_data(&self) -> Result<Secret<String>, Error>;
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/unified_authentication_service.rs<|crate|> router anchor=get_pre_authentication_request_data kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/unified_authentication_service.rs" role="context" start="246" end="275">
fn get_pre_authentication_request_data(
payment_data: &PaymentData<F>,
) -> RouterResult<UasPreAuthenticationRequestData> {
let payment_method_data = payment_data
.payment_method_data
.as_ref()
.ok_or(ApiErrorResponse::InternalServerError)
.attach_printable("payment_data.payment_method_data is missing")?;
let payment_details =
if let payment_method_data::PaymentMethodData::Card(card) = payment_method_data {
Some(PaymentDetails {
pan: card.card_number.clone(),
digital_card_id: None,
payment_data_type: None,
encrypted_src_card_details: None,
card_expiry_date: card.card_exp_year.clone(),
cardholder_name: card.card_holder_name.clone(),
card_token_number: card.card_cvc.clone(),
account_type: card.card_network.clone(),
})
} else {
None
};
Ok(UasPreAuthenticationRequestData {
service_details: None,
transaction_details: None,
payment_details,
authentication_info: None,
})
}
<file_sep path="hyperswitch/crates/router/src/core/unified_authentication_service.rs" role="context" start="245" end="245">
use hyperswitch_domain_models::{
errors::api_error_response::ApiErrorResponse,
payment_method_data,
router_request_types::{
authentication::{MessageCategory, PreAuthenticationData},
unified_authentication_service::{
AuthenticationInfo, PaymentDetails, ServiceSessionIds, TransactionDetails,
UasAuthenticationRequestData, UasConfirmationRequestData,
UasPostAuthenticationRequestData, UasPreAuthenticationRequestData,
},
BrowserInformation,
},
types::{
UasAuthenticationRouterData, UasPostAuthenticationRouterData,
UasPreAuthenticationRouterData,
},
};
use super::{errors::RouterResult, payments::helpers::MerchantConnectorAccountType};
use crate::{
core::{
errors::utils::StorageErrorExt,
payments::PaymentData,
unified_authentication_service::types::{
ClickToPay, ExternalAuthentication, UnifiedAuthenticationService,
UNIFIED_AUTHENTICATION_SERVICE,
},
},
db::domain,
routes::SessionState,
};
<file_sep path="hyperswitch/crates/router/src/core/unified_authentication_service.rs" role="context" start="311" end="362">
fn get_authentication_request_data(
payment_method_data: domain::PaymentMethodData,
billing_address: hyperswitch_domain_models::address::Address,
shipping_address: Option<hyperswitch_domain_models::address::Address>,
browser_details: Option<BrowserInformation>,
amount: Option<common_utils::types::MinorUnit>,
currency: Option<common_enums::Currency>,
message_category: MessageCategory,
device_channel: payments::DeviceChannel,
authentication: 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,
) -> RouterResult<UasAuthenticationRequestData> {
Ok(UasAuthenticationRequestData {
payment_method_data,
billing_address,
shipping_address,
browser_details,
transaction_details: TransactionDetails {
amount,
currency,
device_channel: Some(device_channel),
message_category: Some(message_category),
},
pre_authentication_data: PreAuthenticationData {
threeds_server_transaction_id: authentication.threeds_server_transaction_id.ok_or(
ApiErrorResponse::MissingRequiredField {
field_name: "authentication.threeds_server_transaction_id",
},
)?,
message_version: authentication.message_version.ok_or(
ApiErrorResponse::MissingRequiredField {
field_name: "authentication.message_version",
},
)?,
acquirer_bin: authentication.acquirer_bin,
acquirer_merchant_id: authentication.acquirer_merchant_id,
acquirer_country_code: authentication.acquirer_country_code,
connector_metadata: authentication.connector_metadata,
},
return_url,
sdk_information,
email,
threeds_method_comp_ind,
three_ds_requestor_url,
webhook_url,
})
}
<file_sep path="hyperswitch/crates/router/src/core/unified_authentication_service.rs" role="context" start="278" end="309">
async fn pre_authentication(
state: &SessionState,
_key_store: &domain::MerchantKeyStore,
_business_profile: &domain::Profile,
payment_data: &PaymentData<F>,
merchant_connector_account: &MerchantConnectorAccountType,
connector_name: &str,
authentication_id: &str,
payment_method: common_enums::PaymentMethod,
) -> RouterResult<UasPreAuthenticationRouterData> {
let pre_authentication_data = Self::get_pre_authentication_request_data(payment_data)?;
let pre_auth_router_data: UasPreAuthenticationRouterData =
utils::construct_uas_router_data(
state,
connector_name.to_string(),
payment_method,
payment_data.payment_attempt.merchant_id.clone(),
None,
pre_authentication_data,
merchant_connector_account,
Some(authentication_id.to_owned()),
payment_data.payment_intent.payment_id.clone(),
)?;
utils::do_auth_connector_call(
state,
UNIFIED_AUTHENTICATION_SERVICE.to_string(),
pre_auth_router_data,
)
.await
}
<file_sep path="hyperswitch/crates/router/src/core/unified_authentication_service.rs" role="context" start="167" end="240">
async fn confirmation(
state: &SessionState,
_key_store: &domain::MerchantKeyStore,
_business_profile: &domain::Profile,
payment_data: &PaymentData<F>,
merchant_connector_account: &MerchantConnectorAccountType,
connector_name: &str,
payment_method: common_enums::PaymentMethod,
) -> RouterResult<()> {
let authentication_id = payment_data
.payment_attempt
.authentication_id
.clone()
.ok_or(ApiErrorResponse::InternalServerError)
.attach_printable("Missing authentication id in payment attempt")?;
let currency = payment_data.payment_attempt.currency.ok_or(
ApiErrorResponse::MissingRequiredField {
field_name: "currency",
},
)?;
let current_time = common_utils::date_time::now();
let payment_attempt_status = payment_data.payment_attempt.status;
let (checkout_event_status, confirmation_reason) =
utils::get_checkout_event_status_and_reason(payment_attempt_status);
let click_to_pay_details = payment_data.service_details.clone();
let authentication_confirmation_data = UasConfirmationRequestData {
x_src_flow_id: payment_data
.service_details
.as_ref()
.and_then(|details| details.x_src_flow_id.clone()),
transaction_amount: payment_data.payment_attempt.net_amount.get_order_amount(),
transaction_currency: currency,
checkout_event_type: Some("01".to_string()), // hardcoded to '01' since only authorise flow is implemented
checkout_event_status: checkout_event_status.clone(),
confirmation_status: checkout_event_status.clone(),
confirmation_reason,
confirmation_timestamp: Some(current_time),
network_authorization_code: Some("01".to_string()), // hardcoded to '01' since only authorise flow is implemented
network_transaction_identifier: Some("01".to_string()), // hardcoded to '01' since only authorise flow is implemented
correlation_id: click_to_pay_details
.clone()
.and_then(|details| details.correlation_id),
merchant_transaction_id: click_to_pay_details
.and_then(|details| details.merchant_transaction_id),
};
let authentication_confirmation_router_data : hyperswitch_domain_models::types::UasAuthenticationConfirmationRouterData = utils::construct_uas_router_data(
state,
connector_name.to_string(),
payment_method,
payment_data.payment_attempt.merchant_id.clone(),
None,
authentication_confirmation_data,
merchant_connector_account,
Some(authentication_id.clone()),
payment_data.payment_intent.payment_id.clone()
)?;
utils::do_auth_connector_call(
state,
UNIFIED_AUTHENTICATION_SERVICE.to_string(),
authentication_confirmation_router_data,
)
.await
.ok(); // marking this as .ok() since this is not a required step at our end for completing the transaction
Ok(())
}
<file_sep path="hyperswitch/crates/router/src/core/unified_authentication_service.rs" role="context" start="125" end="165">
async fn post_authentication(
state: &SessionState,
_key_store: &domain::MerchantKeyStore,
_business_profile: &domain::Profile,
payment_data: &PaymentData<F>,
merchant_connector_account: &MerchantConnectorAccountType,
connector_name: &str,
payment_method: common_enums::PaymentMethod,
_authentication: Option<Authentication>,
) -> RouterResult<UasPostAuthenticationRouterData> {
let authentication_id = payment_data
.payment_attempt
.authentication_id
.clone()
.ok_or(ApiErrorResponse::InternalServerError)
.attach_printable("Missing authentication id in payment attempt")?;
let post_authentication_data = UasPostAuthenticationRequestData {
threeds_server_transaction_id: None,
};
let post_auth_router_data: UasPostAuthenticationRouterData =
utils::construct_uas_router_data(
state,
connector_name.to_string(),
payment_method,
payment_data.payment_attempt.merchant_id.clone(),
None,
post_authentication_data,
merchant_connector_account,
Some(authentication_id.clone()),
payment_data.payment_intent.payment_id.clone(),
)?;
utils::do_auth_connector_call(
state,
UNIFIED_AUTHENTICATION_SERVICE.to_string(),
post_auth_router_data,
)
.await
}
<file_sep path="hyperswitch/crates/router/src/core/unified_authentication_service.rs" role="context" start="92" end="123">
async fn pre_authentication(
state: &SessionState,
_key_store: &domain::MerchantKeyStore,
_business_profile: &domain::Profile,
payment_data: &PaymentData<F>,
merchant_connector_account: &MerchantConnectorAccountType,
connector_name: &str,
authentication_id: &str,
payment_method: common_enums::PaymentMethod,
) -> RouterResult<UasPreAuthenticationRouterData> {
let pre_authentication_data = Self::get_pre_authentication_request_data(payment_data)?;
let pre_auth_router_data: UasPreAuthenticationRouterData =
utils::construct_uas_router_data(
state,
connector_name.to_string(),
payment_method,
payment_data.payment_attempt.merchant_id.clone(),
None,
pre_authentication_data,
merchant_connector_account,
Some(authentication_id.to_owned()),
payment_data.payment_intent.payment_id.clone(),
)?;
utils::do_auth_connector_call(
state,
UNIFIED_AUTHENTICATION_SERVICE.to_string(),
pre_auth_router_data,
)
.await
}
<file_sep path="hyperswitch/crates/router/src/compatibility/stripe/customers/types.rs" role="context" start="202" end="207">
pub struct PaymentMethodData {
pub id: Option<String>,
pub object: &'static str,
pub card: Option<CardDetails>,
pub created: Option<time::PrimitiveDateTime>,
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payments/helpers.rs<|crate|> router anchor=get_unified_translation kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="6421" end="6454">
pub async fn get_unified_translation(
state: &SessionState,
unified_code: String,
unified_message: String,
locale: String,
) -> Option<String> {
let get_unified_translation = || async {
state.store.find_translation(
unified_code.clone(),
unified_message.clone(),
locale.clone(),
)
.await
.map_err(|err| {
if err.current_context().is_db_not_found() {
logger::warn!(
"Translation missing for unified_code - {:?}, unified_message - {:?}, locale - {:?}",
unified_code,
unified_message,
locale
);
}
err.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed to fetch translation from unified_translations")
})
};
get_unified_translation()
.await
.inspect_err(|err| {
// warn log should suffice here because we are not propagating this error
logger::warn!(get_translation_error=?err, "error fetching unified translations");
})
.ok()
}
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="6420" end="6420">
use redis_interface::errors::RedisError;
use router_env::{instrument, logger, tracing};
use crate::{
configs::settings::{ConnectorRequestReferenceIdConfig, TempLockerEnableConfig},
connector,
consts::{self, BASE64_ENGINE},
core::{
authentication,
errors::{self, CustomResult, RouterResult, StorageErrorExt},
mandate::helpers::MandateGenericData,
payment_methods::{
self,
cards::{self},
network_tokenization, vault,
},
payments,
pm_auth::retrieve_payment_method_from_auth_service,
},
db::StorageInterface,
routes::{metrics, payment_methods as payment_methods_handler, SessionState},
services,
types::{
api::{self, admin, enums as api_enums, MandateValidationFieldsExt},
domain::{self, types},
storage::{self, enums as storage_enums, ephemeral_key, CardTokenData},
transformers::{ForeignFrom, ForeignTryFrom},
AdditionalMerchantData, AdditionalPaymentMethodConnectorResponse, ErrorResponse,
MandateReference, MerchantAccountData, MerchantRecipientData, PaymentsResponseData,
RecipientIdType, RecurringMandatePaymentData, RouterData,
},
utils::{
self,
crypto::{self, SignMessage},
OptionExt, StringExt,
},
};
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="6480" end="6488">
pub fn validate_session_expiry(session_expiry: u32) -> Result<(), errors::ApiErrorResponse> {
if !(consts::MIN_SESSION_EXPIRY..=consts::MAX_SESSION_EXPIRY).contains(&session_expiry) {
Err(errors::ApiErrorResponse::InvalidRequestData {
message: "session_expiry should be between 60(1 min) to 7890000(3 months).".to_string(),
})
} else {
Ok(())
}
}
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="6455" end="6477">
pub fn validate_order_details_amount(
order_details: Vec<api_models::payments::OrderDetailsWithAmount>,
amount: MinorUnit,
should_validate: bool,
) -> Result<(), errors::ApiErrorResponse> {
if should_validate {
let total_order_details_amount: MinorUnit = order_details
.iter()
.map(|order| order.amount * order.quantity)
.sum();
if total_order_details_amount != amount {
Err(errors::ApiErrorResponse::InvalidRequestData {
message: "Total sum of order details doesn't match amount in payment request"
.to_string(),
})
} else {
Ok(())
}
} else {
Ok(())
}
}
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="6379" end="6419">
pub async fn get_gsm_record(
state: &SessionState,
error_code: Option<String>,
error_message: Option<String>,
connector_name: String,
flow: String,
) -> Option<storage::gsm::GatewayStatusMap> {
let get_gsm = || async {
state.store.find_gsm_rule(
connector_name.clone(),
flow.clone(),
"sub_flow".to_string(),
error_code.clone().unwrap_or_default(), // TODO: make changes in connector to get a mandatory code in case of success or error response
error_message.clone().unwrap_or_default(),
)
.await
.map_err(|err| {
if err.current_context().is_db_not_found() {
logger::warn!(
"GSM miss for connector - {}, flow - {}, error_code - {:?}, error_message - {:?}",
connector_name,
flow,
error_code,
error_message
);
metrics::AUTO_RETRY_GSM_MISS_COUNT.add( 1, &[]);
} else {
metrics::AUTO_RETRY_GSM_FETCH_FAILURE_COUNT.add( 1, &[]);
};
err.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed to fetch decision from gsm")
})
};
get_gsm()
.await
.inspect_err(|err| {
// warn log should suffice here because we are not propagating this error
logger::warn!(get_gsm_decision_fetch_error=?err, "error fetching gsm decision");
})
.ok()
}
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="6364" end="6377">
pub fn validate_payment_link_request(
confirm: Option<bool>,
) -> Result<(), errors::ApiErrorResponse> {
if let Some(cnf) = confirm {
if !cnf {
return Ok(());
} else {
return Err(errors::ApiErrorResponse::InvalidRequestData {
message: "cannot confirm a payment while creating a payment link".to_string(),
});
}
}
Ok(())
}
<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/core/payments/helpers.rs<|crate|> router anchor=validate_mandate kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="1073" end="1095">
pub fn validate_mandate(
req: impl Into<api::MandateValidationFields>,
is_confirm_operation: bool,
) -> CustomResult<Option<api::MandateTransactionType>, errors::ApiErrorResponse> {
let req: api::MandateValidationFields = req.into();
match req.validate_and_get_mandate_type().change_context(
errors::ApiErrorResponse::MandateValidationFailed {
reason: "Expected one out of recurring_details and mandate_data but got both".into(),
},
)? {
Some(api::MandateTransactionType::NewMandateTransaction) => {
validate_new_mandate_request(req, is_confirm_operation)?;
Ok(Some(api::MandateTransactionType::NewMandateTransaction))
}
Some(api::MandateTransactionType::RecurringMandateTransaction) => {
validate_recurring_mandate(req)?;
Ok(Some(
api::MandateTransactionType::RecurringMandateTransaction,
))
}
None => Ok(None),
}
}
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="1072" end="1072">
use redis_interface::errors::RedisError;
use crate::{
configs::settings::{ConnectorRequestReferenceIdConfig, TempLockerEnableConfig},
connector,
consts::{self, BASE64_ENGINE},
core::{
authentication,
errors::{self, CustomResult, RouterResult, StorageErrorExt},
mandate::helpers::MandateGenericData,
payment_methods::{
self,
cards::{self},
network_tokenization, vault,
},
payments,
pm_auth::retrieve_payment_method_from_auth_service,
},
db::StorageInterface,
routes::{metrics, payment_methods as payment_methods_handler, SessionState},
services,
types::{
api::{self, admin, enums as api_enums, MandateValidationFieldsExt},
domain::{self, types},
storage::{self, enums as storage_enums, ephemeral_key, CardTokenData},
transformers::{ForeignFrom, ForeignTryFrom},
AdditionalMerchantData, AdditionalPaymentMethodConnectorResponse, ErrorResponse,
MandateReference, MerchantAccountData, MerchantRecipientData, PaymentsResponseData,
RecipientIdType, RecurringMandatePaymentData, RouterData,
},
utils::{
self,
crypto::{self, SignMessage},
OptionExt, StringExt,
},
};
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="1121" end="1167">
fn validate_new_mandate_request(
req: api::MandateValidationFields,
is_confirm_operation: bool,
) -> RouterResult<()> {
// We need not check for customer_id in the confirm request if it is already passed
// in create request
fp_utils::when(!is_confirm_operation && req.customer_id.is_none(), || {
Err(report!(errors::ApiErrorResponse::PreconditionFailed {
message: "`customer_id` is mandatory for mandates".into()
}))
})?;
let mandate_data = req
.mandate_data
.clone()
.get_required_value("mandate_data")?;
// Only use this validation if the customer_acceptance is present
if mandate_data
.customer_acceptance
.map(|inner| inner.acceptance_type == api::AcceptanceType::Online && inner.online.is_none())
.unwrap_or(false)
{
Err(report!(errors::ApiErrorResponse::PreconditionFailed {
message: "`mandate_data.customer_acceptance.online` is required when \
`mandate_data.customer_acceptance.acceptance_type` is `online`"
.into()
}))?
}
let mandate_details = match mandate_data.mandate_type {
Some(api_models::payments::MandateType::SingleUse(details)) => Some(details),
Some(api_models::payments::MandateType::MultiUse(details)) => details,
_ => None,
};
mandate_details.and_then(|md| md.start_date.zip(md.end_date)).map(|(start_date, end_date)|
utils::when (start_date >= end_date, || {
Err(report!(errors::ApiErrorResponse::PreconditionFailed {
message: "`mandate_data.mandate_type.{multi_use|single_use}.start_date` should be greater than \
`mandate_data.mandate_type.{multi_use|single_use}.end_date`"
.into()
}))
})).transpose()?;
Ok(())
}
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="1097" end="1119">
pub fn validate_recurring_details_and_token(
recurring_details: &Option<RecurringDetails>,
payment_token: &Option<String>,
mandate_id: &Option<String>,
) -> CustomResult<(), errors::ApiErrorResponse> {
utils::when(
recurring_details.is_some() && payment_token.is_some(),
|| {
Err(report!(errors::ApiErrorResponse::PreconditionFailed {
message: "Expected one out of recurring_details and payment_token but got both"
.into()
}))
},
)?;
utils::when(recurring_details.is_some() && mandate_id.is_some(), || {
Err(report!(errors::ApiErrorResponse::PreconditionFailed {
message: "Expected one out of recurring_details and mandate_id but got both".into()
}))
})?;
Ok(())
}
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="1052" end="1071">
pub fn infer_payment_type(
amount: api::Amount,
mandate_type: Option<&api::MandateTransactionType>,
) -> api_enums::PaymentType {
match mandate_type {
Some(api::MandateTransactionType::NewMandateTransaction) => {
if let api::Amount::Value(_) = amount {
api_enums::PaymentType::NewMandate
} else {
api_enums::PaymentType::SetupMandate
}
}
Some(api::MandateTransactionType::RecurringMandateTransaction) => {
api_enums::PaymentType::RecurringMandate
}
None => api_enums::PaymentType::Normal,
}
}
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="1004" end="1050">
pub fn validate_card_expiry(
card_exp_month: &masking::Secret<String>,
card_exp_year: &masking::Secret<String>,
) -> CustomResult<(), errors::ApiErrorResponse> {
let exp_month = card_exp_month
.peek()
.to_string()
.parse::<u8>()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "card_exp_month",
})?;
let month = ::cards::CardExpirationMonth::try_from(exp_month).change_context(
errors::ApiErrorResponse::PreconditionFailed {
message: "Invalid Expiry Month".to_string(),
},
)?;
let mut year_str = card_exp_year.peek().to_string();
if year_str.len() == 2 {
year_str = format!("20{}", year_str);
}
let exp_year =
year_str
.parse::<u16>()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "card_exp_year",
})?;
let year = ::cards::CardExpirationYear::try_from(exp_year).change_context(
errors::ApiErrorResponse::PreconditionFailed {
message: "Invalid Expiry Year".to_string(),
},
)?;
let card_expiration = ::cards::CardExpiration { month, year };
let is_expired = card_expiration.is_expired().change_context(
errors::ApiErrorResponse::PreconditionFailed {
message: "Invalid card data".to_string(),
},
)?;
if is_expired {
Err(report!(errors::ApiErrorResponse::PreconditionFailed {
message: "Card Expired".to_string()
}))?
}
Ok(())
}
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="1269" end="1296">
fn validate_recurring_mandate(req: api::MandateValidationFields) -> RouterResult<()> {
let recurring_details = req
.recurring_details
.get_required_value("recurring_details")?;
match recurring_details {
RecurringDetails::ProcessorPaymentToken(_)
| RecurringDetails::NetworkTransactionIdAndCardDetails(_) => Ok(()),
_ => {
req.customer_id.check_value_present("customer_id")?;
let confirm = req.confirm.get_required_value("confirm")?;
if !confirm {
Err(report!(errors::ApiErrorResponse::PreconditionFailed {
message: "`confirm` must be `true` for mandates".into()
}))?
}
let off_session = req.off_session.get_required_value("off_session")?;
if !off_session {
Err(report!(errors::ApiErrorResponse::PreconditionFailed {
message: "`off_session` should be `true` for mandates".into()
}))?
}
Ok(())
}
}
}
<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/payments/helpers.rs<|crate|> router anchor=validate_mandate kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="1073" end="1095">
pub fn validate_mandate(
req: impl Into<api::MandateValidationFields>,
is_confirm_operation: bool,
) -> CustomResult<Option<api::MandateTransactionType>, errors::ApiErrorResponse> {
let req: api::MandateValidationFields = req.into();
match req.validate_and_get_mandate_type().change_context(
errors::ApiErrorResponse::MandateValidationFailed {
reason: "Expected one out of recurring_details and mandate_data but got both".into(),
},
)? {
Some(api::MandateTransactionType::NewMandateTransaction) => {
validate_new_mandate_request(req, is_confirm_operation)?;
Ok(Some(api::MandateTransactionType::NewMandateTransaction))
}
Some(api::MandateTransactionType::RecurringMandateTransaction) => {
validate_recurring_mandate(req)?;
Ok(Some(
api::MandateTransactionType::RecurringMandateTransaction,
))
}
None => Ok(None),
}
}
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="1072" end="1072">
use redis_interface::errors::RedisError;
use crate::{
configs::settings::{ConnectorRequestReferenceIdConfig, TempLockerEnableConfig},
connector,
consts::{self, BASE64_ENGINE},
core::{
authentication,
errors::{self, CustomResult, RouterResult, StorageErrorExt},
mandate::helpers::MandateGenericData,
payment_methods::{
self,
cards::{self},
network_tokenization, vault,
},
payments,
pm_auth::retrieve_payment_method_from_auth_service,
},
db::StorageInterface,
routes::{metrics, payment_methods as payment_methods_handler, SessionState},
services,
types::{
api::{self, admin, enums as api_enums, MandateValidationFieldsExt},
domain::{self, types},
storage::{self, enums as storage_enums, ephemeral_key, CardTokenData},
transformers::{ForeignFrom, ForeignTryFrom},
AdditionalMerchantData, AdditionalPaymentMethodConnectorResponse, ErrorResponse,
MandateReference, MerchantAccountData, MerchantRecipientData, PaymentsResponseData,
RecipientIdType, RecurringMandatePaymentData, RouterData,
},
utils::{
self,
crypto::{self, SignMessage},
OptionExt, StringExt,
},
};
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="1121" end="1167">
fn validate_new_mandate_request(
req: api::MandateValidationFields,
is_confirm_operation: bool,
) -> RouterResult<()> {
// We need not check for customer_id in the confirm request if it is already passed
// in create request
fp_utils::when(!is_confirm_operation && req.customer_id.is_none(), || {
Err(report!(errors::ApiErrorResponse::PreconditionFailed {
message: "`customer_id` is mandatory for mandates".into()
}))
})?;
let mandate_data = req
.mandate_data
.clone()
.get_required_value("mandate_data")?;
// Only use this validation if the customer_acceptance is present
if mandate_data
.customer_acceptance
.map(|inner| inner.acceptance_type == api::AcceptanceType::Online && inner.online.is_none())
.unwrap_or(false)
{
Err(report!(errors::ApiErrorResponse::PreconditionFailed {
message: "`mandate_data.customer_acceptance.online` is required when \
`mandate_data.customer_acceptance.acceptance_type` is `online`"
.into()
}))?
}
let mandate_details = match mandate_data.mandate_type {
Some(api_models::payments::MandateType::SingleUse(details)) => Some(details),
Some(api_models::payments::MandateType::MultiUse(details)) => details,
_ => None,
};
mandate_details.and_then(|md| md.start_date.zip(md.end_date)).map(|(start_date, end_date)|
utils::when (start_date >= end_date, || {
Err(report!(errors::ApiErrorResponse::PreconditionFailed {
message: "`mandate_data.mandate_type.{multi_use|single_use}.start_date` should be greater than \
`mandate_data.mandate_type.{multi_use|single_use}.end_date`"
.into()
}))
})).transpose()?;
Ok(())
}
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="1097" end="1119">
pub fn validate_recurring_details_and_token(
recurring_details: &Option<RecurringDetails>,
payment_token: &Option<String>,
mandate_id: &Option<String>,
) -> CustomResult<(), errors::ApiErrorResponse> {
utils::when(
recurring_details.is_some() && payment_token.is_some(),
|| {
Err(report!(errors::ApiErrorResponse::PreconditionFailed {
message: "Expected one out of recurring_details and payment_token but got both"
.into()
}))
},
)?;
utils::when(recurring_details.is_some() && mandate_id.is_some(), || {
Err(report!(errors::ApiErrorResponse::PreconditionFailed {
message: "Expected one out of recurring_details and mandate_id but got both".into()
}))
})?;
Ok(())
}
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="1052" end="1071">
pub fn infer_payment_type(
amount: api::Amount,
mandate_type: Option<&api::MandateTransactionType>,
) -> api_enums::PaymentType {
match mandate_type {
Some(api::MandateTransactionType::NewMandateTransaction) => {
if let api::Amount::Value(_) = amount {
api_enums::PaymentType::NewMandate
} else {
api_enums::PaymentType::SetupMandate
}
}
Some(api::MandateTransactionType::RecurringMandateTransaction) => {
api_enums::PaymentType::RecurringMandate
}
None => api_enums::PaymentType::Normal,
}
}
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="1004" end="1050">
pub fn validate_card_expiry(
card_exp_month: &masking::Secret<String>,
card_exp_year: &masking::Secret<String>,
) -> CustomResult<(), errors::ApiErrorResponse> {
let exp_month = card_exp_month
.peek()
.to_string()
.parse::<u8>()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "card_exp_month",
})?;
let month = ::cards::CardExpirationMonth::try_from(exp_month).change_context(
errors::ApiErrorResponse::PreconditionFailed {
message: "Invalid Expiry Month".to_string(),
},
)?;
let mut year_str = card_exp_year.peek().to_string();
if year_str.len() == 2 {
year_str = format!("20{}", year_str);
}
let exp_year =
year_str
.parse::<u16>()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "card_exp_year",
})?;
let year = ::cards::CardExpirationYear::try_from(exp_year).change_context(
errors::ApiErrorResponse::PreconditionFailed {
message: "Invalid Expiry Year".to_string(),
},
)?;
let card_expiration = ::cards::CardExpiration { month, year };
let is_expired = card_expiration.is_expired().change_context(
errors::ApiErrorResponse::PreconditionFailed {
message: "Invalid card data".to_string(),
},
)?;
if is_expired {
Err(report!(errors::ApiErrorResponse::PreconditionFailed {
message: "Card Expired".to_string()
}))?
}
Ok(())
}
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="1269" end="1296">
fn validate_recurring_mandate(req: api::MandateValidationFields) -> RouterResult<()> {
let recurring_details = req
.recurring_details
.get_required_value("recurring_details")?;
match recurring_details {
RecurringDetails::ProcessorPaymentToken(_)
| RecurringDetails::NetworkTransactionIdAndCardDetails(_) => Ok(()),
_ => {
req.customer_id.check_value_present("customer_id")?;
let confirm = req.confirm.get_required_value("confirm")?;
if !confirm {
Err(report!(errors::ApiErrorResponse::PreconditionFailed {
message: "`confirm` must be `true` for mandates".into()
}))?
}
let off_session = req.off_session.get_required_value("off_session")?;
if !off_session {
Err(report!(errors::ApiErrorResponse::PreconditionFailed {
message: "`off_session` should be `true` for mandates".into()
}))?
}
Ok(())
}
}
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/refunds.rs<|crate|> router anchor=refund_retrieve_core_with_internal_reference_id 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="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="1052" end="1052">
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="1124" end="1176">
pub async fn refund_manual_update(
state: SessionState,
req: api_models::refunds::RefundManualUpdateRequest,
) -> RouterResponse<serde_json::Value> {
let key_manager_state = &(&state).into();
let key_store = state
.store
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&req.merchant_id,
&state.store.get_master_key().to_vec().into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)
.attach_printable("Error while fetching the key store by merchant_id")?;
let merchant_account = state
.store
.find_merchant_account_by_merchant_id(key_manager_state, &req.merchant_id, &key_store)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)
.attach_printable("Error while fetching the merchant_account by merchant_id")?;
let refund = state
.store
.find_refund_by_merchant_id_refund_id(
merchant_account.get_id(),
&req.refund_id,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?;
let refund_update = storage::RefundUpdate::ManualUpdate {
refund_status: req.status.map(common_enums::RefundStatus::from),
refund_error_message: req.error_message,
refund_error_code: req.error_code,
updated_by: merchant_account.storage_scheme.to_string(),
};
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
)
})?;
Ok(services::ApplicationResponse::StatusOk)
}
<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/crates/router/src/core/refunds.rs" role="context" start="1034" end="1050">
pub async fn refund_filter_list(
state: SessionState,
merchant_account: domain::MerchantAccount,
req: common_utils::types::TimeRange,
) -> RouterResponse<api_models::refunds::RefundListMetaData> {
let db = state.store;
let filter_list = db
.filter_refund_by_meta_constraints(
merchant_account.get_id(),
&req,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?;
Ok(services::ApplicationResponse::Json(filter_list))
}
<file_sep path="hyperswitch/crates/router/src/core/refunds.rs" role="context" start="988" end="1030">
pub async fn refund_list(
state: SessionState,
merchant_account: domain::MerchantAccount,
profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
req: api_models::refunds::RefundListRequest,
) -> RouterResponse<api_models::refunds::RefundListResponse> {
let db = state.store;
let limit = validator::validate_refund_list(req.limit)?;
let offset = req.offset.unwrap_or_default();
let refund_list = db
.filter_refund_by_constraints(
merchant_account.get_id(),
&(req.clone(), profile_id_list.clone()).try_into()?,
merchant_account.storage_scheme,
limit,
offset,
)
.await
.to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?;
let data: Vec<refunds::RefundResponse> = refund_list
.into_iter()
.map(ForeignInto::foreign_into)
.collect();
let total_count = db
.get_total_count_of_refunds(
merchant_account.get_id(),
&(req, profile_id_list).try_into()?,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::InternalServerError)?;
Ok(services::ApplicationResponse::Json(
api_models::refunds::RefundListResponse {
count: data.len(),
total_count,
data,
},
))
}
<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="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/configs/settings.rs" role="context" start="721" end="724">
pub struct Refund {
pub max_attempts: usize,
pub max_age: i64,
}
<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/payments/operations/payment_response.rs<|crate|> router anchor=response_to_capture_update kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_response.rs" role="context" start="2715" end="2741">
fn response_to_capture_update(
multiple_capture_data: &MultipleCaptureData,
response_list: HashMap<String, CaptureSyncResponse>,
) -> RouterResult<Vec<(storage::Capture, storage::CaptureUpdate)>> {
let mut capture_update_list = vec![];
let mut unmapped_captures = vec![];
for (connector_capture_id, capture_sync_response) in response_list {
let capture =
multiple_capture_data.get_capture_by_connector_capture_id(&connector_capture_id);
if let Some(capture) = capture {
capture_update_list.push((
capture.clone(),
storage::CaptureUpdate::foreign_try_from(capture_sync_response)?,
))
} else {
// connector_capture_id may not be populated in the captures table in some case
// if so, we try to map the unmapped capture response and captures in DB.
unmapped_captures.push(capture_sync_response)
}
}
capture_update_list.extend(get_capture_update_for_unmapped_capture_responses(
unmapped_captures,
multiple_capture_data,
)?);
Ok(capture_update_list)
}
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_response.rs" role="context" start="2714" end="2714">
use std::collections::HashMap;
use crate::{
connector::utils::PaymentResponseRouterData,
consts,
core::{
card_testing_guard::utils as card_testing_guard_utils,
errors::{self, CustomResult, RouterResult, StorageErrorExt},
mandate,
payment_methods::{self, cards::create_encrypted_data},
payments::{
helpers::{
self as payments_helpers,
update_additional_payment_data_with_connector_response_pm_data,
},
tokenization,
types::MultipleCaptureData,
PaymentData, PaymentMethodChecker,
},
utils as core_utils,
},
routes::{metrics, SessionState},
types::{
self, domain,
storage::{self, enums},
transformers::{ForeignFrom, ForeignTryFrom},
CaptureSyncResponse, ErrorResponse,
},
utils,
};
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_response.rs" role="context" start="2771" end="2796">
fn get_total_amount_captured<F: Clone, T: types::Capturable>(
request: &T,
amount_captured: Option<MinorUnit>,
router_data_status: enums::AttemptStatus,
payment_data: &PaymentData<F>,
) -> Option<MinorUnit> {
match &payment_data.multiple_capture_data {
Some(multiple_capture_data) => {
//multiple capture
Some(multiple_capture_data.get_total_blocked_amount())
}
None => {
//Non multiple capture
let amount = request
.get_captured_amount(payment_data)
.map(MinorUnit::new);
amount_captured.or_else(|| {
if router_data_status == enums::AttemptStatus::Charged {
amount
} else {
None
}
})
}
}
}
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_response.rs" role="context" start="2743" end="2769">
fn get_capture_update_for_unmapped_capture_responses(
unmapped_capture_sync_response_list: Vec<CaptureSyncResponse>,
multiple_capture_data: &MultipleCaptureData,
) -> RouterResult<Vec<(storage::Capture, storage::CaptureUpdate)>> {
let mut result = Vec::new();
let captures_without_connector_capture_id: Vec<_> = multiple_capture_data
.get_pending_captures_without_connector_capture_id()
.into_iter()
.cloned()
.collect();
for capture_sync_response in unmapped_capture_sync_response_list {
if let Some(capture) = captures_without_connector_capture_id
.iter()
.find(|capture| {
capture_sync_response.get_connector_response_reference_id()
== Some(capture.capture_id.clone())
|| capture_sync_response.get_amount_captured() == Some(capture.amount)
})
{
result.push((
capture.clone(),
storage::CaptureUpdate::foreign_try_from(capture_sync_response)?,
))
}
}
Ok(result)
}
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_response.rs" role="context" start="2668" end="2713">
fn update_connector_mandate_details_for_the_flow<F: Clone>(
connector_mandate_id: Option<String>,
mandate_metadata: Option<masking::Secret<serde_json::Value>>,
connector_mandate_request_reference_id: Option<String>,
payment_data: &mut PaymentData<F>,
) -> RouterResult<()> {
let mut original_connector_mandate_reference_id = payment_data
.payment_attempt
.connector_mandate_detail
.as_ref()
.map(|detail| ConnectorMandateReferenceId::foreign_from(detail.clone()));
let connector_mandate_reference_id = if connector_mandate_id.is_some() {
if let Some(ref mut record) = original_connector_mandate_reference_id {
record.update(
connector_mandate_id,
None,
None,
mandate_metadata,
connector_mandate_request_reference_id,
);
Some(record.clone())
} else {
Some(ConnectorMandateReferenceId::new(
connector_mandate_id,
None,
None,
mandate_metadata,
connector_mandate_request_reference_id,
))
}
} else {
original_connector_mandate_reference_id
};
payment_data.payment_attempt.connector_mandate_detail = connector_mandate_reference_id
.clone()
.map(ForeignFrom::foreign_from);
payment_data.set_mandate_id(api_models::payments::MandateIds {
mandate_id: None,
mandate_reference_id: connector_mandate_reference_id.map(|connector_mandate_id| {
MandateReferenceId::ConnectorMandateId(connector_mandate_id)
}),
});
Ok(())
}
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_response.rs" role="context" start="2564" end="2664">
async fn save_pm_and_mandate<'b>(
&self,
state: &SessionState,
router_data: &types::RouterData<
F,
types::SetupMandateRequestData,
types::PaymentsResponseData,
>,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
payment_data: &mut PaymentConfirmData<F>,
_business_profile: &domain::Profile,
) -> CustomResult<(), errors::ApiErrorResponse>
where
F: 'b + Clone + Send + Sync,
{
// If we received a payment_method_id from connector in the router data response
// Then we either update the payment method or create a new payment method
// The case for updating the payment method is when the payment is created from the payment method service
let Ok(payments_response) = &router_data.response else {
// In case there was an error response from the connector
// We do not take any action related to the payment method
return Ok(());
};
let connector_request_reference_id = payment_data
.payment_attempt
.connector_token_details
.as_ref()
.and_then(|token_details| token_details.get_connector_token_request_reference_id());
let connector_token =
payments_response.get_updated_connector_token_details(connector_request_reference_id);
let payment_method_id = payment_data.payment_attempt.payment_method_id.clone();
// TODO: check what all conditions we will need to see if card need to be saved
match (
connector_token
.as_ref()
.and_then(|connector_token| connector_token.connector_mandate_id.clone()),
payment_method_id,
) {
(Some(token), Some(payment_method_id)) => {
if !matches!(
router_data.status,
enums::AttemptStatus::Charged | enums::AttemptStatus::Authorized
) {
return Ok(());
}
let connector_id = payment_data
.payment_attempt
.merchant_connector_id
.clone()
.get_required_value("merchant_connector_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("missing connector id")?;
let net_amount = payment_data.payment_attempt.amount_details.get_net_amount();
let currency = payment_data.payment_intent.amount_details.currency;
let connector_token_details_for_payment_method_update =
api_models::payment_methods::ConnectorTokenDetails {
connector_id,
status: common_enums::ConnectorTokenStatus::Active,
connector_token_request_reference_id: connector_token
.and_then(|details| details.connector_token_request_reference_id),
original_payment_authorized_amount: Some(net_amount),
original_payment_authorized_currency: Some(currency),
metadata: None,
token: masking::Secret::new(token),
token_type: common_enums::TokenizationType::MultiUse,
};
let payment_method_update_request =
api_models::payment_methods::PaymentMethodUpdate {
payment_method_data: None,
connector_token_details: Some(
connector_token_details_for_payment_method_update,
),
};
payment_methods::update_payment_method_core(
state,
merchant_account,
key_store,
payment_method_update_request,
&payment_method_id,
)
.await
.attach_printable("Failed to update payment method")?;
}
(Some(_), None) => {
// TODO: create a new payment method
}
(None, Some(_)) | (None, None) => {}
}
Ok(())
}
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_response.rs" role="context" start="1257" end="2115">
async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
state: &SessionState,
mut payment_data: PaymentData<F>,
router_data: types::RouterData<F, T, types::PaymentsResponseData>,
key_store: &domain::MerchantKeyStore,
storage_scheme: enums::MerchantStorageScheme,
locale: &Option<String>,
#[cfg(all(feature = "v1", feature = "dynamic_routing"))] routable_connectors: Vec<
RoutableConnectorChoice,
>,
#[cfg(all(feature = "v1", feature = "dynamic_routing"))] business_profile: &domain::Profile,
) -> RouterResult<PaymentData<F>> {
// Update additional payment data with the payment method response that we received from connector
// This is for details like whether 3ds was upgraded and which version of 3ds was used
// also some connectors might send card network details in the response, which is captured and stored
let additional_payment_method_data = match payment_data.payment_method_data.clone() {
Some(payment_method_data) => match payment_method_data {
hyperswitch_domain_models::payment_method_data::PaymentMethodData::Card(_)
| hyperswitch_domain_models::payment_method_data::PaymentMethodData::CardRedirect(_)
| hyperswitch_domain_models::payment_method_data::PaymentMethodData::Wallet(_)
| hyperswitch_domain_models::payment_method_data::PaymentMethodData::PayLater(_)
| hyperswitch_domain_models::payment_method_data::PaymentMethodData::BankRedirect(_)
| hyperswitch_domain_models::payment_method_data::PaymentMethodData::BankDebit(_)
| hyperswitch_domain_models::payment_method_data::PaymentMethodData::BankTransfer(_)
| hyperswitch_domain_models::payment_method_data::PaymentMethodData::Crypto(_)
| hyperswitch_domain_models::payment_method_data::PaymentMethodData::MandatePayment
| hyperswitch_domain_models::payment_method_data::PaymentMethodData::Reward
| hyperswitch_domain_models::payment_method_data::PaymentMethodData::RealTimePayment(
_,
)
| hyperswitch_domain_models::payment_method_data::PaymentMethodData::MobilePayment(_)
| hyperswitch_domain_models::payment_method_data::PaymentMethodData::Upi(_)
| hyperswitch_domain_models::payment_method_data::PaymentMethodData::Voucher(_)
| hyperswitch_domain_models::payment_method_data::PaymentMethodData::GiftCard(_)
| hyperswitch_domain_models::payment_method_data::PaymentMethodData::CardToken(_)
| hyperswitch_domain_models::payment_method_data::PaymentMethodData::OpenBanking(_) => {
update_additional_payment_data_with_connector_response_pm_data(
payment_data.payment_attempt.payment_method_data.clone(),
router_data
.connector_response
.as_ref()
.and_then(|connector_response| {
connector_response.additional_payment_method_data.clone()
}),
)?
}
hyperswitch_domain_models::payment_method_data::PaymentMethodData::NetworkToken(_) => {
payment_data.payment_attempt.payment_method_data.clone()
}
hyperswitch_domain_models::payment_method_data::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
payment_data.payment_attempt.payment_method_data.clone()
}
},
None => None,
};
router_data.payment_method_status.and_then(|status| {
payment_data
.payment_method_info
.as_mut()
.map(|info| info.status = status)
});
let (capture_update, mut payment_attempt_update) = match router_data.response.clone() {
Err(err) => {
let auth_update = if Some(router_data.auth_type)
!= payment_data.payment_attempt.authentication_type
{
Some(router_data.auth_type)
} else {
None
};
let (capture_update, attempt_update) = match payment_data.multiple_capture_data {
Some(multiple_capture_data) => {
let capture_update = storage::CaptureUpdate::ErrorUpdate {
status: match err.status_code {
500..=511 => enums::CaptureStatus::Pending,
_ => enums::CaptureStatus::Failed,
},
error_code: Some(err.code),
error_message: Some(err.message),
error_reason: err.reason,
};
let capture_update_list = vec![(
multiple_capture_data.get_latest_capture().clone(),
capture_update,
)];
(
Some((multiple_capture_data, capture_update_list)),
auth_update.map(|auth_type| {
storage::PaymentAttemptUpdate::AuthenticationTypeUpdate {
authentication_type: auth_type,
updated_by: storage_scheme.to_string(),
}
}),
)
}
None => {
let connector_name = router_data.connector.to_string();
let flow_name = core_utils::get_flow_name::<F>()?;
let option_gsm = payments_helpers::get_gsm_record(
state,
Some(err.code.clone()),
Some(err.message.clone()),
connector_name,
flow_name.clone(),
)
.await;
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(),
)
};
let unified_translated_message = locale
.as_ref()
.async_and_then(|locale_str| async {
payments_helpers::get_unified_translation(
state,
unified_code.to_owned(),
unified_message.to_owned(),
locale_str.to_owned(),
)
.await
})
.await
.or(Some(unified_message));
let status = match err.attempt_status {
// Use the status sent by connector in error_response if it's present
Some(status) => status,
None =>
// mark previous attempt status for technical failures in PSync flow
{
if flow_name == "PSync" {
match err.status_code {
// marking failure for 2xx because this is genuine payment failure
200..=299 => enums::AttemptStatus::Failure,
_ => router_data.status,
}
} else if flow_name == "Capture" {
match err.status_code {
500..=511 => enums::AttemptStatus::Pending,
// don't update the status for 429 error status
429 => router_data.status,
_ => enums::AttemptStatus::Failure,
}
} else {
match err.status_code {
500..=511 => enums::AttemptStatus::Pending,
_ => enums::AttemptStatus::Failure,
}
}
}
};
(
None,
Some(storage::PaymentAttemptUpdate::ErrorUpdate {
connector: None,
status,
error_message: Some(Some(err.message)),
error_code: Some(Some(err.code)),
error_reason: Some(err.reason),
amount_capturable: router_data
.request
.get_amount_capturable(&payment_data, status)
.map(MinorUnit::new),
updated_by: storage_scheme.to_string(),
unified_code: Some(Some(unified_code)),
unified_message: Some(unified_translated_message),
connector_transaction_id: err.connector_transaction_id,
payment_method_data: additional_payment_method_data,
authentication_type: auth_update,
issuer_error_code: err.network_decline_code,
issuer_error_message: err.network_error_message,
}),
)
}
};
(capture_update, attempt_update)
}
Ok(payments_response) => {
// match on connector integrity check
match router_data.integrity_check.clone() {
Err(err) => {
let auth_update = if Some(router_data.auth_type)
!= payment_data.payment_attempt.authentication_type
{
Some(router_data.auth_type)
} else {
None
};
let field_name = err.field_names;
let connector_transaction_id = err.connector_transaction_id;
(
None,
Some(storage::PaymentAttemptUpdate::ErrorUpdate {
connector: None,
status: enums::AttemptStatus::Pending,
error_message: Some(Some("Integrity Check Failed!".to_string())),
error_code: Some(Some("IE".to_string())),
error_reason: Some(Some(format!(
"Integrity Check Failed! Value mismatched for fields {field_name}"
))),
amount_capturable: None,
updated_by: storage_scheme.to_string(),
unified_code: None,
unified_message: None,
connector_transaction_id,
payment_method_data: None,
authentication_type: auth_update,
issuer_error_code: None,
issuer_error_message: None,
}),
)
}
Ok(()) => {
let attempt_status = payment_data.payment_attempt.status.to_owned();
let connector_status = router_data.status.to_owned();
let updated_attempt_status = match (
connector_status,
attempt_status,
payment_data.frm_message.to_owned(),
) {
(
enums::AttemptStatus::Authorized,
enums::AttemptStatus::Unresolved,
Some(frm_message),
) => match frm_message.frm_status {
enums::FraudCheckStatus::Fraud
| enums::FraudCheckStatus::ManualReview => attempt_status,
_ => router_data.get_attempt_status_for_db_update(&payment_data),
},
_ => router_data.get_attempt_status_for_db_update(&payment_data),
};
match payments_response {
types::PaymentsResponseData::PreProcessingResponse {
pre_processing_id,
connector_metadata,
connector_response_reference_id,
..
} => {
let connector_transaction_id = match pre_processing_id.to_owned() {
types::PreprocessingResponseId::PreProcessingId(_) => None,
types::PreprocessingResponseId::ConnectorTransactionId(
connector_txn_id,
) => Some(connector_txn_id),
};
let preprocessing_step_id = match pre_processing_id {
types::PreprocessingResponseId::PreProcessingId(
pre_processing_id,
) => Some(pre_processing_id),
types::PreprocessingResponseId::ConnectorTransactionId(_) => None,
};
let payment_attempt_update =
storage::PaymentAttemptUpdate::PreprocessingUpdate {
status: updated_attempt_status,
payment_method_id: payment_data
.payment_attempt
.payment_method_id
.clone(),
connector_metadata,
preprocessing_step_id,
connector_transaction_id,
connector_response_reference_id,
updated_by: storage_scheme.to_string(),
};
(None, Some(payment_attempt_update))
}
types::PaymentsResponseData::TransactionResponse {
resource_id,
redirection_data,
connector_metadata,
connector_response_reference_id,
incremental_authorization_allowed,
charges,
..
} => {
payment_data
.payment_intent
.incremental_authorization_allowed =
core_utils::get_incremental_authorization_allowed_value(
incremental_authorization_allowed,
payment_data
.payment_intent
.request_incremental_authorization,
);
let connector_transaction_id = match resource_id {
types::ResponseId::NoResponseId => None,
types::ResponseId::ConnectorTransactionId(ref id)
| types::ResponseId::EncodedData(ref id) => Some(id),
};
let encoded_data = payment_data.payment_attempt.encoded_data.clone();
let authentication_data = (*redirection_data)
.as_ref()
.map(Encode::encode_to_value)
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Could not parse the connector response")?;
let auth_update = if Some(router_data.auth_type)
!= payment_data.payment_attempt.authentication_type
{
Some(router_data.auth_type)
} else {
None
};
// incase of success, update error code and error message
let error_status =
if router_data.status == enums::AttemptStatus::Charged {
Some(None)
} else {
None
};
// update connector_mandate_details in case of Authorized/Charged Payment Status
if matches!(
router_data.status,
enums::AttemptStatus::Charged | enums::AttemptStatus::Authorized
) {
payment_data
.payment_intent
.fingerprint_id
.clone_from(&payment_data.payment_attempt.fingerprint_id);
if let Some(payment_method) =
payment_data.payment_method_info.clone()
{
// Parse value to check for mandates' existence
let mandate_details = payment_method
.get_common_mandate_reference()
.change_context(
errors::ApiErrorResponse::InternalServerError,
)
.attach_printable(
"Failed to deserialize to Payment Mandate Reference ",
)?;
if let Some(mca_id) =
payment_data.payment_attempt.merchant_connector_id.clone()
{
// check if the mandate has not already been set to active
if !mandate_details.payments
.as_ref()
.and_then(|payments| payments.0.get(&mca_id))
.map(|payment_mandate_reference_record| payment_mandate_reference_record.connector_mandate_status == Some(common_enums::ConnectorMandateStatus::Active))
.unwrap_or(false)
{
let (connector_mandate_id, mandate_metadata,connector_mandate_request_reference_id) = payment_data.payment_attempt.connector_mandate_detail.clone()
.map(|cmr| (cmr.connector_mandate_id, cmr.mandate_metadata,cmr.connector_mandate_request_reference_id))
.unwrap_or((None, None,None));
// Update the connector mandate details with the payment attempt connector mandate id
let connector_mandate_details =
tokenization::update_connector_mandate_details(
Some(mandate_details),
payment_data.payment_attempt.payment_method_type,
Some(
payment_data
.payment_attempt
.net_amount
.get_total_amount()
.get_amount_as_i64(),
),
payment_data.payment_attempt.currency,
payment_data.payment_attempt.merchant_connector_id.clone(),
connector_mandate_id,
mandate_metadata,
connector_mandate_request_reference_id
)?;
// Update the payment method table with the active mandate record
payment_methods::cards::update_payment_method_connector_mandate_details(
state,
key_store,
&*state.store,
payment_method,
connector_mandate_details,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update payment method in db")?;
}
}
}
metrics::SUCCESSFUL_PAYMENT.add(1, &[]);
}
let payment_method_id =
payment_data.payment_attempt.payment_method_id.clone();
utils::add_apple_pay_payment_status_metrics(
router_data.status,
router_data.apple_pay_flow.clone(),
payment_data.payment_attempt.connector.clone(),
payment_data.payment_attempt.merchant_id.clone(),
);
let (capture_before, extended_authorization_applied) = router_data
.connector_response
.as_ref()
.and_then(|connector_response| {
connector_response.get_extended_authorization_response_data()
})
.map(|extended_auth_resp| {
(
extended_auth_resp.capture_before,
extended_auth_resp.extended_authentication_applied,
)
})
.unwrap_or((None, None));
let (capture_updates, payment_attempt_update) = match payment_data
.multiple_capture_data
{
Some(multiple_capture_data) => {
let (connector_capture_id, processor_capture_data) =
match resource_id {
types::ResponseId::NoResponseId => (None, None),
types::ResponseId::ConnectorTransactionId(id)
| types::ResponseId::EncodedData(id) => {
let (txn_id, txn_data) =
ConnectorTransactionId::form_id_and_data(id);
(Some(txn_id), txn_data)
}
};
let capture_update = storage::CaptureUpdate::ResponseUpdate {
status: enums::CaptureStatus::foreign_try_from(
router_data.status,
)?,
connector_capture_id: connector_capture_id.clone(),
connector_response_reference_id,
processor_capture_data: processor_capture_data.clone(),
};
let capture_update_list = vec![(
multiple_capture_data.get_latest_capture().clone(),
capture_update,
)];
(Some((multiple_capture_data, capture_update_list)), auth_update.map(|auth_type| {
storage::PaymentAttemptUpdate::AuthenticationTypeUpdate {
authentication_type: auth_type,
updated_by: storage_scheme.to_string(),
}
}))
}
None => (
None,
Some(storage::PaymentAttemptUpdate::ResponseUpdate {
status: updated_attempt_status,
connector: None,
connector_transaction_id: connector_transaction_id.cloned(),
authentication_type: auth_update,
amount_capturable: router_data
.request
.get_amount_capturable(
&payment_data,
updated_attempt_status,
)
.map(MinorUnit::new),
payment_method_id,
mandate_id: payment_data.payment_attempt.mandate_id.clone(),
connector_metadata,
payment_token: None,
error_code: error_status.clone(),
error_message: error_status.clone(),
error_reason: error_status.clone(),
unified_code: error_status.clone(),
unified_message: error_status,
connector_response_reference_id,
updated_by: storage_scheme.to_string(),
authentication_data,
encoded_data,
payment_method_data: additional_payment_method_data,
capture_before,
extended_authorization_applied,
connector_mandate_detail: payment_data
.payment_attempt
.connector_mandate_detail
.clone(),
charges,
}),
),
};
(capture_updates, payment_attempt_update)
}
types::PaymentsResponseData::TransactionUnresolvedResponse {
resource_id,
reason,
connector_response_reference_id,
} => {
let connector_transaction_id = match resource_id {
types::ResponseId::NoResponseId => None,
types::ResponseId::ConnectorTransactionId(id)
| types::ResponseId::EncodedData(id) => Some(id),
};
(
None,
Some(storage::PaymentAttemptUpdate::UnresolvedResponseUpdate {
status: updated_attempt_status,
connector: None,
connector_transaction_id,
payment_method_id: payment_data
.payment_attempt
.payment_method_id
.clone(),
error_code: Some(reason.clone().map(|cd| cd.code)),
error_message: Some(reason.clone().map(|cd| cd.message)),
error_reason: Some(reason.map(|cd| cd.message)),
connector_response_reference_id,
updated_by: storage_scheme.to_string(),
}),
)
}
types::PaymentsResponseData::SessionResponse { .. } => (None, None),
types::PaymentsResponseData::SessionTokenResponse { .. } => (None, None),
types::PaymentsResponseData::TokenizationResponse { .. } => (None, None),
types::PaymentsResponseData::ConnectorCustomerResponse { .. } => {
(None, None)
}
types::PaymentsResponseData::ThreeDSEnrollmentResponse { .. } => {
(None, None)
}
types::PaymentsResponseData::PostProcessingResponse { .. } => (None, None),
types::PaymentsResponseData::IncrementalAuthorizationResponse {
..
} => (None, None),
types::PaymentsResponseData::SessionUpdateResponse { .. } => (None, None),
types::PaymentsResponseData::MultipleCaptureResponse {
capture_sync_response_list,
} => match payment_data.multiple_capture_data {
Some(multiple_capture_data) => {
let capture_update_list = response_to_capture_update(
&multiple_capture_data,
capture_sync_response_list,
)?;
(Some((multiple_capture_data, capture_update_list)), None)
}
None => (None, None),
},
}
}
}
}
};
payment_data.multiple_capture_data = match capture_update {
Some((mut multiple_capture_data, capture_updates)) => {
for (capture, capture_update) in capture_updates {
let updated_capture = state
.store
.update_capture_with_capture_id(capture, capture_update, storage_scheme)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
multiple_capture_data.update_capture(updated_capture);
}
let authorized_amount = payment_data.payment_attempt.get_total_amount();
payment_attempt_update = Some(storage::PaymentAttemptUpdate::AmountToCaptureUpdate {
status: multiple_capture_data.get_attempt_status(authorized_amount),
amount_capturable: authorized_amount
- multiple_capture_data.get_total_blocked_amount(),
updated_by: storage_scheme.to_string(),
});
Some(multiple_capture_data)
}
None => None,
};
// Stage 1
let payment_attempt = payment_data.payment_attempt.clone();
let m_db = state.clone().store;
let m_payment_attempt_update = payment_attempt_update.clone();
let m_payment_attempt = payment_attempt.clone();
let payment_attempt = payment_attempt_update
.map(|payment_attempt_update| {
PaymentAttempt::from_storage_model(
payment_attempt_update
.to_storage_model()
.apply_changeset(payment_attempt.clone().to_storage_model()),
)
})
.unwrap_or_else(|| payment_attempt);
let payment_attempt_fut = tokio::spawn(
async move {
Box::pin(async move {
Ok::<_, error_stack::Report<errors::ApiErrorResponse>>(
match m_payment_attempt_update {
Some(payment_attempt_update) => m_db
.update_payment_attempt_with_attempt_id(
m_payment_attempt,
payment_attempt_update,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?,
None => m_payment_attempt,
},
)
})
.await
}
.in_current_span(),
);
payment_data.payment_attempt = payment_attempt;
payment_data.authentication = match payment_data.authentication {
Some(authentication) => {
let authentication_update = storage::AuthenticationUpdate::PostAuthorizationUpdate {
authentication_lifecycle_status: enums::AuthenticationLifecycleStatus::Used,
};
let updated_authentication = state
.store
.update_authentication_by_merchant_id_authentication_id(
authentication,
authentication_update,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
Some(updated_authentication)
}
None => None,
};
let amount_captured = get_total_amount_captured(
&router_data.request,
router_data.amount_captured.map(MinorUnit::new),
router_data.status,
&payment_data,
);
let payment_intent_update = match &router_data.response {
Err(_) => storage::PaymentIntentUpdate::PGStatusUpdate {
status: api_models::enums::IntentStatus::foreign_from(
payment_data.payment_attempt.status,
),
updated_by: storage_scheme.to_string(),
// make this false only if initial payment fails, if incremental authorization call fails don't make it false
incremental_authorization_allowed: Some(false),
},
Ok(_) => storage::PaymentIntentUpdate::ResponseUpdate {
status: api_models::enums::IntentStatus::foreign_from(
payment_data.payment_attempt.status,
),
amount_captured,
updated_by: storage_scheme.to_string(),
fingerprint_id: payment_data.payment_attempt.fingerprint_id.clone(),
incremental_authorization_allowed: payment_data
.payment_intent
.incremental_authorization_allowed,
},
};
let m_db = state.clone().store;
let m_key_store = key_store.clone();
let m_payment_data_payment_intent = payment_data.payment_intent.clone();
let m_payment_intent_update = payment_intent_update.clone();
let key_manager_state: KeyManagerState = state.into();
let payment_intent_fut = tokio::spawn(
async move {
m_db.update_payment_intent(
&key_manager_state,
m_payment_data_payment_intent,
m_payment_intent_update,
&m_key_store,
storage_scheme,
)
.map(|x| x.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound))
.await
}
.in_current_span(),
);
// When connector requires redirection for mandate creation it can update the connector mandate_id during Psync and CompleteAuthorize
let m_db = state.clone().store;
let m_router_data_merchant_id = router_data.merchant_id.clone();
let m_payment_method_id = payment_data.payment_attempt.payment_method_id.clone();
let m_payment_data_mandate_id =
payment_data
.payment_attempt
.mandate_id
.clone()
.or(payment_data
.mandate_id
.clone()
.and_then(|mandate_ids| mandate_ids.mandate_id));
let m_router_data_response = router_data.response.clone();
let mandate_update_fut = tokio::spawn(
async move {
mandate::update_connector_mandate_id(
m_db.as_ref(),
&m_router_data_merchant_id,
m_payment_data_mandate_id,
m_payment_method_id,
m_router_data_response,
storage_scheme,
)
.await
}
.in_current_span(),
);
let (payment_intent, _, payment_attempt) = futures::try_join!(
utils::flatten_join_error(payment_intent_fut),
utils::flatten_join_error(mandate_update_fut),
utils::flatten_join_error(payment_attempt_fut)
)?;
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
{
if payment_intent.status.is_in_terminal_state()
&& business_profile.dynamic_routing_algorithm.is_some()
{
let dynamic_routing_algo_ref: api_models::routing::DynamicRoutingAlgorithmRef =
business_profile
.dynamic_routing_algorithm
.clone()
.map(|val| val.parse_value("DynamicRoutingAlgorithmRef"))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to deserialize DynamicRoutingAlgorithmRef from JSON")?
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("DynamicRoutingAlgorithmRef not found in profile")?;
let state = state.clone();
let profile_id = business_profile.get_id().to_owned();
let payment_attempt = payment_attempt.clone();
let dynamic_routing_config_params_interpolator =
routing_helpers::DynamicRoutingConfigParamsInterpolator::new(
payment_attempt.payment_method,
payment_attempt.payment_method_type,
payment_attempt.authentication_type,
payment_attempt.currency,
payment_data
.address
.get_payment_billing()
.and_then(|address| address.clone().address)
.and_then(|address| address.country),
payment_attempt
.payment_method_data
.as_ref()
.and_then(|data| data.as_object())
.and_then(|card| card.get("card"))
.and_then(|data| data.as_object())
.and_then(|card| card.get("card_network"))
.and_then(|network| network.as_str())
.map(|network| network.to_string()),
payment_attempt
.payment_method_data
.as_ref()
.and_then(|data| data.as_object())
.and_then(|card| card.get("card"))
.and_then(|data| data.as_object())
.and_then(|card| card.get("card_isin"))
.and_then(|card_isin| card_isin.as_str())
.map(|card_isin| card_isin.to_string()),
);
tokio::spawn(
async move {
routing_helpers::push_metrics_with_update_window_for_success_based_routing(
&state,
&payment_attempt,
routable_connectors.clone(),
&profile_id,
dynamic_routing_algo_ref.clone(),
dynamic_routing_config_params_interpolator.clone(),
)
.await
.map_err(|e| logger::error!(success_based_routing_metrics_error=?e))
.ok();
routing_helpers::push_metrics_with_update_window_for_contract_based_routing(
&state,
&payment_attempt,
routable_connectors,
&profile_id,
dynamic_routing_algo_ref,
dynamic_routing_config_params_interpolator,
)
.await
.map_err(|e| logger::error!(contract_based_routing_metrics_error=?e))
.ok();
}
.in_current_span(),
);
}
}
payment_data.payment_intent = payment_intent;
payment_data.payment_attempt = payment_attempt;
router_data.payment_method_status.and_then(|status| {
payment_data
.payment_method_info
.as_mut()
.map(|info| info.status = status)
});
if payment_data.payment_attempt.status == enums::AttemptStatus::Failure {
let _ = card_testing_guard_utils::increment_blocked_count_in_cache(
state,
payment_data.card_testing_guard_data.clone(),
)
.await;
}
match router_data.integrity_check {
Ok(()) => Ok(payment_data),
Err(err) => {
metrics::INTEGRITY_CHECK_FAILED.add(
1,
router_env::metric_attributes!(
(
"connector",
payment_data
.payment_attempt
.connector
.clone()
.unwrap_or_default(),
),
(
"merchant_id",
payment_data.payment_attempt.merchant_id.clone(),
)
),
);
Err(error_stack::Report::new(
errors::ApiErrorResponse::IntegrityCheckFailed {
connector_transaction_id: payment_data
.payment_attempt
.get_connector_payment_id()
.map(ToString::to_string),
reason: payment_data
.payment_attempt
.error_message
.unwrap_or_default(),
field_names: err.field_names,
},
))
}
}
}
<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/migrations/2023-07-07-091223_create_captures_table/up.sql" role="context" start="1" end="17">
CREATE TYPE "CaptureStatus" AS ENUM (
'started',
'charged',
'pending',
'failed'
);
ALTER TYPE "IntentStatus" ADD VALUE If NOT EXISTS 'partially_captured' AFTER 'requires_capture';
CREATE TABLE captures(
capture_id VARCHAR(64) NOT NULL PRIMARY KEY,
payment_id VARCHAR(64) NOT NULL,
merchant_id VARCHAR(64) NOT NULL,
status "CaptureStatus" NOT NULL,
amount BIGINT NOT NULL,
currency "Currency",
connector VARCHAR(255),
error_message VARCHAR(255),
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payments/operations/payment_start.rs<|crate|> router anchor=make_pm_data kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_start.rs" role="context" start="308" end="343">
async fn make_pm_data<'a>(
&'a self,
state: &'a SessionState,
payment_data: &mut PaymentData<F>,
storage_scheme: storage_enums::MerchantStorageScheme,
merchant_key_store: &domain::MerchantKeyStore,
customer: &Option<domain::Customer>,
business_profile: &domain::Profile,
should_retry_with_pan: bool,
) -> RouterResult<(
PaymentSessionOperation<'a, F>,
Option<domain::PaymentMethodData>,
Option<String>,
)> {
if payment_data
.payment_attempt
.connector
.clone()
.map(|connector_name| connector_name == *"bluesnap".to_string())
.unwrap_or(false)
{
Box::pin(helpers::make_pm_data(
Box::new(self),
state,
payment_data,
merchant_key_store,
customer,
storage_scheme,
business_profile,
should_retry_with_pan,
))
.await
} else {
Ok((Box::new(self), None, None))
}
}
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_start.rs" role="context" start="307" end="307">
use crate::{
core::{
errors::{self, CustomResult, RouterResult, StorageErrorExt},
payments::{helpers, operations, CustomerDetails, PaymentAddress, PaymentData},
},
routes::{app::ReqState, SessionState},
services,
types::{
api::{self, PaymentIdTypeExt},
domain,
storage::{self, enums as storage_enums},
},
utils::OptionExt,
};
type PaymentSessionOperation<'b, F> =
BoxedOperation<'b, F, api::PaymentsStartRequest, PaymentData<F>>;
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_start.rs" role="context" start="357" end="365">
async fn guard_payment_against_blocklist<'a>(
&'a self,
_state: &SessionState,
_merchant_account: &domain::MerchantAccount,
_key_store: &domain::MerchantKeyStore,
_payment_data: &mut PaymentData<F>,
) -> CustomResult<bool, errors::ApiErrorResponse> {
Ok(false)
}
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_start.rs" role="context" start="345" end="354">
async fn get_connector<'a>(
&'a self,
_merchant_account: &domain::MerchantAccount,
state: &SessionState,
_request: &api::PaymentsStartRequest,
_payment_intent: &storage::PaymentIntent,
_mechant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> {
helpers::get_connector_default(state, None).await
}
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_start.rs" role="context" start="284" end="305">
async fn get_or_create_customer_details<'a>(
&'a self,
state: &SessionState,
payment_data: &mut PaymentData<F>,
request: Option<CustomerDetails>,
key_store: &domain::MerchantKeyStore,
storage_scheme: common_enums::enums::MerchantStorageScheme,
) -> CustomResult<
(PaymentSessionOperation<'a, F>, Option<domain::Customer>),
errors::StorageError,
> {
helpers::create_customer_if_not_exist(
state,
Box::new(self),
payment_data,
request,
&key_store.merchant_id,
key_store,
storage_scheme,
)
.await
}
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_start.rs" role="context" start="249" end="272">
fn validate_request<'a, 'b>(
&'b self,
request: &api::PaymentsStartRequest,
merchant_account: &'a domain::MerchantAccount,
) -> RouterResult<(PaymentSessionOperation<'b, F>, operations::ValidateResult)> {
let request_merchant_id = Some(&request.merchant_id);
helpers::validate_merchant_id(merchant_account.get_id(), request_merchant_id)
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "merchant_id".to_string(),
expected_format: "merchant_id from merchant account".to_string(),
})?;
let payment_id = request.payment_id.clone();
Ok((
Box::new(self),
operations::ValidateResult {
merchant_id: merchant_account.get_id().to_owned(),
payment_id: api::PaymentIdType::PaymentIntentId(payment_id),
storage_scheme: merchant_account.storage_scheme,
requeue: false,
},
))
}
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_start.rs" role="context" start="29" end="30">
type PaymentSessionOperation<'b, F> =
BoxedOperation<'b, F, api::PaymentsStartRequest, PaymentData<F>>;
<file_sep path="hyperswitch/crates/router/src/compatibility/stripe/customers/types.rs" role="context" start="202" end="207">
pub struct PaymentMethodData {
pub id: Option<String>,
pub object: &'static str,
pub card: Option<CardDetails>,
pub created: Option<time::PrimitiveDateTime>,
}
<file_sep path="hyperswitch/v2_compatible_migrations/2024-08-28-081721_add_v2_columns/up.sql" role="context" start="1" end="11">
-- This file contains all new columns being added as part of v2 refactoring.
-- The new columns added should work with both v1 and v2 applications.
ALTER TABLE customers
ADD COLUMN IF NOT EXISTS merchant_reference_id VARCHAR(64),
ADD COLUMN IF NOT EXISTS default_billing_address BYTEA DEFAULT NULL,
ADD COLUMN IF NOT EXISTS default_shipping_address BYTEA DEFAULT NULL,
ADD COLUMN IF NOT EXISTS status "DeleteStatus";
CREATE TYPE "OrderFulfillmentTimeOrigin" AS ENUM ('create', 'confirm');
ALTER TABLE business_profile
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payments/operations/payment_start.rs<|crate|> router anchor=make_pm_data kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_start.rs" role="context" start="308" end="343">
async fn make_pm_data<'a>(
&'a self,
state: &'a SessionState,
payment_data: &mut PaymentData<F>,
storage_scheme: storage_enums::MerchantStorageScheme,
merchant_key_store: &domain::MerchantKeyStore,
customer: &Option<domain::Customer>,
business_profile: &domain::Profile,
should_retry_with_pan: bool,
) -> RouterResult<(
PaymentSessionOperation<'a, F>,
Option<domain::PaymentMethodData>,
Option<String>,
)> {
if payment_data
.payment_attempt
.connector
.clone()
.map(|connector_name| connector_name == *"bluesnap".to_string())
.unwrap_or(false)
{
Box::pin(helpers::make_pm_data(
Box::new(self),
state,
payment_data,
merchant_key_store,
customer,
storage_scheme,
business_profile,
should_retry_with_pan,
))
.await
} else {
Ok((Box::new(self), None, None))
}
}
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_start.rs" role="context" start="307" end="307">
use crate::{
core::{
errors::{self, CustomResult, RouterResult, StorageErrorExt},
payments::{helpers, operations, CustomerDetails, PaymentAddress, PaymentData},
},
routes::{app::ReqState, SessionState},
services,
types::{
api::{self, PaymentIdTypeExt},
domain,
storage::{self, enums as storage_enums},
},
utils::OptionExt,
};
type PaymentSessionOperation<'b, F> =
BoxedOperation<'b, F, api::PaymentsStartRequest, PaymentData<F>>;
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_start.rs" role="context" start="357" end="365">
async fn guard_payment_against_blocklist<'a>(
&'a self,
_state: &SessionState,
_merchant_account: &domain::MerchantAccount,
_key_store: &domain::MerchantKeyStore,
_payment_data: &mut PaymentData<F>,
) -> CustomResult<bool, errors::ApiErrorResponse> {
Ok(false)
}
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_start.rs" role="context" start="345" end="354">
async fn get_connector<'a>(
&'a self,
_merchant_account: &domain::MerchantAccount,
state: &SessionState,
_request: &api::PaymentsStartRequest,
_payment_intent: &storage::PaymentIntent,
_mechant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> {
helpers::get_connector_default(state, None).await
}
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_start.rs" role="context" start="284" end="305">
async fn get_or_create_customer_details<'a>(
&'a self,
state: &SessionState,
payment_data: &mut PaymentData<F>,
request: Option<CustomerDetails>,
key_store: &domain::MerchantKeyStore,
storage_scheme: common_enums::enums::MerchantStorageScheme,
) -> CustomResult<
(PaymentSessionOperation<'a, F>, Option<domain::Customer>),
errors::StorageError,
> {
helpers::create_customer_if_not_exist(
state,
Box::new(self),
payment_data,
request,
&key_store.merchant_id,
key_store,
storage_scheme,
)
.await
}
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_start.rs" role="context" start="249" end="272">
fn validate_request<'a, 'b>(
&'b self,
request: &api::PaymentsStartRequest,
merchant_account: &'a domain::MerchantAccount,
) -> RouterResult<(PaymentSessionOperation<'b, F>, operations::ValidateResult)> {
let request_merchant_id = Some(&request.merchant_id);
helpers::validate_merchant_id(merchant_account.get_id(), request_merchant_id)
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "merchant_id".to_string(),
expected_format: "merchant_id from merchant account".to_string(),
})?;
let payment_id = request.payment_id.clone();
Ok((
Box::new(self),
operations::ValidateResult {
merchant_id: merchant_account.get_id().to_owned(),
payment_id: api::PaymentIdType::PaymentIntentId(payment_id),
storage_scheme: merchant_account.storage_scheme,
requeue: false,
},
))
}
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_start.rs" role="context" start="29" end="30">
type PaymentSessionOperation<'b, F> =
BoxedOperation<'b, F, api::PaymentsStartRequest, PaymentData<F>>;
<file_sep path="hyperswitch/crates/router/src/compatibility/stripe/customers/types.rs" role="context" start="202" end="207">
pub struct PaymentMethodData {
pub id: Option<String>,
pub object: &'static str,
pub card: Option<CardDetails>,
pub created: Option<time::PrimitiveDateTime>,
}
<file_sep path="hyperswitch/v2_compatible_migrations/2024-08-28-081721_add_v2_columns/up.sql" role="context" start="1" end="11">
-- This file contains all new columns being added as part of v2 refactoring.
-- The new columns added should work with both v1 and v2 applications.
ALTER TABLE customers
ADD COLUMN IF NOT EXISTS merchant_reference_id VARCHAR(64),
ADD COLUMN IF NOT EXISTS default_billing_address BYTEA DEFAULT NULL,
ADD COLUMN IF NOT EXISTS default_shipping_address BYTEA DEFAULT NULL,
ADD COLUMN IF NOT EXISTS status "DeleteStatus";
CREATE TYPE "OrderFulfillmentTimeOrigin" AS ENUM ('create', 'confirm');
ALTER TABLE business_profile
<file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="2504" end="2539">
pub enum PaymentMethodData {
#[schema(title = "Card")]
Card(Card),
#[schema(title = "CardRedirect")]
CardRedirect(CardRedirectData),
#[schema(title = "Wallet")]
Wallet(WalletData),
#[schema(title = "PayLater")]
PayLater(PayLaterData),
#[schema(title = "BankRedirect")]
BankRedirect(BankRedirectData),
#[schema(title = "BankDebit")]
BankDebit(BankDebitData),
#[schema(title = "BankTransfer")]
BankTransfer(Box<BankTransferData>),
#[schema(title = "RealTimePayment")]
RealTimePayment(Box<RealTimePaymentData>),
#[schema(title = "Crypto")]
Crypto(CryptoData),
#[schema(title = "MandatePayment")]
MandatePayment,
#[schema(title = "Reward")]
Reward,
#[schema(title = "Upi")]
Upi(UpiData),
#[schema(title = "Voucher")]
Voucher(VoucherData),
#[schema(title = "GiftCard")]
GiftCard(Box<GiftCardData>),
#[schema(title = "CardToken")]
CardToken(CardToken),
#[schema(title = "OpenBanking")]
OpenBanking(OpenBankingData),
#[schema(title = "MobilePayment")]
MobilePayment(MobilePaymentData),
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/blocklist/utils.rs<|crate|> router anchor=get_merchant_fingerprint_secret kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/blocklist/utils.rs" role="context" start="203" end="235">
pub async fn get_merchant_fingerprint_secret(
state: &SessionState,
merchant_id: &common_utils::id_type::MerchantId,
) -> RouterResult<String> {
let key = merchant_id.get_merchant_fingerprint_secret_key();
let config_fetch_result = state.store.find_config_by_key(&key).await;
match config_fetch_result {
Ok(config) => Ok(config.config),
Err(e) if e.current_context().is_db_not_found() => {
let new_fingerprint_secret =
utils::generate_id(consts::FINGERPRINT_SECRET_LENGTH, "fs");
let new_config = storage::ConfigNew {
key,
config: new_fingerprint_secret.clone(),
};
state
.store
.insert_config(new_config)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to create new fingerprint secret for merchant")?;
Ok(new_fingerprint_secret)
}
Err(e) => Err(e)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("error fetching merchant fingerprint secret"),
}
}
<file_sep path="hyperswitch/crates/router/src/core/blocklist/utils.rs" role="context" start="202" end="202">
use common_utils::errors::CustomResult;
use super::{errors, transformers::generate_fingerprint, SessionState};
use crate::{
consts,
core::{
errors::{RouterResult, StorageErrorExt},
payments::PaymentData,
},
logger,
types::{domain, storage, transformers::ForeignInto},
utils,
};
<file_sep path="hyperswitch/crates/router/src/core/blocklist/utils.rs" role="context" start="279" end="291">
async fn delete_card_bin_blocklist_entry(
state: &SessionState,
bin: &str,
merchant_id: &common_utils::id_type::MerchantId,
) -> RouterResult<storage::Blocklist> {
state
.store
.delete_blocklist_entry_by_merchant_id_fingerprint_id(merchant_id, bin)
.await
.to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError {
message: "could not find a blocklist entry for the given bin".to_string(),
})
}
<file_sep path="hyperswitch/crates/router/src/core/blocklist/utils.rs" role="context" start="237" end="277">
async fn duplicate_check_insert_bin(
bin: &str,
state: &SessionState,
merchant_id: &common_utils::id_type::MerchantId,
data_kind: common_enums::BlocklistDataKind,
) -> RouterResult<storage::Blocklist> {
let blocklist_entry_result = state
.store
.find_blocklist_entry_by_merchant_id_fingerprint_id(merchant_id, bin)
.await;
match blocklist_entry_result {
Ok(_) => {
return Err(errors::ApiErrorResponse::PreconditionFailed {
message: "provided bin is already blocked".to_string(),
}
.into());
}
Err(e) if e.current_context().is_db_not_found() => {}
err @ Err(_) => {
return err
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to fetch blocklist entry");
}
}
state
.store
.insert_blocklist_entry(storage::BlocklistNew {
merchant_id: merchant_id.to_owned(),
fingerprint_id: bin.to_string(),
data_kind,
metadata: None,
created_at: common_utils::date_time::now(),
})
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("error inserting pm blocklist item")
}
<file_sep path="hyperswitch/crates/router/src/core/blocklist/utils.rs" role="context" start="134" end="201">
pub async fn insert_entry_into_blocklist(
state: &SessionState,
merchant_id: &common_utils::id_type::MerchantId,
to_block: api_blocklist::AddToBlocklistRequest,
) -> RouterResult<api_blocklist::AddToBlocklistResponse> {
let blocklist_entry = match &to_block {
api_blocklist::AddToBlocklistRequest::CardBin(bin) => {
validate_card_bin(bin)?;
duplicate_check_insert_bin(
bin,
state,
merchant_id,
common_enums::BlocklistDataKind::CardBin,
)
.await?
}
api_blocklist::AddToBlocklistRequest::ExtendedCardBin(bin) => {
validate_extended_card_bin(bin)?;
duplicate_check_insert_bin(
bin,
state,
merchant_id,
common_enums::BlocklistDataKind::ExtendedCardBin,
)
.await?
}
api_blocklist::AddToBlocklistRequest::Fingerprint(fingerprint_id) => {
let blocklist_entry_result = state
.store
.find_blocklist_entry_by_merchant_id_fingerprint_id(merchant_id, fingerprint_id)
.await;
match blocklist_entry_result {
Ok(_) => {
return Err(errors::ApiErrorResponse::PreconditionFailed {
message: "data associated with the given fingerprint is already blocked"
.to_string(),
}
.into());
}
// if it is a db not found error, we can proceed as normal
Err(inner) if inner.current_context().is_db_not_found() => {}
err @ Err(_) => {
err.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("error fetching blocklist entry from table")?;
}
}
state
.store
.insert_blocklist_entry(storage::BlocklistNew {
merchant_id: merchant_id.to_owned(),
fingerprint_id: fingerprint_id.clone(),
data_kind: api_models::enums::enums::BlocklistDataKind::PaymentMethod,
metadata: None,
created_at: common_utils::date_time::now(),
})
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed to add fingerprint to blocklist")?
}
};
Ok(blocklist_entry.foreign_into())
}
<file_sep path="hyperswitch/crates/router/src/core/blocklist/utils.rs" role="context" start="122" end="132">
fn validate_extended_card_bin(bin: &str) -> RouterResult<()> {
if bin.len() == 8 && bin.chars().all(|c| c.is_ascii_digit()) {
Ok(())
} else {
Err(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "data".to_string(),
expected_format: "an 8 digit number".to_string(),
}
.into())
}
}
<file_sep path="hyperswitch/crates/router/src/core/blocklist/utils.rs" role="context" start="293" end="442">
pub async fn validate_data_for_blocklist<F>(
state: &SessionState,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
payment_data: &mut PaymentData<F>,
) -> CustomResult<bool, errors::ApiErrorResponse>
where
F: Send + Clone,
{
let db = &state.store;
let merchant_id = merchant_account.get_id();
let merchant_fingerprint_secret = get_merchant_fingerprint_secret(state, merchant_id).await?;
// Hashed Fingerprint to check whether or not this payment should be blocked.
let card_number_fingerprint = if let Some(domain::PaymentMethodData::Card(card)) =
payment_data.payment_method_data.as_ref()
{
generate_fingerprint(
state,
StrongSecret::new(card.card_number.get_card_no()),
StrongSecret::new(merchant_fingerprint_secret.clone()),
api_models::enums::LockerChoice::HyperswitchCardVault,
)
.await
.attach_printable("error in pm fingerprint creation")
.map_or_else(
|error| {
logger::error!(?error);
None
},
Some,
)
.map(|payload| payload.card_fingerprint)
} else {
None
};
// Hashed Cardbin to check whether or not this payment should be blocked.
let card_bin_fingerprint = payment_data
.payment_method_data
.as_ref()
.and_then(|pm_data| match pm_data {
domain::PaymentMethodData::Card(card) => Some(card.card_number.get_card_isin()),
_ => None,
});
// Hashed Extended Cardbin to check whether or not this payment should be blocked.
let extended_card_bin_fingerprint =
payment_data
.payment_method_data
.as_ref()
.and_then(|pm_data| match pm_data {
domain::PaymentMethodData::Card(card) => {
Some(card.card_number.get_extended_card_bin())
}
_ => None,
});
//validating the payment method.
let mut blocklist_futures = Vec::new();
if let Some(card_number_fingerprint) = card_number_fingerprint.as_ref() {
blocklist_futures.push(db.find_blocklist_entry_by_merchant_id_fingerprint_id(
merchant_id,
card_number_fingerprint,
));
}
if let Some(card_bin_fingerprint) = card_bin_fingerprint.as_ref() {
blocklist_futures.push(
db.find_blocklist_entry_by_merchant_id_fingerprint_id(
merchant_id,
card_bin_fingerprint,
),
);
}
if let Some(extended_card_bin_fingerprint) = extended_card_bin_fingerprint.as_ref() {
blocklist_futures.push(db.find_blocklist_entry_by_merchant_id_fingerprint_id(
merchant_id,
extended_card_bin_fingerprint,
));
}
let blocklist_lookups = futures::future::join_all(blocklist_futures).await;
let mut should_payment_be_blocked = false;
for lookup in blocklist_lookups {
match lookup {
Ok(_) => {
should_payment_be_blocked = true;
}
Err(e) => {
logger::error!(blocklist_db_error=?e, "failed db operations for blocklist");
}
}
}
if should_payment_be_blocked {
// Update db for attempt and intent status.
db.update_payment_intent(
&state.into(),
payment_data.payment_intent.clone(),
storage::PaymentIntentUpdate::RejectUpdate {
status: common_enums::IntentStatus::Failed,
merchant_decision: Some(MerchantDecision::Rejected.to_string()),
updated_by: merchant_account.storage_scheme.to_string(),
},
key_store,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)
.attach_printable(
"Failed to update status in Payment Intent to failed due to it being blocklisted",
)?;
// If payment is blocked not showing connector details
let attempt_update = storage::PaymentAttemptUpdate::BlocklistUpdate {
status: common_enums::AttemptStatus::Failure,
error_code: Some(Some("HE-03".to_string())),
error_message: Some(Some("This payment method is blocked".to_string())),
updated_by: merchant_account.storage_scheme.to_string(),
};
db.update_payment_attempt_with_attempt_id(
payment_data.payment_attempt.clone(),
attempt_update,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)
.attach_printable(
"Failed to update status in Payment Attempt to failed, due to it being blocklisted",
)?;
Err(errors::ApiErrorResponse::PaymentBlockedError {
code: 200,
message: "This payment method is blocked".to_string(),
status: "Failed".to_string(),
reason: "Blocked".to_string(),
}
.into())
} else {
payment_data.payment_attempt.fingerprint_id = generate_payment_fingerprint(
state,
payment_data.payment_attempt.merchant_id.clone(),
payment_data.payment_method_data.clone(),
)
.await?;
Ok(false)
}
}
<file_sep path="hyperswitch/crates/router/src/core/blocklist/utils.rs" role="context" start="444" end="474">
pub async fn generate_payment_fingerprint(
state: &SessionState,
merchant_id: common_utils::id_type::MerchantId,
payment_method_data: Option<domain::PaymentMethodData>,
) -> CustomResult<Option<String>, errors::ApiErrorResponse> {
let merchant_fingerprint_secret = get_merchant_fingerprint_secret(state, &merchant_id).await?;
Ok(
if let Some(domain::PaymentMethodData::Card(card)) = payment_method_data.as_ref() {
generate_fingerprint(
state,
StrongSecret::new(card.card_number.get_card_no()),
StrongSecret::new(merchant_fingerprint_secret),
api_models::enums::LockerChoice::HyperswitchCardVault,
)
.await
.attach_printable("error in pm fingerprint creation")
.map_or_else(
|error| {
logger::error!(?error);
None
},
Some,
)
.map(|payload| payload.card_fingerprint)
} else {
logger::error!("failed to retrieve card fingerprint");
None
},
)
}
<file_sep path="hyperswitch/crates/router/tests/utils.rs" role="context" start="389" end="391">
pub struct MerchantId {
merchant_id: common_utils::id_type::MerchantId,
}
<file_sep path="hyperswitch/crates/api_models/src/errors/types.rs" role="context" start="86" end="100">
pub enum ApiErrorResponse {
Unauthorized(ApiError),
ForbiddenCommonResource(ApiError),
ForbiddenPrivateResource(ApiError),
Conflict(ApiError),
Gone(ApiError),
Unprocessable(ApiError),
InternalServerError(ApiError),
NotImplemented(ApiError),
ConnectorError(ApiError, #[serde(skip_serializing)] StatusCode),
NotFound(ApiError),
MethodNotAllowed(ApiError),
BadRequest(ApiError),
DomainError(ApiError),
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payment_methods.rs<|crate|> router anchor=list_customer_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="1815" end="1848">
pub async fn list_customer_payment_method_core(
state: &SessionState,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
customer_id: &id_type::GlobalCustomerId,
) -> RouterResult<api::CustomerPaymentMethodsListResponse> {
let db = &*state.store;
let key_manager_state = &(state).into();
let saved_payment_methods = db
.find_payment_method_by_global_customer_id_merchant_id_status(
key_manager_state,
key_store,
customer_id,
merchant_account.get_id(),
common_enums::PaymentMethodStatus::Active,
None,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
let customer_payment_methods = saved_payment_methods
.into_iter()
.map(ForeignTryFrom::foreign_try_from)
.collect::<Result<Vec<api::CustomerPaymentMethod>, _>>()
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let response = api::CustomerPaymentMethodsListResponse {
customer_payment_methods,
};
Ok(response)
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods.rs" role="context" start="1814" end="1814">
consts::ID_LENGTH,
"token",
)),
),
})
}
};
Ok(payment_method_retrieval_context)
}
#[cfg(all(feature = "v2", feature = "olap"))]
pub async fn list_customer_payment_method_core(
state: &SessionState,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
customer_id: &id_type::GlobalCustomerId,
) -> RouterResult<api::CustomerPaymentMethodsListResponse> {
let db = &*state.store;
let key_manager_state = &(state).into();
let saved_payment_methods = db
.find_payment_method_by_global_customer_id_merchant_id_status(
key_manager_state,
key_store,
<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="1851" end="1869">
pub async fn get_total_payment_method_count_core(
state: &SessionState,
merchant_account: &domain::MerchantAccount,
) -> RouterResult<api::TotalPaymentMethodCountResponse> {
let db = &*state.store;
let total_count = db
.get_payment_method_count_by_merchant_id_status(
merchant_account.get_id(),
common_enums::PaymentMethodStatus::Active,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to get total payment method count")?;
let response = api::TotalPaymentMethodCountResponse { total_count };
Ok(response)
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods.rs" role="context" start="1732" end="1812">
fn get_pm_list_context(
payment_method_type: enums::PaymentMethod,
payment_method: &domain::PaymentMethod,
is_payment_associated: bool,
) -> Result<Option<PaymentMethodListContext>, error_stack::Report<errors::ApiErrorResponse>> {
let payment_method_data = payment_method
.payment_method_data
.clone()
.map(|payment_method_data| payment_method_data.into_inner());
let payment_method_retrieval_context = match payment_method_data {
Some(payment_methods::PaymentMethodsData::Card(card)) => {
Some(PaymentMethodListContext::Card {
card_details: api::CardDetailFromLocker::from(card),
token_data: is_payment_associated.then_some(
storage::PaymentTokenData::permanent_card(
Some(payment_method.get_id().clone()),
payment_method
.locker_id
.as_ref()
.map(|id| id.get_string_repr().to_owned())
.or_else(|| Some(payment_method.get_id().get_string_repr().to_owned())),
payment_method
.locker_id
.as_ref()
.map(|id| id.get_string_repr().to_owned())
.unwrap_or_else(|| {
payment_method.get_id().get_string_repr().to_owned()
}),
),
),
})
}
Some(payment_methods::PaymentMethodsData::BankDetails(bank_details)) => {
let get_bank_account_token_data =
|| -> CustomResult<payment_methods::BankAccountTokenData,errors::ApiErrorResponse> {
let connector_details = bank_details
.connector_details
.first()
.cloned()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to obtain bank account connector details")?;
let payment_method_subtype = payment_method
.get_payment_method_subtype()
.get_required_value("payment_method_subtype")
.attach_printable("PaymentMethodType not found")?;
Ok(payment_methods::BankAccountTokenData {
payment_method_type: payment_method_subtype,
payment_method: payment_method_type,
connector_details,
})
};
// Retrieve the pm_auth connector details so that it can be tokenized
let bank_account_token_data = get_bank_account_token_data()
.inspect_err(|error| logger::error!(?error))
.ok();
bank_account_token_data.map(|data| {
let token_data = storage::PaymentTokenData::AuthBankDebit(data);
PaymentMethodListContext::Bank {
token_data: is_payment_associated.then_some(token_data),
}
})
}
Some(payment_methods::PaymentMethodsData::WalletDetails(_)) | None => {
Some(PaymentMethodListContext::TemporaryToken {
token_data: is_payment_associated.then_some(
storage::PaymentTokenData::temporary_generic(generate_id(
consts::ID_LENGTH,
"token",
)),
),
})
}
};
Ok(payment_method_retrieval_context)
}
<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/payment_methods.rs" role="context" start="1351" end="1364">
pub async fn list_saved_payment_methods_for_customer(
state: SessionState,
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
customer_id: id_type::GlobalCustomerId,
) -> RouterResponse<api::CustomerPaymentMethodsListResponse> {
let customer_payment_methods =
list_customer_payment_method_core(&state, &merchant_account, &key_store, &customer_id)
.await?;
Ok(hyperswitch_domain_models::api::ApplicationResponse::Json(
customer_payment_methods,
))
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods.rs" role="context" start="1302" end="1347">
pub async fn list_payment_methods_for_session(
state: SessionState,
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
profile: domain::Profile,
payment_method_session_id: id_type::GlobalPaymentMethodSessionId,
) -> RouterResponse<api::PaymentMethodListResponse> {
let key_manager_state = &(&state).into();
let db = &*state.store;
let payment_method_session = db
.get_payment_methods_session(key_manager_state, &key_store, &payment_method_session_id)
.await
.change_context(errors::ApiErrorResponse::PaymentMethodNotFound)
.attach_printable("Unable to find payment method")?;
let payment_connector_accounts = db
.list_enabled_connector_accounts_by_profile_id(
key_manager_state,
profile.get_id(),
&key_store,
common_enums::ConnectorType::PaymentProcessor,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("error when fetching merchant connector accounts")?;
let customer_payment_methods = list_customer_payment_method_core(
&state,
&merchant_account,
&key_store,
&payment_method_session.customer_id,
)
.await?;
let response =
hyperswitch_domain_models::merchant_connector_account::FlattenedPaymentMethodsEnabled::from_payment_connectors_list(payment_connector_accounts)
.perform_filtering()
.get_required_fields(RequiredFieldsInput::new(state.conf.required_fields.clone()))
.generate_response(customer_payment_methods.customer_payment_methods);
Ok(hyperswitch_domain_models::api::ApplicationResponse::Json(
response,
))
}
<file_sep path="hyperswitch/crates/router/src/core/errors.rs" role="context" start="31" end="31">
pub type RouterResult<T> = CustomResult<T, ApiErrorResponse>;
<file_sep path="hyperswitch/v2_compatible_migrations/2024-08-28-081757_drop_not_null_constraints_on_v1_columns/up.sql" role="context" start="5" end="21">
ALTER COLUMN org_id DROP NOT NULL;
-- Create index on org_id in organization table
-- This is done to mullify the effects of droping primary key for v1
CREATE INDEX idx_organization_org_id ON organization (org_id);
------------------------ Merchant Account -------------------
-- Drop not null in merchant_account table for v1 columns that are dropped in v2
ALTER TABLE merchant_account
DROP CONSTRAINT merchant_account_pkey,
ALTER COLUMN merchant_id DROP NOT NULL,
ALTER COLUMN primary_business_details DROP NOT NULL,
ALTER COLUMN is_recon_enabled DROP NOT NULL;
-- This is done to mullify the effects of droping primary key for v1
CREATE INDEX idx_merchant_account_merchant_id ON merchant_account (merchant_id);
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payments/helpers.rs<|crate|> router anchor=add_connector_response_to_additional_payment_data kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="6540" end="6573">
pub fn add_connector_response_to_additional_payment_data(
additional_payment_data: api_models::payments::AdditionalPaymentData,
connector_response_payment_method_data: AdditionalPaymentMethodConnectorResponse,
) -> api_models::payments::AdditionalPaymentData {
match (
&additional_payment_data,
connector_response_payment_method_data,
) {
(
api_models::payments::AdditionalPaymentData::Card(additional_card_data),
AdditionalPaymentMethodConnectorResponse::Card {
authentication_data,
payment_checks,
..
},
) => api_models::payments::AdditionalPaymentData::Card(Box::new(
api_models::payments::AdditionalCardInfo {
payment_checks,
authentication_data,
..*additional_card_data.clone()
},
)),
(
api_models::payments::AdditionalPaymentData::PayLater { .. },
AdditionalPaymentMethodConnectorResponse::PayLater {
klarna_sdk: Some(KlarnaSdkResponse { payment_type }),
},
) => api_models::payments::AdditionalPaymentData::PayLater {
klarna_sdk: Some(api_models::payments::KlarnaSdkPaymentMethod { payment_type }),
},
_ => additional_payment_data,
}
}
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="6539" end="6539">
if !(consts::MIN_INTENT_FULFILLMENT_EXPIRY..=consts::MAX_INTENT_FULFILLMENT_EXPIRY)
.contains(&intent_fulfillment_time)
{
Err(errors::ApiErrorResponse::InvalidRequestData {
message: "intent_fulfillment_time should be between 60(1 min) to 1800(30 mins)."
.to_string(),
})
} else {
Ok(())
}
}
pub fn add_connector_response_to_additional_payment_data(
additional_payment_data: api_models::payments::AdditionalPaymentData,
connector_response_payment_method_data: AdditionalPaymentMethodConnectorResponse,
) -> api_models::payments::AdditionalPaymentData {
match (
&additional_payment_data,
connector_response_payment_method_data,
) {
(
api_models::payments::AdditionalPaymentData::Card(additional_card_data),
AdditionalPaymentMethodConnectorResponse::Card {
authentication_data,
payment_checks,
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="6610" end="6618">
pub async fn get_payment_method_details_from_payment_token(
state: &SessionState,
payment_attempt: &PaymentAttempt,
payment_intent: &PaymentIntent,
key_store: &domain::MerchantKeyStore,
storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<Option<(domain::PaymentMethodData, enums::PaymentMethod)>> {
todo!()
}
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="6575" end="6607">
pub fn update_additional_payment_data_with_connector_response_pm_data(
additional_payment_data: Option<serde_json::Value>,
connector_response_pm_data: Option<AdditionalPaymentMethodConnectorResponse>,
) -> RouterResult<Option<serde_json::Value>> {
let parsed_additional_payment_method_data = additional_payment_data
.as_ref()
.map(|payment_method_data| {
payment_method_data
.clone()
.parse_value::<api_models::payments::AdditionalPaymentData>(
"additional_payment_method_data",
)
})
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to parse value into additional_payment_method_data")?;
let additional_payment_method_data = parsed_additional_payment_method_data
.zip(connector_response_pm_data)
.map(|(additional_pm_data, connector_response_pm_data)| {
add_connector_response_to_additional_payment_data(
additional_pm_data,
connector_response_pm_data,
)
});
additional_payment_method_data
.as_ref()
.map(Encode::encode_to_value)
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to encode additional pm data")
}
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="6525" end="6538">
pub fn validate_intent_fulfillment_expiry(
intent_fulfillment_time: u32,
) -> Result<(), errors::ApiErrorResponse> {
if !(consts::MIN_INTENT_FULFILLMENT_EXPIRY..=consts::MAX_INTENT_FULFILLMENT_EXPIRY)
.contains(&intent_fulfillment_time)
{
Err(errors::ApiErrorResponse::InvalidRequestData {
message: "intent_fulfillment_time should be between 60(1 min) to 1800(30 mins)."
.to_string(),
})
} else {
Ok(())
}
}
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="6490" end="6523">
pub fn get_recipient_id_for_open_banking(
merchant_data: &AdditionalMerchantData,
) -> Result<Option<String>, errors::ApiErrorResponse> {
match merchant_data {
AdditionalMerchantData::OpenBankingRecipientData(data) => match data {
MerchantRecipientData::ConnectorRecipientId(id) => Ok(Some(id.peek().clone())),
MerchantRecipientData::AccountData(acc_data) => match acc_data {
MerchantAccountData::Bacs {
connector_recipient_id,
..
} => match connector_recipient_id {
Some(RecipientIdType::ConnectorId(id)) => Ok(Some(id.peek().clone())),
Some(RecipientIdType::LockerId(id)) => Ok(Some(id.peek().clone())),
_ => Err(errors::ApiErrorResponse::InvalidConnectorConfiguration {
config: "recipient_id".to_string(),
}),
},
MerchantAccountData::Iban {
connector_recipient_id,
..
} => match connector_recipient_id {
Some(RecipientIdType::ConnectorId(id)) => Ok(Some(id.peek().clone())),
Some(RecipientIdType::LockerId(id)) => Ok(Some(id.peek().clone())),
_ => Err(errors::ApiErrorResponse::InvalidConnectorConfiguration {
config: "recipient_id".to_string(),
}),
},
},
_ => Err(errors::ApiErrorResponse::InvalidConnectorConfiguration {
config: "recipient_id".to_string(),
}),
},
}
}
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="5783" end="5814">
pub fn new(
root_keys: masking::Secret<String>,
recipient_id: masking::Secret<String>,
private_key: masking::Secret<String>,
) -> CustomResult<Self, errors::GooglePayDecryptionError> {
// base64 decode the private key
let decoded_key = BASE64_ENGINE
.decode(private_key.expose())
.change_context(errors::GooglePayDecryptionError::Base64DecodingFailed)?;
// base64 decode the root signing keys
let decoded_root_signing_keys = BASE64_ENGINE
.decode(root_keys.expose())
.change_context(errors::GooglePayDecryptionError::Base64DecodingFailed)?;
// create a private key from the decoded key
let private_key = PKey::private_key_from_pkcs8(&decoded_key)
.change_context(errors::GooglePayDecryptionError::KeyDeserializationFailed)
.attach_printable("cannot convert private key from decode_key")?;
// parse the root signing keys
let root_keys_vector: Vec<GooglePayRootSigningKey> = decoded_root_signing_keys
.parse_struct("GooglePayRootSigningKey")
.change_context(errors::GooglePayDecryptionError::DeserializationFailed)?;
// parse and filter the root signing keys by protocol version
let filtered_root_signing_keys = filter_root_signing_keys(root_keys_vector)?;
Ok(Self {
root_signing_keys: filtered_root_signing_keys,
recipient_id,
private_key,
})
}
<file_sep path="hyperswitch/crates/router/src/connector/payone/transformers.rs" role="context" start="117" end="121">
pub struct Card {
card_holder_name: Secret<String>,
card_number: CardNumber,
expiry_date: Secret<String>,
}
<file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="1075" end="1083">
pub struct Card {
pub card_number: CardNumber,
pub name_on_card: Option<masking::Secret<String>>,
pub card_exp_month: masking::Secret<String>,
pub card_exp_year: masking::Secret<String>,
pub card_brand: Option<String>,
pub card_isin: Option<String>,
pub nick_name: Option<String>,
}
<file_sep path="hyperswitch/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/event.test.js" role="context" start="61" end="78">
"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.",
);
}
// Response body should have value "succeeded" for "status"
if (jsonData?.status) {
pm.test(
"[POST]::/payments - Content check if value for 'status' matches 'succeeded'",
function () {
pm.expect(jsonData.status).to.eql("succeeded");
},
);
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payment_methods/cards.rs<|crate|> router anchor=decode_and_decrypt_locker_data kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="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="2593" end="2593">
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))
}
#[instrument(skip_all)]
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(
<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/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="2550" end="2591">
pub async fn add_card_hs(
state: &routes::SessionState,
req: api::PaymentMethodCreate,
card: &api::CardDetail,
customer_id: &id_type::CustomerId,
merchant_account: &domain::MerchantAccount,
locker_choice: api_enums::LockerChoice,
card_reference: Option<&str>,
) -> errors::CustomResult<
(
api::PaymentMethodResponse,
Option<payment_methods::DataDuplicationCheck>,
),
errors::VaultError,
> {
let payload = payment_methods::StoreLockerReq::LockerCard(payment_methods::StoreCardReq {
merchant_id: merchant_account.get_id().to_owned(),
merchant_customer_id: customer_id.to_owned(),
requestor_card_reference: card_reference.map(str::to_string),
card: Card {
card_number: card.card_number.to_owned(),
name_on_card: card.card_holder_name.to_owned(),
card_exp_month: card.card_exp_month.to_owned(),
card_exp_year: card.card_exp_year.to_owned(),
card_brand: card.card_network.as_ref().map(ToString::to_string),
card_isin: None,
nick_name: card.nick_name.as_ref().map(Secret::peek).cloned(),
},
ttl: state.conf.locker.ttl_for_storage_in_secs,
});
let store_card_payload =
add_card_to_hs_locker(state, &payload, customer_id, locker_choice).await?;
let payment_method_resp = payment_methods::mk_add_card_response_hs(
card.clone(),
store_card_payload.card_reference,
req,
merchant_account.get_id(),
);
Ok((payment_method_resp, store_card_payload.duplication_check))
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="2541" end="2547">
pub async fn delete_card_by_locker_id(
state: &routes::SessionState,
id: &id_type::GlobalCustomerId,
merchant_id: &id_type::MerchantId,
) -> errors::RouterResult<payment_methods::DeleteCardResp> {
todo!()
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="3065" end="3094">
pub async fn mock_get_payment_method<'a>(
state: &routes::SessionState,
key_store: &domain::MerchantKeyStore,
card_id: &'a str,
) -> errors::CustomResult<payment_methods::GetPaymentMethodResponse, errors::VaultError> {
let db = &*state.store;
let locker_mock_up = db
.find_locker_by_card_id(card_id)
.await
.change_context(errors::VaultError::FetchPaymentMethodFailed)?;
let dec_data = if let Some(e) = locker_mock_up.enc_card_data {
decode_and_decrypt_locker_data(state, key_store, e).await
} else {
Err(report!(errors::VaultError::FetchPaymentMethodFailed))
}?;
let payment_method_response = payment_methods::AddPaymentMethodResponse {
payment_method_id: locker_mock_up
.payment_method_id
.unwrap_or(locker_mock_up.card_id),
external_id: locker_mock_up.external_id,
merchant_id: Some(locker_mock_up.merchant_id.to_owned()),
nickname: locker_mock_up.nickname,
customer_id: locker_mock_up.customer_id,
duplicate: locker_mock_up.duplicate,
payment_method_data: dec_data,
};
Ok(payment_methods::GetPaymentMethodResponse {
payment_method: payment_method_response,
})
}
<file_sep path="hyperswitch/crates/router/src/connector/nmi/transformers.rs" role="context" start="454" end="459">
pub enum PaymentMethod {
CardNonThreeDs(Box<CardData>),
CardThreeDs(Box<CardThreeDsData>),
GPay(Box<GooglePayData>),
ApplePay(Box<ApplePayData>),
}
<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/payment_methods/cards.rs<|crate|> router anchor=validate_payment_method_and_client_secret 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="4284" end="4317">
async fn validate_payment_method_and_client_secret(
state: &routes::SessionState,
cs: &String,
db: &dyn db::StorageInterface,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
) -> Result<(), error_stack::Report<errors::ApiErrorResponse>> {
let pm_vec = cs.split("_secret").collect::<Vec<&str>>();
let pm_id = pm_vec
.first()
.ok_or(errors::ApiErrorResponse::MissingRequiredField {
field_name: "client_secret",
})?;
let payment_method = db
.find_payment_method(
&(state.into()),
key_store,
pm_id,
merchant_account.storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::PaymentMethodNotFound)
.attach_printable("Unable to find payment method")?;
let client_secret_expired =
authenticate_pm_client_secret_and_check_expiry(cs, &payment_method)?;
if client_secret_expired {
return Err::<(), error_stack::Report<errors::ApiErrorResponse>>(
(errors::ApiErrorResponse::ClientSecretExpired).into(),
);
}
Ok(())
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="4283" end="4283">
use std::{
collections::{HashMap, HashSet},
fmt::Debug,
str::FromStr,
};
use diesel_models::payment_method;
use error_stack::{report, ResultExt};
use crate::routes::app::SessionStateInfo;
use crate::types::domain::types::AsyncLift;
use crate::{
configs::{
defaults::{get_billing_required_fields, get_shipping_required_fields},
settings,
},
consts as router_consts,
core::{
errors::{self, StorageErrorExt},
payment_methods::{network_tokenization, transformers as payment_methods, vault},
payments::{
helpers,
routing::{self, SessionFlowRoutingInput},
},
utils as core_utils,
},
db, logger,
pii::prelude::*,
routes::{self, metrics, payment_methods::ParentPaymentMethodToken},
services,
types::{
api::{self, routing as routing_types, PaymentMethodCreateExt},
domain::{self, Profile},
storage::{self, enums, PaymentMethodListContext, PaymentTokenData},
transformers::{ForeignFrom, ForeignTryFrom},
},
utils,
utils::OptionExt,
};
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="4381" end="4434">
pub async fn call_surcharge_decision_management_for_saved_card(
state: &routes::SessionState,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
business_profile: &Profile,
payment_attempt: &storage::PaymentAttempt,
payment_intent: storage::PaymentIntent,
customer_payment_method_response: &mut api::CustomerPaymentMethodsListResponse,
) -> errors::RouterResult<()> {
#[cfg(feature = "v1")]
let algorithm_ref: routing_types::RoutingAlgorithmRef = merchant_account
.routing_algorithm
.clone()
.map(|val| val.parse_value("routing algorithm"))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Could not decode the routing algorithm")?
.unwrap_or_default();
#[cfg(feature = "v2")]
let algorithm_ref: routing_types::RoutingAlgorithmRef = todo!();
// TODO: Move to business profile surcharge column
let surcharge_results = perform_surcharge_decision_management_for_saved_cards(
state,
algorithm_ref,
payment_attempt,
&payment_intent,
&mut customer_payment_method_response.customer_payment_methods,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("error performing surcharge decision operation")?;
if !surcharge_results.is_empty_result() {
surcharge_results
.persist_individual_surcharge_details_in_redis(state, business_profile)
.await?;
let _ = state
.store
.update_payment_intent(
&state.into(),
payment_intent,
storage::PaymentIntentUpdate::SurchargeApplicableUpdate {
surcharge_applicable: true,
updated_by: merchant_account.storage_scheme.to_string(),
},
key_store,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)
.attach_printable("Failed to update surcharge_applicable in Payment Intent");
}
Ok(())
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="4321" end="4378">
pub async fn call_surcharge_decision_management(
state: routes::SessionState,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
business_profile: &Profile,
payment_attempt: &storage::PaymentAttempt,
payment_intent: storage::PaymentIntent,
billing_address: Option<domain::Address>,
response_payment_method_types: &mut [ResponsePaymentMethodsEnabled],
) -> errors::RouterResult<api_surcharge_decision_configs::MerchantSurchargeConfigs> {
#[cfg(feature = "v1")]
let algorithm_ref: routing_types::RoutingAlgorithmRef = merchant_account
.routing_algorithm
.clone()
.map(|val| val.parse_value("routing algorithm"))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Could not decode the routing algorithm")?
.unwrap_or_default();
// TODO: Move to business profile surcharge decision column
#[cfg(feature = "v2")]
let algorithm_ref: routing_types::RoutingAlgorithmRef = todo!();
let (surcharge_results, merchant_sucharge_configs) =
perform_surcharge_decision_management_for_payment_method_list(
&state,
algorithm_ref,
payment_attempt,
&payment_intent,
billing_address.as_ref().map(Into::into),
response_payment_method_types,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("error performing surcharge decision operation")?;
if !surcharge_results.is_empty_result() {
surcharge_results
.persist_individual_surcharge_details_in_redis(&state, business_profile)
.await?;
let _ = state
.store
.update_payment_intent(
&(&state).into(),
payment_intent,
storage::PaymentIntentUpdate::SurchargeApplicableUpdate {
surcharge_applicable: true,
updated_by: merchant_account.storage_scheme.to_string(),
},
key_store,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)
.attach_printable("Failed to update surcharge_applicable in Payment Intent");
}
Ok(merchant_sucharge_configs)
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="4247" end="4278">
fn should_collect_shipping_or_billing_details_from_wallet_connector(
payment_method: api_enums::PaymentMethod,
payment_experience_optional: Option<&api_enums::PaymentExperience>,
business_profile: &Profile,
mut required_fields_hs: HashMap<String, RequiredFieldInfo>,
) -> HashMap<String, RequiredFieldInfo> {
match (payment_method, payment_experience_optional) {
(api_enums::PaymentMethod::Wallet, Some(api_enums::PaymentExperience::InvokeSdkClient))
| (
api_enums::PaymentMethod::PayLater,
Some(api_enums::PaymentExperience::InvokeSdkClient),
) => {
let always_send_billing_details =
business_profile.always_collect_billing_details_from_wallet_connector;
let always_send_shipping_details =
business_profile.always_collect_shipping_details_from_wallet_connector;
if always_send_billing_details == Some(true) {
let billing_details = get_billing_required_fields();
required_fields_hs.extend(billing_details)
};
if always_send_shipping_details == Some(true) {
let shipping_details = get_shipping_required_fields();
required_fields_hs.extend(shipping_details)
};
required_fields_hs
}
_ => required_fields_hs,
}
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="3215" end="4240">
pub async fn list_payment_methods(
state: routes::SessionState,
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
mut req: api::PaymentMethodListRequest,
) -> errors::RouterResponse<api::PaymentMethodListResponse> {
let db = &*state.store;
let pm_config_mapping = &state.conf.pm_filters;
let key_manager_state = &(&state).into();
let payment_intent = if let Some(cs) = &req.client_secret {
if cs.starts_with("pm_") {
validate_payment_method_and_client_secret(
&state,
cs,
db,
&merchant_account,
&key_store,
)
.await?;
None
} else {
helpers::verify_payment_intent_time_and_client_secret(
&state,
&merchant_account,
&key_store,
req.client_secret.clone(),
)
.await?
}
} else {
None
};
let shipping_address = payment_intent
.as_ref()
.async_map(|pi| async {
helpers::get_address_by_id(
&state,
pi.shipping_address_id.clone(),
&key_store,
&pi.payment_id,
merchant_account.get_id(),
merchant_account.storage_scheme,
)
.await
})
.await
.transpose()?
.flatten();
let billing_address = payment_intent
.as_ref()
.async_map(|pi| async {
helpers::get_address_by_id(
&state,
pi.billing_address_id.clone(),
&key_store,
&pi.payment_id,
merchant_account.get_id(),
merchant_account.storage_scheme,
)
.await
})
.await
.transpose()?
.flatten();
let customer = payment_intent
.as_ref()
.async_and_then(|pi| async {
pi.customer_id
.as_ref()
.async_and_then(|cust| async {
db.find_customer_by_customer_id_merchant_id(
key_manager_state,
cust,
&pi.merchant_id,
&key_store,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)
.ok()
})
.await
})
.await;
let payment_attempt = payment_intent
.as_ref()
.async_map(|pi| async {
db.find_payment_attempt_by_payment_id_merchant_id_attempt_id(
&pi.payment_id,
&pi.merchant_id,
&pi.active_attempt.get_id(),
merchant_account.storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::PaymentNotFound)
})
.await
.transpose()?;
let setup_future_usage = payment_intent.as_ref().and_then(|pi| pi.setup_future_usage);
let is_cit_transaction = payment_attempt
.as_ref()
.map(|pa| pa.mandate_details.is_some())
.unwrap_or(false)
|| setup_future_usage
.map(|future_usage| future_usage == common_enums::FutureUsage::OffSession)
.unwrap_or(false);
let payment_type = payment_attempt.as_ref().map(|pa| {
let amount = api::Amount::from(pa.net_amount.get_order_amount());
let mandate_type = if pa.mandate_id.is_some() {
Some(api::MandateTransactionType::RecurringMandateTransaction)
} else if is_cit_transaction {
Some(api::MandateTransactionType::NewMandateTransaction)
} else {
None
};
helpers::infer_payment_type(amount, mandate_type.as_ref())
});
let all_mcas = db
.find_merchant_connector_account_by_merchant_id_and_disabled_list(
key_manager_state,
merchant_account.get_id(),
false,
&key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
let profile_id = payment_intent
.as_ref()
.and_then(|payment_intent| payment_intent.profile_id.as_ref())
.get_required_value("profile_id")
.change_context(errors::ApiErrorResponse::GenericNotFoundError {
message: "Profile id not found".to_string(),
})?;
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(),
})?;
// filter out payment connectors based on profile_id
let filtered_mcas = all_mcas
.clone()
.filter_based_on_profile_and_connector_type(profile_id, ConnectorType::PaymentProcessor);
logger::debug!(mca_before_filtering=?filtered_mcas);
let mut response: Vec<ResponsePaymentMethodIntermediate> = vec![];
// Key creation for storing PM_FILTER_CGRAPH
let key = {
format!(
"pm_filters_cgraph_{}_{}",
merchant_account.get_id().get_string_repr(),
profile_id.get_string_repr()
)
};
if let Some(graph) = get_merchant_pm_filter_graph(&state, &key).await {
// Derivation of PM_FILTER_CGRAPH from MokaCache successful
for mca in &filtered_mcas {
let payment_methods = match &mca.payment_methods_enabled {
Some(pm) => pm,
None => continue,
};
filter_payment_methods(
&graph,
mca.get_id(),
payment_methods,
&mut req,
&mut response,
payment_intent.as_ref(),
payment_attempt.as_ref(),
billing_address.as_ref(),
mca.connector_name.clone(),
&state.conf.saved_payment_methods,
)
.await?;
}
} else {
// No PM_FILTER_CGRAPH Cache present in MokaCache
let mut builder = cgraph::ConstraintGraphBuilder::new();
for mca in &filtered_mcas {
let domain_id = builder.make_domain(
mca.get_id().get_string_repr().to_string(),
mca.connector_name.as_str(),
);
let Ok(domain_id) = domain_id else {
logger::error!("Failed to construct domain for list payment methods");
return Err(errors::ApiErrorResponse::InternalServerError.into());
};
let payment_methods = match &mca.payment_methods_enabled {
Some(pm) => pm,
None => continue,
};
if let Err(e) = make_pm_graph(
&mut builder,
domain_id,
payment_methods,
mca.connector_name.clone(),
pm_config_mapping,
&state.conf.mandates.supported_payment_methods,
&state.conf.mandates.update_mandate_supported,
) {
logger::error!(
"Failed to construct constraint graph for list payment methods {e:?}"
);
}
}
// Refreshing our CGraph cache
let graph = refresh_pm_filters_cache(&state, &key, builder.build()).await;
for mca in &filtered_mcas {
let payment_methods = match &mca.payment_methods_enabled {
Some(pm) => pm,
None => continue,
};
filter_payment_methods(
&graph,
mca.get_id().clone(),
payment_methods,
&mut req,
&mut response,
payment_intent.as_ref(),
payment_attempt.as_ref(),
billing_address.as_ref(),
mca.connector_name.clone(),
&state.conf.saved_payment_methods,
)
.await?;
}
}
logger::info!(
"The Payment Methods available after Constraint Graph filtering are {:?}",
response
);
// Filter out wallet payment method from mca if customer has already saved it
customer
.as_ref()
.async_map(|customer| async {
let wallet_pm_exists = response
.iter()
.any(|mca| mca.payment_method == enums::PaymentMethod::Wallet);
if wallet_pm_exists {
match db
.find_payment_method_by_customer_id_merchant_id_status(
&((&state).into()),
&key_store,
&customer.customer_id,
merchant_account.get_id(),
common_enums::PaymentMethodStatus::Active,
None,
merchant_account.storage_scheme,
)
.await
{
Ok(customer_payment_methods) => {
let customer_wallet_pm = customer_payment_methods
.iter()
.filter(|cust_pm| {
cust_pm.get_payment_method_type() == Some(enums::PaymentMethod::Wallet)
})
.collect::<Vec<_>>();
response.retain(|mca| {
!(mca.payment_method == enums::PaymentMethod::Wallet
&& customer_wallet_pm.iter().any(|cust_pm| {
cust_pm.get_payment_method_subtype() == Some(mca.payment_method_type)
}))
});
logger::debug!("Filtered out wallet payment method from mca since customer has already saved it");
Ok(())
}
Err(error) => {
if error.current_context().is_db_not_found() {
Ok(())
} else {
Err(error)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed to find payment methods for a customer")
}
}
}
} else {
Ok(())
}
})
.await
.transpose()?;
let mut pmt_to_auth_connector: HashMap<
enums::PaymentMethod,
HashMap<enums::PaymentMethodType, String>,
> = HashMap::new();
if let Some((payment_attempt, payment_intent)) =
payment_attempt.as_ref().zip(payment_intent.as_ref())
{
let routing_enabled_pms = &router_consts::ROUTING_ENABLED_PAYMENT_METHODS;
let routing_enabled_pm_types = &router_consts::ROUTING_ENABLED_PAYMENT_METHOD_TYPES;
let mut chosen = api::SessionConnectorDatas::new(Vec::new());
for intermediate in &response {
if routing_enabled_pm_types.contains(&intermediate.payment_method_type)
|| routing_enabled_pms.contains(&intermediate.payment_method)
{
let connector_data = api::ConnectorData::get_connector_by_name(
&state.clone().conf.connectors,
&intermediate.connector,
api::GetToken::from(intermediate.payment_method_type),
None,
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("invalid connector name received")?;
chosen.push(api::SessionConnectorData {
payment_method_sub_type: intermediate.payment_method_type,
payment_method_type: intermediate.payment_method,
connector: connector_data,
business_sub_label: None,
});
}
}
let sfr = SessionFlowRoutingInput {
state: &state,
country: billing_address.clone().and_then(|ad| ad.country),
key_store: &key_store,
merchant_account: &merchant_account,
payment_attempt,
payment_intent,
chosen,
};
let result = routing::perform_session_flow_routing(
sfr,
&business_profile,
&enums::TransactionType::Payment,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("error performing session flow routing")?;
response.retain(|intermediate| {
if !routing_enabled_pm_types.contains(&intermediate.payment_method_type)
&& !routing_enabled_pms.contains(&intermediate.payment_method)
{
return true;
}
if let Some(choice) = result.get(&intermediate.payment_method_type) {
if let Some(first_routable_connector) = choice.first() {
intermediate.connector
== first_routable_connector
.connector
.connector_name
.to_string()
&& first_routable_connector
.connector
.merchant_connector_id
.as_ref()
.map(|merchant_connector_id| {
*merchant_connector_id.get_string_repr()
== intermediate.merchant_connector_id
})
.unwrap_or_default()
} else {
false
}
} else {
false
}
});
let mut routing_info: storage::PaymentRoutingInfo = payment_attempt
.straight_through_algorithm
.clone()
.map(|val| val.parse_value("PaymentRoutingInfo"))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Invalid PaymentRoutingInfo format found in payment attempt")?
.unwrap_or(storage::PaymentRoutingInfo {
algorithm: None,
pre_routing_results: None,
});
let mut pre_routing_results: HashMap<
api_enums::PaymentMethodType,
storage::PreRoutingConnectorChoice,
> = HashMap::new();
for (pm_type, routing_choice) in result {
let mut routable_choice_list = vec![];
for choice in routing_choice {
let routable_choice = routing_types::RoutableConnectorChoice {
choice_kind: routing_types::RoutableChoiceKind::FullStruct,
connector: choice
.connector
.connector_name
.to_string()
.parse::<api_enums::RoutableConnectors>()
.change_context(errors::ApiErrorResponse::InternalServerError)?,
merchant_connector_id: choice.connector.merchant_connector_id.clone(),
};
routable_choice_list.push(routable_choice);
}
pre_routing_results.insert(
pm_type,
storage::PreRoutingConnectorChoice::Multiple(routable_choice_list),
);
}
let redis_conn = db
.get_redis_conn()
.map_err(|redis_error| logger::error!(?redis_error))
.ok();
let mut val = Vec::new();
for (payment_method_type, routable_connector_choice) in &pre_routing_results {
let routable_connector_list = match routable_connector_choice {
storage::PreRoutingConnectorChoice::Single(routable_connector) => {
vec![routable_connector.clone()]
}
storage::PreRoutingConnectorChoice::Multiple(routable_connector_list) => {
routable_connector_list.clone()
}
};
let first_routable_connector = routable_connector_list
.first()
.ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)?;
let matched_mca = filtered_mcas.iter().find(|m| {
first_routable_connector.merchant_connector_id.as_ref() == Some(&m.get_id())
});
if let Some(m) = matched_mca {
let pm_auth_config = m
.pm_auth_config
.as_ref()
.map(|config| {
serde_json::from_value::<PaymentMethodAuthConfig>(config.clone().expose())
.change_context(errors::StorageError::DeserializationFailed)
.attach_printable("Failed to deserialize Payment Method Auth config")
})
.transpose()
.unwrap_or_else(|error| {
logger::error!(?error);
None
});
if let Some(config) = pm_auth_config {
for inner_config in config.enabled_payment_methods.iter() {
let is_active_mca = all_mcas
.iter()
.any(|mca| mca.get_id() == inner_config.mca_id);
if inner_config.payment_method_type == *payment_method_type && is_active_mca
{
let pm = pmt_to_auth_connector
.get(&inner_config.payment_method)
.cloned();
let inner_map = if let Some(mut inner_map) = pm {
inner_map.insert(
*payment_method_type,
inner_config.connector_name.clone(),
);
inner_map
} else {
HashMap::from([(
*payment_method_type,
inner_config.connector_name.clone(),
)])
};
pmt_to_auth_connector.insert(inner_config.payment_method, inner_map);
val.push(inner_config.clone());
}
}
};
}
}
let pm_auth_key = payment_intent.payment_id.get_pm_auth_key();
let redis_expiry = state.conf.payment_method_auth.get_inner().redis_expiry;
if let Some(rc) = redis_conn {
rc.serialize_and_set_key_with_expiry(&pm_auth_key.as_str().into(), val, redis_expiry)
.await
.attach_printable("Failed to store pm auth data in redis")
.unwrap_or_else(|error| {
logger::error!(?error);
})
};
routing_info.pre_routing_results = Some(pre_routing_results);
let encoded = routing_info
.encode_to_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to serialize payment routing info to value")?;
let attempt_update = storage::PaymentAttemptUpdate::UpdateTrackers {
payment_token: None,
connector: None,
straight_through_algorithm: Some(encoded),
amount_capturable: None,
updated_by: merchant_account.storage_scheme.to_string(),
merchant_connector_id: None,
surcharge_amount: None,
tax_amount: None,
};
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)?;
}
// Check for `use_billing_as_payment_method_billing` config under business_profile
// If this is disabled, then the billing details in required fields will be empty and have to be collected by the customer
let billing_address_for_calculating_required_fields = business_profile
.use_billing_as_payment_method_billing
.unwrap_or(true)
.then_some(billing_address.as_ref())
.flatten();
let req = api_models::payments::PaymentsRequest::foreign_try_from((
payment_attempt.as_ref(),
payment_intent.as_ref(),
shipping_address.as_ref(),
billing_address_for_calculating_required_fields,
customer.as_ref(),
))?;
let req_val = serde_json::to_value(req).ok();
logger::debug!(filtered_payment_methods=?response);
let mut payment_experiences_consolidated_hm: HashMap<
api_enums::PaymentMethod,
HashMap<api_enums::PaymentMethodType, HashMap<api_enums::PaymentExperience, Vec<String>>>,
> = HashMap::new();
let mut card_networks_consolidated_hm: HashMap<
api_enums::PaymentMethod,
HashMap<api_enums::PaymentMethodType, HashMap<api_enums::CardNetwork, Vec<String>>>,
> = HashMap::new();
let mut banks_consolidated_hm: HashMap<api_enums::PaymentMethodType, Vec<String>> =
HashMap::new();
let mut bank_debits_consolidated_hm =
HashMap::<api_enums::PaymentMethodType, Vec<String>>::new();
let mut bank_transfer_consolidated_hm =
HashMap::<api_enums::PaymentMethodType, Vec<String>>::new();
// All the required fields will be stored here and later filtered out based on business profile config
let mut required_fields_hm = HashMap::<
api_enums::PaymentMethod,
HashMap<api_enums::PaymentMethodType, HashMap<String, RequiredFieldInfo>>,
>::new();
for element in response.clone() {
let payment_method = element.payment_method;
let payment_method_type = element.payment_method_type;
let connector = element.connector.clone();
let connector_variant = api_enums::Connector::from_str(connector.as_str())
.change_context(errors::ConnectorError::InvalidConnectorName)
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "connector",
})
.attach_printable_lazy(|| format!("unable to parse connector name {connector:?}"))?;
state.conf.required_fields.0.get(&payment_method).map(
|required_fields_hm_for_each_payment_method_type| {
required_fields_hm_for_each_payment_method_type
.0
.get(&payment_method_type)
.map(|required_fields_hm_for_each_connector| {
required_fields_hm.entry(payment_method).or_default();
required_fields_hm_for_each_connector
.fields
.get(&connector_variant)
.map(|required_fields_final| {
let mut required_fields_hs = required_fields_final.common.clone();
if is_cit_transaction {
required_fields_hs
.extend(required_fields_final.mandate.clone());
} else {
required_fields_hs
.extend(required_fields_final.non_mandate.clone());
}
required_fields_hs = should_collect_shipping_or_billing_details_from_wallet_connector(
payment_method,
element.payment_experience.as_ref(),
&business_profile,
required_fields_hs.clone(),
);
// get the config, check the enums while adding
{
for (key, val) in &mut required_fields_hs {
let temp = req_val
.as_ref()
.and_then(|r| get_val(key.to_owned(), r));
if let Some(s) = temp {
val.value = Some(s.into())
};
}
}
let existing_req_fields_hs = required_fields_hm
.get_mut(&payment_method)
.and_then(|inner_hm| inner_hm.get_mut(&payment_method_type));
// If payment_method_type already exist in required_fields_hm, extend the required_fields hs to existing hs.
if let Some(inner_hs) = existing_req_fields_hs {
inner_hs.extend(required_fields_hs);
} else {
required_fields_hm.get_mut(&payment_method).map(|inner_hm| {
inner_hm.insert(payment_method_type, required_fields_hs)
});
}
})
})
},
);
if let Some(payment_experience) = element.payment_experience {
if let Some(payment_method_hm) =
payment_experiences_consolidated_hm.get_mut(&payment_method)
{
if let Some(payment_method_type_hm) =
payment_method_hm.get_mut(&payment_method_type)
{
if let Some(vector_of_connectors) =
payment_method_type_hm.get_mut(&payment_experience)
{
vector_of_connectors.push(connector);
} else {
payment_method_type_hm.insert(payment_experience, vec![connector]);
}
} else {
payment_method_hm.insert(
payment_method_type,
HashMap::from([(payment_experience, vec![connector])]),
);
}
} else {
let inner_hm = HashMap::from([(payment_experience, vec![connector])]);
let payment_method_type_hm = HashMap::from([(payment_method_type, inner_hm)]);
payment_experiences_consolidated_hm.insert(payment_method, payment_method_type_hm);
}
}
if let Some(card_networks) = element.card_networks {
if let Some(payment_method_hm) = card_networks_consolidated_hm.get_mut(&payment_method)
{
if let Some(payment_method_type_hm) =
payment_method_hm.get_mut(&payment_method_type)
{
for card_network in card_networks {
if let Some(vector_of_connectors) =
payment_method_type_hm.get_mut(&card_network)
{
let connector = element.connector.clone();
vector_of_connectors.push(connector);
} else {
let connector = element.connector.clone();
payment_method_type_hm.insert(card_network, vec![connector]);
}
}
} else {
let mut inner_hashmap: HashMap<api_enums::CardNetwork, Vec<String>> =
HashMap::new();
for card_network in card_networks {
if let Some(vector_of_connectors) = inner_hashmap.get_mut(&card_network) {
let connector = element.connector.clone();
vector_of_connectors.push(connector);
} else {
let connector = element.connector.clone();
inner_hashmap.insert(card_network, vec![connector]);
}
}
payment_method_hm.insert(payment_method_type, inner_hashmap);
}
} else {
let mut inner_hashmap: HashMap<api_enums::CardNetwork, Vec<String>> =
HashMap::new();
for card_network in card_networks {
if let Some(vector_of_connectors) = inner_hashmap.get_mut(&card_network) {
let connector = element.connector.clone();
vector_of_connectors.push(connector);
} else {
let connector = element.connector.clone();
inner_hashmap.insert(card_network, vec![connector]);
}
}
let payment_method_type_hm = HashMap::from([(payment_method_type, inner_hashmap)]);
card_networks_consolidated_hm.insert(payment_method, payment_method_type_hm);
}
}
if element.payment_method == api_enums::PaymentMethod::BankRedirect {
let connector = element.connector.clone();
if let Some(vector_of_connectors) =
banks_consolidated_hm.get_mut(&element.payment_method_type)
{
vector_of_connectors.push(connector);
} else {
banks_consolidated_hm.insert(element.payment_method_type, vec![connector]);
}
}
if element.payment_method == api_enums::PaymentMethod::BankDebit {
let connector = element.connector.clone();
if let Some(vector_of_connectors) =
bank_debits_consolidated_hm.get_mut(&element.payment_method_type)
{
vector_of_connectors.push(connector);
} else {
bank_debits_consolidated_hm.insert(element.payment_method_type, vec![connector]);
}
}
if element.payment_method == api_enums::PaymentMethod::BankTransfer {
let connector = element.connector.clone();
if let Some(vector_of_connectors) =
bank_transfer_consolidated_hm.get_mut(&element.payment_method_type)
{
vector_of_connectors.push(connector);
} else {
bank_transfer_consolidated_hm.insert(element.payment_method_type, vec![connector]);
}
}
}
let mut payment_method_responses: Vec<ResponsePaymentMethodsEnabled> = vec![];
for key in payment_experiences_consolidated_hm.iter() {
let mut payment_method_types = vec![];
for payment_method_types_hm in key.1 {
let mut payment_experience_types = vec![];
for payment_experience_type in payment_method_types_hm.1 {
payment_experience_types.push(PaymentExperienceTypes {
payment_experience_type: *payment_experience_type.0,
eligible_connectors: payment_experience_type.1.clone(),
})
}
payment_method_types.push(ResponsePaymentMethodTypes {
payment_method_type: *payment_method_types_hm.0,
payment_experience: Some(payment_experience_types),
card_networks: None,
bank_names: None,
bank_debits: None,
bank_transfers: None,
// Required fields for PayLater payment method
required_fields: required_fields_hm
.get(key.0)
.and_then(|inner_hm| inner_hm.get(payment_method_types_hm.0))
.cloned(),
surcharge_details: None,
pm_auth_connector: pmt_to_auth_connector
.get(key.0)
.and_then(|pm_map| pm_map.get(payment_method_types_hm.0))
.cloned(),
})
}
payment_method_responses.push(ResponsePaymentMethodsEnabled {
payment_method: *key.0,
payment_method_types,
})
}
for key in card_networks_consolidated_hm.iter() {
let mut payment_method_types = vec![];
for payment_method_types_hm in key.1 {
let mut card_network_types = vec![];
for card_network_type in payment_method_types_hm.1 {
card_network_types.push(CardNetworkTypes {
card_network: card_network_type.0.clone(),
eligible_connectors: card_network_type.1.clone(),
surcharge_details: None,
})
}
payment_method_types.push(ResponsePaymentMethodTypes {
payment_method_type: *payment_method_types_hm.0,
card_networks: Some(card_network_types),
payment_experience: None,
bank_names: None,
bank_debits: None,
bank_transfers: None,
// Required fields for Card payment method
required_fields: required_fields_hm
.get(key.0)
.and_then(|inner_hm| inner_hm.get(payment_method_types_hm.0))
.cloned(),
surcharge_details: None,
pm_auth_connector: pmt_to_auth_connector
.get(key.0)
.and_then(|pm_map| pm_map.get(payment_method_types_hm.0))
.cloned(),
})
}
payment_method_responses.push(ResponsePaymentMethodsEnabled {
payment_method: *key.0,
payment_method_types,
})
}
let mut bank_redirect_payment_method_types = vec![];
for key in banks_consolidated_hm.iter() {
let payment_method_type = *key.0;
let connectors = key.1.clone();
let bank_names = get_banks(&state, payment_method_type, connectors)?;
bank_redirect_payment_method_types.push({
ResponsePaymentMethodTypes {
payment_method_type,
bank_names: Some(bank_names),
payment_experience: None,
card_networks: None,
bank_debits: None,
bank_transfers: None,
// Required fields for BankRedirect payment method
required_fields: required_fields_hm
.get(&api_enums::PaymentMethod::BankRedirect)
.and_then(|inner_hm| inner_hm.get(key.0))
.cloned(),
surcharge_details: None,
pm_auth_connector: pmt_to_auth_connector
.get(&enums::PaymentMethod::BankRedirect)
.and_then(|pm_map| pm_map.get(key.0))
.cloned(),
}
})
}
if !bank_redirect_payment_method_types.is_empty() {
payment_method_responses.push(ResponsePaymentMethodsEnabled {
payment_method: api_enums::PaymentMethod::BankRedirect,
payment_method_types: bank_redirect_payment_method_types,
});
}
let mut bank_debit_payment_method_types = vec![];
for key in bank_debits_consolidated_hm.iter() {
let payment_method_type = *key.0;
let connectors = key.1.clone();
bank_debit_payment_method_types.push({
ResponsePaymentMethodTypes {
payment_method_type,
bank_names: None,
payment_experience: None,
card_networks: None,
bank_debits: Some(api_models::payment_methods::BankDebitTypes {
eligible_connectors: connectors.clone(),
}),
bank_transfers: None,
// Required fields for BankDebit payment method
required_fields: required_fields_hm
.get(&api_enums::PaymentMethod::BankDebit)
.and_then(|inner_hm| inner_hm.get(key.0))
.cloned(),
surcharge_details: None,
pm_auth_connector: pmt_to_auth_connector
.get(&enums::PaymentMethod::BankDebit)
.and_then(|pm_map| pm_map.get(key.0))
.cloned(),
}
})
}
if !bank_debit_payment_method_types.is_empty() {
payment_method_responses.push(ResponsePaymentMethodsEnabled {
payment_method: api_enums::PaymentMethod::BankDebit,
payment_method_types: bank_debit_payment_method_types,
});
}
let mut bank_transfer_payment_method_types = vec![];
for key in bank_transfer_consolidated_hm.iter() {
let payment_method_type = *key.0;
let connectors = key.1.clone();
bank_transfer_payment_method_types.push({
ResponsePaymentMethodTypes {
payment_method_type,
bank_names: None,
payment_experience: None,
card_networks: None,
bank_debits: None,
bank_transfers: Some(api_models::payment_methods::BankTransferTypes {
eligible_connectors: connectors,
}),
// Required fields for BankTransfer payment method
required_fields: required_fields_hm
.get(&api_enums::PaymentMethod::BankTransfer)
.and_then(|inner_hm| inner_hm.get(key.0))
.cloned(),
surcharge_details: None,
pm_auth_connector: pmt_to_auth_connector
.get(&enums::PaymentMethod::BankTransfer)
.and_then(|pm_map| pm_map.get(key.0))
.cloned(),
}
})
}
if !bank_transfer_payment_method_types.is_empty() {
payment_method_responses.push(ResponsePaymentMethodsEnabled {
payment_method: api_enums::PaymentMethod::BankTransfer,
payment_method_types: bank_transfer_payment_method_types,
});
}
let currency = payment_intent.as_ref().and_then(|pi| pi.currency);
let skip_external_tax_calculation = payment_intent
.as_ref()
.and_then(|intent| intent.skip_external_tax_calculation)
.unwrap_or(false);
let request_external_three_ds_authentication = payment_intent
.as_ref()
.and_then(|intent| intent.request_external_three_ds_authentication)
.unwrap_or(false);
let merchant_surcharge_configs = if let Some((payment_attempt, payment_intent)) =
payment_attempt.as_ref().zip(payment_intent)
{
Box::pin(call_surcharge_decision_management(
state,
&merchant_account,
&key_store,
&business_profile,
payment_attempt,
payment_intent,
billing_address,
&mut payment_method_responses,
))
.await?
} else {
api_surcharge_decision_configs::MerchantSurchargeConfigs::default()
};
let collect_shipping_details_from_wallets = if business_profile
.always_collect_shipping_details_from_wallet_connector
.unwrap_or(false)
{
business_profile.always_collect_shipping_details_from_wallet_connector
} else {
business_profile.collect_shipping_details_from_wallet_connector
};
let collect_billing_details_from_wallets = if business_profile
.always_collect_billing_details_from_wallet_connector
.unwrap_or(false)
{
business_profile.always_collect_billing_details_from_wallet_connector
} else {
business_profile.collect_billing_details_from_wallet_connector
};
let is_tax_connector_enabled = business_profile.get_is_tax_connector_enabled();
Ok(services::ApplicationResponse::Json(
api::PaymentMethodListResponse {
redirect_url: business_profile.return_url.clone(),
merchant_name: merchant_account.merchant_name,
payment_type,
payment_methods: payment_method_responses,
mandate_payment: payment_attempt.and_then(|inner| inner.mandate_details).map(
|d| match d {
hyperswitch_domain_models::mandates::MandateDataType::SingleUse(i) => {
api::MandateType::SingleUse(api::MandateAmountData {
amount: i.amount,
currency: i.currency,
start_date: i.start_date,
end_date: i.end_date,
metadata: i.metadata,
})
}
hyperswitch_domain_models::mandates::MandateDataType::MultiUse(Some(i)) => {
api::MandateType::MultiUse(Some(api::MandateAmountData {
amount: i.amount,
currency: i.currency,
start_date: i.start_date,
end_date: i.end_date,
metadata: i.metadata,
}))
}
hyperswitch_domain_models::mandates::MandateDataType::MultiUse(None) => {
api::MandateType::MultiUse(None)
}
},
),
show_surcharge_breakup_screen: merchant_surcharge_configs
.show_surcharge_breakup_screen
.unwrap_or_default(),
currency,
request_external_three_ds_authentication,
collect_shipping_details_from_wallets,
collect_billing_details_from_wallets,
is_tax_calculation_enabled: is_tax_connector_enabled && !skip_external_tax_calculation,
},
))
}
<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/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/webhooks/recovery_incoming.rs<|crate|> router anchor=get_billing_connector_payment_details kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/webhooks/recovery_incoming.rs" role="context" start="717" end="752">
async fn get_billing_connector_payment_details(
should_billing_connector_payment_api_called: bool,
state: &SessionState,
merchant_account: &domain::MerchantAccount,
billing_connector_account: &hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount,
connector_name: &str,
object_ref_id: &webhooks::ObjectReferenceId,
) -> CustomResult<
Option<revenue_recovery_response::BillingConnectorPaymentsSyncResponse>,
errors::RevenueRecoveryError,
> {
let response_data = match should_billing_connector_payment_api_called {
true => {
let billing_connector_transaction_id = object_ref_id
.clone()
.get_connector_transaction_id_as_string()
.change_context(
errors::RevenueRecoveryError::BillingConnectorPaymentsSyncFailed,
)
.attach_printable("Billing connector Payments api call failed")?;
let billing_connector_payment_details =
Self::handle_billing_connector_payment_sync_call(
state,
merchant_account,
billing_connector_account,
connector_name,
&billing_connector_transaction_id,
)
.await?;
Some(billing_connector_payment_details.inner())
}
false => None,
};
Ok(response_data)
}
<file_sep path="hyperswitch/crates/router/src/core/webhooks/recovery_incoming.rs" role="context" start="716" end="716">
use std::{marker::PhantomData, str::FromStr};
use api_models::{payments as api_payments, webhooks};
use hyperswitch_domain_models::{
errors::api_error_response, revenue_recovery, router_data_v2::flow_common_types,
router_flow_types, router_request_types::revenue_recovery as revenue_recovery_request,
router_response_types::revenue_recovery as revenue_recovery_response, types as router_types,
};
use hyperswitch_interfaces::webhooks as interface_webhooks;
use crate::{
core::{
errors::{self, CustomResult},
payments::{self, helpers},
},
db::{errors::RevenueRecoveryError, StorageInterface},
routes::{app::ReqState, metrics, SessionState},
services::{
self,
connector_integration_interface::{self, RouterDataConversion},
},
types::{self, api, domain, storage::revenue_recovery as storage_churn_recovery},
workflows::revenue_recovery as revenue_recovery_flow,
};
<file_sep path="hyperswitch/crates/router/src/core/webhooks/recovery_incoming.rs" role="context" start="760" end="795">
async fn construct_router_data_for_billing_connector_payment_sync_call(
state: &SessionState,
connector_name: &str,
merchant_connector_account: &hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount,
merchant_account: &domain::MerchantAccount,
billing_connector_psync_id: &str,
) -> CustomResult<Self, errors::RevenueRecoveryError> {
let auth_type: types::ConnectorAuthType = helpers::MerchantConnectorAccountType::DbVal(
Box::new(merchant_connector_account.clone()),
)
.get_connector_account_details()
.parse_value("ConnectorAuthType")
.change_context(errors::RevenueRecoveryError::BillingConnectorPaymentsSyncFailed)?;
let router_data = types::RouterDataV2 {
flow: PhantomData::<router_flow_types::BillingConnectorPaymentsSync>,
tenant_id: state.tenant.tenant_id.clone(),
resource_common_data: flow_common_types::BillingConnectorPaymentsSyncFlowData,
connector_auth_type: auth_type,
request: revenue_recovery_request::BillingConnectorPaymentsSyncRequest {
billing_connector_psync_id: billing_connector_psync_id.to_string(),
},
response: Err(types::ErrorResponse::default()),
};
let old_router_data =
flow_common_types::BillingConnectorPaymentsSyncFlowData::to_old_router_data(
router_data,
)
.change_context(errors::RevenueRecoveryError::BillingConnectorPaymentsSyncFailed)
.attach_printable(
"Cannot construct router data for making the billing connector payments api call",
)?;
Ok(Self(old_router_data))
}
<file_sep path="hyperswitch/crates/router/src/core/webhooks/recovery_incoming.rs" role="context" start="754" end="756">
fn inner(self) -> revenue_recovery_response::BillingConnectorPaymentsSyncResponse {
self.0
}
<file_sep path="hyperswitch/crates/router/src/core/webhooks/recovery_incoming.rs" role="context" start="658" end="715">
async fn handle_billing_connector_payment_sync_call(
state: &SessionState,
merchant_account: &domain::MerchantAccount,
merchant_connector_account: &hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount,
connector_name: &str,
id: &str,
) -> CustomResult<Self, errors::RevenueRecoveryError> {
let connector_data = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
connector_name,
api::GetToken::Connector,
None,
)
.change_context(errors::RevenueRecoveryError::BillingConnectorPaymentsSyncFailed)
.attach_printable("invalid connector name received in payment attempt")?;
let connector_integration: services::BoxedBillingConnectorPaymentsSyncIntegrationInterface<
router_flow_types::BillingConnectorPaymentsSync,
revenue_recovery_request::BillingConnectorPaymentsSyncRequest,
revenue_recovery_response::BillingConnectorPaymentsSyncResponse,
> = connector_data.connector.get_connector_integration();
let router_data =
BillingConnectorPaymentsSyncFlowRouterData::construct_router_data_for_billing_connector_payment_sync_call(
state,
connector_name,
merchant_connector_account,
merchant_account,
id,
)
.await
.change_context(errors::RevenueRecoveryError::BillingConnectorPaymentsSyncFailed)
.attach_printable(
"Failed while constructing router data for billing connector psync call",
)?
.inner();
let response = services::execute_connector_processing_step(
state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
)
.await
.change_context(errors::RevenueRecoveryError::BillingConnectorPaymentsSyncFailed)
.attach_printable("Failed while fetching billing connector payment details")?;
let additional_recovery_details = match response.response {
Ok(response) => Ok(response),
error @ Err(_) => {
router_env::logger::error!(?error);
Err(errors::RevenueRecoveryError::BillingConnectorPaymentsSyncFailed)
.attach_printable("Failed while fetching billing connector payment details")
}
}?;
Ok(Self(additional_recovery_details))
}
<file_sep path="hyperswitch/crates/router/src/core/webhooks/recovery_incoming.rs" role="context" start="574" end="647">
async fn insert_execute_pcr_task(
db: &dyn StorageInterface,
merchant_id: id_type::MerchantId,
payment_intent: revenue_recovery::RecoveryPaymentIntent,
profile_id: id_type::ProfileId,
payment_attempt_id: Option<id_type::GlobalAttemptId>,
runner: storage::ProcessTrackerRunner,
) -> CustomResult<webhooks::WebhookResponseTracker, errors::RevenueRecoveryError> {
let task = "EXECUTE_WORKFLOW";
let payment_id = payment_intent.payment_id.clone();
let process_tracker_id = format!("{runner}_{task}_{}", payment_id.get_string_repr());
let total_retry_count = payment_intent
.feature_metadata
.and_then(|feature_metadata| feature_metadata.get_retry_count())
.unwrap_or(0);
let schedule_time = revenue_recovery_flow::get_schedule_time_to_retry_mit_payments(
db,
&merchant_id,
(total_retry_count + 1).into(),
)
.await
.map_or_else(
|| {
Err(
report!(errors::RevenueRecoveryError::ScheduleTimeFetchFailed)
.attach_printable("Failed to get schedule time for pcr workflow"),
)
},
Ok, // Simply returns `time` wrapped in `Ok`
)?;
let payment_attempt_id = payment_attempt_id
.ok_or(report!(
errors::RevenueRecoveryError::PaymentAttemptIdNotFound
))
.attach_printable("payment attempt id is required for pcr workflow tracking")?;
let execute_workflow_tracking_data = storage_churn_recovery::PcrWorkflowTrackingData {
global_payment_id: payment_id.clone(),
merchant_id,
profile_id,
payment_attempt_id,
};
let tag = ["PCR"];
let process_tracker_entry = storage::ProcessTrackerNew::new(
process_tracker_id,
task,
runner,
tag,
execute_workflow_tracking_data,
Some(total_retry_count.into()),
schedule_time,
common_enums::ApiVersion::V2,
)
.change_context(errors::RevenueRecoveryError::ProcessTrackerCreationError)
.attach_printable("Failed to construct process tracker entry")?;
db.insert_process(process_tracker_entry)
.await
.change_context(errors::RevenueRecoveryError::ProcessTrackerResponseError)
.attach_printable("Failed to enter process_tracker_entry in DB")?;
metrics::TASKS_ADDED_COUNT.add(1, router_env::metric_attributes!(("flow", "ExecutePCR")));
Ok(webhooks::WebhookResponseTracker::Payment {
payment_id,
status: payment_intent.status,
})
}
<file_sep path="hyperswitch/crates/router/src/core/webhooks/recovery_incoming.rs" role="context" start="37" end="173">
pub async fn recovery_incoming_webhook_flow(
state: SessionState,
merchant_account: domain::MerchantAccount,
business_profile: domain::Profile,
key_store: domain::MerchantKeyStore,
_webhook_details: api::IncomingWebhookDetails,
source_verified: bool,
connector_enum: &connector_integration_interface::ConnectorEnum,
billing_connector_account: hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount,
connector_name: &str,
request_details: &hyperswitch_interfaces::webhooks::IncomingWebhookRequestDetails<'_>,
event_type: webhooks::IncomingWebhookEvent,
req_state: ReqState,
object_ref_id: &webhooks::ObjectReferenceId,
) -> CustomResult<webhooks::WebhookResponseTracker, errors::RevenueRecoveryError> {
// Source verification is necessary for revenue recovery webhooks flow since We don't have payment intent/attempt object created before in our system.
common_utils::fp_utils::when(!source_verified, || {
Err(report!(
errors::RevenueRecoveryError::WebhookAuthenticationFailed
))
})?;
let connector = api_models::enums::Connector::from_str(connector_name)
.change_context(errors::RevenueRecoveryError::InvoiceWebhookProcessingFailed)
.attach_printable_lazy(|| format!("unable to parse connector name {connector_name:?}"))?;
let billing_connectors_with_payment_sync_call = &state.conf.billing_connectors_payment_sync;
let should_billing_connector_payment_api_called = billing_connectors_with_payment_sync_call
.billing_connectors_which_require_payment_sync
.contains(&connector);
let billing_connector_payment_details =
BillingConnectorPaymentsSyncResponseData::get_billing_connector_payment_details(
should_billing_connector_payment_api_called,
&state,
&merchant_account,
&billing_connector_account,
connector_name,
object_ref_id,
)
.await?;
// Checks whether we have data in recovery_details , If its there then it will use the data and convert it into required from or else fetches from Incoming webhook
let invoice_details = RevenueRecoveryInvoice::get_recovery_invoice_details(
connector_enum,
request_details,
billing_connector_payment_details.as_ref(),
)?;
// Fetch the intent using merchant reference id, if not found create new intent.
let payment_intent = invoice_details
.get_payment_intent(
&state,
&req_state,
&merchant_account,
&business_profile,
&key_store,
)
.await
.transpose()
.async_unwrap_or_else(|| async {
invoice_details
.create_payment_intent(
&state,
&req_state,
&merchant_account,
&business_profile,
&key_store,
)
.await
})
.await?;
let is_event_recovery_transaction_event = event_type.is_recovery_transaction_event();
let payment_attempt = RevenueRecoveryAttempt::get_recovery_payment_attempt(
is_event_recovery_transaction_event,
&billing_connector_account,
&state,
&key_store,
connector_enum,
&req_state,
billing_connector_payment_details.as_ref(),
request_details,
&merchant_account,
&business_profile,
&payment_intent,
)
.await?;
let attempt_triggered_by = payment_attempt
.as_ref()
.and_then(revenue_recovery::RecoveryPaymentAttempt::get_attempt_triggered_by);
let action = revenue_recovery::RecoveryAction::get_action(event_type, attempt_triggered_by);
match action {
revenue_recovery::RecoveryAction::CancelInvoice => todo!(),
revenue_recovery::RecoveryAction::ScheduleFailedPayment => {
Ok(RevenueRecoveryAttempt::insert_execute_pcr_task(
&*state.store,
merchant_account.get_id().to_owned(),
payment_intent,
business_profile.get_id().to_owned(),
payment_attempt.map(|attempt| attempt.attempt_id.clone()),
storage::ProcessTrackerRunner::PassiveRecoveryWorkflow,
)
.await
.change_context(errors::RevenueRecoveryError::InvoiceWebhookProcessingFailed)?)
}
revenue_recovery::RecoveryAction::SuccessPaymentExternal => {
// Need to add recovery stop flow for this scenario
router_env::logger::info!("Payment has been succeeded via external system");
Ok(webhooks::WebhookResponseTracker::NoEffect)
}
revenue_recovery::RecoveryAction::PendingPayment => {
router_env::logger::info!(
"Pending transactions are not consumed by the revenue recovery webhooks"
);
Ok(webhooks::WebhookResponseTracker::NoEffect)
}
revenue_recovery::RecoveryAction::NoAction => {
router_env::logger::info!(
"No Recovery action is taken place for recovery event : {:?} and attempt triggered_by : {:?} ", event_type.clone(), attempt_triggered_by
);
Ok(webhooks::WebhookResponseTracker::NoEffect)
}
revenue_recovery::RecoveryAction::InvalidAction => {
router_env::logger::error!(
"Invalid Revenue recovery action state has been received, event : {:?}, triggered_by : {:?}", event_type, attempt_triggered_by
);
Ok(webhooks::WebhookResponseTracker::NoEffect)
}
}
}
<file_sep path="hyperswitch/crates/router/src/routes/app.rs" role="context" start="562" end="562">
pub struct Payments;
<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/webhooks.rs" role="context" start="247" end="256">
pub enum ObjectReferenceId {
PaymentId(payments::PaymentIdType),
RefundId(RefundIdType),
MandateId(MandateIdType),
ExternalAuthenticationID(AuthenticationIdType),
#[cfg(feature = "payouts")]
PayoutId(PayoutIdType),
#[cfg(all(feature = "revenue_recovery", feature = "v2"))]
InvoiceId(InvoiceIdType),
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payment_methods/cards.rs<|crate|> router anchor=tokenize_card_flow 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="6000" end="6032">
pub async fn tokenize_card_flow(
state: &routes::SessionState,
req: domain::CardNetworkTokenizeRequest,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
) -> errors::RouterResult<api::CardNetworkTokenizeResponse> {
match req.data {
domain::TokenizeDataRequest::Card(ref card_req) => {
let executor = tokenize::CardNetworkTokenizeExecutor::new(
state,
key_store,
merchant_account,
card_req,
&req.customer,
);
let builder =
tokenize::NetworkTokenizationBuilder::<tokenize::TokenizeWithCard>::default();
execute_card_tokenization(executor, builder, card_req).await
}
domain::TokenizeDataRequest::ExistingPaymentMethod(ref payment_method) => {
let executor = tokenize::CardNetworkTokenizeExecutor::new(
state,
key_store,
merchant_account,
payment_method,
&req.customer,
);
let builder =
tokenize::NetworkTokenizationBuilder::<tokenize::TokenizeWithPmId>::default();
execute_payment_method_tokenization(executor, builder, payment_method).await
}
}
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="5999" end="5999">
.map(|country_code| CountryCodeWithName {
code: country_code,
name: common_enums::Country::from_alpha2(country_code),
})
.collect(),
}
}
#[cfg(all(
any(feature = "v1", feature = "v2"),
not(feature = "payment_methods_v2")
))]
pub async fn tokenize_card_flow(
state: &routes::SessionState,
req: domain::CardNetworkTokenizeRequest,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
) -> errors::RouterResult<api::CardNetworkTokenizeResponse> {
match req.data {
domain::TokenizeDataRequest::Card(ref card_req) => {
let executor = tokenize::CardNetworkTokenizeExecutor::new(
state,
key_store,
merchant_account,
card_req,
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="6103" end="6172">
pub async fn execute_payment_method_tokenization(
executor: tokenize::CardNetworkTokenizeExecutor<'_, domain::TokenizePaymentMethodRequest>,
builder: tokenize::NetworkTokenizationBuilder<'_, tokenize::TokenizeWithPmId>,
req: &domain::TokenizePaymentMethodRequest,
) -> errors::RouterResult<api::CardNetworkTokenizeResponse> {
// Fetch payment method
let payment_method = executor
.fetch_payment_method(&req.payment_method_id)
.await?;
let builder = builder.set_payment_method(&payment_method);
// Validate payment method and customer
let (locker_id, customer) = executor
.validate_request_and_locker_reference_and_customer(&payment_method)
.await?;
let builder = builder.set_validate_result(&customer);
// Fetch card from locker
let card_details = get_card_from_locker(
executor.state,
&customer.id,
executor.merchant_account.get_id(),
&locker_id,
)
.await?;
// Perform BIN lookup and validate card network
let optional_card_info = executor
.fetch_bin_details_and_validate_card_network(
card_details.card_number.clone(),
None,
None,
None,
None,
)
.await?;
let builder = builder.set_card_details(&card_details, optional_card_info, req.card_cvc.clone());
// Tokenize card
let (optional_card, optional_cvc) = builder.get_optional_card_and_cvc();
let domain_card = optional_card.get_required_value("card")?;
let network_token_details = executor
.tokenize_card(&customer.id, &domain_card, optional_cvc)
.await?;
let builder = builder.set_token_details(&network_token_details);
// Store token in locker
let store_token_resp = executor
.store_network_token_in_locker(
&network_token_details,
&customer.id,
card_details.name_on_card.clone(),
card_details.nick_name.clone().map(Secret::new),
)
.await?;
let builder = builder.set_stored_token_response(&store_token_resp);
// Update payment method
let updated_payment_method = executor
.update_payment_method(
&store_token_resp,
payment_method,
&network_token_details,
&domain_card,
)
.await?;
let builder = builder.set_payment_method(&updated_payment_method);
Ok(builder.build())
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="6038" end="6097">
pub async fn execute_card_tokenization(
executor: tokenize::CardNetworkTokenizeExecutor<'_, domain::TokenizeCardRequest>,
builder: tokenize::NetworkTokenizationBuilder<'_, tokenize::TokenizeWithCard>,
req: &domain::TokenizeCardRequest,
) -> errors::RouterResult<api::CardNetworkTokenizeResponse> {
// Validate request and get optional customer
let optional_customer = executor
.validate_request_and_fetch_optional_customer()
.await?;
let builder = builder.set_validate_result();
// Perform BIN lookup and validate card network
let optional_card_info = executor
.fetch_bin_details_and_validate_card_network(
req.raw_card_number.clone(),
req.card_issuer.as_ref(),
req.card_network.as_ref(),
req.card_type.as_ref(),
req.card_issuing_country.as_ref(),
)
.await?;
let builder = builder.set_card_details(req, optional_card_info);
// Create customer if not present
let customer = match optional_customer {
Some(customer) => customer,
None => executor.create_customer().await?,
};
let builder = builder.set_customer(&customer);
// Tokenize card
let (optional_card, optional_cvc) = builder.get_optional_card_and_cvc();
let domain_card = optional_card
.get_required_value("card")
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let network_token_details = executor
.tokenize_card(&customer.id, &domain_card, optional_cvc)
.await?;
let builder = builder.set_token_details(&network_token_details);
// Store card and token in locker
let store_card_and_token_resp = executor
.store_card_and_token_in_locker(&network_token_details, &domain_card, &customer.id)
.await?;
let builder = builder.set_stored_card_response(&store_card_and_token_resp);
let builder = builder.set_stored_token_response(&store_card_and_token_resp);
// Create payment method
let payment_method = executor
.create_payment_method(
&store_card_and_token_resp,
&network_token_details,
&domain_card,
&customer.id,
)
.await?;
let builder = builder.set_payment_method_response(&payment_method);
Ok(builder.build())
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="5956" end="5994">
pub async fn list_countries_currencies_for_connector_payment_method_util(
connector_filters: settings::ConnectorFilters,
connector: api_enums::Connector,
payment_method_type: api_enums::PaymentMethodType,
) -> ListCountriesCurrenciesResponse {
let payment_method_type =
settings::PaymentMethodFilterKey::PaymentMethodType(payment_method_type);
let (currencies, country_codes) = connector_filters
.0
.get(&connector.to_string())
.and_then(|filter| filter.0.get(&payment_method_type))
.map(|filter| (filter.currency.clone(), filter.country.clone()))
.unwrap_or_else(|| {
connector_filters
.0
.get("default")
.and_then(|filter| filter.0.get(&payment_method_type))
.map_or((None, None), |filter| {
(filter.currency.clone(), filter.country.clone())
})
});
let currencies =
currencies.unwrap_or_else(|| api_enums::Currency::iter().collect::<HashSet<_>>());
let country_codes =
country_codes.unwrap_or_else(|| api_enums::CountryAlpha2::iter().collect::<HashSet<_>>());
ListCountriesCurrenciesResponse {
currencies,
countries: country_codes
.into_iter()
.map(|country_code| CountryCodeWithName {
code: country_code,
name: common_enums::Country::from_alpha2(country_code),
})
.collect(),
}
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="5939" end="5952">
pub async fn list_countries_currencies_for_connector_payment_method(
state: routes::SessionState,
req: ListCountriesCurrenciesRequest,
_profile_id: Option<id_type::ProfileId>,
) -> errors::RouterResponse<ListCountriesCurrenciesResponse> {
Ok(services::ApplicationResponse::Json(
list_countries_currencies_for_connector_payment_method_util(
state.conf.pm_filters.clone(),
req.connector,
req.payment_method_type,
)
.await,
))
}
<file_sep path="hyperswitch/crates/router/src/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/payouts.rs<|crate|> router anchor=complete_payout_eligibility 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="1413" end="1447">
pub async fn complete_payout_eligibility(
state: &SessionState,
merchant_account: &domain::MerchantAccount,
connector_data: &api::ConnectorData,
payout_data: &mut PayoutData,
) -> RouterResult<()> {
let payout_attempt = &payout_data.payout_attempt.to_owned();
if !payout_data.should_terminate
&& payout_attempt.is_eligible.is_none()
&& connector_data
.connector_name
.supports_payout_eligibility(payout_data.payouts.payout_type)
{
check_payout_eligibility(state, merchant_account, connector_data, payout_data)
.await
.attach_printable("Eligibility failed for given Payout request")?;
}
utils::when(
!payout_attempt
.is_eligible
.unwrap_or(state.conf.payouts.payout_eligibility),
|| {
Err(report!(errors::ApiErrorResponse::PayoutFailed {
data: Some(serde_json::json!({
"message": "Payout method data is invalid"
}))
})
.attach_printable("Payout data provided is invalid"))
},
)?;
Ok(())
}
<file_sep path="hyperswitch/crates/router/src/core/payouts.rs" role="context" start="1412" end="1412">
use api_models::{self, enums as api_enums, payouts::PayoutLinkResponse};
use error_stack::{report, ResultExt};
use scheduler::utils as pt_utils;
use serde_json;
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="1584" end="1649">
pub async fn complete_create_payout(
state: &SessionState,
merchant_account: &domain::MerchantAccount,
connector_data: &api::ConnectorData,
payout_data: &mut PayoutData,
) -> RouterResult<()> {
if !payout_data.should_terminate
&& matches!(
payout_data.payout_attempt.status,
storage_enums::PayoutStatus::RequiresCreation
| storage_enums::PayoutStatus::RequiresConfirmation
| storage_enums::PayoutStatus::RequiresPayoutMethodData
)
{
if connector_data
.connector_name
.supports_instant_payout(payout_data.payouts.payout_type)
{
// create payout_object only in router
let db = &*state.store;
let payout_attempt = &payout_data.payout_attempt;
let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate {
connector_payout_id: payout_data.payout_attempt.connector_payout_id.clone(),
status: storage::enums::PayoutStatus::RequiresFulfillment,
error_code: None,
error_message: None,
is_eligible: None,
unified_code: None,
unified_message: None,
};
payout_data.payout_attempt = db
.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 = db
.update_payout(
&payout_data.payouts,
storage::PayoutsUpdate::StatusUpdate {
status: storage::enums::PayoutStatus::RequiresFulfillment,
},
&payout_data.payout_attempt,
merchant_account.storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating payouts in db")?;
} else {
// create payout_object in connector as well as router
Box::pin(create_payout(
state,
merchant_account,
connector_data,
payout_data,
))
.await
.attach_printable("Payout creation failed for given Payout request")?;
}
}
Ok(())
}
<file_sep path="hyperswitch/crates/router/src/core/payouts.rs" role="context" start="1449" end="1582">
pub async fn check_payout_eligibility(
state: &SessionState,
merchant_account: &domain::MerchantAccount,
connector_data: &api::ConnectorData,
payout_data: &mut PayoutData,
) -> RouterResult<()> {
// 1. Form Router data
let router_data = core_utils::construct_payout_router_data(
state,
connector_data,
merchant_account,
payout_data,
)
.await?;
// 2. Fetch connector integration details
let connector_integration: services::BoxedPayoutConnectorIntegrationInterface<
api::PoEligibility,
types::PayoutsData,
types::PayoutsResponseData,
> = connector_data.connector.get_connector_integration();
// 3. Call connector service
let router_data_resp = services::execute_connector_processing_step(
state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
)
.await
.to_payout_failed_response()?;
// 4. Process data returned by the connector
let db = &*state.store;
match router_data_resp.response {
Ok(payout_response_data) => {
let payout_attempt = &payout_data.payout_attempt;
let status = payout_response_data
.status
.unwrap_or(payout_attempt.status.to_owned());
let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate {
connector_payout_id: payout_response_data.connector_payout_id,
status,
error_code: None,
error_message: None,
is_eligible: payout_response_data.payout_eligible,
unified_code: None,
unified_message: None,
};
payout_data.payout_attempt = db
.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 = db
.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")?;
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_data.payout_attempt.error_message.as_ref(), "error_code": payout_data.payout_attempt.error_code.as_ref()})
),
}));
}
}
Err(err) => {
let status = storage_enums::PayoutStatus::Failed;
let (error_code, error_message) = (Some(err.code), Some(err.message));
let (unified_code, unified_message) = helpers::get_gsm_record(
state,
error_code.clone(),
error_message.clone(),
payout_data.payout_attempt.connector.clone(),
consts::PAYOUT_FLOW_STR,
)
.await
.map_or((None, None), |gsm| (gsm.unified_code, gsm.unified_message));
let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate {
connector_payout_id: payout_data.payout_attempt.connector_payout_id.to_owned(),
status,
error_code,
error_message,
is_eligible: Some(false),
unified_code: unified_code
.map(UnifiedCode::try_from)
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "unified_code",
})?,
unified_message: unified_message
.map(UnifiedMessage::try_from)
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "unified_message",
})?,
};
payout_data.payout_attempt = db
.update_payout_attempt(
&payout_data.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 = db
.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")?;
}
};
Ok(())
}
<file_sep path="hyperswitch/crates/router/src/core/payouts.rs" role="context" start="1403" end="1411">
pub async fn create_recipient(
state: &SessionState,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
connector_data: &api::ConnectorData,
payout_data: &mut PayoutData,
) -> RouterResult<()> {
todo!()
}
<file_sep path="hyperswitch/crates/router/src/core/payouts.rs" role="context" start="1203" end="1400">
pub async fn create_recipient(
state: &SessionState,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
connector_data: &api::ConnectorData,
payout_data: &mut PayoutData,
) -> RouterResult<()> {
let customer_details = payout_data.customer_details.to_owned();
let connector_name = connector_data.connector_name.to_string();
// Create the connector label using {profile_id}_{connector_name}
let connector_label = format!(
"{}_{}",
payout_data.profile_id.get_string_repr(),
connector_name
);
let (should_call_connector, _connector_customer_id) =
helpers::should_call_payout_connector_create_customer(
state,
connector_data,
&customer_details,
&connector_label,
);
if should_call_connector {
// 1. Form router data
let router_data = core_utils::construct_payout_router_data(
state,
connector_data,
merchant_account,
payout_data,
)
.await?;
// 2. Fetch connector integration details
let connector_integration: services::BoxedPayoutConnectorIntegrationInterface<
api::PoRecipient,
types::PayoutsData,
types::PayoutsResponseData,
> = connector_data.connector.get_connector_integration();
// 3. Call connector service
let router_resp = services::execute_connector_processing_step(
state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
)
.await
.to_payout_failed_response()?;
match router_resp.response {
Ok(recipient_create_data) => {
let db = &*state.store;
if let Some(customer) = customer_details {
if let Some(updated_customer) =
customers::update_connector_customer_in_customers(
&connector_label,
Some(&customer),
recipient_create_data.connector_payout_id.clone(),
)
.await
{
#[cfg(all(
any(feature = "v1", feature = "v2"),
not(feature = "customer_v2")
))]
{
let customer_id = customer.customer_id.to_owned();
payout_data.customer_details = Some(
db.update_customer_by_customer_id_merchant_id(
&state.into(),
customer_id,
merchant_account.get_id().to_owned(),
customer,
updated_customer,
key_store,
merchant_account.storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating customers in db")?,
);
}
#[cfg(all(feature = "v2", feature = "customer_v2"))]
{
let customer_id = customer.get_id().clone();
payout_data.customer_details = Some(
db.update_customer_by_global_id(
&state.into(),
&customer_id,
customer,
merchant_account.get_id(),
updated_customer,
key_store,
merchant_account.storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating customers in db")?,
);
}
}
}
// Add next step to ProcessTracker
if recipient_create_data.should_add_next_step_to_process_tracker {
add_external_account_addition_task(
&*state.store,
payout_data,
common_utils::date_time::now().saturating_add(Duration::seconds(consts::STRIPE_ACCOUNT_ONBOARDING_DELAY_IN_SECONDS)),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while adding attach_payout_account_workflow workflow to process tracker")?;
// Update payout status in DB
let status = recipient_create_data
.status
.unwrap_or(api_enums::PayoutStatus::RequiresVendorAccountCreation);
let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate {
connector_payout_id: payout_data
.payout_attempt
.connector_payout_id
.to_owned(),
status,
error_code: None,
error_message: None,
is_eligible: recipient_create_data.payout_eligible,
unified_code: None,
unified_message: None,
};
payout_data.payout_attempt = db
.update_payout_attempt(
&payout_data.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 = db
.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")?;
// Helps callee functions skip the execution
payout_data.should_terminate = true;
} else if let Some(status) = recipient_create_data.status {
let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate {
connector_payout_id: payout_data
.payout_attempt
.connector_payout_id
.to_owned(),
status,
error_code: None,
error_message: None,
is_eligible: recipient_create_data.payout_eligible,
unified_code: None,
unified_message: None,
};
payout_data.payout_attempt = db
.update_payout_attempt(
&payout_data.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 = db
.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")?;
}
}
Err(err) => Err(errors::ApiErrorResponse::PayoutFailed {
data: serde_json::to_value(err).ok(),
})?,
}
}
Ok(())
}
<file_sep path="hyperswitch/crates/router/src/core/payouts.rs" role="context" start="1048" end="1168">
pub async fn call_connector_payout(
state: &SessionState,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
connector_data: &api::ConnectorData,
payout_data: &mut PayoutData,
) -> RouterResult<()> {
let payout_attempt = &payout_data.payout_attempt.to_owned();
let payouts = &payout_data.payouts.to_owned();
// fetch merchant connector account if not present
if payout_data.merchant_connector_account.is_none()
|| payout_data.payout_attempt.merchant_connector_id.is_none()
{
let merchant_connector_account = get_mca_from_profile_id(
state,
merchant_account,
&payout_data.profile_id,
&connector_data.connector_name.to_string(),
payout_attempt
.merchant_connector_id
.clone()
.or(connector_data.merchant_connector_id.clone())
.as_ref(),
key_store,
)
.await?;
payout_data.payout_attempt.merchant_connector_id = merchant_connector_account.get_mca_id();
payout_data.merchant_connector_account = Some(merchant_connector_account);
}
// update connector_name
if payout_data.payout_attempt.connector.is_none()
|| payout_data.payout_attempt.connector != Some(connector_data.connector_name.to_string())
{
payout_data.payout_attempt.connector = Some(connector_data.connector_name.to_string());
let updated_payout_attempt = storage::PayoutAttemptUpdate::UpdateRouting {
connector: connector_data.connector_name.to_string(),
routing_info: payout_data.payout_attempt.routing_info.clone(),
merchant_connector_id: payout_data.payout_attempt.merchant_connector_id.clone(),
};
let db = &*state.store;
payout_data.payout_attempt = db
.update_payout_attempt(
&payout_data.payout_attempt,
updated_payout_attempt,
payouts,
merchant_account.storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating routing info in payout_attempt")?;
};
// Fetch / store payout_method_data
if payout_data.payout_method_data.is_none() || payout_attempt.payout_token.is_none() {
let customer_id = payouts
.customer_id
.clone()
.get_required_value("customer_id")?;
payout_data.payout_method_data = Some(
helpers::make_payout_method_data(
state,
payout_data.payout_method_data.to_owned().as_ref(),
payout_attempt.payout_token.as_deref(),
&customer_id,
&payout_attempt.merchant_id,
payouts.payout_type,
key_store,
Some(payout_data),
merchant_account.storage_scheme,
)
.await?
.get_required_value("payout_method_data")?,
);
}
// Eligibility flow
complete_payout_eligibility(state, merchant_account, connector_data, payout_data).await?;
// Create customer flow
Box::pin(complete_create_recipient(
state,
merchant_account,
key_store,
connector_data,
payout_data,
))
.await?;
// Create customer's disbursement account flow
Box::pin(complete_create_recipient_disburse_account(
state,
merchant_account,
connector_data,
payout_data,
key_store,
))
.await?;
// Payout creation flow
Box::pin(complete_create_payout(
state,
merchant_account,
connector_data,
payout_data,
))
.await?;
// Auto fulfillment flow
let status = payout_data.payout_attempt.status;
if payouts.auto_fulfill && status == storage_enums::PayoutStatus::RequiresFulfillment {
Box::pin(fulfill_payout(
state,
merchant_account,
key_store,
connector_data,
payout_data,
))
.await
.attach_printable("Payout fulfillment failed for given Payout request")?;
}
Ok(())
}
<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/crates/router/src/core/errors.rs" role="context" start="31" end="31">
pub type RouterResult<T> = CustomResult<T, ApiErrorResponse>;
<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/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/payment_methods/vault.rs<|crate|> router anchor=store_payment_method_data_in_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/vault.rs" role="context" start="903" end="934">
pub async fn store_payment_method_data_in_locker(
state: &routes::SessionState,
token_id: Option<String>,
payment_method: &domain::PaymentMethodData,
customer_id: Option<id_type::CustomerId>,
pm: enums::PaymentMethod,
merchant_key_store: &domain::MerchantKeyStore,
) -> RouterResult<String> {
let value1 = payment_method
.get_value1(customer_id.clone())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error getting Value1 for locker")?;
let value2 = payment_method
.get_value2(customer_id)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error getting Value12 for locker")?;
let lookup_key = token_id.unwrap_or_else(|| generate_id_with_default_len("token"));
let lookup_key = create_tokenize(
state,
value1,
Some(value2),
lookup_key,
merchant_key_store.key.get_inner(),
)
.await?;
add_delete_tokenized_data_task(&*state.store, &lookup_key, pm).await?;
metrics::TOKENIZED_DATA_COUNT.add(1, &[]);
Ok(lookup_key)
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/vault.rs" role="context" start="902" end="902">
use common_utils::{
crypto::{DecodeMessage, EncodeMessage, GcmAes256},
ext_traits::{BytesExt, Encode},
generate_id_with_default_len, id_type,
pii::Email,
};
use crate::{
consts,
core::errors::{self, CustomResult, RouterResult},
db, logger, routes,
routes::metrics,
types::{
api, domain,
storage::{self, enums},
},
utils::StringExt,
};
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/vault.rs" role="context" start="955" end="986">
pub async fn store_payout_method_data_in_locker(
state: &routes::SessionState,
token_id: Option<String>,
payout_method: &api::PayoutMethodData,
customer_id: Option<id_type::CustomerId>,
merchant_key_store: &domain::MerchantKeyStore,
) -> RouterResult<String> {
let value1 = payout_method
.get_value1(customer_id.clone())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error getting Value1 for locker")?;
let value2 = payout_method
.get_value2(customer_id)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error getting Value2 for locker")?;
let lookup_key =
token_id.unwrap_or_else(|| generate_id_with_default_len("temporary_token"));
let lookup_key = create_tokenize(
state,
value1,
Some(value2),
lookup_key,
merchant_key_store.key.get_inner(),
)
.await?;
// add_delete_tokenized_data_task(&*state.store, &lookup_key, pm).await?;
// scheduler_metrics::TOKENIZED_DATA_COUNT.add(1, &[]);
Ok(lookup_key)
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/vault.rs" role="context" start="938" end="951">
pub async fn get_payout_method_data_from_temporary_locker(
state: &routes::SessionState,
lookup_key: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> RouterResult<(Option<api::PayoutMethodData>, SupplementaryVaultData)> {
let de_tokenize =
get_tokenized_data(state, lookup_key, true, merchant_key_store.key.get_inner()).await?;
let (payout_method, supp_data) =
api::PayoutMethodData::from_values(de_tokenize.value1, de_tokenize.value2)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error parsing Payout Method from Values")?;
Ok((Some(payout_method), supp_data))
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/vault.rs" role="context" start="887" end="900">
pub async fn get_payment_method_data_from_locker(
state: &routes::SessionState,
lookup_key: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> RouterResult<(Option<domain::PaymentMethodData>, SupplementaryVaultData)> {
let de_tokenize =
get_tokenized_data(state, lookup_key, true, merchant_key_store.key.get_inner()).await?;
let (payment_method, customer_id) =
domain::PaymentMethodData::from_values(de_tokenize.value1, de_tokenize.value2)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error parsing Payment Method from Values")?;
Ok((Some(payment_method), customer_id))
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/vault.rs" role="context" start="844" end="874">
fn from_values(
value1: String,
value2: String,
) -> CustomResult<(Self, SupplementaryVaultData), errors::VaultError> {
let value1: VaultPayoutMethod = value1
.parse_struct("VaultMethodValue1")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Could not deserialize into vault method value 1")?;
let value2: VaultPayoutMethod = value2
.parse_struct("VaultMethodValue2")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Could not deserialize into vault method value 2")?;
match (value1, value2) {
(VaultPayoutMethod::Card(mvalue1), VaultPayoutMethod::Card(mvalue2)) => {
let (card, supp_data) = api::CardPayout::from_values(mvalue1, mvalue2)?;
Ok((Self::Card(card), supp_data))
}
(VaultPayoutMethod::Bank(mvalue1), VaultPayoutMethod::Bank(mvalue2)) => {
let (bank, supp_data) = api::BankPayout::from_values(mvalue1, mvalue2)?;
Ok((Self::Bank(bank), supp_data))
}
(VaultPayoutMethod::Wallet(mvalue1), VaultPayoutMethod::Wallet(mvalue2)) => {
let (wallet, supp_data) = api::WalletPayout::from_values(mvalue1, mvalue2)?;
Ok((Self::Wallet(wallet), supp_data))
}
_ => Err(errors::VaultError::PayoutMethodNotSupported)
.attach_printable("Payout method not supported"),
}
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/vault.rs" role="context" start="1011" end="1073">
pub async fn create_tokenize(
state: &routes::SessionState,
value1: String,
value2: Option<String>,
lookup_key: String,
encryption_key: &masking::Secret<Vec<u8>>,
) -> RouterResult<String> {
let redis_key = get_redis_locker_key(lookup_key.as_str());
let func = || async {
metrics::CREATED_TOKENIZED_CARD.add(1, &[]);
let payload_to_be_encrypted = api::TokenizePayloadRequest {
value1: value1.clone(),
value2: value2.clone().unwrap_or_default(),
lookup_key: lookup_key.clone(),
service_name: VAULT_SERVICE_NAME.to_string(),
};
let payload = payload_to_be_encrypted
.encode_to_string_of_json()
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let encrypted_payload = GcmAes256
.encode_message(encryption_key.peek().as_ref(), payload.as_bytes())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to encode redis temp locker data")?;
let redis_conn = state
.store
.get_redis_conn()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get redis connection")?;
redis_conn
.set_key_if_not_exists_with_expiry(
&redis_key.as_str().into(),
bytes::Bytes::from(encrypted_payload),
Some(i64::from(consts::LOCKER_REDIS_EXPIRY_SECONDS)),
)
.await
.map(|_| lookup_key.clone())
.inspect_err(|error| {
metrics::TEMP_LOCKER_FAILURES.add(1, &[]);
logger::error!(?error, "Failed to store tokenized data in Redis");
})
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error from redis locker")
};
match func().await {
Ok(s) => {
logger::info!(
"Insert payload in redis locker successful with lookup key: {:?}",
redis_key
);
Ok(s)
}
Err(err) => {
logger::error!("Redis Temp locker Failed: {:?}", err);
Err(err)
}
}
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/vault.rs" role="context" start="1378" end="1417">
pub async fn add_delete_tokenized_data_task(
db: &dyn db::StorageInterface,
lookup_key: &str,
pm: enums::PaymentMethod,
) -> RouterResult<()> {
let runner = storage::ProcessTrackerRunner::DeleteTokenizeDataWorkflow;
let process_tracker_id = format!("{runner}_{lookup_key}");
let task = runner.to_string();
let tag = ["BASILISK-V3"];
let tracking_data = storage::TokenizeCoreWorkflow {
lookup_key: lookup_key.to_owned(),
pm,
};
let schedule_time = get_delete_tokenize_schedule_time(db, pm, 0)
.await
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to obtain initial process tracker schedule time")?;
let process_tracker_entry = storage::ProcessTrackerNew::new(
process_tracker_id,
&task,
runner,
tag,
tracking_data,
None,
schedule_time,
common_types::consts::API_VERSION,
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to construct delete tokenized data process tracker task")?;
let response = db.insert_process(process_tracker_entry).await;
response.map(|_| ()).or_else(|err| {
if err.current_context().is_db_unique_violation() {
Ok(())
} else {
Err(report!(errors::ApiErrorResponse::InternalServerError))
}
})
}
<file_sep path="hyperswitch/crates/router/src/connector/nmi/transformers.rs" role="context" start="454" end="459">
pub enum PaymentMethod {
CardNonThreeDs(Box<CardData>),
CardThreeDs(Box<CardThreeDsData>),
GPay(Box<GooglePayData>),
ApplePay(Box<ApplePayData>),
}
<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/payment_methods/tokenize.rs<|crate|> router anchor=parse_csv kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/tokenize.rs" role="context" start="40" end="72">
pub fn parse_csv(
merchant_id: &id_type::MerchantId,
data: &[u8],
) -> csv::Result<Vec<payment_methods_api::CardNetworkTokenizeRequest>> {
let mut csv_reader = csv::ReaderBuilder::new()
.has_headers(true)
.from_reader(data);
let mut records = Vec::new();
let mut id_counter = 0;
for (i, result) in csv_reader
.deserialize::<domain::CardNetworkTokenizeRecord>()
.enumerate()
{
match result {
Ok(mut record) => {
logger::info!("Parsed Record (line {}): {:?}", i + 1, record);
id_counter += 1;
record.line_number = Some(id_counter);
record.merchant_id = Some(merchant_id.clone());
match payment_methods_api::CardNetworkTokenizeRequest::foreign_try_from(record) {
Ok(record) => {
records.push(record);
}
Err(err) => {
logger::error!("Error parsing line {}: {}", i + 1, err.to_string());
}
}
}
Err(e) => logger::error!("Error parsing line {}: {}", i + 1, e),
}
}
Ok(records)
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/tokenize.rs" role="context" start="39" end="39">
use api_models::{enums as api_enums, payment_methods as payment_methods_api};
use common_utils::{
crypto::Encryptable,
id_type,
transformers::{ForeignFrom, ForeignTryFrom},
};
use router_env::logger;
use crate::{
core::payment_methods::{
cards::{add_card_to_hs_locker, create_encrypted_data, tokenize_card_flow},
network_tokenization, transformers as pm_transformers,
},
errors::{self, RouterResult},
services,
types::{api, domain, payment_methods as pm_types},
SessionState,
};
pub use card_executor::*;
pub use payment_method_executor::*;
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/tokenize.rs" role="context" start="97" end="135">
pub async fn tokenize_cards(
state: &SessionState,
records: Vec<payment_methods_api::CardNetworkTokenizeRequest>,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
) -> errors::RouterResponse<Vec<payment_methods_api::CardNetworkTokenizeResponse>> {
use futures::stream::StreamExt;
// Process all records in parallel
let responses = futures::stream::iter(records.into_iter())
.map(|record| async move {
let tokenize_request = record.data.clone();
let customer = record.customer.clone();
Box::pin(tokenize_card_flow(
state,
domain::CardNetworkTokenizeRequest::foreign_from(record),
merchant_account,
key_store,
))
.await
.unwrap_or_else(|e| {
let err = e.current_context();
payment_methods_api::CardNetworkTokenizeResponse {
tokenization_data: Some(tokenize_request),
error_code: Some(err.error_code()),
error_message: Some(err.error_message()),
card_tokenized: false,
payment_method_response: None,
customer: Some(customer),
}
})
})
.buffer_unordered(10)
.collect()
.await;
// Return the final response
Ok(services::ApplicationResponse::Json(responses))
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/tokenize.rs" role="context" start="74" end="95">
pub fn get_tokenize_card_form_records(
form: CardNetworkTokenizeForm,
) -> Result<
(
id_type::MerchantId,
Vec<payment_methods_api::CardNetworkTokenizeRequest>,
),
errors::ApiErrorResponse,
> {
match parse_csv(&form.merchant_id, form.file.data.to_bytes()) {
Ok(records) => {
logger::info!("Parsed a total of {} records", records.len());
Ok((form.merchant_id.0, records))
}
Err(e) => {
logger::error!("Failed to parse CSV: {:?}", e);
Err(errors::ApiErrorResponse::PreconditionFailed {
message: e.to_string(),
})
}
}
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/tokenize.rs" role="context" start="248" end="262">
fn new(
state: &'a SessionState,
key_store: &'a domain::MerchantKeyStore,
merchant_account: &'a domain::MerchantAccount,
data: &'a D,
customer: &'a domain_request_types::CustomerDetails,
) -> Self {
Self {
data,
customer,
state,
merchant_account,
key_store,
}
}
<file_sep path="hyperswitch/crates/router/tests/utils.rs" role="context" start="399" end="401">
pub struct Error {
pub message: Message,
}
<file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="2478" end="2478">
type Error = error_stack::Report<errors::ValidationError>;
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payments/helpers.rs<|crate|> router anchor=construct_signed_data_for_intermediate_signing_key_verification kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="5948" end="5970">
fn construct_signed_data_for_intermediate_signing_key_verification(
&self,
sender_id: &str,
protocol_version: &str,
signed_key: &str,
) -> CustomResult<Vec<u8>, errors::GooglePayDecryptionError> {
let length_of_sender_id = u32::try_from(sender_id.len())
.change_context(errors::GooglePayDecryptionError::ParsingFailed)?;
let length_of_protocol_version = u32::try_from(protocol_version.len())
.change_context(errors::GooglePayDecryptionError::ParsingFailed)?;
let length_of_signed_key = u32::try_from(signed_key.len())
.change_context(errors::GooglePayDecryptionError::ParsingFailed)?;
let mut signed_data: Vec<u8> = Vec::new();
signed_data.append(&mut get_little_endian_format(length_of_sender_id));
signed_data.append(&mut sender_id.as_bytes().to_vec());
signed_data.append(&mut get_little_endian_format(length_of_protocol_version));
signed_data.append(&mut protocol_version.as_bytes().to_vec());
signed_data.append(&mut get_little_endian_format(length_of_signed_key));
signed_data.append(&mut signed_key.as_bytes().to_vec());
Ok(signed_data)
}
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="5947" end="5947">
)?;
if result {
return Ok(());
}
}
}
Err(errors::GooglePayDecryptionError::InvalidIntermediateSignature.into())
}
// Construct signed data for intermediate signing key verification
fn construct_signed_data_for_intermediate_signing_key_verification(
&self,
sender_id: &str,
protocol_version: &str,
signed_key: &str,
) -> CustomResult<Vec<u8>, errors::GooglePayDecryptionError> {
let length_of_sender_id = u32::try_from(sender_id.len())
.change_context(errors::GooglePayDecryptionError::ParsingFailed)?;
let length_of_protocol_version = u32::try_from(protocol_version.len())
.change_context(errors::GooglePayDecryptionError::ParsingFailed)?;
let length_of_signed_key = u32::try_from(signed_key.len())
.change_context(errors::GooglePayDecryptionError::ParsingFailed)?;
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="5993" end="6042">
fn verify_message_signature(
&self,
encrypted_data: &EncryptedData,
signed_key: &GooglePaySignedKey,
) -> CustomResult<(), errors::GooglePayDecryptionError> {
// create a public key from the intermediate signing key
let public_key = self.load_public_key(signed_key.key_value.peek())?;
// base64 decode the signature
let signature = BASE64_ENGINE
.decode(&encrypted_data.signature)
.change_context(errors::GooglePayDecryptionError::Base64DecodingFailed)?;
// parse the signature using ECDSA
let ecdsa_signature = openssl::ecdsa::EcdsaSig::from_der(&signature)
.change_context(errors::GooglePayDecryptionError::EcdsaSignatureFailed)?;
// get the EC key from the public key
let ec_key = public_key
.ec_key()
.change_context(errors::GooglePayDecryptionError::DerivingEcKeyFailed)?;
// get the sender id i.e. Google
let sender_id = String::from_utf8(consts::SENDER_ID.to_vec())
.change_context(errors::GooglePayDecryptionError::DeserializationFailed)?;
// serialize the signed message to string
let signed_message = serde_json::to_string(&encrypted_data.signed_message)
.change_context(errors::GooglePayDecryptionError::SignedKeyParsingFailure)?;
// construct the signed data
let signed_data = self.construct_signed_data_for_signature_verification(
&sender_id,
consts::PROTOCOL,
&signed_message,
)?;
// hash the signed data
let message_hash = openssl::sha::sha256(&signed_data);
// verify the signature
let result = ecdsa_signature
.verify(&message_hash, &ec_key)
.change_context(errors::GooglePayDecryptionError::SignatureVerificationFailed)?;
if result {
Ok(())
} else {
Err(errors::GooglePayDecryptionError::InvalidSignature)?
}
}
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="5973" end="5990">
fn validate_signed_key(
&self,
intermediate_signing_key: &IntermediateSigningKey,
) -> CustomResult<GooglePaySignedKey, errors::GooglePayDecryptionError> {
let signed_key: GooglePaySignedKey = intermediate_signing_key
.signed_key
.clone()
.expose()
.parse_struct("GooglePaySignedKey")
.change_context(errors::GooglePayDecryptionError::SignedKeyParsingFailure)?;
if !matches!(
check_expiration_date_is_valid(&signed_key.key_expiration),
Ok(true)
) {
return Err(errors::GooglePayDecryptionError::SignedKeyExpired)?;
}
Ok(signed_key)
}
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="5891" end="5945">
fn verify_intermediate_signing_key(
&self,
encrypted_data: &EncryptedData,
) -> CustomResult<(), errors::GooglePayDecryptionError> {
let mut signatrues: Vec<openssl::ecdsa::EcdsaSig> = Vec::new();
// decode and parse the signatures
for signature in encrypted_data.intermediate_signing_key.signatures.iter() {
let signature = BASE64_ENGINE
.decode(signature.peek())
.change_context(errors::GooglePayDecryptionError::Base64DecodingFailed)?;
let ecdsa_signature = openssl::ecdsa::EcdsaSig::from_der(&signature)
.change_context(errors::GooglePayDecryptionError::EcdsaSignatureParsingFailed)?;
signatrues.push(ecdsa_signature);
}
// get the sender id i.e. Google
let sender_id = String::from_utf8(consts::SENDER_ID.to_vec())
.change_context(errors::GooglePayDecryptionError::DeserializationFailed)?;
// construct the signed data
let signed_data = self.construct_signed_data_for_intermediate_signing_key_verification(
&sender_id,
consts::PROTOCOL,
encrypted_data.intermediate_signing_key.signed_key.peek(),
)?;
// check if any of the signatures are valid for any of the root signing keys
for key in self.root_signing_keys.iter() {
// decode and create public key
let public_key = self
.load_public_key(key.key_value.peek())
.change_context(errors::GooglePayDecryptionError::DerivingPublicKeyFailed)?;
// fetch the ec key from public key
let ec_key = public_key
.ec_key()
.change_context(errors::GooglePayDecryptionError::DerivingEcKeyFailed)?;
// hash the signed data
let message_hash = openssl::sha::sha256(&signed_data);
// verify if any of the signatures is valid against the given key
for signature in signatrues.iter() {
let result = signature.verify(&message_hash, &ec_key).change_context(
errors::GooglePayDecryptionError::SignatureVerificationFailed,
)?;
if result {
return Ok(());
}
}
}
Err(errors::GooglePayDecryptionError::InvalidIntermediateSignature.into())
}
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="5873" end="5888">
fn verify_signature(
&self,
encrypted_data: &EncryptedData,
) -> CustomResult<(), errors::GooglePayDecryptionError> {
// check the protocol version
if encrypted_data.protocol_version != GooglePayProtocolVersion::EcProtocolVersion2 {
return Err(errors::GooglePayDecryptionError::InvalidProtocolVersion.into());
}
// verify the intermediate signing key
self.verify_intermediate_signing_key(encrypted_data)?;
// validate and fetch the signed key
let signed_key = self.validate_signed_key(&encrypted_data.intermediate_signing_key)?;
// verify the signature of the token
self.verify_message_signature(encrypted_data, &signed_key)
}
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="5748" end="5750">
fn get_little_endian_format(number: u32) -> Vec<u8> {
number.to_le_bytes().to_vec()
}
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="5783" end="5814">
pub fn new(
root_keys: masking::Secret<String>,
recipient_id: masking::Secret<String>,
private_key: masking::Secret<String>,
) -> CustomResult<Self, errors::GooglePayDecryptionError> {
// base64 decode the private key
let decoded_key = BASE64_ENGINE
.decode(private_key.expose())
.change_context(errors::GooglePayDecryptionError::Base64DecodingFailed)?;
// base64 decode the root signing keys
let decoded_root_signing_keys = BASE64_ENGINE
.decode(root_keys.expose())
.change_context(errors::GooglePayDecryptionError::Base64DecodingFailed)?;
// create a private key from the decoded key
let private_key = PKey::private_key_from_pkcs8(&decoded_key)
.change_context(errors::GooglePayDecryptionError::KeyDeserializationFailed)
.attach_printable("cannot convert private key from decode_key")?;
// parse the root signing keys
let root_keys_vector: Vec<GooglePayRootSigningKey> = decoded_root_signing_keys
.parse_struct("GooglePayRootSigningKey")
.change_context(errors::GooglePayDecryptionError::DeserializationFailed)?;
// parse and filter the root signing keys by protocol version
let filtered_root_signing_keys = filter_root_signing_keys(root_keys_vector)?;
Ok(Self {
root_signing_keys: filtered_root_signing_keys,
recipient_id,
private_key,
})
}
<file_sep path="hyperswitch/crates/router/src/core/errors.rs" role="context" start="247" end="296">
pub enum GooglePayDecryptionError {
#[error("Invalid expiration time")]
InvalidExpirationTime,
#[error("Failed to base64 decode input data")]
Base64DecodingFailed,
#[error("Failed to decrypt input data")]
DecryptionFailed,
#[error("Failed to deserialize input data")]
DeserializationFailed,
#[error("Certificate parsing failed")]
CertificateParsingFailed,
#[error("Key deserialization failure")]
KeyDeserializationFailed,
#[error("Failed to derive a shared ephemeral key")]
DerivingSharedEphemeralKeyFailed,
#[error("Failed to derive a shared secret key")]
DerivingSharedSecretKeyFailed,
#[error("Failed to parse the tag")]
ParsingTagError,
#[error("HMAC verification failed")]
HmacVerificationFailed,
#[error("Failed to derive Elliptic Curve key")]
DerivingEcKeyFailed,
#[error("Failed to Derive Public key")]
DerivingPublicKeyFailed,
#[error("Failed to Derive Elliptic Curve group")]
DerivingEcGroupFailed,
#[error("Failed to allocate memory for big number")]
BigNumAllocationFailed,
#[error("Failed to get the ECDSA signature")]
EcdsaSignatureFailed,
#[error("Failed to verify the signature")]
SignatureVerificationFailed,
#[error("Invalid signature is provided")]
InvalidSignature,
#[error("Failed to parse the Signed Key")]
SignedKeyParsingFailure,
#[error("The Signed Key is expired")]
SignedKeyExpired,
#[error("Failed to parse the ECDSA signature")]
EcdsaSignatureParsingFailed,
#[error("Invalid intermediate signature is provided")]
InvalidIntermediateSignature,
#[error("Invalid protocol version")]
InvalidProtocolVersion,
#[error("Decrypted Token has expired")]
DecryptedTokenExpired,
#[error("Failed to parse the given value")]
ParsingFailed,
}
<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/refunds.rs<|crate|> router anchor=add_refund_execute_task 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="1645" end="1679">
pub async fn add_refund_execute_task(
db: &dyn db::StorageInterface,
refund: &storage::Refund,
runner: storage::ProcessTrackerRunner,
) -> RouterResult<storage::ProcessTracker> {
let task = "EXECUTE_REFUND";
let process_tracker_id = format!("{runner}_{task}_{}", refund.internal_reference_id);
let tag = ["REFUND"];
let schedule_time = common_utils::date_time::now();
let refund_workflow_tracking_data = refund_to_refund_core_workflow_model(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 execute 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
)
})?;
Ok(response)
}
<file_sep path="hyperswitch/crates/router/src/core/refunds.rs" role="context" start="1644" end="1644">
use common_utils::{
ext_traits::AsyncExt,
types::{ConnectorTransactionId, MinorUnit},
};
use diesel_models::process_tracker::business_status;
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="1681" end="1707">
pub async fn get_refund_sync_process_schedule_time(
db: &dyn db::StorageInterface,
connector: &str,
merchant_id: &common_utils::id_type::MerchantId,
retry_count: i32,
) -> Result<Option<time::PrimitiveDateTime>, errors::ProcessTrackerError> {
let redis_mapping: errors::CustomResult<process_data::ConnectorPTMapping, errors::RedisError> =
db::get_and_deserialize_key(
db,
&format!("pt_mapping_refund_sync_{connector}"),
"ConnectorPTMapping",
)
.await;
let mapping = match redis_mapping {
Ok(x) => x,
Err(err) => {
logger::error!("Error: while getting connector mapping: {err:?}");
process_data::ConnectorPTMapping::default()
}
};
let time_delta =
process_tracker_utils::get_schedule_time(mapping, merchant_id, retry_count + 1);
Ok(process_tracker_utils::get_time_from_delta(time_delta))
}
<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="1593" end="1603">
pub fn refund_to_refund_core_workflow_model(
refund: &storage::Refund,
) -> storage::RefundCoreWorkflow {
storage::RefundCoreWorkflow {
refund_internal_reference_id: refund.internal_reference_id.clone(),
connector_transaction_id: refund.connector_transaction_id.clone(),
merchant_id: refund.merchant_id.clone(),
payment_id: refund.payment_id.clone(),
processor_transaction_data: refund.processor_transaction_data.clone(),
}
}
<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/configs/settings.rs" role="context" start="721" end="724">
pub struct Refund {
pub max_attempts: usize,
pub max_age: i64,
}
<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/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.rs<|crate|> router anchor=decide_action_type kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="6986" end="7020">
pub async fn decide_action_type(
state: &SessionState,
is_connector_agnostic_mit_enabled: Option<bool>,
is_network_tokenization_enabled: bool,
payment_method_info: &domain::PaymentMethod,
filtered_nt_supported_connectors: Vec<api::ConnectorData>, //network tokenization supported connectors
) -> Option<ActionType> {
match (
is_network_token_with_network_transaction_id_flow(
is_connector_agnostic_mit_enabled,
is_network_tokenization_enabled,
payment_method_info,
),
!filtered_nt_supported_connectors.is_empty(),
) {
(IsNtWithNtiFlow::NtWithNtiSupported(network_transaction_id), true) => {
if let Ok((token_exp_month, token_exp_year)) =
network_tokenization::do_status_check_for_network_token(state, payment_method_info)
.await
{
Some(ActionType::NetworkTokenWithNetworkTransactionId(
NTWithNTIRef {
token_exp_month,
token_exp_year,
network_transaction_id,
},
))
} else {
None
}
}
(IsNtWithNtiFlow::NtWithNtiSupported(_), false)
| (IsNtWithNtiFlow::NTWithNTINotSupported, _) => None,
}
}
<file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="6985" end="6985">
pub fn filter_network_tokenization_supported_connectors(
connectors: Vec<api::ConnectorData>,
network_tokenization_supported_connectors: &HashSet<enums::Connector>,
) -> Vec<api::ConnectorData> {
connectors
.into_iter()
.filter(|data| network_tokenization_supported_connectors.contains(&data.connector_name))
.collect()
}
#[cfg(feature = "v1")]
pub async fn decide_action_type(
state: &SessionState,
is_connector_agnostic_mit_enabled: Option<bool>,
is_network_tokenization_enabled: bool,
payment_method_info: &domain::PaymentMethod,
filtered_nt_supported_connectors: Vec<api::ConnectorData>, //network tokenization supported connectors
) -> Option<ActionType> {
match (
is_network_token_with_network_transaction_id_flow(
is_connector_agnostic_mit_enabled,
is_network_tokenization_enabled,
payment_method_info,
),
<file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="7045" end="7070">
pub fn is_network_token_with_network_transaction_id_flow(
is_connector_agnostic_mit_enabled: Option<bool>,
is_network_tokenization_enabled: bool,
payment_method_info: &domain::PaymentMethod,
) -> IsNtWithNtiFlow {
match (
is_connector_agnostic_mit_enabled,
is_network_tokenization_enabled,
payment_method_info.get_payment_method_type(),
payment_method_info.network_transaction_id.clone(),
payment_method_info.network_token_locker_id.is_some(),
payment_method_info
.network_token_requestor_reference_id
.is_some(),
) {
(
Some(true),
true,
Some(storage_enums::PaymentMethod::Card),
Some(network_transaction_id),
true,
true,
) => IsNtWithNtiFlow::NtWithNtiSupported(network_transaction_id),
_ => IsNtWithNtiFlow::NTWithNTINotSupported,
}
}
<file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="7022" end="7037">
pub fn is_network_transaction_id_flow(
state: &SessionState,
is_connector_agnostic_mit_enabled: Option<bool>,
connector: enums::Connector,
payment_method_info: &domain::PaymentMethod,
) -> bool {
let ntid_supported_connectors = &state
.conf
.network_transaction_id_supported_connectors
.connector_list;
is_connector_agnostic_mit_enabled == Some(true)
&& payment_method_info.get_payment_method_type() == Some(storage_enums::PaymentMethod::Card)
&& ntid_supported_connectors.contains(&connector)
&& payment_method_info.network_transaction_id.is_some()
}
<file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="6975" end="6983">
pub fn filter_network_tokenization_supported_connectors(
connectors: Vec<api::ConnectorData>,
network_tokenization_supported_connectors: &HashSet<enums::Connector>,
) -> Vec<api::ConnectorData> {
connectors
.into_iter()
.filter(|data| network_tokenization_supported_connectors.contains(&data.connector_name))
.collect()
}
<file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="6947" end="6955">
pub fn filter_ntid_supported_connectors(
connectors: Vec<api::ConnectorData>,
ntid_supported_connectors: &HashSet<enums::Connector>,
) -> Vec<api::ConnectorData> {
connectors
.into_iter()
.filter(|data| ntid_supported_connectors.contains(&data.connector_name))
.collect()
}
<file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="6645" end="6805">
pub async fn decide_multiplex_connector_for_normal_or_recurring_payment<F: Clone, D>(
state: &SessionState,
payment_data: &mut D,
routing_data: &mut storage::RoutingData,
connectors: Vec<api::ConnectorData>,
mandate_type: Option<api::MandateTransactionType>,
is_connector_agnostic_mit_enabled: Option<bool>,
is_network_tokenization_enabled: bool,
) -> RouterResult<ConnectorCallType>
where
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
{
match (
payment_data.get_payment_intent().setup_future_usage,
payment_data.get_token_data().as_ref(),
payment_data.get_recurring_details().as_ref(),
payment_data.get_payment_intent().off_session,
mandate_type,
) {
(
Some(storage_enums::FutureUsage::OffSession),
Some(_),
None,
None,
Some(api::MandateTransactionType::RecurringMandateTransaction),
)
| (
None,
None,
Some(RecurringDetails::PaymentMethodId(_)),
Some(true),
Some(api::MandateTransactionType::RecurringMandateTransaction),
)
| (None, Some(_), None, Some(true), _) => {
logger::debug!("performing routing for token-based MIT flow");
let payment_method_info = payment_data
.get_payment_method_info()
.get_required_value("payment_method_info")?
.clone();
//fetch connectors that support ntid flow
let ntid_supported_connectors = &state
.conf
.network_transaction_id_supported_connectors
.connector_list;
//filered connectors list with ntid_supported_connectors
let filtered_ntid_supported_connectors =
filter_ntid_supported_connectors(connectors.clone(), ntid_supported_connectors);
//fetch connectors that support network tokenization flow
let network_tokenization_supported_connectors = &state
.conf
.network_tokenization_supported_connectors
.connector_list;
//filered connectors list with ntid_supported_connectors and network_tokenization_supported_connectors
let filtered_nt_supported_connectors = filter_network_tokenization_supported_connectors(
filtered_ntid_supported_connectors,
network_tokenization_supported_connectors,
);
let action_type = decide_action_type(
state,
is_connector_agnostic_mit_enabled,
is_network_tokenization_enabled,
&payment_method_info,
filtered_nt_supported_connectors.clone(),
)
.await;
match action_type {
Some(ActionType::NetworkTokenWithNetworkTransactionId(nt_data)) => {
logger::info!(
"using network_tokenization with network_transaction_id for MIT flow"
);
let mandate_reference_id =
Some(payments_api::MandateReferenceId::NetworkTokenWithNTI(
payments_api::NetworkTokenWithNTIRef {
network_transaction_id: nt_data.network_transaction_id.to_string(),
token_exp_month: nt_data.token_exp_month,
token_exp_year: nt_data.token_exp_year,
},
));
let chosen_connector_data = filtered_nt_supported_connectors
.first()
.ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)
.attach_printable(
"no eligible connector found for token-based MIT payment",
)?;
routing_data.routed_through =
Some(chosen_connector_data.connector_name.to_string());
routing_data
.merchant_connector_id
.clone_from(&chosen_connector_data.merchant_connector_id);
payment_data.set_mandate_id(payments_api::MandateIds {
mandate_id: None,
mandate_reference_id,
});
Ok(ConnectorCallType::PreDetermined(
chosen_connector_data.clone(),
))
}
None => {
decide_connector_for_normal_or_recurring_payment(
state,
payment_data,
routing_data,
connectors,
is_connector_agnostic_mit_enabled,
&payment_method_info,
)
.await
}
}
}
(
None,
None,
Some(RecurringDetails::ProcessorPaymentToken(_token)),
Some(true),
Some(api::MandateTransactionType::RecurringMandateTransaction),
) => {
if let Some(connector) = connectors.first() {
routing_data.routed_through = Some(connector.connector_name.clone().to_string());
routing_data
.merchant_connector_id
.clone_from(&connector.merchant_connector_id);
Ok(ConnectorCallType::PreDetermined(api::ConnectorData {
connector: connector.connector.clone(),
connector_name: connector.connector_name,
get_token: connector.get_token.clone(),
merchant_connector_id: connector.merchant_connector_id.clone(),
}))
} else {
logger::error!("no eligible connector found for the ppt_mandate payment");
Err(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration.into())
}
}
_ => {
helpers::override_setup_future_usage_to_on_session(&*state.store, payment_data).await?;
let first_choice = connectors
.first()
.ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)
.attach_printable("no eligible connector found for payment")?
.clone();
routing_data.routed_through = Some(first_choice.connector_name.to_string());
routing_data.merchant_connector_id = first_choice.merchant_connector_id;
Ok(ConnectorCallType::Retryable(connectors))
}
}
}
<file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="7040" end="7043">
pub enum IsNtWithNtiFlow {
NtWithNtiSupported(String), //Network token with Network transaction id supported flow
NTWithNTINotSupported, //Network token with Network transaction id not supported
}
<file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="6971" end="6973">
pub enum ActionType {
NetworkTokenWithNetworkTransactionId(NTWithNTIRef),
}
<file_sep path="hyperswitch/crates/router/src/connector/nmi/transformers.rs" role="context" start="454" end="459">
pub enum PaymentMethod {
CardNonThreeDs(Box<CardData>),
CardThreeDs(Box<CardThreeDsData>),
GPay(Box<GooglePayData>),
ApplePay(Box<ApplePayData>),
}
<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/webhooks/incoming.rs<|crate|> router anchor=insert_mandate_details kind=fn pack=symbol_neighborhood lang=rust role_window=k2 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/webhooks/incoming.rs" role="context" start="2126" end="2162">
fn insert_mandate_details(
payment_attempt: &PaymentAttempt,
webhook_mandate_details: &hyperswitch_domain_models::router_flow_types::ConnectorMandateDetails,
payment_method_mandate_details: Option<CommonMandateReference>,
) -> CustomResult<Option<CommonMandateReference>, errors::ApiErrorResponse> {
let (mandate_metadata, connector_mandate_request_reference_id) = payment_attempt
.connector_mandate_detail
.clone()
.map(|mandate_reference| {
(
mandate_reference.mandate_metadata,
mandate_reference.connector_mandate_request_reference_id,
)
})
.unwrap_or((None, None));
let connector_mandate_details = tokenization::update_connector_mandate_details(
payment_method_mandate_details,
payment_attempt.payment_method_type,
Some(
payment_attempt
.net_amount
.get_total_amount()
.get_amount_as_i64(),
),
payment_attempt.currency,
payment_attempt.merchant_connector_id.clone(),
Some(
webhook_mandate_details
.connector_mandate_id
.peek()
.to_string(),
),
mandate_metadata,
connector_mandate_request_reference_id,
)?;
Ok(connector_mandate_details)
}
<file_sep path="hyperswitch/crates/router/src/core/webhooks/incoming.rs" role="context" start="2125" end="2125">
use common_utils::{errors::ReportSwitchExt, events::ApiEventsType};
use hyperswitch_domain_models::{
mandates::CommonMandateReference,
payments::{payment_attempt::PaymentAttempt, HeaderPayload},
router_request_types::VerifyWebhookSourceRequestData,
router_response_types::{VerifyWebhookSourceResponseData, VerifyWebhookStatus},
};
use crate::{
consts,
core::{
api_locking,
errors::{self, ConnectorErrorExt, CustomResult, RouterResponse, StorageErrorExt},
metrics,
payments::{self, tokenization},
refunds, relay, utils as core_utils,
webhooks::utils::construct_webhook_router_data,
},
db::StorageInterface,
events::api_logs::ApiEvent,
logger,
routes::{
app::{ReqState, SessionStateInfo},
lock_utils, SessionState,
},
services::{
self, authentication as auth, connector_integration_interface::ConnectorEnum,
ConnectorValidation,
},
types::{
api::{
self, mandates::MandateResponseExt, ConnectorCommon, ConnectorData, GetToken,
IncomingWebhook,
},
domain,
storage::{self, enums},
transformers::{ForeignFrom, ForeignInto, ForeignTryFrom},
},
utils::{self as helper_utils, ext_traits::OptionExt, generate_id},
};
<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/src/core/webhooks/incoming.rs" role="context" start="1972" end="1977">
fn should_update_connector_mandate_details(
source_verified: bool,
event_type: webhooks::IncomingWebhookEvent,
) -> bool {
source_verified && event_type == webhooks::IncomingWebhookEvent::PaymentIntentSuccess
}
<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,
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/gsm.rs<|crate|> router anchor=update_gsm_rule kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/gsm.rs" role="context" start="53" end="97">
pub async fn update_gsm_rule(
state: SessionState,
gsm_request: gsm_api_types::GsmUpdateRequest,
) -> RouterResponse<gsm_api_types::GsmResponse> {
let db = state.store.as_ref();
let gsm_api_types::GsmUpdateRequest {
connector,
flow,
sub_flow,
code,
message,
decision,
status,
router_error,
step_up_possible,
unified_code,
unified_message,
error_category,
clear_pan_possible,
} = gsm_request;
GsmInterface::update_gsm_rule(
db,
connector.to_string(),
flow,
sub_flow,
code,
message,
storage::GatewayStatusMappingUpdate {
decision: decision.map(|d| d.to_string()),
status,
router_error: Some(router_error),
step_up_possible,
unified_code,
unified_message,
error_category,
clear_pan_possible,
},
)
.await
.to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError {
message: "GSM with given key does not exist in our records".to_string(),
})
.attach_printable("Failed while updating Gsm rule")
.map(|gsm| services::ApplicationResponse::Json(gsm.foreign_into()))
}
<file_sep path="hyperswitch/crates/router/src/core/gsm.rs" role="context" start="52" end="52">
use api_models::gsm as gsm_api_types;
use diesel_models::gsm as storage;
use crate::{
core::{
errors,
errors::{RouterResponse, StorageErrorExt},
},
db::gsm::GsmInterface,
services,
types::transformers::ForeignInto,
SessionState,
};
<file_sep path="hyperswitch/crates/router/src/core/gsm.rs" role="context" start="100" end="144">
pub async fn delete_gsm_rule(
state: SessionState,
gsm_request: gsm_api_types::GsmDeleteRequest,
) -> RouterResponse<gsm_api_types::GsmDeleteResponse> {
let db = state.store.as_ref();
let gsm_api_types::GsmDeleteRequest {
connector,
flow,
sub_flow,
code,
message,
} = gsm_request;
match GsmInterface::delete_gsm_rule(
db,
connector.to_string(),
flow.to_owned(),
sub_flow.to_owned(),
code.to_owned(),
message.to_owned(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError {
message: "GSM with given key does not exist in our records".to_string(),
})
.attach_printable("Failed while Deleting Gsm rule")
{
Ok(is_deleted) => {
if is_deleted {
Ok(services::ApplicationResponse::Json(
gsm_api_types::GsmDeleteResponse {
gsm_rule_delete: true,
connector,
flow,
sub_flow,
code,
},
))
} else {
Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while Deleting Gsm rule, got response as false")
}
}
Err(err) => Err(err),
}
}
<file_sep path="hyperswitch/crates/router/src/core/gsm.rs" role="context" start="32" end="50">
pub async fn retrieve_gsm_rule(
state: SessionState,
gsm_request: gsm_api_types::GsmRetrieveRequest,
) -> RouterResponse<gsm_api_types::GsmResponse> {
let db = state.store.as_ref();
let gsm_api_types::GsmRetrieveRequest {
connector,
flow,
sub_flow,
code,
message,
} = gsm_request;
GsmInterface::find_gsm_rule(db, connector.to_string(), flow, sub_flow, code, message)
.await
.to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError {
message: "GSM with given key does not exist in our records".to_string(),
})
.map(|gsm| services::ApplicationResponse::Json(gsm.foreign_into()))
}
<file_sep path="hyperswitch/crates/router/src/core/gsm.rs" role="context" start="18" end="29">
pub async fn create_gsm_rule(
state: SessionState,
gsm_rule: gsm_api_types::GsmCreateRequest,
) -> RouterResponse<gsm_api_types::GsmResponse> {
let db = state.store.as_ref();
GsmInterface::add_gsm_rule(db, gsm_rule.foreign_into())
.await
.to_duplicate_response(errors::ApiErrorResponse::GenericDuplicateError {
message: "GSM with given key already exists in our records".to_string(),
})
.map(|gsm| services::ApplicationResponse::Json(gsm.foreign_into()))
}
<file_sep path="hyperswitch/crates/router/src/routes/app.rs" role="context" start="2071" end="2071">
pub struct Gsm;
<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/gsm.rs<|crate|> router anchor=update_gsm_rule kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/gsm.rs" role="context" start="53" end="97">
pub async fn update_gsm_rule(
state: SessionState,
gsm_request: gsm_api_types::GsmUpdateRequest,
) -> RouterResponse<gsm_api_types::GsmResponse> {
let db = state.store.as_ref();
let gsm_api_types::GsmUpdateRequest {
connector,
flow,
sub_flow,
code,
message,
decision,
status,
router_error,
step_up_possible,
unified_code,
unified_message,
error_category,
clear_pan_possible,
} = gsm_request;
GsmInterface::update_gsm_rule(
db,
connector.to_string(),
flow,
sub_flow,
code,
message,
storage::GatewayStatusMappingUpdate {
decision: decision.map(|d| d.to_string()),
status,
router_error: Some(router_error),
step_up_possible,
unified_code,
unified_message,
error_category,
clear_pan_possible,
},
)
.await
.to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError {
message: "GSM with given key does not exist in our records".to_string(),
})
.attach_printable("Failed while updating Gsm rule")
.map(|gsm| services::ApplicationResponse::Json(gsm.foreign_into()))
}
<file_sep path="hyperswitch/crates/router/src/core/gsm.rs" role="context" start="52" end="52">
use api_models::gsm as gsm_api_types;
use diesel_models::gsm as storage;
use crate::{
core::{
errors,
errors::{RouterResponse, StorageErrorExt},
},
db::gsm::GsmInterface,
services,
types::transformers::ForeignInto,
SessionState,
};
<file_sep path="hyperswitch/crates/router/src/core/gsm.rs" role="context" start="100" end="144">
pub async fn delete_gsm_rule(
state: SessionState,
gsm_request: gsm_api_types::GsmDeleteRequest,
) -> RouterResponse<gsm_api_types::GsmDeleteResponse> {
let db = state.store.as_ref();
let gsm_api_types::GsmDeleteRequest {
connector,
flow,
sub_flow,
code,
message,
} = gsm_request;
match GsmInterface::delete_gsm_rule(
db,
connector.to_string(),
flow.to_owned(),
sub_flow.to_owned(),
code.to_owned(),
message.to_owned(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError {
message: "GSM with given key does not exist in our records".to_string(),
})
.attach_printable("Failed while Deleting Gsm rule")
{
Ok(is_deleted) => {
if is_deleted {
Ok(services::ApplicationResponse::Json(
gsm_api_types::GsmDeleteResponse {
gsm_rule_delete: true,
connector,
flow,
sub_flow,
code,
},
))
} else {
Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while Deleting Gsm rule, got response as false")
}
}
Err(err) => Err(err),
}
}
<file_sep path="hyperswitch/crates/router/src/core/gsm.rs" role="context" start="32" end="50">
pub async fn retrieve_gsm_rule(
state: SessionState,
gsm_request: gsm_api_types::GsmRetrieveRequest,
) -> RouterResponse<gsm_api_types::GsmResponse> {
let db = state.store.as_ref();
let gsm_api_types::GsmRetrieveRequest {
connector,
flow,
sub_flow,
code,
message,
} = gsm_request;
GsmInterface::find_gsm_rule(db, connector.to_string(), flow, sub_flow, code, message)
.await
.to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError {
message: "GSM with given key does not exist in our records".to_string(),
})
.map(|gsm| services::ApplicationResponse::Json(gsm.foreign_into()))
}
<file_sep path="hyperswitch/crates/router/src/core/gsm.rs" role="context" start="18" end="29">
pub async fn create_gsm_rule(
state: SessionState,
gsm_rule: gsm_api_types::GsmCreateRequest,
) -> RouterResponse<gsm_api_types::GsmResponse> {
let db = state.store.as_ref();
GsmInterface::add_gsm_rule(db, gsm_rule.foreign_into())
.await
.to_duplicate_response(errors::ApiErrorResponse::GenericDuplicateError {
message: "GSM with given key already exists in our records".to_string(),
})
.map(|gsm| services::ApplicationResponse::Json(gsm.foreign_into()))
}
<file_sep path="hyperswitch/crates/router/src/routes/app.rs" role="context" start="2071" end="2071">
pub struct Gsm;
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payments/flows/authorize_flow.rs<|crate|> router anchor=process_capture_flow kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/payments/flows/authorize_flow.rs" role="context" start="635" end="674">
async fn process_capture_flow(
mut router_data: types::RouterData<
api::Authorize,
types::PaymentsAuthorizeData,
types::PaymentsResponseData,
>,
authorize_response: types::PaymentsResponseData,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
business_profile: &domain::Profile,
header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<
types::RouterData<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData>,
> {
// Convert RouterData into Capture RouterData
let capture_router_data = helpers::router_data_type_conversion(
router_data.clone(),
types::PaymentsCaptureData::foreign_try_from(router_data.clone())?,
Err(types::ErrorResponse::default()),
);
// Call capture request
let post_capture_router_data = super::call_capture_request(
capture_router_data,
state,
connector,
call_connector_action,
business_profile,
header_payload,
)
.await;
// Process capture response
let (updated_status, updated_response) =
super::handle_post_capture_response(authorize_response, post_capture_router_data)?;
router_data.status = updated_status;
router_data.response = Ok(updated_response);
Ok(router_data)
}
<file_sep path="hyperswitch/crates/router/src/core/payments/flows/authorize_flow.rs" role="context" start="634" end="634">
use hyperswitch_domain_models::errors::api_error_response::ApiErrorResponse;
use hyperswitch_domain_models::payments::PaymentConfirmData;
use super::{ConstructFlowSpecificData, Feature};
use crate::{
core::{
errors::{ConnectorErrorExt, RouterResult},
mandate,
payments::{
self, access_token, customers, helpers, tokenization, transformers, PaymentData,
},
},
logger,
routes::{metrics, SessionState},
services::{self, api::ConnectorValidation},
types::{
self, api, domain,
transformers::{ForeignFrom, ForeignTryFrom},
},
utils::OptionExt,
};
<file_sep path="hyperswitch/crates/router/src/core/payments/flows/authorize_flow.rs" role="context" start="600" end="632">
fn foreign_try_from(
item: types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let response = item
.response
.map_err(|err| ApiErrorResponse::ExternalConnectorError {
code: err.code,
message: err.message,
connector: item.connector.clone(),
status_code: err.status_code,
reason: err.reason,
})?;
Ok(Self {
amount_to_capture: item.request.amount,
currency: item.request.currency,
connector_transaction_id: types::PaymentsResponseData::get_connector_transaction_id(
&response,
)?,
payment_amount: item.request.amount,
multiple_capture_data: None,
connector_meta: types::PaymentsResponseData::get_connector_metadata(&response)
.map(|secret| secret.expose()),
browser_info: None,
metadata: None,
capture_method: item.request.capture_method,
minor_payment_amount: item.request.minor_amount,
minor_amount_to_capture: item.request.minor_amount,
integrity_object: None,
split_payments: item.request.split_payments,
webhook_url: item.request.webhook_url,
})
}
<file_sep path="hyperswitch/crates/router/src/core/payments/flows/authorize_flow.rs" role="context" start="544" end="592">
pub async fn authorize_postprocessing_steps<F: Clone>(
state: &SessionState,
router_data: &types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>,
confirm: bool,
connector: &api::ConnectorData,
) -> RouterResult<types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>> {
if confirm {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::PostProcessing,
types::PaymentsPostProcessingData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
let postprocessing_request_data =
types::PaymentsPostProcessingData::try_from(router_data.to_owned())?;
let postprocessing_response_data: Result<
types::PaymentsResponseData,
types::ErrorResponse,
> = Err(types::ErrorResponse::default());
let postprocessing_router_data =
helpers::router_data_type_conversion::<_, api::PostProcessing, _, _, _, _>(
router_data.clone(),
postprocessing_request_data,
postprocessing_response_data,
);
let resp = services::execute_connector_processing_step(
state,
connector_integration,
&postprocessing_router_data,
payments::CallConnectorAction::Trigger,
None,
)
.await
.to_payment_failed_response()?;
let authorize_router_data = helpers::router_data_type_conversion::<_, F, _, _, _, _>(
resp.clone(),
router_data.request.to_owned(),
resp.response,
);
Ok(authorize_router_data)
} else {
Ok(router_data.clone())
}
}
<file_sep path="hyperswitch/crates/router/src/core/payments/flows/authorize_flow.rs" role="context" start="173" end="237">
async fn decide_flows<'a>(
mut self,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
connector_request: Option<services::Request>,
business_profile: &domain::Profile,
header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<Self> {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::Authorize,
types::PaymentsAuthorizeData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
if self.should_proceed_with_authorize() {
self.decide_authentication_type();
logger::debug!(auth_type=?self.auth_type);
let mut auth_router_data = services::execute_connector_processing_step(
state,
connector_integration,
&self,
call_connector_action.clone(),
connector_request,
)
.await
.to_payment_failed_response()?;
// Initiating Integrity check
let integrity_result = helpers::check_integrity_based_on_flow(
&auth_router_data.request,
&auth_router_data.response,
);
auth_router_data.integrity_check = integrity_result;
metrics::PAYMENT_COUNT.add(1, &[]); // Move outside of the if block
match auth_router_data.response.clone() {
Err(_) => Ok(auth_router_data),
Ok(authorize_response) => {
// Check if the Capture API should be called based on the connector and other parameters
if super::should_initiate_capture_flow(
&connector.connector_name,
self.request.customer_acceptance,
self.request.capture_method,
self.request.setup_future_usage,
auth_router_data.status,
) {
auth_router_data = Box::pin(process_capture_flow(
auth_router_data,
authorize_response,
state,
connector,
call_connector_action.clone(),
business_profile,
header_payload,
))
.await?;
}
Ok(auth_router_data)
}
}
} else {
Ok(self.clone())
}
}
<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-07-07-091223_create_captures_table/up.sql" role="context" start="1" end="17">
CREATE TYPE "CaptureStatus" AS ENUM (
'started',
'charged',
'pending',
'failed'
);
ALTER TYPE "IntentStatus" ADD VALUE If NOT EXISTS 'partially_captured' AFTER 'requires_capture';
CREATE TABLE captures(
capture_id VARCHAR(64) NOT NULL PRIMARY KEY,
payment_id VARCHAR(64) NOT NULL,
merchant_id VARCHAR(64) NOT NULL,
status "CaptureStatus" NOT NULL,
amount BIGINT NOT NULL,
currency "Currency",
connector VARCHAR(255),
error_message VARCHAR(255),
<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/gsm.rs<|crate|> router anchor=delete_gsm_rule kind=fn pack=symbol_neighborhood lang=rust role_window=k2 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/gsm.rs" role="context" start="100" end="144">
pub async fn delete_gsm_rule(
state: SessionState,
gsm_request: gsm_api_types::GsmDeleteRequest,
) -> RouterResponse<gsm_api_types::GsmDeleteResponse> {
let db = state.store.as_ref();
let gsm_api_types::GsmDeleteRequest {
connector,
flow,
sub_flow,
code,
message,
} = gsm_request;
match GsmInterface::delete_gsm_rule(
db,
connector.to_string(),
flow.to_owned(),
sub_flow.to_owned(),
code.to_owned(),
message.to_owned(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError {
message: "GSM with given key does not exist in our records".to_string(),
})
.attach_printable("Failed while Deleting Gsm rule")
{
Ok(is_deleted) => {
if is_deleted {
Ok(services::ApplicationResponse::Json(
gsm_api_types::GsmDeleteResponse {
gsm_rule_delete: true,
connector,
flow,
sub_flow,
code,
},
))
} else {
Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while Deleting Gsm rule, got response as false")
}
}
Err(err) => Err(err),
}
}
<file_sep path="hyperswitch/crates/router/src/core/gsm.rs" role="context" start="99" end="99">
use api_models::gsm as gsm_api_types;
use diesel_models::gsm as storage;
use crate::{
core::{
errors,
errors::{RouterResponse, StorageErrorExt},
},
db::gsm::GsmInterface,
services,
types::transformers::ForeignInto,
SessionState,
};
<file_sep path="hyperswitch/crates/router/src/core/gsm.rs" role="context" start="53" end="97">
pub async fn update_gsm_rule(
state: SessionState,
gsm_request: gsm_api_types::GsmUpdateRequest,
) -> RouterResponse<gsm_api_types::GsmResponse> {
let db = state.store.as_ref();
let gsm_api_types::GsmUpdateRequest {
connector,
flow,
sub_flow,
code,
message,
decision,
status,
router_error,
step_up_possible,
unified_code,
unified_message,
error_category,
clear_pan_possible,
} = gsm_request;
GsmInterface::update_gsm_rule(
db,
connector.to_string(),
flow,
sub_flow,
code,
message,
storage::GatewayStatusMappingUpdate {
decision: decision.map(|d| d.to_string()),
status,
router_error: Some(router_error),
step_up_possible,
unified_code,
unified_message,
error_category,
clear_pan_possible,
},
)
.await
.to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError {
message: "GSM with given key does not exist in our records".to_string(),
})
.attach_printable("Failed while updating Gsm rule")
.map(|gsm| services::ApplicationResponse::Json(gsm.foreign_into()))
}
<file_sep path="hyperswitch/crates/router/src/core/gsm.rs" role="context" start="32" end="50">
pub async fn retrieve_gsm_rule(
state: SessionState,
gsm_request: gsm_api_types::GsmRetrieveRequest,
) -> RouterResponse<gsm_api_types::GsmResponse> {
let db = state.store.as_ref();
let gsm_api_types::GsmRetrieveRequest {
connector,
flow,
sub_flow,
code,
message,
} = gsm_request;
GsmInterface::find_gsm_rule(db, connector.to_string(), flow, sub_flow, code, message)
.await
.to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError {
message: "GSM with given key does not exist in our records".to_string(),
})
.map(|gsm| services::ApplicationResponse::Json(gsm.foreign_into()))
}
<file_sep path="hyperswitch/crates/router/src/routes/app.rs" role="context" start="2071" end="2071">
pub struct Gsm;
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payments/flows/complete_authorize_flow.rs<|crate|> router anchor=process_capture_flow kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/payments/flows/complete_authorize_flow.rs" role="context" start="328" end="372">
async fn process_capture_flow(
mut router_data: types::RouterData<
api::CompleteAuthorize,
types::CompleteAuthorizeData,
types::PaymentsResponseData,
>,
complete_authorize_response: types::PaymentsResponseData,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
business_profile: &domain::Profile,
header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<
types::RouterData<
api::CompleteAuthorize,
types::CompleteAuthorizeData,
types::PaymentsResponseData,
>,
> {
// Convert RouterData into Capture RouterData
let capture_router_data = helpers::router_data_type_conversion(
router_data.clone(),
types::PaymentsCaptureData::foreign_try_from(router_data.clone())?,
Err(types::ErrorResponse::default()),
);
// Call capture request
let post_capture_router_data = super::call_capture_request(
capture_router_data,
state,
connector,
call_connector_action,
business_profile,
header_payload,
)
.await;
// Process capture response
let (updated_status, updated_response) =
super::handle_post_capture_response(complete_authorize_response, post_capture_router_data)?;
router_data.status = updated_status;
router_data.response = Ok(updated_response);
Ok(router_data)
}
<file_sep path="hyperswitch/crates/router/src/core/payments/flows/complete_authorize_flow.rs" role="context" start="327" end="327">
use super::{ConstructFlowSpecificData, Feature};
use crate::{
core::{
errors::{ApiErrorResponse, ConnectorErrorExt, RouterResult},
payments::{self, access_token, helpers, transformers, PaymentData},
},
routes::{metrics, SessionState},
services,
types::{self, api, domain, transformers::ForeignTryFrom},
};
<file_sep path="hyperswitch/crates/router/src/core/payments/flows/complete_authorize_flow.rs" role="context" start="293" end="325">
fn foreign_try_from(
item: types::RouterData<F, types::CompleteAuthorizeData, types::PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let response = item
.response
.map_err(|err| ApiErrorResponse::ExternalConnectorError {
code: err.code,
message: err.message,
connector: item.connector.clone().to_string(),
status_code: err.status_code,
reason: err.reason,
})?;
Ok(Self {
amount_to_capture: item.request.amount,
currency: item.request.currency,
connector_transaction_id: types::PaymentsResponseData::get_connector_transaction_id(
&response,
)?,
payment_amount: item.request.amount,
multiple_capture_data: None,
connector_meta: types::PaymentsResponseData::get_connector_metadata(&response)
.map(|secret| secret.expose()),
browser_info: None,
metadata: None,
capture_method: item.request.capture_method,
minor_payment_amount: item.request.minor_amount,
minor_amount_to_capture: item.request.minor_amount,
integrity_object: None,
split_payments: None,
webhook_url: None,
})
}
<file_sep path="hyperswitch/crates/router/src/core/payments/flows/complete_authorize_flow.rs" role="context" start="222" end="285">
pub async fn complete_authorize_preprocessing_steps<F: Clone>(
state: &SessionState,
router_data: &types::RouterData<F, types::CompleteAuthorizeData, types::PaymentsResponseData>,
confirm: bool,
connector: &api::ConnectorData,
) -> RouterResult<types::RouterData<F, types::CompleteAuthorizeData, types::PaymentsResponseData>> {
if confirm {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::PreProcessing,
types::PaymentsPreProcessingData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
let preprocessing_request_data =
types::PaymentsPreProcessingData::try_from(router_data.request.to_owned())?;
let preprocessing_response_data: Result<types::PaymentsResponseData, types::ErrorResponse> =
Err(types::ErrorResponse::default());
let preprocessing_router_data =
helpers::router_data_type_conversion::<_, api::PreProcessing, _, _, _, _>(
router_data.clone(),
preprocessing_request_data,
preprocessing_response_data,
);
let resp = services::execute_connector_processing_step(
state,
connector_integration,
&preprocessing_router_data,
payments::CallConnectorAction::Trigger,
None,
)
.await
.to_payment_failed_response()?;
metrics::PREPROCESSING_STEPS_COUNT.add(
1,
router_env::metric_attributes!(
("connector", connector.connector_name.to_string()),
("payment_method", router_data.payment_method.to_string()),
),
);
let mut router_data_request = router_data.request.to_owned();
if let Ok(types::PaymentsResponseData::TransactionResponse {
connector_metadata, ..
}) = &resp.response
{
connector_metadata.clone_into(&mut router_data_request.connector_meta);
};
let authorize_router_data = helpers::router_data_type_conversion::<_, F, _, _, _, _>(
resp.clone(),
router_data_request,
resp.response,
);
Ok(authorize_router_data)
} else {
Ok(router_data.clone())
}
}
<file_sep path="hyperswitch/crates/router/src/core/payments/flows/complete_authorize_flow.rs" role="context" start="99" end="148">
async fn decide_flows<'a>(
mut self,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
connector_request: Option<services::Request>,
business_profile: &domain::Profile,
header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<Self> {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::CompleteAuthorize,
types::CompleteAuthorizeData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
let mut complete_authorize_router_data = services::execute_connector_processing_step(
state,
connector_integration,
&self,
call_connector_action.clone(),
connector_request,
)
.await
.to_payment_failed_response()?;
match complete_authorize_router_data.response.clone() {
Err(_) => Ok(complete_authorize_router_data),
Ok(complete_authorize_response) => {
// Check if the Capture API should be called based on the connector and other parameters
if super::should_initiate_capture_flow(
&connector.connector_name,
self.request.customer_acceptance,
self.request.capture_method,
self.request.setup_future_usage,
complete_authorize_router_data.status,
) {
complete_authorize_router_data = Box::pin(process_capture_flow(
complete_authorize_router_data,
complete_authorize_response,
state,
connector,
call_connector_action.clone(),
business_profile,
header_payload,
))
.await?;
}
Ok(complete_authorize_router_data)
}
}
}
<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-07-07-091223_create_captures_table/up.sql" role="context" start="1" end="17">
CREATE TYPE "CaptureStatus" AS ENUM (
'started',
'charged',
'pending',
'failed'
);
ALTER TYPE "IntentStatus" ADD VALUE If NOT EXISTS 'partially_captured' AFTER 'requires_capture';
CREATE TABLE captures(
capture_id VARCHAR(64) NOT NULL PRIMARY KEY,
payment_id VARCHAR(64) NOT NULL,
merchant_id VARCHAR(64) NOT NULL,
status "CaptureStatus" NOT NULL,
amount BIGINT NOT NULL,
currency "Currency",
connector VARCHAR(255),
error_message VARCHAR(255),
<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>,
}
<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/complete_authorize_flow.rs<|crate|> router anchor=process_capture_flow kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/payments/flows/complete_authorize_flow.rs" role="context" start="328" end="372">
async fn process_capture_flow(
mut router_data: types::RouterData<
api::CompleteAuthorize,
types::CompleteAuthorizeData,
types::PaymentsResponseData,
>,
complete_authorize_response: types::PaymentsResponseData,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
business_profile: &domain::Profile,
header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<
types::RouterData<
api::CompleteAuthorize,
types::CompleteAuthorizeData,
types::PaymentsResponseData,
>,
> {
// Convert RouterData into Capture RouterData
let capture_router_data = helpers::router_data_type_conversion(
router_data.clone(),
types::PaymentsCaptureData::foreign_try_from(router_data.clone())?,
Err(types::ErrorResponse::default()),
);
// Call capture request
let post_capture_router_data = super::call_capture_request(
capture_router_data,
state,
connector,
call_connector_action,
business_profile,
header_payload,
)
.await;
// Process capture response
let (updated_status, updated_response) =
super::handle_post_capture_response(complete_authorize_response, post_capture_router_data)?;
router_data.status = updated_status;
router_data.response = Ok(updated_response);
Ok(router_data)
}
<file_sep path="hyperswitch/crates/router/src/core/payments/flows/complete_authorize_flow.rs" role="context" start="327" end="327">
use super::{ConstructFlowSpecificData, Feature};
use crate::{
core::{
errors::{ApiErrorResponse, ConnectorErrorExt, RouterResult},
payments::{self, access_token, helpers, transformers, PaymentData},
},
routes::{metrics, SessionState},
services,
types::{self, api, domain, transformers::ForeignTryFrom},
};
<file_sep path="hyperswitch/crates/router/src/core/payments/flows/complete_authorize_flow.rs" role="context" start="293" end="325">
fn foreign_try_from(
item: types::RouterData<F, types::CompleteAuthorizeData, types::PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let response = item
.response
.map_err(|err| ApiErrorResponse::ExternalConnectorError {
code: err.code,
message: err.message,
connector: item.connector.clone().to_string(),
status_code: err.status_code,
reason: err.reason,
})?;
Ok(Self {
amount_to_capture: item.request.amount,
currency: item.request.currency,
connector_transaction_id: types::PaymentsResponseData::get_connector_transaction_id(
&response,
)?,
payment_amount: item.request.amount,
multiple_capture_data: None,
connector_meta: types::PaymentsResponseData::get_connector_metadata(&response)
.map(|secret| secret.expose()),
browser_info: None,
metadata: None,
capture_method: item.request.capture_method,
minor_payment_amount: item.request.minor_amount,
minor_amount_to_capture: item.request.minor_amount,
integrity_object: None,
split_payments: None,
webhook_url: None,
})
}
<file_sep path="hyperswitch/crates/router/src/core/payments/flows/complete_authorize_flow.rs" role="context" start="222" end="285">
pub async fn complete_authorize_preprocessing_steps<F: Clone>(
state: &SessionState,
router_data: &types::RouterData<F, types::CompleteAuthorizeData, types::PaymentsResponseData>,
confirm: bool,
connector: &api::ConnectorData,
) -> RouterResult<types::RouterData<F, types::CompleteAuthorizeData, types::PaymentsResponseData>> {
if confirm {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::PreProcessing,
types::PaymentsPreProcessingData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
let preprocessing_request_data =
types::PaymentsPreProcessingData::try_from(router_data.request.to_owned())?;
let preprocessing_response_data: Result<types::PaymentsResponseData, types::ErrorResponse> =
Err(types::ErrorResponse::default());
let preprocessing_router_data =
helpers::router_data_type_conversion::<_, api::PreProcessing, _, _, _, _>(
router_data.clone(),
preprocessing_request_data,
preprocessing_response_data,
);
let resp = services::execute_connector_processing_step(
state,
connector_integration,
&preprocessing_router_data,
payments::CallConnectorAction::Trigger,
None,
)
.await
.to_payment_failed_response()?;
metrics::PREPROCESSING_STEPS_COUNT.add(
1,
router_env::metric_attributes!(
("connector", connector.connector_name.to_string()),
("payment_method", router_data.payment_method.to_string()),
),
);
let mut router_data_request = router_data.request.to_owned();
if let Ok(types::PaymentsResponseData::TransactionResponse {
connector_metadata, ..
}) = &resp.response
{
connector_metadata.clone_into(&mut router_data_request.connector_meta);
};
let authorize_router_data = helpers::router_data_type_conversion::<_, F, _, _, _, _>(
resp.clone(),
router_data_request,
resp.response,
);
Ok(authorize_router_data)
} else {
Ok(router_data.clone())
}
}
<file_sep path="hyperswitch/crates/router/src/core/payments/flows/complete_authorize_flow.rs" role="context" start="99" end="148">
async fn decide_flows<'a>(
mut self,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
connector_request: Option<services::Request>,
business_profile: &domain::Profile,
header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<Self> {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::CompleteAuthorize,
types::CompleteAuthorizeData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
let mut complete_authorize_router_data = services::execute_connector_processing_step(
state,
connector_integration,
&self,
call_connector_action.clone(),
connector_request,
)
.await
.to_payment_failed_response()?;
match complete_authorize_router_data.response.clone() {
Err(_) => Ok(complete_authorize_router_data),
Ok(complete_authorize_response) => {
// Check if the Capture API should be called based on the connector and other parameters
if super::should_initiate_capture_flow(
&connector.connector_name,
self.request.customer_acceptance,
self.request.capture_method,
self.request.setup_future_usage,
complete_authorize_router_data.status,
) {
complete_authorize_router_data = Box::pin(process_capture_flow(
complete_authorize_router_data,
complete_authorize_response,
state,
connector,
call_connector_action.clone(),
business_profile,
header_payload,
))
.await?;
}
Ok(complete_authorize_router_data)
}
}
}
<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-07-07-091223_create_captures_table/up.sql" role="context" start="1" end="17">
CREATE TYPE "CaptureStatus" AS ENUM (
'started',
'charged',
'pending',
'failed'
);
ALTER TYPE "IntentStatus" ADD VALUE If NOT EXISTS 'partially_captured' AFTER 'requires_capture';
CREATE TABLE captures(
capture_id VARCHAR(64) NOT NULL PRIMARY KEY,
payment_id VARCHAR(64) NOT NULL,
merchant_id VARCHAR(64) NOT NULL,
status "CaptureStatus" NOT NULL,
amount BIGINT NOT NULL,
currency "Currency",
connector VARCHAR(255),
error_message VARCHAR(255),
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/webhooks/outgoing.rs<|crate|> router anchor=api_client_error_handler kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/webhooks/outgoing.rs" role="context" start="736" end="775">
async fn api_client_error_handler(
state: SessionState,
merchant_key_store: domain::MerchantKeyStore,
merchant_id: &common_utils::id_type::MerchantId,
event_id: &str,
client_error: error_stack::Report<errors::ApiClientError>,
delivery_attempt: enums::WebhookDeliveryAttempt,
schedule_webhook_retry: ScheduleWebhookRetry,
) -> CustomResult<(), errors::WebhooksFlowError> {
// Not including detailed error message in response information since it contains too
// much of diagnostic information to be exposed to the merchant.
update_event_if_client_error(
state.clone(),
merchant_key_store,
merchant_id,
event_id,
"Unable to send request to merchant server".to_string(),
)
.await?;
let error = client_error.change_context(errors::WebhooksFlowError::CallToMerchantFailed);
logger::error!(
?error,
?delivery_attempt,
"An error occurred when sending webhook to merchant"
);
if let ScheduleWebhookRetry::WithProcessTracker(process_tracker) = schedule_webhook_retry {
// Schedule a retry attempt for webhook delivery
outgoing_webhook_retry::retry_webhook_delivery_task(
&*state.store,
merchant_id,
*process_tracker,
)
.await
.change_context(errors::WebhooksFlowError::OutgoingWebhookRetrySchedulingFailed)?;
}
Err(error)
}
<file_sep path="hyperswitch/crates/router/src/core/webhooks/outgoing.rs" role="context" start="735" end="735">
use common_utils::{
ext_traits::{Encode, StringExt},
request::RequestContent,
type_name,
types::keymanager::{Identifier, KeyManagerState},
};
use diesel_models::process_tracker::business_status;
use error_stack::{report, ResultExt};
use crate::{
core::{
errors::{self, CustomResult},
metrics,
},
db::StorageInterface,
events::outgoing_webhook_logs::{
OutgoingWebhookEvent, OutgoingWebhookEventContent, OutgoingWebhookEventMetric,
},
logger,
routes::{app::SessionStateInfo, SessionState},
services,
types::{
api,
domain::{self},
storage::{self, enums},
transformers::ForeignFrom,
},
utils::{OptionExt, ValueExt},
workflows::outgoing_webhook_retry,
};
<file_sep path="hyperswitch/crates/router/src/core/webhooks/outgoing.rs" role="context" start="857" end="893">
async fn update_overall_delivery_status_in_storage(
state: SessionState,
merchant_key_store: domain::MerchantKeyStore,
merchant_id: &common_utils::id_type::MerchantId,
updated_event: domain::Event,
) -> CustomResult<(), errors::WebhooksFlowError> {
let key_manager_state = &(&state).into();
let update_overall_delivery_status = domain::EventUpdate::OverallDeliveryStatusUpdate {
is_overall_delivery_successful: true,
};
let initial_attempt_id = updated_event.initial_attempt_id.as_ref();
let delivery_attempt = updated_event.delivery_attempt;
if let Some((
initial_attempt_id,
enums::WebhookDeliveryAttempt::InitialAttempt
| enums::WebhookDeliveryAttempt::AutomaticRetry,
)) = initial_attempt_id.zip(delivery_attempt)
{
state
.store
.update_event_by_merchant_id_event_id(
key_manager_state,
merchant_id,
initial_attempt_id.as_str(),
update_overall_delivery_status,
&merchant_key_store,
)
.await
.change_context(errors::WebhooksFlowError::WebhookEventUpdationFailed)
.attach_printable("Failed to update initial delivery attempt")?;
}
Ok(())
}
<file_sep path="hyperswitch/crates/router/src/core/webhooks/outgoing.rs" role="context" start="777" end="855">
async fn update_event_in_storage(
state: SessionState,
merchant_key_store: domain::MerchantKeyStore,
merchant_id: &common_utils::id_type::MerchantId,
event_id: &str,
response: reqwest::Response,
) -> CustomResult<domain::Event, errors::WebhooksFlowError> {
let status_code = response.status();
let is_webhook_notified = status_code.is_success();
let key_manager_state = &(&state).into();
let response_headers = response
.headers()
.iter()
.map(|(name, value)| {
(
name.as_str().to_owned(),
value
.to_str()
.map(|s| Secret::from(String::from(s)))
.unwrap_or_else(|error| {
logger::warn!(
"Response header {} contains non-UTF-8 characters: {error:?}",
name.as_str()
);
Secret::from(String::from("Non-UTF-8 header value"))
}),
)
})
.collect::<Vec<_>>();
let response_body = response
.text()
.await
.map(Secret::from)
.unwrap_or_else(|error| {
logger::warn!("Response contains non-UTF-8 characters: {error:?}");
Secret::from(String::from("Non-UTF-8 response body"))
});
let response_to_store = OutgoingWebhookResponseContent {
body: Some(response_body),
headers: Some(response_headers),
status_code: Some(status_code.as_u16()),
error_message: None,
};
let event_update = domain::EventUpdate::UpdateResponse {
is_webhook_notified,
response: Some(
crypto_operation(
key_manager_state,
type_name!(domain::Event),
CryptoOperation::Encrypt(
response_to_store
.encode_to_string_of_json()
.change_context(
errors::WebhooksFlowError::OutgoingWebhookResponseEncodingFailed,
)
.map(Secret::new)?,
),
Identifier::Merchant(merchant_key_store.merchant_id.clone()),
merchant_key_store.key.get_inner().peek(),
)
.await
.and_then(|val| val.try_into_operation())
.change_context(errors::WebhooksFlowError::WebhookEventUpdationFailed)
.attach_printable("Failed to encrypt outgoing webhook response content")?,
),
};
state
.store
.update_event_by_merchant_id_event_id(
key_manager_state,
merchant_id,
event_id,
event_update,
&merchant_key_store,
)
.await
.change_context(errors::WebhooksFlowError::WebhookEventUpdationFailed)
}
<file_sep path="hyperswitch/crates/router/src/core/webhooks/outgoing.rs" role="context" start="683" end="734">
async fn update_event_if_client_error(
state: SessionState,
merchant_key_store: domain::MerchantKeyStore,
merchant_id: &common_utils::id_type::MerchantId,
event_id: &str,
error_message: String,
) -> CustomResult<domain::Event, errors::WebhooksFlowError> {
let is_webhook_notified = false;
let key_manager_state = &(&state).into();
let response_to_store = OutgoingWebhookResponseContent {
body: None,
headers: None,
status_code: None,
error_message: Some(error_message),
};
let event_update = domain::EventUpdate::UpdateResponse {
is_webhook_notified,
response: Some(
crypto_operation(
key_manager_state,
type_name!(domain::Event),
CryptoOperation::Encrypt(
response_to_store
.encode_to_string_of_json()
.change_context(
errors::WebhooksFlowError::OutgoingWebhookResponseEncodingFailed,
)
.map(Secret::new)?,
),
Identifier::Merchant(merchant_key_store.merchant_id.clone()),
merchant_key_store.key.get_inner().peek(),
)
.await
.and_then(|val| val.try_into_operation())
.change_context(errors::WebhooksFlowError::WebhookEventUpdationFailed)
.attach_printable("Failed to encrypt outgoing webhook response content")?,
),
};
state
.store
.update_event_by_merchant_id_event_id(
key_manager_state,
merchant_id,
event_id,
event_update,
&merchant_key_store,
)
.await
.change_context(errors::WebhooksFlowError::WebhookEventUpdationFailed)
}
<file_sep path="hyperswitch/crates/router/src/core/webhooks/outgoing.rs" role="context" start="608" end="675">
pub(crate) fn get_outgoing_webhook_request(
merchant_account: &domain::MerchantAccount,
outgoing_webhook: api::OutgoingWebhook,
business_profile: &domain::Profile,
) -> CustomResult<OutgoingWebhookRequestContent, errors::WebhooksFlowError> {
#[inline]
fn get_outgoing_webhook_request_inner<WebhookType: types::OutgoingWebhookType>(
outgoing_webhook: api::OutgoingWebhook,
business_profile: &domain::Profile,
) -> CustomResult<OutgoingWebhookRequestContent, errors::WebhooksFlowError> {
let mut headers = vec![
(
reqwest::header::CONTENT_TYPE.to_string(),
mime::APPLICATION_JSON.essence_str().into(),
),
(
reqwest::header::USER_AGENT.to_string(),
consts::USER_AGENT.to_string().into(),
),
];
let transformed_outgoing_webhook = WebhookType::from(outgoing_webhook);
let payment_response_hash_key = business_profile.payment_response_hash_key.clone();
let custom_headers = business_profile
.outgoing_webhook_custom_http_headers
.clone()
.map(|headers| {
headers
.into_inner()
.expose()
.parse_value::<HashMap<String, String>>("HashMap<String,String>")
.change_context(errors::WebhooksFlowError::OutgoingWebhookEncodingFailed)
.attach_printable("Failed to deserialize outgoing webhook custom HTTP headers")
})
.transpose()?;
if let Some(ref map) = custom_headers {
headers.extend(
map.iter()
.map(|(key, value)| (key.clone(), value.clone().into_masked())),
);
};
let outgoing_webhooks_signature = transformed_outgoing_webhook
.get_outgoing_webhooks_signature(payment_response_hash_key)?;
if let Some(signature) = outgoing_webhooks_signature.signature {
WebhookType::add_webhook_header(&mut headers, signature)
}
Ok(OutgoingWebhookRequestContent {
body: outgoing_webhooks_signature.payload,
headers: headers
.into_iter()
.map(|(name, value)| (name, Secret::new(value.into_inner())))
.collect(),
})
}
match merchant_account.get_compatible_connector() {
#[cfg(feature = "stripe")]
Some(api_models::enums::Connector::Stripe) => get_outgoing_webhook_request_inner::<
stripe_webhooks::StripeOutgoingWebhook,
>(outgoing_webhook, business_profile),
_ => get_outgoing_webhook_request_inner::<webhooks::OutgoingWebhook>(
outgoing_webhook,
business_profile,
),
}
}
<file_sep path="hyperswitch/crates/router/src/core/webhooks/outgoing.rs" role="context" start="238" end="455">
async fn trigger_webhook_to_merchant(
state: SessionState,
business_profile: domain::Profile,
merchant_key_store: &domain::MerchantKeyStore,
event: domain::Event,
request_content: OutgoingWebhookRequestContent,
delivery_attempt: enums::WebhookDeliveryAttempt,
process_tracker: Option<storage::ProcessTracker>,
) -> CustomResult<(), errors::WebhooksFlowError> {
let webhook_url = match (
get_webhook_url_from_business_profile(&business_profile),
process_tracker.clone(),
) {
(Ok(webhook_url), _) => Ok(webhook_url),
(Err(error), Some(process_tracker)) => {
if !error
.current_context()
.is_webhook_delivery_retryable_error()
{
logger::debug!("Failed to obtain merchant webhook URL, aborting retries");
state
.store
.as_scheduler()
.finish_process_with_business_status(process_tracker, business_status::FAILURE)
.await
.change_context(
errors::WebhooksFlowError::OutgoingWebhookProcessTrackerTaskUpdateFailed,
)?;
}
Err(error)
}
(Err(error), None) => Err(error),
}?;
let event_id = event.event_id;
let headers = request_content
.headers
.into_iter()
.map(|(name, value)| (name, value.into_masked()))
.collect();
let request = services::RequestBuilder::new()
.method(services::Method::Post)
.url(&webhook_url)
.attach_default_headers()
.headers(headers)
.set_body(RequestContent::RawBytes(
request_content.body.expose().into_bytes(),
))
.build();
let response = state
.api_client
.send_request(&state, request, Some(OUTGOING_WEBHOOK_TIMEOUT_SECS), false)
.await;
metrics::WEBHOOK_OUTGOING_COUNT.add(
1,
router_env::metric_attributes!((MERCHANT_ID, business_profile.merchant_id.clone())),
);
logger::debug!(outgoing_webhook_response=?response);
match delivery_attempt {
enums::WebhookDeliveryAttempt::InitialAttempt => match response {
Err(client_error) => {
api_client_error_handler(
state.clone(),
merchant_key_store.clone(),
&business_profile.merchant_id,
&event_id,
client_error,
delivery_attempt,
ScheduleWebhookRetry::NoSchedule,
)
.await?
}
Ok(response) => {
let status_code = response.status();
let updated_event = update_event_in_storage(
state.clone(),
merchant_key_store.clone(),
&business_profile.merchant_id,
&event_id,
response,
)
.await?;
if status_code.is_success() {
update_overall_delivery_status_in_storage(
state.clone(),
merchant_key_store.clone(),
&business_profile.merchant_id,
updated_event,
)
.await?;
success_response_handler(
state.clone(),
&business_profile.merchant_id,
process_tracker,
business_status::INITIAL_DELIVERY_ATTEMPT_SUCCESSFUL,
)
.await?;
} else {
error_response_handler(
state.clone(),
&business_profile.merchant_id,
delivery_attempt,
status_code.as_u16(),
"Ignoring error when sending webhook to merchant",
ScheduleWebhookRetry::NoSchedule,
)
.await?;
}
}
},
enums::WebhookDeliveryAttempt::AutomaticRetry => {
let process_tracker = process_tracker
.get_required_value("process_tracker")
.change_context(errors::WebhooksFlowError::OutgoingWebhookRetrySchedulingFailed)
.attach_printable("`process_tracker` is unavailable in automatic retry flow")?;
match response {
Err(client_error) => {
api_client_error_handler(
state.clone(),
merchant_key_store.clone(),
&business_profile.merchant_id,
&event_id,
client_error,
delivery_attempt,
ScheduleWebhookRetry::WithProcessTracker(Box::new(process_tracker)),
)
.await?;
}
Ok(response) => {
let status_code = response.status();
let updated_event = update_event_in_storage(
state.clone(),
merchant_key_store.clone(),
&business_profile.merchant_id,
&event_id,
response,
)
.await?;
if status_code.is_success() {
update_overall_delivery_status_in_storage(
state.clone(),
merchant_key_store.clone(),
&business_profile.merchant_id,
updated_event,
)
.await?;
success_response_handler(
state.clone(),
&business_profile.merchant_id,
Some(process_tracker),
"COMPLETED_BY_PT",
)
.await?;
} else {
error_response_handler(
state.clone(),
&business_profile.merchant_id,
delivery_attempt,
status_code.as_u16(),
"An error occurred when sending webhook to merchant",
ScheduleWebhookRetry::WithProcessTracker(Box::new(process_tracker)),
)
.await?;
}
}
}
}
enums::WebhookDeliveryAttempt::ManualRetry => match response {
Err(client_error) => {
api_client_error_handler(
state.clone(),
merchant_key_store.clone(),
&business_profile.merchant_id,
&event_id,
client_error,
delivery_attempt,
ScheduleWebhookRetry::NoSchedule,
)
.await?
}
Ok(response) => {
let status_code = response.status();
let _updated_event = update_event_in_storage(
state.clone(),
merchant_key_store.clone(),
&business_profile.merchant_id,
&event_id,
response,
)
.await?;
if status_code.is_success() {
increment_webhook_outgoing_received_count(&business_profile.merchant_id);
} else {
error_response_handler(
state,
&business_profile.merchant_id,
delivery_attempt,
status_code.as_u16(),
"Ignoring error when sending webhook to merchant",
ScheduleWebhookRetry::NoSchedule,
)
.await?;
}
}
},
}
Ok(())
}
<file_sep path="hyperswitch/crates/router/src/core/webhooks/outgoing.rs" role="context" start="678" end="681">
enum ScheduleWebhookRetry {
WithProcessTracker(Box<storage::ProcessTracker>),
NoSchedule,
}
<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/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/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/payments/routing.rs<|crate|> router anchor=perform_eligibility_analysis_with_fallback 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="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="929" end="929">
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="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="881" end="928">
pub async fn perform_fallback_routing(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
transaction_data: &routing::TransactionData<'_>,
eligible_connectors: Option<&Vec<api_enums::RoutableConnectors>>,
business_profile: &domain::Profile,
) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> {
#[cfg(feature = "v1")]
let fallback_config = routing::helpers::get_merchant_default_config(
&*state.store,
match transaction_data {
routing::TransactionData::Payment(payment_data) => payment_data
.payment_intent
.profile_id
.as_ref()
.get_required_value("profile_id")
.change_context(errors::RoutingError::ProfileIdMissing)?
.get_string_repr(),
#[cfg(feature = "payouts")]
routing::TransactionData::Payout(payout_data) => {
payout_data.payout_attempt.profile_id.get_string_repr()
}
},
&api_enums::TransactionType::from(transaction_data),
)
.await
.change_context(errors::RoutingError::FallbackConfigFetchFailed)?;
#[cfg(feature = "v2")]
let fallback_config = admin::ProfileWrapper::new(business_profile.clone())
.get_default_fallback_list_of_connector_under_profile()
.change_context(errors::RoutingError::FallbackConfigFetchFailed)?;
let backend_input = match transaction_data {
routing::TransactionData::Payment(payment_data) => make_dsl_input(payment_data)?,
#[cfg(feature = "payouts")]
routing::TransactionData::Payout(payout_data) => make_dsl_input_for_payouts(payout_data)?,
};
perform_cgraph_filtering(
state,
key_store,
fallback_config,
backend_input,
eligible_connectors,
business_profile.get_id(),
&api_enums::TransactionType::from(transaction_data),
)
.await
}
<file_sep path="hyperswitch/crates/router/src/core/payments/routing.rs" role="context" start="855" end="879">
pub async fn perform_eligibility_analysis(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
chosen: Vec<routing_types::RoutableConnectorChoice>,
transaction_data: &routing::TransactionData<'_>,
eligible_connectors: Option<&Vec<api_enums::RoutableConnectors>>,
profile_id: &common_utils::id_type::ProfileId,
) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> {
let backend_input = match transaction_data {
routing::TransactionData::Payment(payment_data) => make_dsl_input(payment_data)?,
#[cfg(feature = "payouts")]
routing::TransactionData::Payout(payout_data) => make_dsl_input_for_payouts(payout_data)?,
};
perform_cgraph_filtering(
state,
key_store,
chosen,
backend_input,
eligible_connectors,
profile_id,
&api_enums::TransactionType::from(transaction_data),
)
.await
}
<file_sep path="hyperswitch/crates/router/src/core/payments/routing.rs" role="context" start="111" end="111">
type RoutingResult<O> = oss_errors::CustomResult<O, errors::RoutingError>;
<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/payouts.rs<|crate|> router anchor=create_payout_retrieve 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="1869" end="1916">
pub async fn create_payout_retrieve(
state: &SessionState,
merchant_account: &domain::MerchantAccount,
connector_data: &api::ConnectorData,
payout_data: &mut PayoutData,
) -> RouterResult<()> {
// 1. Form Router data
let mut router_data = core_utils::construct_payout_router_data(
state,
connector_data,
merchant_account,
payout_data,
)
.await?;
// 2. Get/Create access token
access_token::create_access_token(
state,
connector_data,
merchant_account,
&mut router_data,
payout_data.payouts.payout_type.to_owned(),
)
.await?;
// 3. Fetch connector integration details
let connector_integration: services::BoxedPayoutConnectorIntegrationInterface<
api::PoSync,
types::PayoutsData,
types::PayoutsResponseData,
> = connector_data.connector.get_connector_integration();
// 4. Call connector service
let router_data_resp = services::execute_connector_processing_step(
state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
)
.await
.to_payout_failed_response()?;
// 5. Process data returned by the connector
update_retrieve_payout_tracker(state, merchant_account, payout_data, &router_data_resp).await?;
Ok(())
}
<file_sep path="hyperswitch/crates/router/src/core/payouts.rs" role="context" start="1868" end="1868">
use api_models::payments as payment_enums;
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::types::PayoutActionData;
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="2009" end="2039">
pub async fn complete_create_recipient_disburse_account(
state: &SessionState,
merchant_account: &domain::MerchantAccount,
connector_data: &api::ConnectorData,
payout_data: &mut PayoutData,
key_store: &domain::MerchantKeyStore,
) -> RouterResult<()> {
if !payout_data.should_terminate
&& matches!(
payout_data.payout_attempt.status,
storage_enums::PayoutStatus::RequiresVendorAccountCreation
| storage_enums::PayoutStatus::RequiresCreation
)
&& connector_data
.connector_name
.supports_vendor_disburse_account_create_for_payout()
&& helpers::should_create_connector_transfer_method(&*payout_data, connector_data)?
.is_none()
{
Box::pin(create_recipient_disburse_account(
state,
merchant_account,
connector_data,
payout_data,
key_store,
))
.await
.attach_printable("Creation of customer failed")?;
}
Ok(())
}
<file_sep path="hyperswitch/crates/router/src/core/payouts.rs" role="context" start="1918" end="2007">
pub async fn update_retrieve_payout_tracker<F, T>(
state: &SessionState,
merchant_account: &domain::MerchantAccount,
payout_data: &mut PayoutData,
payout_router_data: &types::RouterData<F, T, types::PayoutsResponseData>,
) -> RouterResult<()> {
let db = &*state.store;
match payout_router_data.response.as_ref() {
Ok(payout_response_data) => {
let payout_attempt = &payout_data.payout_attempt;
let status = payout_response_data
.status
.unwrap_or(payout_attempt.status.to_owned());
let updated_payout_attempt = if helpers::is_payout_err_state(status) {
let (error_code, error_message) = (
payout_response_data.error_code.clone(),
payout_response_data.error_message.clone(),
);
let (unified_code, unified_message) = helpers::get_gsm_record(
state,
error_code.clone(),
error_message.clone(),
payout_data.payout_attempt.connector.clone(),
consts::PAYOUT_FLOW_STR,
)
.await
.map_or((None, None), |gsm| (gsm.unified_code, gsm.unified_message));
storage::PayoutAttemptUpdate::StatusUpdate {
connector_payout_id: payout_response_data.connector_payout_id.clone(),
status,
error_code,
error_message,
is_eligible: payout_response_data.payout_eligible,
unified_code: unified_code
.map(UnifiedCode::try_from)
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "unified_code",
})?,
unified_message: unified_message
.map(UnifiedMessage::try_from)
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "unified_message",
})?,
}
} else {
storage::PayoutAttemptUpdate::StatusUpdate {
connector_payout_id: payout_response_data.connector_payout_id.clone(),
status,
error_code: None,
error_message: None,
is_eligible: payout_response_data.payout_eligible,
unified_code: None,
unified_message: None,
}
};
payout_data.payout_attempt = db
.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 = db
.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")?;
}
Err(err) => {
// log in case of error in retrieval
logger::error!("Error in payout retrieval");
// show error in the response of sync
payout_data.payout_attempt.error_code = Some(err.code.to_owned());
payout_data.payout_attempt.error_message = Some(err.message.to_owned());
}
};
Ok(())
}
<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="1838" end="1857">
pub async fn complete_payout_retrieve(
state: &SessionState,
merchant_account: &domain::MerchantAccount,
connector_call_type: api::ConnectorCallType,
payout_data: &mut PayoutData,
) -> RouterResult<()> {
match connector_call_type {
api::ConnectorCallType::PreDetermined(connector_data) => {
create_payout_retrieve(state, merchant_account, &connector_data, payout_data)
.await
.attach_printable("Payout retrieval failed for given Payout request")?;
}
api::ConnectorCallType::Retryable(_) | api::ConnectorCallType::SessionMultiple(_) => {
Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Payout retrieval not supported for given ConnectorCallType")?
}
}
Ok(())
}
<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/crates/router/src/connector/utils.rs" role="context" start="1344" end="1350">
pub trait PayoutsData {
fn get_transfer_id(&self) -> Result<String, Error>;
fn get_customer_details(&self) -> Result<types::CustomerDetails, Error>;
fn get_vendor_details(&self) -> Result<PayoutVendorAccountDetails, Error>;
#[cfg(feature = "payouts")]
fn get_payout_type(&self) -> Result<storage_enums::PayoutType, Error>;
}
<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/payment_methods/vault.rs<|crate|> router anchor=add_delete_tokenized_data_task kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/vault.rs" role="context" start="1378" end="1417">
pub async fn add_delete_tokenized_data_task(
db: &dyn db::StorageInterface,
lookup_key: &str,
pm: enums::PaymentMethod,
) -> RouterResult<()> {
let runner = storage::ProcessTrackerRunner::DeleteTokenizeDataWorkflow;
let process_tracker_id = format!("{runner}_{lookup_key}");
let task = runner.to_string();
let tag = ["BASILISK-V3"];
let tracking_data = storage::TokenizeCoreWorkflow {
lookup_key: lookup_key.to_owned(),
pm,
};
let schedule_time = get_delete_tokenize_schedule_time(db, pm, 0)
.await
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to obtain initial process tracker schedule time")?;
let process_tracker_entry = storage::ProcessTrackerNew::new(
process_tracker_id,
&task,
runner,
tag,
tracking_data,
None,
schedule_time,
common_types::consts::API_VERSION,
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to construct delete tokenized data process tracker task")?;
let response = db.insert_process(process_tracker_entry).await;
response.map(|_| ()).or_else(|err| {
if err.current_context().is_db_unique_violation() {
Ok(())
} else {
Err(report!(errors::ApiErrorResponse::InternalServerError))
}
})
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/vault.rs" role="context" start="1377" end="1377">
use error_stack::{report, ResultExt};
use crate::{
consts,
core::errors::{self, CustomResult, RouterResult},
db, logger, routes,
routes::metrics,
types::{
api, domain,
storage::{self, enums},
},
utils::StringExt,
};
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/vault.rs" role="context" start="1455" end="1476">
pub async fn get_delete_tokenize_schedule_time(
db: &dyn db::StorageInterface,
pm: enums::PaymentMethod,
retry_count: i32,
) -> Option<time::PrimitiveDateTime> {
let redis_mapping = db::get_and_deserialize_key(
db,
&format!("pt_mapping_delete_{pm}_tokenize_data"),
"PaymentMethodsPTMapping",
)
.await;
let mapping = match redis_mapping {
Ok(x) => x,
Err(error) => {
logger::info!(?error, "Redis Mapping Error");
process_data::PaymentMethodsPTMapping::default()
}
};
let time_delta = process_tracker_utils::get_pm_schedule_time(mapping, pm, retry_count + 1);
process_tracker_utils::get_time_from_delta(time_delta)
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/vault.rs" role="context" start="1419" end="1453">
pub async fn start_tokenize_data_workflow(
state: &routes::SessionState,
tokenize_tracker: &storage::ProcessTracker,
) -> Result<(), errors::ProcessTrackerError> {
let db = &*state.store;
let delete_tokenize_data = serde_json::from_value::<storage::TokenizeCoreWorkflow>(
tokenize_tracker.tracking_data.clone(),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| {
format!(
"unable to convert into DeleteTokenizeByTokenRequest {:?}",
tokenize_tracker.tracking_data
)
})?;
match delete_tokenized_data(state, &delete_tokenize_data.lookup_key).await {
Ok(()) => {
logger::info!("Card From locker deleted Successfully");
//mark task as finished
db.as_scheduler()
.finish_process_with_business_status(
tokenize_tracker.clone(),
diesel_models::process_tracker::business_status::COMPLETED_BY_PT,
)
.await?;
}
Err(err) => {
logger::error!("Err: Deleting Card From Locker : {:?}", err);
retry_delete_tokenize(db, delete_tokenize_data.pm, tokenize_tracker.to_owned()).await?;
metrics::RETRIED_DELETE_DATA_COUNT.add(1, &[]);
}
}
Ok(())
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/vault.rs" role="context" start="1350" end="1374">
pub async fn delete_payment_method_data_from_vault(
state: &routes::SessionState,
merchant_account: &domain::MerchantAccount,
vault_id: domain::VaultId,
) -> CustomResult<pm_types::VaultDeleteResponse, errors::VaultError> {
let payload = pm_types::VaultDeleteRequest {
entity_id: merchant_account.get_id().to_owned(),
vault_id,
}
.encode_to_vec()
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode VaultDeleteRequest")?;
let resp = call_to_vault::<pm_types::VaultDelete>(state, payload)
.await
.change_context(errors::VaultError::VaultAPIError)
.attach_printable("Call to vault failed")?;
let stored_pm_resp: pm_types::VaultDeleteResponse = resp
.parse_struct("VaultDeleteResponse")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Failed to parse data into VaultDeleteResponse")?;
Ok(stored_pm_resp)
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/vault.rs" role="context" start="1316" end="1346">
pub async fn retrieve_payment_method_from_vault(
state: &routes::SessionState,
merchant_account: &domain::MerchantAccount,
pm: &domain::PaymentMethod,
) -> CustomResult<pm_types::VaultRetrieveResponse, errors::VaultError> {
let payload = pm_types::VaultRetrieveRequest {
entity_id: merchant_account.get_id().to_owned(),
vault_id: pm
.locker_id
.clone()
.ok_or(errors::VaultError::MissingRequiredField {
field_name: "locker_id",
})
.attach_printable("Missing locker_id for VaultRetrieveRequest")?,
}
.encode_to_vec()
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode VaultRetrieveRequest")?;
let resp = call_to_vault::<pm_types::VaultRetrieve>(state, payload)
.await
.change_context(errors::VaultError::VaultAPIError)
.attach_printable("Call to vault failed")?;
let stored_pm_resp: pm_types::VaultRetrieveResponse = resp
.parse_struct("VaultRetrieveResponse")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Failed to parse data into VaultRetrieveResponse")?;
Ok(stored_pm_resp)
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/vault.rs" role="context" start="903" end="934">
pub async fn store_payment_method_data_in_locker(
state: &routes::SessionState,
token_id: Option<String>,
payment_method: &domain::PaymentMethodData,
customer_id: Option<id_type::CustomerId>,
pm: enums::PaymentMethod,
merchant_key_store: &domain::MerchantKeyStore,
) -> RouterResult<String> {
let value1 = payment_method
.get_value1(customer_id.clone())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error getting Value1 for locker")?;
let value2 = payment_method
.get_value2(customer_id)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error getting Value12 for locker")?;
let lookup_key = token_id.unwrap_or_else(|| generate_id_with_default_len("token"));
let lookup_key = create_tokenize(
state,
value1,
Some(value2),
lookup_key,
merchant_key_store.key.get_inner(),
)
.await?;
add_delete_tokenized_data_task(&*state.store, &lookup_key, pm).await?;
metrics::TOKENIZED_DATA_COUNT.add(1, &[]);
Ok(lookup_key)
}
<file_sep path="hyperswitch/crates/router/src/connector/nmi/transformers.rs" role="context" start="454" end="459">
pub enum PaymentMethod {
CardNonThreeDs(Box<CardData>),
CardThreeDs(Box<CardThreeDsData>),
GPay(Box<GooglePayData>),
ApplePay(Box<ApplePayData>),
}
<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/payments.rs<|crate|> router anchor=tokenize_in_router_when_confirm_false_or_external_authentication kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="5264" end="5304">
pub async fn tokenize_in_router_when_confirm_false_or_external_authentication<F, Req, D>(
state: &SessionState,
operation: &BoxedOperation<'_, F, Req, D>,
payment_data: &mut D,
validate_result: &operations::ValidateResult,
merchant_key_store: &domain::MerchantKeyStore,
customer: &Option<domain::Customer>,
business_profile: &domain::Profile,
) -> RouterResult<D>
where
F: Send + Clone,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
{
// On confirm is false and only router related
let is_external_authentication_requested = payment_data
.get_payment_intent()
.request_external_three_ds_authentication;
let payment_data =
if !is_operation_confirm(operation) || is_external_authentication_requested == Some(true) {
let (_operation, payment_method_data, pm_id) = operation
.to_domain()?
.make_pm_data(
state,
payment_data,
validate_result.storage_scheme,
merchant_key_store,
customer,
business_profile,
false,
)
.await?;
payment_data.set_payment_method_data(payment_method_data);
if let Some(payment_method_id) = pm_id {
payment_data.set_payment_method_id_in_attempt(Some(payment_method_id));
}
payment_data
} else {
payment_data
};
Ok(payment_data.to_owned())
}
<file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="5263" end="5263">
merchant_key_store: &domain::MerchantKeyStore,
customer: &Option<domain::Customer>,
business_profile: &domain::Profile,
) -> RouterResult<D>
where
F: Send + Clone,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
{
todo!()
}
#[cfg(feature = "v1")]
pub async fn tokenize_in_router_when_confirm_false_or_external_authentication<F, Req, D>(
state: &SessionState,
operation: &BoxedOperation<'_, F, Req, D>,
payment_data: &mut D,
validate_result: &operations::ValidateResult,
merchant_key_store: &domain::MerchantKeyStore,
customer: &Option<domain::Customer>,
business_profile: &domain::Profile,
) -> RouterResult<D>
where
F: Send + Clone,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
{
<file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="5399" end="5404">
fn to_event(&self) -> PaymentEvent {
PaymentEvent {
payment_intent: self.payment_intent.clone(),
payment_attempt: self.payment_attempt.clone(),
}
}
<file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="5379" end="5397">
fn get_card_discovery_for_card_payment_method(&self) -> Option<common_enums::CardDiscovery> {
match self.payment_attempt.payment_method {
Some(storage_enums::PaymentMethod::Card) => {
if self
.token_data
.as_ref()
.map(storage::PaymentTokenData::is_permanent_card)
.unwrap_or(false)
{
Some(common_enums::CardDiscovery::SavedCard)
} else if self.service_details.is_some() {
Some(common_enums::CardDiscovery::ClickToPay)
} else {
Some(common_enums::CardDiscovery::Manual)
}
}
_ => None,
}
}
<file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="5247" end="5261">
pub async fn tokenize_in_router_when_confirm_false_or_external_authentication<F, Req, D>(
state: &SessionState,
operation: &BoxedOperation<'_, F, Req, D>,
payment_data: &mut D,
validate_result: &operations::ValidateResult,
merchant_key_store: &domain::MerchantKeyStore,
customer: &Option<domain::Customer>,
business_profile: &domain::Profile,
) -> RouterResult<D>
where
F: Send + Clone,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
{
todo!()
}
<file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="5102" end="5244">
pub async fn get_connector_tokenization_action_when_confirm_true<F, Req, D>(
state: &SessionState,
operation: &BoxedOperation<'_, F, Req, D>,
payment_data: &mut D,
validate_result: &operations::ValidateResult,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
merchant_key_store: &domain::MerchantKeyStore,
customer: &Option<domain::Customer>,
business_profile: &domain::Profile,
should_retry_with_pan: bool,
) -> RouterResult<(D, TokenizationAction)>
where
F: Send + Clone,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
{
let connector = payment_data.get_payment_attempt().connector.to_owned();
let is_mandate = payment_data
.get_mandate_id()
.as_ref()
.and_then(|inner| inner.mandate_reference_id.as_ref())
.map(|mandate_reference| match mandate_reference {
api_models::payments::MandateReferenceId::ConnectorMandateId(_) => true,
api_models::payments::MandateReferenceId::NetworkMandateId(_)
| api_models::payments::MandateReferenceId::NetworkTokenWithNTI(_) => false,
})
.unwrap_or(false);
let payment_data_and_tokenization_action = match connector {
Some(_) if is_mandate => (
payment_data.to_owned(),
TokenizationAction::SkipConnectorTokenization,
),
Some(connector) if is_operation_confirm(&operation) => {
let payment_method = payment_data
.get_payment_attempt()
.payment_method
.get_required_value("payment_method")?;
let payment_method_type = payment_data.get_payment_attempt().payment_method_type;
let apple_pay_flow =
decide_apple_pay_flow(state, payment_method_type, Some(merchant_connector_account));
let is_connector_tokenization_enabled =
is_payment_method_tokenization_enabled_for_connector(
state,
&connector,
payment_method,
payment_method_type,
&apple_pay_flow,
)?;
add_apple_pay_flow_metrics(
&apple_pay_flow,
payment_data.get_payment_attempt().connector.clone(),
payment_data.get_payment_attempt().merchant_id.clone(),
);
let payment_method_action = decide_payment_method_tokenize_action(
state,
&connector,
payment_method,
payment_data.get_token(),
is_connector_tokenization_enabled,
apple_pay_flow,
payment_method_type,
merchant_connector_account,
)
.await?;
let connector_tokenization_action = match payment_method_action {
TokenizationAction::TokenizeInRouter => {
let (_operation, payment_method_data, pm_id) = operation
.to_domain()?
.make_pm_data(
state,
payment_data,
validate_result.storage_scheme,
merchant_key_store,
customer,
business_profile,
should_retry_with_pan,
)
.await?;
payment_data.set_payment_method_data(payment_method_data);
payment_data.set_payment_method_id_in_attempt(pm_id);
TokenizationAction::SkipConnectorTokenization
}
TokenizationAction::TokenizeInConnector => TokenizationAction::TokenizeInConnector,
TokenizationAction::TokenizeInConnectorAndRouter => {
let (_operation, payment_method_data, pm_id) = operation
.to_domain()?
.make_pm_data(
state,
payment_data,
validate_result.storage_scheme,
merchant_key_store,
customer,
business_profile,
should_retry_with_pan,
)
.await?;
payment_data.set_payment_method_data(payment_method_data);
payment_data.set_payment_method_id_in_attempt(pm_id);
TokenizationAction::TokenizeInConnector
}
TokenizationAction::ConnectorToken(token) => {
payment_data.set_pm_token(token);
TokenizationAction::SkipConnectorTokenization
}
TokenizationAction::SkipConnectorTokenization => {
TokenizationAction::SkipConnectorTokenization
}
TokenizationAction::DecryptApplePayToken(payment_processing_details) => {
TokenizationAction::DecryptApplePayToken(payment_processing_details)
}
TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt(
payment_processing_details,
) => TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt(
payment_processing_details,
),
TokenizationAction::DecryptPazeToken(paze_payment_processing_details) => {
TokenizationAction::DecryptPazeToken(paze_payment_processing_details)
}
TokenizationAction::DecryptGooglePayToken(
google_pay_payment_processing_details,
) => {
TokenizationAction::DecryptGooglePayToken(google_pay_payment_processing_details)
}
};
(payment_data.to_owned(), connector_tokenization_action)
}
_ => (
payment_data.to_owned(),
TokenizationAction::SkipConnectorTokenization,
),
};
Ok(payment_data_and_tokenization_action)
}
<file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="258" end="893">
pub async fn payments_operation_core<F, Req, Op, FData, D>(
state: &SessionState,
req_state: ReqState,
merchant_account: domain::MerchantAccount,
profile_id_from_auth_layer: Option<id_type::ProfileId>,
key_store: domain::MerchantKeyStore,
operation: Op,
req: Req,
call_connector_action: CallConnectorAction,
auth_flow: services::AuthFlow,
eligible_connectors: Option<Vec<common_enums::RoutableConnectors>>,
header_payload: HeaderPayload,
platform_merchant_account: Option<domain::MerchantAccount>,
) -> RouterResult<(D, Req, Option<domain::Customer>, Option<u16>, Option<u128>)>
where
F: Send + Clone + Sync,
Req: Authenticate + Clone,
Op: Operation<F, Req, Data = D> + Send + Sync,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
// To create connector flow specific interface data
D: ConstructFlowSpecificData<F, FData, router_types::PaymentsResponseData>,
RouterData<F, FData, router_types::PaymentsResponseData>: Feature<F, FData>,
// To construct connector flow specific api
dyn api::Connector:
services::api::ConnectorIntegration<F, FData, router_types::PaymentsResponseData>,
// To perform router related operation for PaymentResponse
PaymentResponse: Operation<F, FData, Data = D>,
FData: Send + Sync + Clone,
{
let operation: BoxedOperation<'_, F, Req, D> = Box::new(operation);
tracing::Span::current().record("merchant_id", merchant_account.get_id().get_string_repr());
let (operation, validate_result) = operation
.to_validate_request()?
.validate_request(&req, &merchant_account)?;
tracing::Span::current().record("payment_id", format!("{}", validate_result.payment_id));
// get profile from headers
let operations::GetTrackerResponse {
operation,
customer_details,
mut payment_data,
business_profile,
mandate_type,
} = operation
.to_get_tracker()?
.get_trackers(
state,
&validate_result.payment_id,
&req,
&merchant_account,
&key_store,
auth_flow,
&header_payload,
platform_merchant_account.as_ref(),
)
.await?;
operation
.to_get_tracker()?
.validate_request_with_state(state, &req, &mut payment_data, &business_profile)
.await?;
core_utils::validate_profile_id_from_auth_layer(
profile_id_from_auth_layer,
&payment_data.get_payment_intent().clone(),
)?;
let (operation, customer) = operation
.to_domain()?
// get_customer_details
.get_or_create_customer_details(
state,
&mut payment_data,
customer_details,
&key_store,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)
.attach_printable("Failed while fetching/creating customer")?;
let authentication_type =
call_decision_manager(state, &merchant_account, &business_profile, &payment_data).await?;
payment_data.set_authentication_type_in_attempt(authentication_type);
let connector = get_connector_choice(
&operation,
state,
&req,
&merchant_account,
&business_profile,
&key_store,
&mut payment_data,
eligible_connectors,
mandate_type,
)
.await?;
let should_add_task_to_process_tracker = should_add_task_to_process_tracker(&payment_data);
let locale = header_payload.locale.clone();
payment_data = tokenize_in_router_when_confirm_false_or_external_authentication(
state,
&operation,
&mut payment_data,
&validate_result,
&key_store,
&customer,
&business_profile,
)
.await?;
let mut connector_http_status_code = None;
let mut external_latency = None;
if let Some(connector_details) = connector {
// Fetch and check FRM configs
#[cfg(feature = "frm")]
let mut frm_info = None;
#[allow(unused_variables, unused_mut)]
let mut should_continue_transaction: bool = true;
#[cfg(feature = "frm")]
let mut should_continue_capture: bool = true;
#[cfg(feature = "frm")]
let frm_configs = if state.conf.frm.enabled {
Box::pin(frm_core::call_frm_before_connector_call(
&operation,
&merchant_account,
&mut payment_data,
state,
&mut frm_info,
&customer,
&mut should_continue_transaction,
&mut should_continue_capture,
key_store.clone(),
))
.await?
} else {
None
};
#[cfg(feature = "frm")]
logger::debug!(
"frm_configs: {:?}\nshould_continue_transaction: {:?}\nshould_continue_capture: {:?}",
frm_configs,
should_continue_transaction,
should_continue_capture,
);
let is_eligible_for_uas =
helpers::is_merchant_eligible_authentication_service(merchant_account.get_id(), state)
.await?;
if is_eligible_for_uas {
let should_do_uas_confirmation_call = false;
operation
.to_domain()?
.call_unified_authentication_service_if_eligible(
state,
&mut payment_data,
&mut should_continue_transaction,
&connector_details,
&business_profile,
&key_store,
mandate_type,
&should_do_uas_confirmation_call,
)
.await?;
} else {
logger::info!(
"skipping authentication service call since the merchant is not eligible."
);
operation
.to_domain()?
.call_external_three_ds_authentication_if_eligible(
state,
&mut payment_data,
&mut should_continue_transaction,
&connector_details,
&business_profile,
&key_store,
mandate_type,
)
.await?;
};
operation
.to_domain()?
.payments_dynamic_tax_calculation(
state,
&mut payment_data,
&connector_details,
&business_profile,
&key_store,
&merchant_account,
)
.await?;
if should_continue_transaction {
#[cfg(feature = "frm")]
match (
should_continue_capture,
payment_data.get_payment_attempt().capture_method,
) {
(
false,
Some(storage_enums::CaptureMethod::Automatic)
| Some(storage_enums::CaptureMethod::SequentialAutomatic),
)
| (false, Some(storage_enums::CaptureMethod::Scheduled)) => {
if let Some(info) = &mut frm_info {
if let Some(frm_data) = &mut info.frm_data {
frm_data.fraud_check.payment_capture_method =
payment_data.get_payment_attempt().capture_method;
}
}
payment_data
.set_capture_method_in_attempt(storage_enums::CaptureMethod::Manual);
logger::debug!("payment_id : {:?} capture method has been changed to manual, since it has configured Post FRM flow",payment_data.get_payment_attempt().payment_id);
}
_ => (),
};
payment_data = match connector_details {
ConnectorCallType::PreDetermined(ref connector) => {
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
let routable_connectors =
convert_connector_data_to_routable_connectors(&[connector.clone()])
.map_err(|e| logger::error!(routable_connector_error=?e))
.unwrap_or_default();
let schedule_time = if should_add_task_to_process_tracker {
payment_sync::get_sync_process_schedule_time(
&*state.store,
connector.connector.id(),
merchant_account.get_id(),
0,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while getting process schedule time")?
} else {
None
};
let (router_data, mca) = call_connector_service(
state,
req_state.clone(),
&merchant_account,
&key_store,
connector.clone(),
&operation,
&mut payment_data,
&customer,
call_connector_action.clone(),
&validate_result,
schedule_time,
header_payload.clone(),
#[cfg(feature = "frm")]
frm_info.as_ref().and_then(|fi| fi.suggested_action),
#[cfg(not(feature = "frm"))]
None,
&business_profile,
false,
false,
)
.await?;
if is_eligible_for_uas {
let should_do_uas_confirmation_call = true;
operation
.to_domain()?
.call_unified_authentication_service_if_eligible(
state,
&mut payment_data,
&mut should_continue_transaction,
&connector_details,
&business_profile,
&key_store,
mandate_type,
&should_do_uas_confirmation_call,
)
.await?;
}
let op_ref = &operation;
let should_trigger_post_processing_flows = is_operation_confirm(&operation);
let operation = Box::new(PaymentResponse);
connector_http_status_code = router_data.connector_http_status_code;
external_latency = router_data.external_latency;
//add connector http status code metrics
add_connector_http_status_code_metrics(connector_http_status_code);
operation
.to_post_update_tracker()?
.save_pm_and_mandate(
state,
&router_data,
&merchant_account,
&key_store,
&mut payment_data,
&business_profile,
)
.await?;
let mut payment_data = operation
.to_post_update_tracker()?
.update_tracker(
state,
payment_data,
router_data,
&key_store,
merchant_account.storage_scheme,
&locale,
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
routable_connectors,
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
&business_profile,
)
.await?;
if should_trigger_post_processing_flows {
complete_postprocessing_steps_if_required(
state,
&merchant_account,
&key_store,
&customer,
&mca,
connector,
&mut payment_data,
op_ref,
Some(header_payload.clone()),
)
.await?;
}
payment_data
}
ConnectorCallType::Retryable(ref connectors) => {
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
let routable_connectors =
convert_connector_data_to_routable_connectors(connectors)
.map_err(|e| logger::error!(routable_connector_error=?e))
.unwrap_or_default();
let mut connectors = connectors.clone().into_iter();
let connector_data = get_connector_data(&mut connectors)?;
let schedule_time = if should_add_task_to_process_tracker {
payment_sync::get_sync_process_schedule_time(
&*state.store,
connector_data.connector.id(),
merchant_account.get_id(),
0,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while getting process schedule time")?
} else {
None
};
let (router_data, mca) = call_connector_service(
state,
req_state.clone(),
&merchant_account,
&key_store,
connector_data.clone(),
&operation,
&mut payment_data,
&customer,
call_connector_action.clone(),
&validate_result,
schedule_time,
header_payload.clone(),
#[cfg(feature = "frm")]
frm_info.as_ref().and_then(|fi| fi.suggested_action),
#[cfg(not(feature = "frm"))]
None,
&business_profile,
false,
false,
)
.await?;
#[cfg(all(feature = "retry", feature = "v1"))]
let mut router_data = router_data;
#[cfg(all(feature = "retry", feature = "v1"))]
{
use crate::core::payments::retry::{self, GsmValidation};
let config_bool = retry::config_should_call_gsm(
&*state.store,
merchant_account.get_id(),
&business_profile,
)
.await;
if config_bool && router_data.should_call_gsm() {
router_data = retry::do_gsm_actions(
state,
req_state.clone(),
&mut payment_data,
connectors,
&connector_data,
router_data,
&merchant_account,
&key_store,
&operation,
&customer,
&validate_result,
schedule_time,
#[cfg(feature = "frm")]
frm_info.as_ref().and_then(|fi| fi.suggested_action),
#[cfg(not(feature = "frm"))]
None,
&business_profile,
)
.await?;
};
}
let op_ref = &operation;
let should_trigger_post_processing_flows = is_operation_confirm(&operation);
if is_eligible_for_uas {
let should_do_uas_confirmation_call = true;
operation
.to_domain()?
.call_unified_authentication_service_if_eligible(
state,
&mut payment_data,
&mut should_continue_transaction,
&connector_details,
&business_profile,
&key_store,
mandate_type,
&should_do_uas_confirmation_call,
)
.await?;
}
let operation = Box::new(PaymentResponse);
connector_http_status_code = router_data.connector_http_status_code;
external_latency = router_data.external_latency;
//add connector http status code metrics
add_connector_http_status_code_metrics(connector_http_status_code);
operation
.to_post_update_tracker()?
.save_pm_and_mandate(
state,
&router_data,
&merchant_account,
&key_store,
&mut payment_data,
&business_profile,
)
.await?;
let mut payment_data = operation
.to_post_update_tracker()?
.update_tracker(
state,
payment_data,
router_data,
&key_store,
merchant_account.storage_scheme,
&locale,
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
routable_connectors,
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
&business_profile,
)
.await?;
if should_trigger_post_processing_flows {
complete_postprocessing_steps_if_required(
state,
&merchant_account,
&key_store,
&customer,
&mca,
&connector_data,
&mut payment_data,
op_ref,
Some(header_payload.clone()),
)
.await?;
}
payment_data
}
ConnectorCallType::SessionMultiple(connectors) => {
let session_surcharge_details =
call_surcharge_decision_management_for_session_flow(
state,
&merchant_account,
&business_profile,
payment_data.get_payment_attempt(),
payment_data.get_payment_intent(),
payment_data.get_billing_address(),
&connectors,
)
.await?;
Box::pin(call_multiple_connectors_service(
state,
&merchant_account,
&key_store,
connectors,
&operation,
payment_data,
&customer,
session_surcharge_details,
&business_profile,
header_payload.clone(),
))
.await?
}
};
#[cfg(feature = "frm")]
if let Some(fraud_info) = &mut frm_info {
#[cfg(feature = "v1")]
Box::pin(frm_core::post_payment_frm_core(
state,
req_state,
&merchant_account,
&mut payment_data,
fraud_info,
frm_configs
.clone()
.ok_or(errors::ApiErrorResponse::MissingRequiredField {
field_name: "frm_configs",
})
.attach_printable("Frm configs label not found")?,
&customer,
key_store.clone(),
&mut should_continue_capture,
platform_merchant_account.as_ref(),
))
.await?;
}
} else {
(_, payment_data) = operation
.to_update_tracker()?
.update_trackers(
state,
req_state,
payment_data.clone(),
customer.clone(),
validate_result.storage_scheme,
None,
&key_store,
#[cfg(feature = "frm")]
frm_info.and_then(|info| info.suggested_action),
#[cfg(not(feature = "frm"))]
None,
header_payload.clone(),
)
.await?;
}
let payment_intent_status = payment_data.get_payment_intent().status;
payment_data
.get_payment_attempt()
.payment_token
.as_ref()
.zip(payment_data.get_payment_attempt().payment_method)
.map(ParentPaymentMethodToken::create_key_for_token)
.async_map(|key_for_hyperswitch_token| async move {
if key_for_hyperswitch_token
.should_delete_payment_method_token(payment_intent_status)
{
let _ = key_for_hyperswitch_token.delete(state).await;
}
})
.await;
} else {
(_, payment_data) = operation
.to_update_tracker()?
.update_trackers(
state,
req_state,
payment_data.clone(),
customer.clone(),
validate_result.storage_scheme,
None,
&key_store,
None,
header_payload.clone(),
)
.await?;
}
let cloned_payment_data = payment_data.clone();
let cloned_customer = customer.clone();
#[cfg(feature = "v1")]
operation
.to_domain()?
.store_extended_card_info_temporarily(
state,
payment_data.get_payment_intent().get_id(),
&business_profile,
payment_data.get_payment_method_data(),
)
.await?;
utils::trigger_payments_webhook(
merchant_account,
business_profile,
&key_store,
cloned_payment_data,
cloned_customer,
state,
operation,
)
.await
.map_err(|error| logger::warn!(payments_outgoing_webhook_error=?error))
.ok();
Ok((
payment_data,
req,
customer,
connector_http_status_code,
external_latency,
))
}
<file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="5561" end="5563">
pub fn is_operation_confirm<Op: Debug>(operation: &Op) -> bool {
matches!(format!("{operation:?}").as_str(), "PaymentConfirm")
}
<file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="8054" end="8097">
pub trait OperationSessionSetters<F> {
// Setter functions for PaymentData
fn set_payment_intent(&mut self, payment_intent: storage::PaymentIntent);
fn set_payment_attempt(&mut self, payment_attempt: storage::PaymentAttempt);
fn set_payment_method_data(&mut self, payment_method_data: Option<domain::PaymentMethodData>);
fn set_email_if_not_present(&mut self, email: pii::Email);
fn set_payment_method_id_in_attempt(&mut self, payment_method_id: Option<String>);
fn set_pm_token(&mut self, token: String);
fn set_connector_customer_id(&mut self, customer_id: Option<String>);
fn push_sessions_token(&mut self, token: api::SessionToken);
fn set_surcharge_details(&mut self, surcharge_details: Option<types::SurchargeDetails>);
fn set_merchant_connector_id_in_attempt(
&mut self,
merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
);
#[cfg(feature = "v1")]
fn set_capture_method_in_attempt(&mut self, capture_method: enums::CaptureMethod);
fn set_frm_message(&mut self, frm_message: FraudCheck);
fn set_payment_intent_status(&mut self, status: storage_enums::IntentStatus);
fn set_authentication_type_in_attempt(
&mut self,
authentication_type: Option<enums::AuthenticationType>,
);
fn set_recurring_mandate_payment_data(
&mut self,
recurring_mandate_payment_data:
hyperswitch_domain_models::router_data::RecurringMandatePaymentData,
);
fn set_mandate_id(&mut self, mandate_id: api_models::payments::MandateIds);
fn set_setup_future_usage_in_payment_intent(
&mut self,
setup_future_usage: storage_enums::FutureUsage,
);
#[cfg(feature = "v1")]
fn set_straight_through_algorithm_in_payment_attempt(
&mut self,
straight_through_algorithm: serde_json::Value,
);
fn set_connector_in_payment_attempt(&mut self, connector: Option<String>);
#[cfg(feature = "v1")]
fn set_vault_operation(&mut self, vault_operation: domain_payments::VaultOperation);
}
<file_sep path="hyperswitch/crates/router/src/core/payments.rs" role="context" start="8013" end="8052">
pub trait OperationSessionGetters<F> {
fn get_payment_attempt(&self) -> &storage::PaymentAttempt;
fn get_payment_intent(&self) -> &storage::PaymentIntent;
fn get_payment_method_info(&self) -> Option<&domain::PaymentMethod>;
fn get_mandate_id(&self) -> Option<&payments_api::MandateIds>;
fn get_address(&self) -> &PaymentAddress;
fn get_creds_identifier(&self) -> Option<&str>;
fn get_token(&self) -> Option<&str>;
fn get_multiple_capture_data(&self) -> Option<&types::MultipleCaptureData>;
fn get_payment_link_data(&self) -> Option<api_models::payments::PaymentLinkResponse>;
fn get_ephemeral_key(&self) -> Option<ephemeral_key::EphemeralKey>;
fn get_setup_mandate(&self) -> Option<&MandateData>;
fn get_poll_config(&self) -> Option<router_types::PollConfig>;
fn get_authentication(&self) -> Option<&storage::Authentication>;
fn get_frm_message(&self) -> Option<FraudCheck>;
fn get_refunds(&self) -> Vec<storage::Refund>;
fn get_disputes(&self) -> Vec<storage::Dispute>;
fn get_authorizations(&self) -> Vec<diesel_models::authorization::Authorization>;
fn get_attempts(&self) -> Option<Vec<storage::PaymentAttempt>>;
fn get_recurring_details(&self) -> Option<&RecurringDetails>;
// TODO: this should be a mandatory field, should we throw an error instead of returning an Option?
fn get_payment_intent_profile_id(&self) -> Option<&id_type::ProfileId>;
fn get_currency(&self) -> storage_enums::Currency;
fn get_amount(&self) -> api::Amount;
fn get_payment_attempt_connector(&self) -> Option<&str>;
fn get_billing_address(&self) -> Option<hyperswitch_domain_models::address::Address>;
fn get_payment_method_data(&self) -> Option<&domain::PaymentMethodData>;
fn get_sessions_token(&self) -> Vec<api::SessionToken>;
fn get_token_data(&self) -> Option<&storage::PaymentTokenData>;
fn get_mandate_connector(&self) -> Option<&MandateConnectorDetails>;
fn get_force_sync(&self) -> Option<bool>;
fn get_capture_method(&self) -> Option<enums::CaptureMethod>;
fn get_merchant_connector_id_in_attempt(&self) -> Option<id_type::MerchantConnectorAccountId>;
#[cfg(feature = "v1")]
fn get_vault_operation(&self) -> Option<&domain_payments::VaultOperation>;
#[cfg(feature = "v2")]
fn get_optional_payment_attempt(&self) -> Option<&storage::PaymentAttempt>;
}
<file_sep path="hyperswitch/crates/router/src/routes/app.rs" role="context" start="1906" end="1906">
pub struct Profile;
<file_sep path="hyperswitch/v2_compatible_migrations/2024-08-28-081721_add_v2_columns/up.sql" role="context" start="1" end="11">
-- This file contains all new columns being added as part of v2 refactoring.
-- The new columns added should work with both v1 and v2 applications.
ALTER TABLE customers
ADD COLUMN IF NOT EXISTS merchant_reference_id VARCHAR(64),
ADD COLUMN IF NOT EXISTS default_billing_address BYTEA DEFAULT NULL,
ADD COLUMN IF NOT EXISTS default_shipping_address BYTEA DEFAULT NULL,
ADD COLUMN IF NOT EXISTS status "DeleteStatus";
CREATE TYPE "OrderFulfillmentTimeOrigin" AS ENUM ('create', 'confirm');
ALTER TABLE business_profile
<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/card_testing_guard/utils.rs<|crate|> router anchor=increment_blocked_count_in_cache kind=fn pack=symbol_neighborhood lang=rust role_window=k2 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/card_testing_guard/utils.rs" role="context" start="151" end="196">
pub async fn increment_blocked_count_in_cache(
state: &SessionState,
card_testing_guard_data: Option<CardTestingGuardData>,
) -> RouterResult<()> {
if let Some(card_testing_guard_data) = card_testing_guard_data.clone() {
if card_testing_guard_data.is_card_ip_blocking_enabled
&& !card_testing_guard_data
.card_ip_blocking_cache_key
.is_empty()
{
let _ = services::card_testing_guard::increment_blocked_count_in_cache(
state,
&card_testing_guard_data.card_ip_blocking_cache_key,
card_testing_guard_data.card_testing_guard_expiry.into(),
)
.await;
}
if card_testing_guard_data.is_guest_user_card_blocking_enabled
&& !card_testing_guard_data
.guest_user_card_blocking_cache_key
.is_empty()
{
let _ = services::card_testing_guard::increment_blocked_count_in_cache(
state,
&card_testing_guard_data.guest_user_card_blocking_cache_key,
card_testing_guard_data.card_testing_guard_expiry.into(),
)
.await;
}
if card_testing_guard_data.is_customer_id_blocking_enabled
&& !card_testing_guard_data
.customer_id_blocking_cache_key
.is_empty()
{
let _ = services::card_testing_guard::increment_blocked_count_in_cache(
state,
&card_testing_guard_data.customer_id_blocking_cache_key,
card_testing_guard_data.card_testing_guard_expiry.into(),
)
.await;
}
}
Ok(())
}
<file_sep path="hyperswitch/crates/router/src/core/card_testing_guard/utils.rs" role="context" start="150" end="150">
use hyperswitch_domain_models::{
card_testing_guard_data::CardTestingGuardData, router_request_types::BrowserInformation,
};
use crate::{
core::{errors::RouterResult, payments::helpers},
routes::SessionState,
services,
types::{api, domain},
utils::crypto::{self, SignMessage},
};
<file_sep path="hyperswitch/crates/router/src/core/card_testing_guard/utils.rs" role="context" start="111" end="149">
pub async fn generate_fingerprint(
payment_method_data: Option<&api_models::payments::PaymentMethodData>,
business_profile: &domain::Profile,
) -> RouterResult<Secret<String>> {
let card_testing_secret_key = &business_profile.card_testing_secret_key;
match card_testing_secret_key {
Some(card_testing_secret_key) => {
let card_number_fingerprint = payment_method_data
.as_ref()
.and_then(|pm_data| match pm_data {
api_models::payments::PaymentMethodData::Card(card) => {
crypto::HmacSha512::sign_message(
&crypto::HmacSha512,
card_testing_secret_key.get_inner().peek().as_bytes(),
card.card_number.clone().get_card_no().as_bytes(),
)
.attach_printable("error in pm fingerprint creation")
.map_or_else(
|err| {
logger::error!(error=?err);
None
},
Some,
)
}
_ => None,
})
.map(hex::encode);
card_number_fingerprint.map(Secret::new).ok_or_else(|| {
error_stack::report!(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error while masking fingerprint")
})
}
None => Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable("card testing secret key not configured")?,
}
}
<file_sep path="hyperswitch/crates/router/src/core/card_testing_guard/utils.rs" role="context" start="17" end="109">
pub async fn validate_card_testing_guard_checks(
state: &SessionState,
request: &api::PaymentsRequest,
payment_method_data: Option<&api_models::payments::PaymentMethodData>,
customer_id: &Option<common_utils::id_type::CustomerId>,
business_profile: &domain::Profile,
) -> RouterResult<Option<CardTestingGuardData>> {
match &business_profile.card_testing_guard_config {
Some(card_testing_guard_config) => {
let fingerprint = generate_fingerprint(payment_method_data, business_profile).await?;
let card_testing_guard_expiry = card_testing_guard_config.card_testing_guard_expiry;
let mut card_ip_blocking_cache_key = String::new();
let mut guest_user_card_blocking_cache_key = String::new();
let mut customer_id_blocking_cache_key = String::new();
if card_testing_guard_config.is_card_ip_blocking_enabled {
if let Some(browser_info) = &request.browser_info {
#[cfg(feature = "v1")]
{
let browser_info =
serde_json::from_value::<BrowserInformation>(browser_info.clone())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("could not parse browser_info")?;
if let Some(browser_info_ip) = browser_info.ip_address {
card_ip_blocking_cache_key =
helpers::validate_card_ip_blocking_for_business_profile(
state,
browser_info_ip,
fingerprint.clone(),
card_testing_guard_config,
)
.await?;
}
}
#[cfg(feature = "v2")]
{
if let Some(browser_info_ip) = browser_info.ip_address {
card_ip_blocking_cache_key =
helpers::validate_card_ip_blocking_for_business_profile(
state,
browser_info_ip,
fingerprint.clone(),
card_testing_guard_config,
)
.await?;
}
}
}
}
if card_testing_guard_config.is_guest_user_card_blocking_enabled {
guest_user_card_blocking_cache_key =
helpers::validate_guest_user_card_blocking_for_business_profile(
state,
fingerprint.clone(),
customer_id.clone(),
card_testing_guard_config,
)
.await?;
}
if card_testing_guard_config.is_customer_id_blocking_enabled {
if let Some(customer_id) = customer_id.clone() {
customer_id_blocking_cache_key =
helpers::validate_customer_id_blocking_for_business_profile(
state,
customer_id.clone(),
business_profile.get_id(),
card_testing_guard_config,
)
.await?;
}
}
Ok(Some(CardTestingGuardData {
is_card_ip_blocking_enabled: card_testing_guard_config.is_card_ip_blocking_enabled,
card_ip_blocking_cache_key,
is_guest_user_card_blocking_enabled: card_testing_guard_config
.is_guest_user_card_blocking_enabled,
guest_user_card_blocking_cache_key,
is_customer_id_blocking_enabled: card_testing_guard_config
.is_customer_id_blocking_enabled,
customer_id_blocking_cache_key,
card_testing_guard_expiry,
}))
}
None => Ok(None),
}
}
<file_sep path="hyperswitch/crates/router/src/core/errors.rs" role="context" start="31" end="31">
pub type RouterResult<T> = CustomResult<T, ApiErrorResponse>;
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/api_keys.rs<|crate|> router anchor=keyed_hash kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/api_keys.rs" role="context" start="78" end="108">
pub fn keyed_hash(&self, key: &[u8; Self::HASH_KEY_LEN]) -> HashedApiKey {
/*
Decisions regarding API key hashing algorithm chosen:
- Since API key hash verification would be done for each request, there is a requirement
for the hashing to be quick.
- Password hashing algorithms would not be suitable for this purpose as they're designed to
prevent brute force attacks, considering that the same password could be shared across
multiple sites by the user.
- Moreover, password hash verification happens once per user session, so the delay involved
is negligible, considering the security benefits it provides.
While with API keys (assuming uniqueness of keys across the application), the delay
involved in hashing (with the use of a password hashing algorithm) becomes significant,
considering that it must be done per request.
- Since we are the only ones generating API keys and are able to guarantee their uniqueness,
a simple hash algorithm is sufficient for this purpose.
Hash algorithms considered:
- Password hashing algorithms: Argon2id and PBKDF2
- Simple hashing algorithms: HMAC-SHA256, HMAC-SHA512, BLAKE3
After benchmarking the simple hashing algorithms, we decided to go with the BLAKE3 keyed
hashing algorithm, with a randomly generated key for the hash key.
*/
HashedApiKey(
blake3::keyed_hash(key, self.0.peek().as_bytes())
.to_hex()
.to_string(),
)
}
<file_sep path="hyperswitch/crates/router/src/core/api_keys.rs" role="context" start="77" end="77">
use common_utils::date_time;
use diesel_models::{api_keys::ApiKey, enums as storage_enums};
use error_stack::{report, ResultExt};
use masking::{PeekInterface, StrongSecret};
use router_env::{instrument, tracing};
use crate::{
configs::settings,
consts,
core::errors::{self, RouterResponse, StorageErrorExt},
db::domain,
routes::{metrics, SessionState},
services::{authentication, ApplicationResponse},
types::{api, storage, transformers::ForeignInto},
};
<file_sep path="hyperswitch/crates/router/src/core/api_keys.rs" role="context" start="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="112" end="184">
pub async fn create_api_key(
state: SessionState,
api_key: api::CreateApiKeyRequest,
key_store: domain::MerchantKeyStore,
) -> RouterResponse<api::CreateApiKeyResponse> {
let api_key_config = state.conf.api_keys.get_inner();
let store = state.store.as_ref();
let merchant_id = key_store.merchant_id.clone();
let hash_key = api_key_config.get_hash_key()?;
let plaintext_api_key = PlaintextApiKey::new(consts::API_KEY_LENGTH);
let api_key = storage::ApiKeyNew {
key_id: PlaintextApiKey::new_key_id(),
merchant_id: merchant_id.to_owned(),
name: api_key.name,
description: api_key.description,
hashed_api_key: plaintext_api_key.keyed_hash(hash_key.peek()).into(),
prefix: plaintext_api_key.prefix(),
created_at: date_time::now(),
expires_at: api_key.expiration.into(),
last_used: None,
};
let api_key = store
.insert_api_key(api_key)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to insert new API key")?;
let state_inner = state.clone();
let hashed_api_key = api_key.hashed_api_key.clone();
let merchant_id_inner = merchant_id.clone();
let key_id = api_key.key_id.clone();
let expires_at = api_key.expires_at;
authentication::decision::spawn_tracked_job(
async move {
authentication::decision::add_api_key(
&state_inner,
hashed_api_key.into_inner().into(),
merchant_id_inner,
key_id,
expires_at.map(authentication::decision::convert_expiry),
)
.await
},
authentication::decision::ADD,
);
metrics::API_KEY_CREATED.add(
1,
router_env::metric_attributes!(("merchant", merchant_id.clone())),
);
// Add process to process_tracker for email reminder, only if expiry is set to future date
// If the `api_key` is set to expire in less than 7 days, the merchant is not notified about it's expiry
#[cfg(feature = "email")]
{
if api_key.expires_at.is_some() {
let expiry_reminder_days = state.conf.api_keys.get_inner().expiry_reminder_days.clone();
add_api_key_expiry_task(store, &api_key, expiry_reminder_days)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to insert API key expiry reminder to process tracker")?;
}
}
Ok(ApplicationResponse::Json(
(api_key, plaintext_api_key).foreign_into(),
))
}
<file_sep path="hyperswitch/crates/router/src/core/api_keys.rs" role="context" start="74" end="76">
pub fn peek(&self) -> &str {
self.0.peek()
}
<file_sep path="hyperswitch/crates/router/src/core/api_keys.rs" role="context" start="70" end="72">
pub fn prefix(&self) -> String {
self.0.peek().chars().take(Self::PREFIX_LEN).collect()
}
<file_sep path="hyperswitch/crates/router/src/core/api_keys.rs" role="context" start="52" end="52">
pub struct HashedApiKey(String);
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/webhooks/incoming.rs<|crate|> router anchor=relay_incoming_webhook_flow 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="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="1078" end="1078">
use api_models::webhooks::{self, WebhookResponseTracker};
use common_utils::{errors::ReportSwitchExt, events::ApiEventsType};
use hyperswitch_interfaces::webhooks::{IncomingWebhookFlowError, IncomingWebhookRequestDetails};
use super::{types, utils, MERCHANT_ID};
use crate::{
consts,
core::{
api_locking,
errors::{self, ConnectorErrorExt, CustomResult, RouterResponse, StorageErrorExt},
metrics,
payments::{self, tokenization},
refunds, relay, utils as core_utils,
webhooks::utils::construct_webhook_router_data,
},
db::StorageInterface,
events::api_logs::ApiEvent,
logger,
routes::{
app::{ReqState, SessionStateInfo},
lock_utils, SessionState,
},
services::{
self, authentication as auth, connector_integration_interface::ConnectorEnum,
ConnectorValidation,
},
types::{
api::{
self, mandates::MandateResponseExt, ConnectorCommon, ConnectorData, GetToken,
IncomingWebhook,
},
domain,
storage::{self, enums},
transformers::{ForeignFrom, ForeignInto, ForeignTryFrom},
},
utils::{self as helper_utils, ext_traits::OptionExt, generate_id},
};
use crate::{core::payouts, types::storage::PayoutAttemptUpdate};
<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="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="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="886" end="975">
async fn relay_refunds_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 db = &*state.store;
let key_manager_state = &(&state).into();
let relay_record = match webhook_details.object_reference_id {
webhooks::ObjectReferenceId::RefundId(refund_id_type) => match refund_id_type {
webhooks::RefundIdType::RefundId(refund_id) => {
let relay_id = common_utils::id_type::RelayId::from_str(&refund_id)
.change_context(errors::ValidationError::IncorrectValueProvided {
field_name: "relay_id",
})
.change_context(errors::ApiErrorResponse::InternalServerError)?;
db.find_relay_by_id(key_manager_state, &merchant_key_store, &relay_id)
.await
.to_not_found_response(errors::ApiErrorResponse::WebhookResourceNotFound)
.attach_printable("Failed to fetch the relay record")?
}
webhooks::RefundIdType::ConnectorRefundId(connector_refund_id) => db
.find_relay_by_profile_id_connector_reference_id(
key_manager_state,
&merchant_key_store,
business_profile.get_id(),
&connector_refund_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::WebhookResourceNotFound)
.attach_printable("Failed to fetch the relay record")?,
},
_ => Err(errors::ApiErrorResponse::WebhookProcessingFailure)
.attach_printable("received a non-refund id when processing relay refund webhooks")?,
};
// if source_verified then update relay status else trigger relay force sync
let relay_response = if source_verified {
let relay_update = hyperswitch_domain_models::relay::RelayUpdate::StatusUpdate {
connector_reference_id: None,
status: common_enums::RelayStatus::foreign_try_from(event_type)
.change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
.attach_printable("failed relay refund status mapping from event type")?,
};
db.update_relay(
key_manager_state,
&merchant_key_store,
relay_record,
relay_update,
)
.await
.map(api_models::relay::RelayResponse::from)
.to_not_found_response(errors::ApiErrorResponse::WebhookResourceNotFound)
.attach_printable("Failed to update relay")?
} else {
let relay_retrieve_request = api_models::relay::RelayRetrieveRequest {
force_sync: true,
id: relay_record.id,
};
let relay_force_sync_response = Box::pin(relay::relay_retrieve(
state,
merchant_account,
Some(business_profile.get_id().clone()),
merchant_key_store,
relay_retrieve_request,
))
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to force sync relay")?;
if let hyperswitch_domain_models::api::ApplicationResponse::Json(response) =
relay_force_sync_response
{
response
} else {
Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unexpected response from force sync relay")?
}
};
Ok(WebhookResponseTracker::Relay {
relay_id: relay_response.id,
status: relay_response.status,
})
}
<file_sep path="hyperswitch/crates/router/src/core/webhooks/incoming.rs" role="context" start="126" end="556">
async fn incoming_webhooks_core<W: types::OutgoingWebhookType>(
state: SessionState,
req_state: ReqState,
req: &actix_web::HttpRequest,
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
connector_name_or_mca_id: &str,
body: actix_web::web::Bytes,
is_relay_webhook: bool,
) -> errors::RouterResult<(
services::ApplicationResponse<serde_json::Value>,
WebhookResponseTracker,
serde_json::Value,
)> {
let key_manager_state = &(&state).into();
metrics::WEBHOOK_INCOMING_COUNT.add(
1,
router_env::metric_attributes!((MERCHANT_ID, merchant_account.get_id().clone())),
);
let mut request_details = IncomingWebhookRequestDetails {
method: req.method().clone(),
uri: req.uri().clone(),
headers: req.headers(),
query_params: req.query_string().to_string(),
body: &body,
};
// Fetch the merchant connector account to get the webhooks source secret
// `webhooks source secret` is a secret shared between the merchant and connector
// This is used for source verification and webhooks integrity
let (merchant_connector_account, connector, connector_name) = fetch_optional_mca_and_connector(
&state,
&merchant_account,
connector_name_or_mca_id,
&key_store,
)
.await?;
let decoded_body = connector
.decode_webhook_body(
&request_details,
merchant_account.get_id(),
merchant_connector_account
.clone()
.and_then(|merchant_connector_account| {
merchant_connector_account.connector_webhook_details
}),
connector_name.as_str(),
)
.await
.switch()
.attach_printable("There was an error in incoming webhook body decoding")?;
request_details.body = &decoded_body;
let event_type = match connector
.get_webhook_event_type(&request_details)
.allow_webhook_event_type_not_found(
state
.clone()
.conf
.webhooks
.ignore_error
.event_type
.unwrap_or(true),
)
.switch()
.attach_printable("Could not find event type in incoming webhook body")?
{
Some(event_type) => event_type,
// Early return allows us to acknowledge the webhooks that we do not support
None => {
logger::error!(
webhook_payload =? request_details.body,
"Failed while identifying the event type",
);
metrics::WEBHOOK_EVENT_TYPE_IDENTIFICATION_FAILURE_COUNT.add(
1,
router_env::metric_attributes!(
(MERCHANT_ID, merchant_account.get_id().clone()),
("connector", connector_name)
),
);
let response = connector
.get_webhook_api_response(&request_details, None)
.switch()
.attach_printable("Failed while early return in case of event type parsing")?;
return Ok((
response,
WebhookResponseTracker::NoEffect,
serde_json::Value::Null,
));
}
};
logger::info!(event_type=?event_type);
let is_webhook_event_supported = !matches!(
event_type,
webhooks::IncomingWebhookEvent::EventNotSupported
);
let is_webhook_event_enabled = !utils::is_webhook_event_disabled(
&*state.clone().store,
connector_name.as_str(),
merchant_account.get_id(),
&event_type,
)
.await;
//process webhook further only if webhook event is enabled and is not event_not_supported
let process_webhook_further = is_webhook_event_enabled && is_webhook_event_supported;
logger::info!(process_webhook=?process_webhook_further);
let flow_type: api::WebhookFlow = event_type.into();
let mut event_object: Box<dyn masking::ErasedMaskSerialize> = Box::new(serde_json::Value::Null);
let webhook_effect = if process_webhook_further
&& !matches!(flow_type, api::WebhookFlow::ReturnResponse)
{
let object_ref_id = connector
.get_webhook_object_reference_id(&request_details)
.switch()
.attach_printable("Could not find object reference id in incoming webhook body")?;
let connector_enum = api_models::enums::Connector::from_str(&connector_name)
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "connector",
})
.attach_printable_lazy(|| {
format!("unable to parse connector name {connector_name:?}")
})?;
let connectors_with_source_verification_call = &state.conf.webhook_source_verification_call;
let merchant_connector_account = match merchant_connector_account {
Some(merchant_connector_account) => merchant_connector_account,
None => {
match Box::pin(helper_utils::get_mca_from_object_reference_id(
&state,
object_ref_id.clone(),
&merchant_account,
&connector_name,
&key_store,
))
.await
{
Ok(mca) => mca,
Err(error) => {
return handle_incoming_webhook_error(
error,
&connector,
connector_name.as_str(),
&request_details,
);
}
}
}
};
let source_verified = if connectors_with_source_verification_call
.connectors_with_webhook_source_verification_call
.contains(&connector_enum)
{
verify_webhook_source_verification_call(
connector.clone(),
&state,
&merchant_account,
merchant_connector_account.clone(),
&connector_name,
&request_details,
)
.await
.or_else(|error| match error.current_context() {
errors::ConnectorError::WebhookSourceVerificationFailed => {
logger::error!(?error, "Source Verification Failed");
Ok(false)
}
_ => Err(error),
})
.switch()
.attach_printable("There was an issue in incoming webhook source verification")?
} else {
connector
.clone()
.verify_webhook_source(
&request_details,
merchant_account.get_id(),
merchant_connector_account.connector_webhook_details.clone(),
merchant_connector_account.connector_account_details.clone(),
connector_name.as_str(),
)
.await
.or_else(|error| match error.current_context() {
errors::ConnectorError::WebhookSourceVerificationFailed => {
logger::error!(?error, "Source Verification Failed");
Ok(false)
}
_ => Err(error),
})
.switch()
.attach_printable("There was an issue in incoming webhook source verification")?
};
if source_verified {
metrics::WEBHOOK_SOURCE_VERIFIED_COUNT.add(
1,
router_env::metric_attributes!((MERCHANT_ID, merchant_account.get_id().clone())),
);
} else if connector.is_webhook_source_verification_mandatory() {
// if webhook consumption is mandatory for connector, fail webhook
// so that merchant can retrigger it after updating merchant_secret
return Err(errors::ApiErrorResponse::WebhookAuthenticationFailed.into());
}
logger::info!(source_verified=?source_verified);
event_object = connector
.get_webhook_resource_object(&request_details)
.switch()
.attach_printable("Could not find resource object in incoming webhook body")?;
let webhook_details = api::IncomingWebhookDetails {
object_reference_id: object_ref_id.clone(),
resource_object: serde_json::to_vec(&event_object)
.change_context(errors::ParsingError::EncodeError("byte-vec"))
.attach_printable("Unable to convert webhook payload to a value")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"There was an issue when encoding the incoming webhook body to bytes",
)?,
};
let profile_id = &merchant_connector_account.profile_id;
let business_profile = state
.store
.find_business_profile_by_profile_id(key_manager_state, &key_store, profile_id)
.await
.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
// If the incoming webhook is a relay webhook, then we need to trigger the relay webhook flow
let result_response = if is_relay_webhook {
let relay_webhook_response = Box::pin(relay_incoming_webhook_flow(
state.clone(),
merchant_account,
business_profile,
key_store,
webhook_details,
event_type,
source_verified,
))
.await
.attach_printable("Incoming webhook flow for relay failed");
// Using early return ensures unsupported webhooks are acknowledged to the connector
if let Some(errors::ApiErrorResponse::NotSupported { .. }) = relay_webhook_response
.as_ref()
.err()
.map(|a| a.current_context())
{
logger::error!(
webhook_payload =? request_details.body,
"Failed while identifying the event type",
);
let response = connector
.get_webhook_api_response(&request_details, None)
.switch()
.attach_printable(
"Failed while early return in case of not supported event type in relay webhooks",
)?;
return Ok((
response,
WebhookResponseTracker::NoEffect,
serde_json::Value::Null,
));
};
relay_webhook_response
} else {
match flow_type {
api::WebhookFlow::Payment => Box::pin(payments_incoming_webhook_flow(
state.clone(),
req_state,
merchant_account,
business_profile,
key_store,
webhook_details,
source_verified,
&connector,
&request_details,
event_type,
))
.await
.attach_printable("Incoming webhook flow for payments failed"),
api::WebhookFlow::Refund => Box::pin(refunds_incoming_webhook_flow(
state.clone(),
merchant_account,
business_profile,
key_store,
webhook_details,
connector_name.as_str(),
source_verified,
event_type,
))
.await
.attach_printable("Incoming webhook flow for refunds failed"),
api::WebhookFlow::Dispute => Box::pin(disputes_incoming_webhook_flow(
state.clone(),
merchant_account,
business_profile,
key_store,
webhook_details,
source_verified,
&connector,
&request_details,
event_type,
))
.await
.attach_printable("Incoming webhook flow for disputes failed"),
api::WebhookFlow::BankTransfer => Box::pin(bank_transfer_webhook_flow(
state.clone(),
req_state,
merchant_account,
business_profile,
key_store,
webhook_details,
source_verified,
))
.await
.attach_printable("Incoming bank-transfer webhook flow failed"),
api::WebhookFlow::ReturnResponse => Ok(WebhookResponseTracker::NoEffect),
api::WebhookFlow::Mandate => Box::pin(mandates_incoming_webhook_flow(
state.clone(),
merchant_account,
business_profile,
key_store,
webhook_details,
source_verified,
event_type,
))
.await
.attach_printable("Incoming webhook flow for mandates failed"),
api::WebhookFlow::ExternalAuthentication => {
Box::pin(external_authentication_incoming_webhook_flow(
state.clone(),
req_state,
merchant_account,
key_store,
source_verified,
event_type,
&request_details,
&connector,
object_ref_id,
business_profile,
merchant_connector_account,
))
.await
.attach_printable("Incoming webhook flow for external authentication failed")
}
api::WebhookFlow::FraudCheck => Box::pin(frm_incoming_webhook_flow(
state.clone(),
req_state,
merchant_account,
key_store,
source_verified,
event_type,
object_ref_id,
business_profile,
))
.await
.attach_printable("Incoming webhook flow for fraud check failed"),
#[cfg(feature = "payouts")]
api::WebhookFlow::Payout => Box::pin(payouts_incoming_webhook_flow(
state.clone(),
merchant_account,
business_profile,
key_store,
webhook_details,
event_type,
source_verified,
))
.await
.attach_printable("Incoming webhook flow for payouts failed"),
_ => Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unsupported Flow Type received in incoming webhooks"),
}
};
match result_response {
Ok(response) => response,
Err(error) => {
return handle_incoming_webhook_error(
error,
&connector,
connector_name.as_str(),
&request_details,
);
}
}
} else {
metrics::WEBHOOK_INCOMING_FILTERED_COUNT.add(
1,
router_env::metric_attributes!((MERCHANT_ID, merchant_account.get_id().clone())),
);
WebhookResponseTracker::NoEffect
};
let response = connector
.get_webhook_api_response(&request_details, None)
.switch()
.attach_printable("Could not get incoming webhook api response from connector")?;
let serialized_request = event_object
.masked_serialize()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Could not convert webhook effect to string")?;
Ok((response, webhook_effect, serialized_request))
}
<file_sep path="hyperswitch/crates/router/src/configs/settings.rs" role="context" start="721" end="724">
pub struct Refund {
pub max_attempts: usize,
pub max_age: i64,
}
<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/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/operations/payment_response.rs<|crate|> router anchor=save_pm_and_mandate kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_response.rs" role="context" start="577" end="628">
async fn save_pm_and_mandate<'b>(
&self,
state: &SessionState,
resp: &types::RouterData<F, types::PaymentsSyncData, types::PaymentsResponseData>,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
payment_data: &mut PaymentData<F>,
_business_profile: &domain::Profile,
) -> CustomResult<(), errors::ApiErrorResponse>
where
F: 'b + Clone + Send + Sync,
{
let (connector_mandate_id, mandate_metadata, connector_mandate_request_reference_id) = resp
.response
.clone()
.ok()
.and_then(|resp| {
if let types::PaymentsResponseData::TransactionResponse {
mandate_reference, ..
} = resp
{
mandate_reference.map(|mandate_ref| {
(
mandate_ref.connector_mandate_id.clone(),
mandate_ref.mandate_metadata.clone(),
mandate_ref.connector_mandate_request_reference_id.clone(),
)
})
} else {
None
}
})
.unwrap_or((None, None, None));
update_connector_mandate_details_for_the_flow(
connector_mandate_id,
mandate_metadata,
connector_mandate_request_reference_id,
payment_data,
)?;
update_payment_method_status_and_ntid(
state,
key_store,
payment_data,
resp.status,
resp.response.clone(),
merchant_account.storage_scheme,
)
.await?;
Ok(())
}
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_response.rs" role="context" start="576" end="576">
use common_utils::{
ext_traits::{AsyncExt, Encode},
types::{keymanager::KeyManagerState, ConnectorTransactionId, MinorUnit},
};
use crate::{
connector::utils::PaymentResponseRouterData,
consts,
core::{
card_testing_guard::utils as card_testing_guard_utils,
errors::{self, CustomResult, RouterResult, StorageErrorExt},
mandate,
payment_methods::{self, cards::create_encrypted_data},
payments::{
helpers::{
self as payments_helpers,
update_additional_payment_data_with_connector_response_pm_data,
},
tokenization,
types::MultipleCaptureData,
PaymentData, PaymentMethodChecker,
},
utils as core_utils,
},
routes::{metrics, SessionState},
types::{
self, domain,
storage::{self, enums},
transformers::{ForeignFrom, ForeignTryFrom},
CaptureSyncResponse, ErrorResponse,
},
utils,
};
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_response.rs" role="context" start="675" end="791">
async fn update_tracker<'b>(
&'b self,
db: &'b SessionState,
mut payment_data: PaymentData<F>,
router_data: types::RouterData<
F,
types::SdkPaymentsSessionUpdateData,
types::PaymentsResponseData,
>,
key_store: &domain::MerchantKeyStore,
storage_scheme: enums::MerchantStorageScheme,
_locale: &Option<String>,
#[cfg(feature = "dynamic_routing")] _routable_connector: Vec<RoutableConnectorChoice>,
#[cfg(feature = "dynamic_routing")] _business_profile: &domain::Profile,
) -> RouterResult<PaymentData<F>>
where
F: 'b + Send,
{
let connector = payment_data
.payment_attempt
.connector
.clone()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("connector not found")?;
let key_manager_state = db.into();
// For PayPal, if we call TaxJar for tax calculation, we need to call the connector again to update the order amount so that we can confirm the updated amount and order details. Therefore, we will store the required changes in the database during the post_update_tracker call.
if payment_data.should_update_in_post_update_tracker() {
match router_data.response.clone() {
Ok(types::PaymentsResponseData::SessionUpdateResponse { status }) => {
if status == SessionUpdateStatus::Success {
let shipping_address = payment_data
.tax_data
.clone()
.map(|tax_data| tax_data.shipping_details);
let shipping_details = shipping_address
.clone()
.async_map(|shipping_details| {
create_encrypted_data(
&key_manager_state,
key_store,
shipping_details,
)
})
.await
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt shipping details")?;
let shipping_address =
payments_helpers::create_or_update_address_for_payment_by_request(
db,
shipping_address.map(From::from).as_ref(),
payment_data.payment_intent.shipping_address_id.as_deref(),
&payment_data.payment_intent.merchant_id,
payment_data.payment_intent.customer_id.as_ref(),
key_store,
&payment_data.payment_intent.payment_id,
storage_scheme,
)
.await?;
let payment_intent_update = hyperswitch_domain_models::payments::payment_intent::PaymentIntentUpdate::SessionResponseUpdate {
tax_details: payment_data.payment_intent.tax_details.clone().ok_or(errors::ApiErrorResponse::InternalServerError).attach_printable("payment_intent.tax_details not found")?,
shipping_address_id: shipping_address.map(|address| address.address_id),
updated_by: payment_data.payment_intent.updated_by.clone(),
shipping_details,
};
let m_db = db.clone().store;
let payment_intent = payment_data.payment_intent.clone();
let key_manager_state: KeyManagerState = db.into();
let updated_payment_intent = m_db
.update_payment_intent(
&key_manager_state,
payment_intent,
payment_intent_update,
key_store,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
payment_data.payment_intent = updated_payment_intent;
} else {
router_data.response.map_err(|err| {
errors::ApiErrorResponse::ExternalConnectorError {
code: err.code,
message: err.message,
connector,
status_code: err.status_code,
reason: err.reason,
}
})?;
}
}
Err(err) => {
Err(errors::ApiErrorResponse::ExternalConnectorError {
code: err.code,
message: err.message,
connector,
status_code: err.status_code,
reason: err.reason,
})?;
}
_ => {
Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unexpected response in session_update flow")?;
}
}
}
Ok(payment_data)
}
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_response.rs" role="context" start="636" end="667">
async fn update_tracker<'b>(
&'b self,
db: &'b SessionState,
mut payment_data: PaymentData<F>,
router_data: types::RouterData<F, types::PaymentsSessionData, types::PaymentsResponseData>,
key_store: &domain::MerchantKeyStore,
storage_scheme: enums::MerchantStorageScheme,
locale: &Option<String>,
#[cfg(all(feature = "v1", feature = "dynamic_routing"))] routable_connector: Vec<
RoutableConnectorChoice,
>,
#[cfg(all(feature = "v1", feature = "dynamic_routing"))] business_profile: &domain::Profile,
) -> RouterResult<PaymentData<F>>
where
F: 'b + Send,
{
payment_data = Box::pin(payment_response_update_tracker(
db,
payment_data,
router_data,
key_store,
storage_scheme,
locale,
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
routable_connector,
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
business_profile,
))
.await?;
Ok(payment_data)
}
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_response.rs" role="context" start="546" end="575">
async fn update_tracker<'b>(
&'b self,
db: &'b SessionState,
payment_data: PaymentData<F>,
router_data: types::RouterData<F, types::PaymentsSyncData, types::PaymentsResponseData>,
key_store: &domain::MerchantKeyStore,
storage_scheme: enums::MerchantStorageScheme,
locale: &Option<String>,
#[cfg(all(feature = "v1", feature = "dynamic_routing"))] routable_connector: Vec<
RoutableConnectorChoice,
>,
#[cfg(all(feature = "v1", feature = "dynamic_routing"))] business_profile: &domain::Profile,
) -> RouterResult<PaymentData<F>>
where
F: 'b + Send,
{
Box::pin(payment_response_update_tracker(
db,
payment_data,
router_data,
key_store,
storage_scheme,
locale,
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
routable_connector,
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
business_profile,
))
.await
}
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_response.rs" role="context" start="380" end="540">
async fn update_tracker<'b>(
&'b self,
state: &'b SessionState,
mut payment_data: PaymentData<F>,
router_data: types::RouterData<
F,
types::PaymentsIncrementalAuthorizationData,
types::PaymentsResponseData,
>,
key_store: &domain::MerchantKeyStore,
storage_scheme: enums::MerchantStorageScheme,
_locale: &Option<String>,
#[cfg(all(feature = "v1", feature = "dynamic_routing"))] _routable_connector: Vec<
RoutableConnectorChoice,
>,
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
_business_profile: &domain::Profile,
) -> RouterResult<PaymentData<F>>
where
F: 'b + Send,
{
let incremental_authorization_details = payment_data
.incremental_authorization_details
.clone()
.ok_or_else(|| {
report!(errors::ApiErrorResponse::InternalServerError)
.attach_printable("missing incremental_authorization_details in payment_data")
})?;
// Update payment_intent and payment_attempt 'amount' if incremental_authorization is successful
let (option_payment_attempt_update, option_payment_intent_update) = match router_data
.response
.clone()
{
Err(_) => (None, None),
Ok(types::PaymentsResponseData::IncrementalAuthorizationResponse {
status, ..
}) => {
if status == AuthorizationStatus::Success {
(
Some(
storage::PaymentAttemptUpdate::IncrementalAuthorizationAmountUpdate {
net_amount: hyperswitch_domain_models::payments::payment_attempt::NetAmount::new(
incremental_authorization_details.total_amount,
None,
None,
None,
None,
),
amount_capturable: incremental_authorization_details.total_amount,
},
),
Some(
storage::PaymentIntentUpdate::IncrementalAuthorizationAmountUpdate {
amount: incremental_authorization_details.total_amount,
},
),
)
} else {
(None, None)
}
}
_ => Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unexpected response in incremental_authorization flow")?,
};
//payment_attempt update
if let Some(payment_attempt_update) = option_payment_attempt_update {
#[cfg(feature = "v1")]
{
payment_data.payment_attempt = state
.store
.update_payment_attempt_with_attempt_id(
payment_data.payment_attempt.clone(),
payment_attempt_update,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
}
#[cfg(feature = "v2")]
{
payment_data.payment_attempt = state
.store
.update_payment_attempt_with_attempt_id(
&state.into(),
key_store,
payment_data.payment_attempt.clone(),
payment_attempt_update,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
}
}
// payment_intent update
if let Some(payment_intent_update) = option_payment_intent_update {
payment_data.payment_intent = state
.store
.update_payment_intent(
&state.into(),
payment_data.payment_intent.clone(),
payment_intent_update,
key_store,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
}
// Update the status of authorization record
let authorization_update = match &router_data.response {
Err(res) => Ok(storage::AuthorizationUpdate::StatusUpdate {
status: AuthorizationStatus::Failure,
error_code: Some(res.code.clone()),
error_message: Some(res.message.clone()),
connector_authorization_id: None,
}),
Ok(types::PaymentsResponseData::IncrementalAuthorizationResponse {
status,
error_code,
error_message,
connector_authorization_id,
}) => Ok(storage::AuthorizationUpdate::StatusUpdate {
status: status.clone(),
error_code: error_code.clone(),
error_message: error_message.clone(),
connector_authorization_id: connector_authorization_id.clone(),
}),
Ok(_) => Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unexpected response in incremental_authorization flow"),
}?;
let authorization_id = incremental_authorization_details
.authorization_id
.clone()
.ok_or(
report!(errors::ApiErrorResponse::InternalServerError).attach_printable(
"missing authorization_id in incremental_authorization_details in payment_data",
),
)?;
state
.store
.update_authorization_by_merchant_id_authorization_id(
router_data.merchant_id.clone(),
authorization_id,
authorization_update,
)
.await
.to_not_found_response(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed while updating authorization")?;
//Fetch all the authorizations of the payment and send in incremental authorization response
let authorizations = state
.store
.find_all_authorizations_by_merchant_id_payment_id(
&router_data.merchant_id,
payment_data.payment_intent.get_id(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed while retrieving authorizations")?;
payment_data.authorizations = authorizations;
Ok(payment_data)
}
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_response.rs" role="context" start="2133" end="2220">
async fn update_payment_method_status_and_ntid<F: Clone>(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
payment_data: &mut PaymentData<F>,
attempt_status: common_enums::AttemptStatus,
payment_response: Result<types::PaymentsResponseData, ErrorResponse>,
storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<()> {
// If the payment_method is deleted then ignore the error related to retrieving payment method
// This should be handled when the payment method is soft deleted
if let Some(id) = &payment_data.payment_attempt.payment_method_id {
let payment_method = match state
.store
.find_payment_method(&(state.into()), key_store, id, storage_scheme)
.await
{
Ok(payment_method) => payment_method,
Err(error) => {
if error.current_context().is_db_not_found() {
logger::info!(
"Payment Method not found in db and skipping payment method update {:?}",
error
);
return Ok(());
} else {
Err(error)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error retrieving payment method from db in update_payment_method_status_and_ntid")?
}
}
};
let pm_resp_network_transaction_id = payment_response
.map(|resp| if let types::PaymentsResponseData::TransactionResponse { network_txn_id: network_transaction_id, .. } = resp {
network_transaction_id
} else {None})
.map_err(|err| {
logger::error!(error=?err, "Failed to obtain the network_transaction_id from payment response");
})
.ok()
.flatten();
let network_transaction_id = if payment_data.payment_intent.setup_future_usage
== Some(diesel_models::enums::FutureUsage::OffSession)
{
if pm_resp_network_transaction_id.is_some() {
pm_resp_network_transaction_id
} else {
logger::info!("Skip storing network transaction id");
None
}
} else {
None
};
let pm_update = if payment_method.status != common_enums::PaymentMethodStatus::Active
&& payment_method.status != attempt_status.into()
{
let updated_pm_status = common_enums::PaymentMethodStatus::from(attempt_status);
payment_data
.payment_method_info
.as_mut()
.map(|info| info.status = updated_pm_status);
storage::PaymentMethodUpdate::NetworkTransactionIdAndStatusUpdate {
network_transaction_id,
status: Some(updated_pm_status),
}
} else {
storage::PaymentMethodUpdate::NetworkTransactionIdAndStatusUpdate {
network_transaction_id,
status: None,
}
};
state
.store
.update_payment_method(
&(state.into()),
key_store,
payment_method,
pm_update,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update payment method in db")?;
};
Ok(())
}
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_response.rs" role="context" start="2668" end="2713">
fn update_connector_mandate_details_for_the_flow<F: Clone>(
connector_mandate_id: Option<String>,
mandate_metadata: Option<masking::Secret<serde_json::Value>>,
connector_mandate_request_reference_id: Option<String>,
payment_data: &mut PaymentData<F>,
) -> RouterResult<()> {
let mut original_connector_mandate_reference_id = payment_data
.payment_attempt
.connector_mandate_detail
.as_ref()
.map(|detail| ConnectorMandateReferenceId::foreign_from(detail.clone()));
let connector_mandate_reference_id = if connector_mandate_id.is_some() {
if let Some(ref mut record) = original_connector_mandate_reference_id {
record.update(
connector_mandate_id,
None,
None,
mandate_metadata,
connector_mandate_request_reference_id,
);
Some(record.clone())
} else {
Some(ConnectorMandateReferenceId::new(
connector_mandate_id,
None,
None,
mandate_metadata,
connector_mandate_request_reference_id,
))
}
} else {
original_connector_mandate_reference_id
};
payment_data.payment_attempt.connector_mandate_detail = connector_mandate_reference_id
.clone()
.map(ForeignFrom::foreign_from);
payment_data.set_mandate_id(api_models::payments::MandateIds {
mandate_id: None,
mandate_reference_id: connector_mandate_reference_id.map(|connector_mandate_id| {
MandateReferenceId::ConnectorMandateId(connector_mandate_id)
}),
});
Ok(())
}
<file_sep path="hyperswitch/crates/router/src/routes/app.rs" role="context" start="1906" end="1906">
pub struct Profile;
<file_sep path="hyperswitch/v2_compatible_migrations/2024-08-28-081757_drop_not_null_constraints_on_v1_columns/up.sql" role="context" start="5" end="21">
ALTER COLUMN org_id DROP NOT NULL;
-- Create index on org_id in organization table
-- This is done to mullify the effects of droping primary key for v1
CREATE INDEX idx_organization_org_id ON organization (org_id);
------------------------ Merchant Account -------------------
-- Drop not null in merchant_account table for v1 columns that are dropped in v2
ALTER TABLE merchant_account
DROP CONSTRAINT merchant_account_pkey,
ALTER COLUMN merchant_id DROP NOT NULL,
ALTER COLUMN primary_business_details DROP NOT NULL,
ALTER COLUMN is_recon_enabled DROP NOT NULL;
-- This is done to mullify the effects of droping primary key for v1
CREATE INDEX idx_merchant_account_merchant_id ON merchant_account (merchant_id);
<file_sep path="hyperswitch/crates/api_models/src/errors/types.rs" role="context" start="86" end="100">
pub enum ApiErrorResponse {
Unauthorized(ApiError),
ForbiddenCommonResource(ApiError),
ForbiddenPrivateResource(ApiError),
Conflict(ApiError),
Gone(ApiError),
Unprocessable(ApiError),
InternalServerError(ApiError),
NotImplemented(ApiError),
ConnectorError(ApiError, #[serde(skip_serializing)] StatusCode),
NotFound(ApiError),
MethodNotAllowed(ApiError),
BadRequest(ApiError),
DomainError(ApiError),
}
<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/helpers.rs<|crate|> router anchor=construct_signed_data_for_signature_verification kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="6066" end="6093">
fn construct_signed_data_for_signature_verification(
&self,
sender_id: &str,
protocol_version: &str,
signed_key: &str,
) -> CustomResult<Vec<u8>, errors::GooglePayDecryptionError> {
let recipient_id = self.recipient_id.clone().expose();
let length_of_sender_id = u32::try_from(sender_id.len())
.change_context(errors::GooglePayDecryptionError::ParsingFailed)?;
let length_of_recipient_id = u32::try_from(recipient_id.len())
.change_context(errors::GooglePayDecryptionError::ParsingFailed)?;
let length_of_protocol_version = u32::try_from(protocol_version.len())
.change_context(errors::GooglePayDecryptionError::ParsingFailed)?;
let length_of_signed_key = u32::try_from(signed_key.len())
.change_context(errors::GooglePayDecryptionError::ParsingFailed)?;
let mut signed_data: Vec<u8> = Vec::new();
signed_data.append(&mut get_little_endian_format(length_of_sender_id));
signed_data.append(&mut sender_id.as_bytes().to_vec());
signed_data.append(&mut get_little_endian_format(length_of_recipient_id));
signed_data.append(&mut recipient_id.as_bytes().to_vec());
signed_data.append(&mut get_little_endian_format(length_of_protocol_version));
signed_data.append(&mut protocol_version.as_bytes().to_vec());
signed_data.append(&mut get_little_endian_format(length_of_signed_key));
signed_data.append(&mut signed_key.as_bytes().to_vec());
Ok(signed_data)
}
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="6065" end="6065">
// parse the DER-encoded data as an EC public key
let ec_key = openssl::ec::EcKey::public_key_from_der(&der_data)
.change_context(errors::GooglePayDecryptionError::DerivingEcKeyFailed)?;
// wrap the EC key in a PKey (a more general-purpose public key type in OpenSSL)
let public_key = PKey::from_ec_key(ec_key)
.change_context(errors::GooglePayDecryptionError::DerivingPublicKeyFailed)?;
Ok(public_key)
}
// Construct signed data for signature verification
fn construct_signed_data_for_signature_verification(
&self,
sender_id: &str,
protocol_version: &str,
signed_key: &str,
) -> CustomResult<Vec<u8>, errors::GooglePayDecryptionError> {
let recipient_id = self.recipient_id.clone().expose();
let length_of_sender_id = u32::try_from(sender_id.len())
.change_context(errors::GooglePayDecryptionError::ParsingFailed)?;
let length_of_recipient_id = u32::try_from(recipient_id.len())
.change_context(errors::GooglePayDecryptionError::ParsingFailed)?;
let length_of_protocol_version = u32::try_from(protocol_version.len())
.change_context(errors::GooglePayDecryptionError::ParsingFailed)?;
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="6137" end="6162">
fn derive_key(
&self,
ephemeral_public_key_bytes: &[u8],
shared_key: &[u8],
) -> CustomResult<Vec<u8>, errors::GooglePayDecryptionError> {
// concatenate ephemeral public key and shared key
let input_key_material = [ephemeral_public_key_bytes, shared_key].concat();
// initialize HKDF with SHA-256 as the hash function
// Salt is not provided as per the Google Pay documentation
// https://developers.google.com/pay/api/android/guides/resources/payment-data-cryptography#encrypt-spec
let hkdf: ::hkdf::Hkdf<sha2::Sha256> = ::hkdf::Hkdf::new(None, &input_key_material);
// derive 64 bytes for the output key (symmetric encryption + MAC key)
let mut output_key = vec![0u8; 64];
hkdf.expand(consts::SENDER_ID, &mut output_key)
.map_err(|err| {
logger::error!(
"Failed to derive the shared ephemeral key for Google Pay decryption flow: {:?}",
err
);
report!(errors::GooglePayDecryptionError::DerivingSharedEphemeralKeyFailed)
})?;
Ok(output_key)
}
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="6096" end="6134">
fn get_shared_key(
&self,
ephemeral_public_key_bytes: &[u8],
) -> CustomResult<Vec<u8>, errors::GooglePayDecryptionError> {
let group = openssl::ec::EcGroup::from_curve_name(openssl::nid::Nid::X9_62_PRIME256V1)
.change_context(errors::GooglePayDecryptionError::DerivingEcGroupFailed)?;
let mut big_num_context = openssl::bn::BigNumContext::new()
.change_context(errors::GooglePayDecryptionError::BigNumAllocationFailed)?;
let ec_key = openssl::ec::EcPoint::from_bytes(
&group,
ephemeral_public_key_bytes,
&mut big_num_context,
)
.change_context(errors::GooglePayDecryptionError::DerivingEcKeyFailed)?;
// create an ephemeral public key from the given bytes
let ephemeral_public_key = openssl::ec::EcKey::from_public_key(&group, &ec_key)
.change_context(errors::GooglePayDecryptionError::DerivingPublicKeyFailed)?;
// wrap the public key in a PKey
let ephemeral_pkey = PKey::from_ec_key(ephemeral_public_key)
.change_context(errors::GooglePayDecryptionError::DerivingPublicKeyFailed)?;
// perform ECDH to derive the shared key
let mut deriver = Deriver::new(&self.private_key)
.change_context(errors::GooglePayDecryptionError::DerivingSharedSecretKeyFailed)?;
deriver
.set_peer(&ephemeral_pkey)
.change_context(errors::GooglePayDecryptionError::DerivingSharedSecretKeyFailed)?;
let shared_key = deriver
.derive_to_vec()
.change_context(errors::GooglePayDecryptionError::DerivingSharedSecretKeyFailed)?;
Ok(shared_key)
}
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="6045" end="6063">
fn load_public_key(
&self,
key: &str,
) -> CustomResult<PKey<openssl::pkey::Public>, errors::GooglePayDecryptionError> {
// decode the base64 string
let der_data = BASE64_ENGINE
.decode(key)
.change_context(errors::GooglePayDecryptionError::Base64DecodingFailed)?;
// parse the DER-encoded data as an EC public key
let ec_key = openssl::ec::EcKey::public_key_from_der(&der_data)
.change_context(errors::GooglePayDecryptionError::DerivingEcKeyFailed)?;
// wrap the EC key in a PKey (a more general-purpose public key type in OpenSSL)
let public_key = PKey::from_ec_key(ec_key)
.change_context(errors::GooglePayDecryptionError::DerivingPublicKeyFailed)?;
Ok(public_key)
}
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="5993" end="6042">
fn verify_message_signature(
&self,
encrypted_data: &EncryptedData,
signed_key: &GooglePaySignedKey,
) -> CustomResult<(), errors::GooglePayDecryptionError> {
// create a public key from the intermediate signing key
let public_key = self.load_public_key(signed_key.key_value.peek())?;
// base64 decode the signature
let signature = BASE64_ENGINE
.decode(&encrypted_data.signature)
.change_context(errors::GooglePayDecryptionError::Base64DecodingFailed)?;
// parse the signature using ECDSA
let ecdsa_signature = openssl::ecdsa::EcdsaSig::from_der(&signature)
.change_context(errors::GooglePayDecryptionError::EcdsaSignatureFailed)?;
// get the EC key from the public key
let ec_key = public_key
.ec_key()
.change_context(errors::GooglePayDecryptionError::DerivingEcKeyFailed)?;
// get the sender id i.e. Google
let sender_id = String::from_utf8(consts::SENDER_ID.to_vec())
.change_context(errors::GooglePayDecryptionError::DeserializationFailed)?;
// serialize the signed message to string
let signed_message = serde_json::to_string(&encrypted_data.signed_message)
.change_context(errors::GooglePayDecryptionError::SignedKeyParsingFailure)?;
// construct the signed data
let signed_data = self.construct_signed_data_for_signature_verification(
&sender_id,
consts::PROTOCOL,
&signed_message,
)?;
// hash the signed data
let message_hash = openssl::sha::sha256(&signed_data);
// verify the signature
let result = ecdsa_signature
.verify(&message_hash, &ec_key)
.change_context(errors::GooglePayDecryptionError::SignatureVerificationFailed)?;
if result {
Ok(())
} else {
Err(errors::GooglePayDecryptionError::InvalidSignature)?
}
}
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="5783" end="5814">
pub fn new(
root_keys: masking::Secret<String>,
recipient_id: masking::Secret<String>,
private_key: masking::Secret<String>,
) -> CustomResult<Self, errors::GooglePayDecryptionError> {
// base64 decode the private key
let decoded_key = BASE64_ENGINE
.decode(private_key.expose())
.change_context(errors::GooglePayDecryptionError::Base64DecodingFailed)?;
// base64 decode the root signing keys
let decoded_root_signing_keys = BASE64_ENGINE
.decode(root_keys.expose())
.change_context(errors::GooglePayDecryptionError::Base64DecodingFailed)?;
// create a private key from the decoded key
let private_key = PKey::private_key_from_pkcs8(&decoded_key)
.change_context(errors::GooglePayDecryptionError::KeyDeserializationFailed)
.attach_printable("cannot convert private key from decode_key")?;
// parse the root signing keys
let root_keys_vector: Vec<GooglePayRootSigningKey> = decoded_root_signing_keys
.parse_struct("GooglePayRootSigningKey")
.change_context(errors::GooglePayDecryptionError::DeserializationFailed)?;
// parse and filter the root signing keys by protocol version
let filtered_root_signing_keys = filter_root_signing_keys(root_keys_vector)?;
Ok(Self {
root_signing_keys: filtered_root_signing_keys,
recipient_id,
private_key,
})
}
<file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="5748" end="5750">
fn get_little_endian_format(number: u32) -> Vec<u8> {
number.to_le_bytes().to_vec()
}
<file_sep path="hyperswitch/crates/router/src/core/errors.rs" role="context" start="247" end="296">
pub enum GooglePayDecryptionError {
#[error("Invalid expiration time")]
InvalidExpirationTime,
#[error("Failed to base64 decode input data")]
Base64DecodingFailed,
#[error("Failed to decrypt input data")]
DecryptionFailed,
#[error("Failed to deserialize input data")]
DeserializationFailed,
#[error("Certificate parsing failed")]
CertificateParsingFailed,
#[error("Key deserialization failure")]
KeyDeserializationFailed,
#[error("Failed to derive a shared ephemeral key")]
DerivingSharedEphemeralKeyFailed,
#[error("Failed to derive a shared secret key")]
DerivingSharedSecretKeyFailed,
#[error("Failed to parse the tag")]
ParsingTagError,
#[error("HMAC verification failed")]
HmacVerificationFailed,
#[error("Failed to derive Elliptic Curve key")]
DerivingEcKeyFailed,
#[error("Failed to Derive Public key")]
DerivingPublicKeyFailed,
#[error("Failed to Derive Elliptic Curve group")]
DerivingEcGroupFailed,
#[error("Failed to allocate memory for big number")]
BigNumAllocationFailed,
#[error("Failed to get the ECDSA signature")]
EcdsaSignatureFailed,
#[error("Failed to verify the signature")]
SignatureVerificationFailed,
#[error("Invalid signature is provided")]
InvalidSignature,
#[error("Failed to parse the Signed Key")]
SignedKeyParsingFailure,
#[error("The Signed Key is expired")]
SignedKeyExpired,
#[error("Failed to parse the ECDSA signature")]
EcdsaSignatureParsingFailed,
#[error("Invalid intermediate signature is provided")]
InvalidIntermediateSignature,
#[error("Invalid protocol version")]
InvalidProtocolVersion,
#[error("Decrypted Token has expired")]
DecryptedTokenExpired,
#[error("Failed to parse the given value")]
ParsingFailed,
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/revenue_recovery/types.rs<|crate|> router anchor=execute_payment kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/revenue_recovery/types.rs" role="context" start="146" end="191">
pub async fn execute_payment(
state: &SessionState,
merchant_id: &id_type::MerchantId,
payment_intent: &PaymentIntent,
process: &storage::ProcessTracker,
pcr_data: &storage::revenue_recovery::PcrPaymentData,
revenue_recovery_metadata: &PaymentRevenueRecoveryMetadata,
) -> RecoveryResult<Self> {
let db = &*state.store;
let response =
call_proxy_api(state, payment_intent, pcr_data, revenue_recovery_metadata).await;
// handle proxy api's response
match response {
Ok(payment_data) => match payment_data.payment_attempt.status.foreign_into() {
PcrAttemptStatus::Succeeded => Ok(Self::SuccessfulPayment(
payment_data.payment_attempt.clone(),
)),
PcrAttemptStatus::Failed => {
Self::decide_retry_failure_action(
db,
merchant_id,
process.clone(),
&payment_data.payment_attempt,
)
.await
}
PcrAttemptStatus::Processing => {
Ok(Self::SyncPayment(payment_data.payment_attempt.id.clone()))
}
PcrAttemptStatus::InvalidStatus(action) => {
logger::info!(?action, "Invalid Payment Status For PCR Payment");
Ok(Self::ManualReviewAction)
}
},
Err(err) =>
// check for an active attempt being constructed or not
{
logger::error!(execute_payment_res=?err);
match payment_intent.active_attempt_id.clone() {
Some(attempt_id) => Ok(Self::SyncPayment(attempt_id)),
None => Ok(Self::ReviewPayment),
}
}
}
}
<file_sep path="hyperswitch/crates/router/src/core/revenue_recovery/types.rs" role="context" start="145" end="145">
}
#[derive(Debug, Clone)]
pub enum Action {
SyncPayment(id_type::GlobalAttemptId),
RetryPayment(PrimitiveDateTime),
TerminalFailure(payment_attempt::PaymentAttempt),
SuccessfulPayment(payment_attempt::PaymentAttempt),
ReviewPayment,
ManualReviewAction,
}
impl Action {
pub async fn execute_payment(
state: &SessionState,
merchant_id: &id_type::MerchantId,
payment_intent: &PaymentIntent,
process: &storage::ProcessTracker,
pcr_data: &storage::revenue_recovery::PcrPaymentData,
revenue_recovery_metadata: &PaymentRevenueRecoveryMetadata,
) -> RecoveryResult<Self> {
let db = &*state.store;
let response =
call_proxy_api(state, payment_intent, pcr_data, revenue_recovery_metadata).await;
// handle proxy api's response
match response {
<file_sep path="hyperswitch/crates/router/src/core/revenue_recovery/types.rs" role="context" start="320" end="372">
async fn record_back_to_billing_connector(
&self,
state: &SessionState,
payment_attempt: &payment_attempt::PaymentAttempt,
payment_intent: &PaymentIntent,
billing_mca: &merchant_connector_account::MerchantConnectorAccount,
) -> RecoveryResult<()> {
let connector_name = billing_mca.connector_name.to_string();
let connector_data = api_types::ConnectorData::get_connector_by_name(
&state.conf.connectors,
&connector_name,
api_types::GetToken::Connector,
Some(billing_mca.get_id()),
)
.change_context(errors::RecoveryError::RecordBackToBillingConnectorFailed)
.attach_printable(
"invalid connector name received in billing merchant connector account",
)?;
let connector_integration: services::BoxedRevenueRecoveryRecordBackInterface<
router_flow_types::RecoveryRecordBack,
revenue_recovery_request::RevenueRecoveryRecordBackRequest,
revenue_recovery_response::RevenueRecoveryRecordBackResponse,
> = connector_data.connector.get_connector_integration();
let router_data = self.construct_recovery_record_back_router_data(
state,
billing_mca,
payment_attempt,
payment_intent,
)?;
let response = services::execute_connector_processing_step(
state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
)
.await
.change_context(errors::RecoveryError::RecordBackToBillingConnectorFailed)
.attach_printable("Failed while handling response of record back to billing connector")?;
let record_back_response = match response.response {
Ok(response) => Ok(response),
error @ Err(_) => {
router_env::logger::error!(?error);
Err(errors::RecoveryError::RecordBackToBillingConnectorFailed)
.attach_printable("Failed while recording back to billing connector")
}
}?;
Ok(())
}
<file_sep path="hyperswitch/crates/router/src/core/revenue_recovery/types.rs" role="context" start="193" end="318">
pub async fn execute_payment_task_response_handler(
&self,
state: &SessionState,
payment_intent: &PaymentIntent,
execute_task_process: &storage::ProcessTracker,
pcr_data: &storage::revenue_recovery::PcrPaymentData,
revenue_recovery_metadata: &mut PaymentRevenueRecoveryMetadata,
billing_mca: &merchant_connector_account::MerchantConnectorAccount,
) -> Result<(), errors::ProcessTrackerError> {
let db = &*state.store;
match self {
Self::SyncPayment(attempt_id) => {
core_pcr::insert_psync_pcr_task(
db,
pcr_data.merchant_account.get_id().to_owned(),
payment_intent.id.clone(),
pcr_data.profile.get_id().to_owned(),
attempt_id.clone(),
storage::ProcessTrackerRunner::PassiveRecoveryWorkflow,
)
.await
.change_context(errors::RecoveryError::ProcessTrackerFailure)
.attach_printable("Failed to create a psync workflow in the process tracker")?;
db.as_scheduler()
.finish_process_with_business_status(
execute_task_process.clone(),
business_status::EXECUTE_WORKFLOW_COMPLETE_FOR_PSYNC,
)
.await
.change_context(errors::RecoveryError::ProcessTrackerFailure)
.attach_printable("Failed to update the process tracker")?;
Ok(())
}
Self::RetryPayment(schedule_time) => {
db.as_scheduler()
.retry_process(execute_task_process.clone(), *schedule_time)
.await?;
// update the connector payment transmission field to Unsuccessful and unset active attempt id
revenue_recovery_metadata.set_payment_transmission_field_for_api_request(
enums::PaymentConnectorTransmission::ConnectorCallUnsuccessful,
);
let payment_update_req = PaymentsUpdateIntentRequest::update_feature_metadata_and_active_attempt_with_api(
payment_intent.feature_metadata.clone().unwrap_or_default().convert_back().set_payment_revenue_recovery_metadata_using_api(
revenue_recovery_metadata.clone()
),
api_enums::UpdateActiveAttempt::Unset,
);
logger::info!(
"Call made to payments update intent api , with the request body {:?}",
payment_update_req
);
update_payment_intent_api(
state,
payment_intent.id.clone(),
pcr_data,
payment_update_req,
)
.await
.change_context(errors::RecoveryError::PaymentCallFailed)?;
Ok(())
}
Self::TerminalFailure(payment_attempt) => {
db.as_scheduler()
.finish_process_with_business_status(
execute_task_process.clone(),
business_status::EXECUTE_WORKFLOW_COMPLETE,
)
.await
.change_context(errors::RecoveryError::ProcessTrackerFailure)
.attach_printable("Failed to update the process tracker")?;
// Record back to billing connector for terminal status
// TODO: Add support for retrying failed outgoing recordback webhooks
self.record_back_to_billing_connector(
state,
payment_attempt,
payment_intent,
billing_mca,
)
.await
.change_context(errors::RecoveryError::RecordBackToBillingConnectorFailed)
.attach_printable("Failed to record back the billing connector")?;
Ok(())
}
Self::SuccessfulPayment(payment_attempt) => {
db.as_scheduler()
.finish_process_with_business_status(
execute_task_process.clone(),
business_status::EXECUTE_WORKFLOW_COMPLETE,
)
.await
.change_context(errors::RecoveryError::ProcessTrackerFailure)
.attach_printable("Failed to update the process tracker")?;
// Record back to billing connector for terminal status
// TODO: Add support for retrying failed outgoing recordback webhooks
self.record_back_to_billing_connector(
state,
payment_attempt,
payment_intent,
billing_mca,
)
.await
.change_context(errors::RecoveryError::RecordBackToBillingConnectorFailed)
.attach_printable("Failed to update the process tracker")?;
Ok(())
}
Self::ReviewPayment => Ok(()),
Self::ManualReviewAction => {
logger::debug!("Invalid Payment Status For PCR Payment");
let pt_update = storage::ProcessTrackerUpdate::StatusUpdate {
status: enums::ProcessTrackerStatus::Review,
business_status: Some(String::from(business_status::EXECUTE_WORKFLOW_COMPLETE)),
};
// update the process tracker status as Review
db.as_scheduler()
.update_process(execute_task_process.clone(), pt_update)
.await?;
Ok(())
}
}
}
<file_sep path="hyperswitch/crates/router/src/core/revenue_recovery/types.rs" role="context" start="101" end="133">
pub async fn get_decision_based_on_params(
state: &SessionState,
intent_status: enums::IntentStatus,
called_connector: enums::PaymentConnectorTransmission,
active_attempt_id: Option<id_type::GlobalAttemptId>,
pcr_data: &storage::revenue_recovery::PcrPaymentData,
payment_id: &id_type::GlobalPaymentId,
) -> RecoveryResult<Self> {
Ok(match (intent_status, called_connector, active_attempt_id) {
(
enums::IntentStatus::Failed,
enums::PaymentConnectorTransmission::ConnectorCallUnsuccessful,
None,
) => Self::Execute,
(
enums::IntentStatus::Processing,
enums::PaymentConnectorTransmission::ConnectorCallSucceeded,
Some(_),
) => {
let psync_data = core_pcr::call_psync_api(state, payment_id, pcr_data)
.await
.change_context(errors::RecoveryError::PaymentCallFailed)
.attach_printable("Error while executing the Psync call")?;
let payment_attempt = psync_data
.payment_attempt
.get_required_value("Payment Attempt")
.change_context(errors::RecoveryError::ValueNotFound)
.attach_printable("Error while executing the Psync call")?;
Self::Psync(payment_attempt.status, payment_attempt.get_id().clone())
}
_ => Self::InvalidDecision,
})
}
<file_sep path="hyperswitch/crates/router/src/core/revenue_recovery/types.rs" role="context" start="61" end="91">
pub(crate) async fn update_pt_status_based_on_attempt_status_for_execute_payment(
&self,
db: &dyn StorageInterface,
execute_task_process: &storage::ProcessTracker,
) -> Result<(), errors::ProcessTrackerError> {
match &self {
Self::Succeeded | Self::Failed | Self::Processing => {
// finish the current execute task
db.finish_process_with_business_status(
execute_task_process.clone(),
business_status::EXECUTE_WORKFLOW_COMPLETE_FOR_PSYNC,
)
.await?;
}
Self::InvalidStatus(action) => {
logger::debug!(
"Invalid Attempt Status for the Recovery Payment : {}",
action
);
let pt_update = storage::ProcessTrackerUpdate::StatusUpdate {
status: enums::ProcessTrackerStatus::Review,
business_status: Some(String::from(business_status::EXECUTE_WORKFLOW_COMPLETE)),
};
// update the process tracker status as Review
db.update_process(execute_task_process.clone(), pt_update)
.await?;
}
};
Ok(())
}
<file_sep path="hyperswitch/crates/router/src/core/revenue_recovery/types.rs" role="context" start="420" end="433">
pub(crate) async fn decide_retry_failure_action(
db: &dyn StorageInterface,
merchant_id: &id_type::MerchantId,
pt: storage::ProcessTracker,
payment_attempt: &payment_attempt::PaymentAttempt,
) -> RecoveryResult<Self> {
let schedule_time =
get_schedule_time_to_retry_mit_payments(db, merchant_id, pt.retry_count + 1).await;
match schedule_time {
Some(schedule_time) => Ok(Self::RetryPayment(schedule_time)),
None => Ok(Self::TerminalFailure(payment_attempt.clone())),
}
}
<file_sep path="hyperswitch/crates/router/src/core/revenue_recovery/types.rs" role="context" start="436" end="493">
async fn call_proxy_api(
state: &SessionState,
payment_intent: &PaymentIntent,
pcr_data: &storage::revenue_recovery::PcrPaymentData,
revenue_recovery: &PaymentRevenueRecoveryMetadata,
) -> RouterResult<PaymentConfirmData<payments_types::Authorize>> {
let operation = payments::operations::proxy_payments_intent::PaymentProxyIntent;
let req = ProxyPaymentsRequest {
return_url: None,
amount: AmountDetails::new(payment_intent.amount_details.clone().into()),
recurring_details: revenue_recovery.get_payment_token_for_api_request(),
shipping: None,
browser_info: None,
connector: revenue_recovery.connector.to_string(),
merchant_connector_id: revenue_recovery.get_merchant_connector_id_for_api_request(),
};
logger::info!(
"Call made to payments proxy api , with the request body {:?}",
req
);
// TODO : Use api handler instead of calling get_tracker and payments_operation_core
// Get the tracker related information. This includes payment intent and payment attempt
let get_tracker_response = operation
.to_get_tracker()?
.get_trackers(
state,
payment_intent.get_id(),
&req,
&pcr_data.merchant_account,
&pcr_data.profile,
&pcr_data.key_store,
&hyperswitch_domain_models::payments::HeaderPayload::default(),
None,
)
.await?;
let (payment_data, _req, _, _) = Box::pin(payments::proxy_for_payments_operation_core::<
payments_types::Authorize,
_,
_,
_,
PaymentConfirmData<payments_types::Authorize>,
>(
state,
state.get_req_state(),
pcr_data.merchant_account.clone(),
pcr_data.key_store.clone(),
pcr_data.profile.clone(),
operation,
req,
get_tracker_response,
payments::CallConnectorAction::Trigger,
hyperswitch_domain_models::payments::HeaderPayload::default(),
))
.await?;
Ok(payment_data)
}
<file_sep path="hyperswitch/crates/router/src/core/revenue_recovery/types.rs" role="context" start="52" end="58">
pub enum PcrAttemptStatus {
Succeeded,
Failed,
Processing,
InvalidStatus(String),
// Cancelled,
}
<file_sep path="hyperswitch/crates/router/src/core/revenue_recovery/types.rs" role="context" start="48" end="48">
type RecoveryResult<T> = error_stack::Result<T, errors::RecoveryError>;
<file_sep path="hyperswitch/crates/router/tests/utils.rs" role="context" start="414" end="416">
pub struct Status {
status: String,
}
<file_sep path="hyperswitch/v2_compatible_migrations/2024-08-28-081721_add_v2_columns/up.sql" role="context" start="19" end="35">
-- Intentionally not adding a default value here since we would have to
-- check if any merchants have enabled this from configs table,
-- before filling data for this column.
-- If no merchants have enabled this, then we can use `false` as the default value
-- when adding the column, later we can drop the default added for the column
-- so that we ensure new records inserted always have a value for the column.
ADD COLUMN should_collect_cvv_during_payment BOOLEAN;
ALTER TABLE payment_intent
ADD COLUMN merchant_reference_id VARCHAR(64),
ADD COLUMN billing_address BYTEA DEFAULT NULL,
ADD COLUMN shipping_address BYTEA DEFAULT NULL,
ADD COLUMN capture_method "CaptureMethod",
ADD COLUMN authentication_type "AuthenticationType",
ADD COLUMN amount_to_capture bigint,
ADD COLUMN prerouting_algorithm JSONB,
ADD COLUMN surcharge_amount bigint,
<file_sep path="hyperswitch/crates/api_models/src/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/payment_methods.rs<|crate|> router anchor=list_payment_methods_for_session 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="1302" end="1347">
pub async fn list_payment_methods_for_session(
state: SessionState,
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
profile: domain::Profile,
payment_method_session_id: id_type::GlobalPaymentMethodSessionId,
) -> RouterResponse<api::PaymentMethodListResponse> {
let key_manager_state = &(&state).into();
let db = &*state.store;
let payment_method_session = db
.get_payment_methods_session(key_manager_state, &key_store, &payment_method_session_id)
.await
.change_context(errors::ApiErrorResponse::PaymentMethodNotFound)
.attach_printable("Unable to find payment method")?;
let payment_connector_accounts = db
.list_enabled_connector_accounts_by_profile_id(
key_manager_state,
profile.get_id(),
&key_store,
common_enums::ConnectorType::PaymentProcessor,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("error when fetching merchant connector accounts")?;
let customer_payment_methods = list_customer_payment_method_core(
&state,
&merchant_account,
&key_store,
&payment_method_session.customer_id,
)
.await?;
let response =
hyperswitch_domain_models::merchant_connector_account::FlattenedPaymentMethodsEnabled::from_payment_connectors_list(payment_connector_accounts)
.perform_filtering()
.get_required_fields(RequiredFieldsInput::new(state.conf.required_fields.clone()))
.generate_response(customer_payment_methods.customer_payment_methods);
Ok(hyperswitch_domain_models::api::ApplicationResponse::Json(
response,
))
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods.rs" role="context" start="1301" end="1301">
#[cfg(feature = "v2")]
impl PerformFilteringOnEnabledPaymentMethods
for hyperswitch_domain_models::merchant_connector_account::FlattenedPaymentMethodsEnabled
{
fn perform_filtering(self) -> FilteredPaymentMethodsEnabled {
FilteredPaymentMethodsEnabled(self.payment_methods_enabled)
}
}
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
#[instrument(skip_all)]
pub async fn list_payment_methods_for_session(
state: SessionState,
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
profile: domain::Profile,
payment_method_session_id: id_type::GlobalPaymentMethodSessionId,
) -> RouterResponse<api::PaymentMethodListResponse> {
let key_manager_state = &(&state).into();
let db = &*state.store;
let payment_method_session = db
.get_payment_methods_session(key_manager_state, &key_store, &payment_method_session_id)
<file_sep path="hyperswitch/crates/router/src/core/payment_methods.rs" role="context" start="1368" end="1378">
pub async fn get_total_saved_payment_methods_for_merchant(
state: SessionState,
merchant_account: domain::MerchantAccount,
) -> RouterResponse<api::TotalPaymentMethodCountResponse> {
let total_payment_method_count =
get_total_payment_method_count_core(&state, &merchant_account).await?;
Ok(hyperswitch_domain_models::api::ApplicationResponse::Json(
total_payment_method_count,
))
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods.rs" role="context" start="1351" end="1364">
pub async fn list_saved_payment_methods_for_customer(
state: SessionState,
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
customer_id: id_type::GlobalCustomerId,
) -> RouterResponse<api::CustomerPaymentMethodsListResponse> {
let customer_payment_methods =
list_customer_payment_method_core(&state, &merchant_account, &key_store, &customer_id)
.await?;
Ok(hyperswitch_domain_models::api::ApplicationResponse::Json(
customer_payment_methods,
))
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods.rs" role="context" start="1295" end="1297">
fn perform_filtering(self) -> FilteredPaymentMethodsEnabled {
FilteredPaymentMethodsEnabled(self.payment_methods_enabled)
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods.rs" role="context" start="1224" end="1284">
pub async fn payment_method_intent_create(
state: &SessionState,
req: api::PaymentMethodIntentCreate,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
) -> RouterResponse<api::PaymentMethodResponse> {
let db = &*state.store;
let merchant_id = merchant_account.get_id();
let customer_id = req.customer_id.to_owned();
let key_manager_state = &(state).into();
db.find_customer_by_global_id(
key_manager_state,
&customer_id,
merchant_account.get_id(),
key_store,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)
.attach_printable("Customer not found for the payment method")?;
let payment_method_billing_address = req
.billing
.clone()
.async_map(|billing| cards::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")?
.map(|encoded_address| {
encoded_address.deserialize_inner_value(|value| value.parse_value("Address"))
})
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to parse Payment method billing address")?;
// create pm entry
let payment_method_id =
id_type::GlobalPaymentMethodId::generate(&state.conf.cell_information.id)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to generate GlobalPaymentMethodId")?;
let payment_method = create_payment_method_for_intent(
state,
req.metadata.clone(),
&customer_id,
payment_method_id,
merchant_id,
key_store,
merchant_account.storage_scheme,
payment_method_billing_address,
)
.await
.attach_printable("Failed to add Payment method to DB")?;
let resp = pm_transforms::generate_payment_method_response(&payment_method, &None)?;
Ok(services::ApplicationResponse::Json(resp))
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods.rs" role="context" start="1388" end="1392">
fn new(required_fields_config: settings::RequiredFields) -> Self {
Self {
required_fields_config,
}
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods.rs" role="context" start="1815" end="1848">
pub async fn list_customer_payment_method_core(
state: &SessionState,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
customer_id: &id_type::GlobalCustomerId,
) -> RouterResult<api::CustomerPaymentMethodsListResponse> {
let db = &*state.store;
let key_manager_state = &(state).into();
let saved_payment_methods = db
.find_payment_method_by_global_customer_id_merchant_id_status(
key_manager_state,
key_store,
customer_id,
merchant_account.get_id(),
common_enums::PaymentMethodStatus::Active,
None,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
let customer_payment_methods = saved_payment_methods
.into_iter()
.map(ForeignTryFrom::foreign_try_from)
.collect::<Result<Vec<api::CustomerPaymentMethod>, _>>()
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let response = api::CustomerPaymentMethodsListResponse {
customer_payment_methods,
};
Ok(response)
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods.rs" role="context" start="1382" end="1384">
struct RequiredFieldsInput {
required_fields_config: settings::RequiredFields,
}
<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/operations/payment_response.rs<|crate|> router anchor=update_connector_mandate_details_for_the_flow kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_response.rs" role="context" start="2668" end="2713">
fn update_connector_mandate_details_for_the_flow<F: Clone>(
connector_mandate_id: Option<String>,
mandate_metadata: Option<masking::Secret<serde_json::Value>>,
connector_mandate_request_reference_id: Option<String>,
payment_data: &mut PaymentData<F>,
) -> RouterResult<()> {
let mut original_connector_mandate_reference_id = payment_data
.payment_attempt
.connector_mandate_detail
.as_ref()
.map(|detail| ConnectorMandateReferenceId::foreign_from(detail.clone()));
let connector_mandate_reference_id = if connector_mandate_id.is_some() {
if let Some(ref mut record) = original_connector_mandate_reference_id {
record.update(
connector_mandate_id,
None,
None,
mandate_metadata,
connector_mandate_request_reference_id,
);
Some(record.clone())
} else {
Some(ConnectorMandateReferenceId::new(
connector_mandate_id,
None,
None,
mandate_metadata,
connector_mandate_request_reference_id,
))
}
} else {
original_connector_mandate_reference_id
};
payment_data.payment_attempt.connector_mandate_detail = connector_mandate_reference_id
.clone()
.map(ForeignFrom::foreign_from);
payment_data.set_mandate_id(api_models::payments::MandateIds {
mandate_id: None,
mandate_reference_id: connector_mandate_reference_id.map(|connector_mandate_id| {
MandateReferenceId::ConnectorMandateId(connector_mandate_id)
}),
});
Ok(())
}
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_response.rs" role="context" start="2667" end="2667">
use api_models::payments::{ConnectorMandateReferenceId, MandateReferenceId};
use api_models::routing::RoutableConnectorChoice;
use hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt;
use hyperswitch_domain_models::payments::{
PaymentConfirmData, PaymentIntentData, PaymentStatusData,
};
use crate::{
connector::utils::PaymentResponseRouterData,
consts,
core::{
card_testing_guard::utils as card_testing_guard_utils,
errors::{self, CustomResult, RouterResult, StorageErrorExt},
mandate,
payment_methods::{self, cards::create_encrypted_data},
payments::{
helpers::{
self as payments_helpers,
update_additional_payment_data_with_connector_response_pm_data,
},
tokenization,
types::MultipleCaptureData,
PaymentData, PaymentMethodChecker,
},
utils as core_utils,
},
routes::{metrics, SessionState},
types::{
self, domain,
storage::{self, enums},
transformers::{ForeignFrom, ForeignTryFrom},
CaptureSyncResponse, ErrorResponse,
},
utils,
};
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_response.rs" role="context" start="2743" end="2769">
fn get_capture_update_for_unmapped_capture_responses(
unmapped_capture_sync_response_list: Vec<CaptureSyncResponse>,
multiple_capture_data: &MultipleCaptureData,
) -> RouterResult<Vec<(storage::Capture, storage::CaptureUpdate)>> {
let mut result = Vec::new();
let captures_without_connector_capture_id: Vec<_> = multiple_capture_data
.get_pending_captures_without_connector_capture_id()
.into_iter()
.cloned()
.collect();
for capture_sync_response in unmapped_capture_sync_response_list {
if let Some(capture) = captures_without_connector_capture_id
.iter()
.find(|capture| {
capture_sync_response.get_connector_response_reference_id()
== Some(capture.capture_id.clone())
|| capture_sync_response.get_amount_captured() == Some(capture.amount)
})
{
result.push((
capture.clone(),
storage::CaptureUpdate::foreign_try_from(capture_sync_response)?,
))
}
}
Ok(result)
}
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_response.rs" role="context" start="2715" end="2741">
fn response_to_capture_update(
multiple_capture_data: &MultipleCaptureData,
response_list: HashMap<String, CaptureSyncResponse>,
) -> RouterResult<Vec<(storage::Capture, storage::CaptureUpdate)>> {
let mut capture_update_list = vec![];
let mut unmapped_captures = vec![];
for (connector_capture_id, capture_sync_response) in response_list {
let capture =
multiple_capture_data.get_capture_by_connector_capture_id(&connector_capture_id);
if let Some(capture) = capture {
capture_update_list.push((
capture.clone(),
storage::CaptureUpdate::foreign_try_from(capture_sync_response)?,
))
} else {
// connector_capture_id may not be populated in the captures table in some case
// if so, we try to map the unmapped capture response and captures in DB.
unmapped_captures.push(capture_sync_response)
}
}
capture_update_list.extend(get_capture_update_for_unmapped_capture_responses(
unmapped_captures,
multiple_capture_data,
)?);
Ok(capture_update_list)
}
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_response.rs" role="context" start="2564" end="2664">
async fn save_pm_and_mandate<'b>(
&self,
state: &SessionState,
router_data: &types::RouterData<
F,
types::SetupMandateRequestData,
types::PaymentsResponseData,
>,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
payment_data: &mut PaymentConfirmData<F>,
_business_profile: &domain::Profile,
) -> CustomResult<(), errors::ApiErrorResponse>
where
F: 'b + Clone + Send + Sync,
{
// If we received a payment_method_id from connector in the router data response
// Then we either update the payment method or create a new payment method
// The case for updating the payment method is when the payment is created from the payment method service
let Ok(payments_response) = &router_data.response else {
// In case there was an error response from the connector
// We do not take any action related to the payment method
return Ok(());
};
let connector_request_reference_id = payment_data
.payment_attempt
.connector_token_details
.as_ref()
.and_then(|token_details| token_details.get_connector_token_request_reference_id());
let connector_token =
payments_response.get_updated_connector_token_details(connector_request_reference_id);
let payment_method_id = payment_data.payment_attempt.payment_method_id.clone();
// TODO: check what all conditions we will need to see if card need to be saved
match (
connector_token
.as_ref()
.and_then(|connector_token| connector_token.connector_mandate_id.clone()),
payment_method_id,
) {
(Some(token), Some(payment_method_id)) => {
if !matches!(
router_data.status,
enums::AttemptStatus::Charged | enums::AttemptStatus::Authorized
) {
return Ok(());
}
let connector_id = payment_data
.payment_attempt
.merchant_connector_id
.clone()
.get_required_value("merchant_connector_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("missing connector id")?;
let net_amount = payment_data.payment_attempt.amount_details.get_net_amount();
let currency = payment_data.payment_intent.amount_details.currency;
let connector_token_details_for_payment_method_update =
api_models::payment_methods::ConnectorTokenDetails {
connector_id,
status: common_enums::ConnectorTokenStatus::Active,
connector_token_request_reference_id: connector_token
.and_then(|details| details.connector_token_request_reference_id),
original_payment_authorized_amount: Some(net_amount),
original_payment_authorized_currency: Some(currency),
metadata: None,
token: masking::Secret::new(token),
token_type: common_enums::TokenizationType::MultiUse,
};
let payment_method_update_request =
api_models::payment_methods::PaymentMethodUpdate {
payment_method_data: None,
connector_token_details: Some(
connector_token_details_for_payment_method_update,
),
};
payment_methods::update_payment_method_core(
state,
merchant_account,
key_store,
payment_method_update_request,
&payment_method_id,
)
.await
.attach_printable("Failed to update payment method")?;
}
(Some(_), None) => {
// TODO: create a new payment method
}
(None, Some(_)) | (None, None) => {}
}
Ok(())
}
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_response.rs" role="context" start="2505" end="2562">
async fn update_tracker<'b>(
&'b self,
state: &'b SessionState,
mut payment_data: PaymentConfirmData<F>,
response: types::RouterData<F, types::SetupMandateRequestData, types::PaymentsResponseData>,
key_store: &domain::MerchantKeyStore,
storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<PaymentConfirmData<F>>
where
F: 'b + Send + Sync,
types::RouterData<F, types::SetupMandateRequestData, types::PaymentsResponseData>:
hyperswitch_domain_models::router_data::TrackerPostUpdateObjects<
F,
types::SetupMandateRequestData,
PaymentConfirmData<F>,
>,
{
use hyperswitch_domain_models::router_data::TrackerPostUpdateObjects;
let db = &*state.store;
let key_manager_state = &state.into();
let response_router_data = response;
let payment_intent_update =
response_router_data.get_payment_intent_update(&payment_data, storage_scheme);
let payment_attempt_update =
response_router_data.get_payment_attempt_update(&payment_data, storage_scheme);
let updated_payment_intent = db
.update_payment_intent(
key_manager_state,
payment_data.payment_intent,
payment_intent_update,
key_store,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to update payment intent")?;
let updated_payment_attempt = db
.update_payment_attempt(
key_manager_state,
key_store,
payment_data.payment_attempt,
payment_attempt_update,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to update payment attempt")?;
payment_data.payment_intent = updated_payment_intent;
payment_data.payment_attempt = updated_payment_attempt;
Ok(payment_data)
}
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_response.rs" role="context" start="577" end="628">
async fn save_pm_and_mandate<'b>(
&self,
state: &SessionState,
resp: &types::RouterData<F, types::PaymentsSyncData, types::PaymentsResponseData>,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
payment_data: &mut PaymentData<F>,
_business_profile: &domain::Profile,
) -> CustomResult<(), errors::ApiErrorResponse>
where
F: 'b + Clone + Send + Sync,
{
let (connector_mandate_id, mandate_metadata, connector_mandate_request_reference_id) = resp
.response
.clone()
.ok()
.and_then(|resp| {
if let types::PaymentsResponseData::TransactionResponse {
mandate_reference, ..
} = resp
{
mandate_reference.map(|mandate_ref| {
(
mandate_ref.connector_mandate_id.clone(),
mandate_ref.mandate_metadata.clone(),
mandate_ref.connector_mandate_request_reference_id.clone(),
)
})
} else {
None
}
})
.unwrap_or((None, None, None));
update_connector_mandate_details_for_the_flow(
connector_mandate_id,
mandate_metadata,
connector_mandate_request_reference_id,
payment_data,
)?;
update_payment_method_status_and_ntid(
state,
key_store,
payment_data,
resp.status,
resp.response.clone(),
merchant_account.storage_scheme,
)
.await?;
Ok(())
}
<file_sep path="hyperswitch/crates/router/src/core/payments/operations/payment_response.rs" role="context" start="1201" end="1251">
async fn save_pm_and_mandate<'b>(
&self,
state: &SessionState,
resp: &types::RouterData<F, types::CompleteAuthorizeData, types::PaymentsResponseData>,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
payment_data: &mut PaymentData<F>,
_business_profile: &domain::Profile,
) -> CustomResult<(), errors::ApiErrorResponse>
where
F: 'b + Clone + Send + Sync,
{
let (connector_mandate_id, mandate_metadata, connector_mandate_request_reference_id) = resp
.response
.clone()
.ok()
.and_then(|resp| {
if let types::PaymentsResponseData::TransactionResponse {
mandate_reference, ..
} = resp
{
mandate_reference.map(|mandate_ref| {
(
mandate_ref.connector_mandate_id.clone(),
mandate_ref.mandate_metadata.clone(),
mandate_ref.connector_mandate_request_reference_id.clone(),
)
})
} else {
None
}
})
.unwrap_or((None, None, None));
update_connector_mandate_details_for_the_flow(
connector_mandate_id,
mandate_metadata,
connector_mandate_request_reference_id,
payment_data,
)?;
update_payment_method_status_and_ntid(
state,
key_store,
payment_data,
resp.status,
resp.response.clone(),
merchant_account.storage_scheme,
)
.await?;
Ok(())
}
<file_sep path="hyperswitch/crates/router/src/types/transformers.rs" role="context" start="45" end="47">
pub trait ForeignFrom<F> {
fn foreign_from(from: F) -> Self;
}
<file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="1670" end="1670">
type Value = PaymentMethodListRequest;
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payment_methods.rs<|crate|> router anchor=add_payment_method_status_update_task 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="469" end="521">
pub async fn add_payment_method_status_update_task(
db: &dyn StorageInterface,
payment_method: &domain::PaymentMethod,
prev_status: enums::PaymentMethodStatus,
curr_status: enums::PaymentMethodStatus,
merchant_id: &id_type::MerchantId,
) -> Result<(), ProcessTrackerError> {
let created_at = payment_method.created_at;
let schedule_time =
created_at.saturating_add(Duration::seconds(consts::DEFAULT_SESSION_EXPIRY));
let tracking_data = storage::PaymentMethodStatusTrackingData {
payment_method_id: payment_method.get_id().clone(),
prev_status,
curr_status,
merchant_id: merchant_id.to_owned(),
};
let runner = storage::ProcessTrackerRunner::PaymentMethodStatusUpdateWorkflow;
let task = PAYMENT_METHOD_STATUS_UPDATE_TASK;
let tag = [PAYMENT_METHOD_STATUS_TAG];
let process_tracker_id = generate_task_id_for_payment_method_status_update_workflow(
payment_method.get_id().as_str(),
runner,
task,
);
let process_tracker_entry = storage::ProcessTrackerNew::new(
process_tracker_id,
task,
runner,
tag,
tracking_data,
None,
schedule_time,
common_types::consts::API_VERSION,
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to construct PAYMENT_METHOD_STATUS_UPDATE process tracker task")?;
db
.insert_process(process_tracker_entry)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| {
format!(
"Failed while inserting PAYMENT_METHOD_STATUS_UPDATE reminder to process_tracker for payment_method_id: {}",
payment_method.get_id().clone()
)
})?;
Ok(())
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods.rs" role="context" start="468" end="468">
fn generate_task_id_for_payment_method_status_update_workflow(
key_id: &str,
runner: storage::ProcessTrackerRunner,
task: &str,
) -> String {
format!("{runner}_{task}_{key_id}")
}
#[cfg(all(
any(feature = "v1", feature = "v2"),
not(feature = "payment_methods_v2")
))]
pub async fn add_payment_method_status_update_task(
db: &dyn StorageInterface,
payment_method: &domain::PaymentMethod,
prev_status: enums::PaymentMethodStatus,
curr_status: enums::PaymentMethodStatus,
merchant_id: &id_type::MerchantId,
) -> Result<(), ProcessTrackerError> {
let created_at = payment_method.created_at;
let schedule_time =
created_at.saturating_add(Duration::seconds(consts::DEFAULT_SESSION_EXPIRY));
let tracking_data = storage::PaymentMethodStatusTrackingData {
payment_method_id: payment_method.get_id().clone(),
<file_sep path="hyperswitch/crates/router/src/core/payment_methods.rs" role="context" start="547" end="709">
pub async fn retrieve_payment_method_with_token(
state: &SessionState,
merchant_key_store: &domain::MerchantKeyStore,
token_data: &storage::PaymentTokenData,
payment_intent: &PaymentIntent,
payment_attempt: &PaymentAttempt,
card_token_data: Option<&domain::CardToken>,
customer: &Option<domain::Customer>,
storage_scheme: common_enums::enums::MerchantStorageScheme,
mandate_id: Option<api_models::payments::MandateIds>,
payment_method_info: Option<domain::PaymentMethod>,
business_profile: &domain::Profile,
should_retry_with_pan: bool,
vault_data: Option<&VaultData>,
) -> RouterResult<storage::PaymentMethodDataWithId> {
let token = match token_data {
storage::PaymentTokenData::TemporaryGeneric(generic_token) => {
payment_helpers::retrieve_payment_method_with_temporary_token(
state,
&generic_token.token,
payment_intent,
payment_attempt,
merchant_key_store,
card_token_data,
)
.await?
.map(
|(payment_method_data, payment_method)| storage::PaymentMethodDataWithId {
payment_method_data: Some(payment_method_data),
payment_method: Some(payment_method),
payment_method_id: None,
},
)
.unwrap_or_default()
}
storage::PaymentTokenData::Temporary(generic_token) => {
payment_helpers::retrieve_payment_method_with_temporary_token(
state,
&generic_token.token,
payment_intent,
payment_attempt,
merchant_key_store,
card_token_data,
)
.await?
.map(
|(payment_method_data, payment_method)| storage::PaymentMethodDataWithId {
payment_method_data: Some(payment_method_data),
payment_method: Some(payment_method),
payment_method_id: None,
},
)
.unwrap_or_default()
}
storage::PaymentTokenData::Permanent(card_token) => {
payment_helpers::retrieve_payment_method_data_with_permanent_token(
state,
card_token.locker_id.as_ref().unwrap_or(&card_token.token),
card_token
.payment_method_id
.as_ref()
.unwrap_or(&card_token.token),
payment_intent,
card_token_data,
merchant_key_store,
storage_scheme,
mandate_id,
payment_method_info
.get_required_value("PaymentMethod")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("PaymentMethod not found")?,
business_profile,
payment_attempt.connector.clone(),
should_retry_with_pan,
vault_data,
)
.await
.map(|card| Some((card, enums::PaymentMethod::Card)))?
.map(
|(payment_method_data, payment_method)| storage::PaymentMethodDataWithId {
payment_method_data: Some(payment_method_data),
payment_method: Some(payment_method),
payment_method_id: Some(
card_token
.payment_method_id
.as_ref()
.unwrap_or(&card_token.token)
.to_string(),
),
},
)
.unwrap_or_default()
}
storage::PaymentTokenData::PermanentCard(card_token) => {
payment_helpers::retrieve_payment_method_data_with_permanent_token(
state,
card_token.locker_id.as_ref().unwrap_or(&card_token.token),
card_token
.payment_method_id
.as_ref()
.unwrap_or(&card_token.token),
payment_intent,
card_token_data,
merchant_key_store,
storage_scheme,
mandate_id,
payment_method_info
.get_required_value("PaymentMethod")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("PaymentMethod not found")?,
business_profile,
payment_attempt.connector.clone(),
should_retry_with_pan,
vault_data,
)
.await
.map(|card| Some((card, enums::PaymentMethod::Card)))?
.map(
|(payment_method_data, payment_method)| storage::PaymentMethodDataWithId {
payment_method_data: Some(payment_method_data),
payment_method: Some(payment_method),
payment_method_id: Some(
card_token
.payment_method_id
.as_ref()
.unwrap_or(&card_token.token)
.to_string(),
),
},
)
.unwrap_or_default()
}
storage::PaymentTokenData::AuthBankDebit(auth_token) => {
pm_auth::retrieve_payment_method_from_auth_service(
state,
merchant_key_store,
auth_token,
payment_intent,
customer,
)
.await?
.map(
|(payment_method_data, payment_method)| storage::PaymentMethodDataWithId {
payment_method_data: Some(payment_method_data),
payment_method: Some(payment_method),
payment_method_id: None,
},
)
.unwrap_or_default()
}
storage::PaymentTokenData::WalletToken(_) => storage::PaymentMethodDataWithId {
payment_method: None,
payment_method_data: None,
payment_method_id: None,
},
};
Ok(token)
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods.rs" role="context" start="526" end="539">
pub async fn retrieve_payment_method_with_token(
_state: &SessionState,
_merchant_key_store: &domain::MerchantKeyStore,
_token_data: &storage::PaymentTokenData,
_payment_intent: &PaymentIntent,
_card_token_data: Option<&domain::CardToken>,
_customer: &Option<domain::Customer>,
_storage_scheme: common_enums::enums::MerchantStorageScheme,
_mandate_id: Option<api_models::payments::MandateIds>,
_payment_method_info: Option<domain::PaymentMethod>,
_business_profile: &domain::Profile,
) -> RouterResult<storage::PaymentMethodDataWithId> {
todo!()
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods.rs" role="context" start="457" end="463">
fn generate_task_id_for_payment_method_status_update_workflow(
key_id: &str,
runner: storage::ProcessTrackerRunner,
task: &str,
) -> String {
format!("{runner}_{task}_{key_id}")
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods.rs" role="context" start="293" end="455">
pub async fn render_pm_collect_link(
state: SessionState,
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
req: payment_methods::PaymentMethodCollectLinkRenderRequest,
) -> RouterResponse<services::GenericLinkFormData> {
let db: &dyn StorageInterface = &*state.store;
// Fetch pm collect link
let pm_collect_link = db
.find_pm_collect_link_by_link_id(&req.pm_collect_link_id)
.await
.to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError {
message: "payment method collect link not found".to_string(),
})?;
// Check status and return form data accordingly
let has_expired = common_utils::date_time::now() > pm_collect_link.expiry;
let status = pm_collect_link.link_status;
let link_data = pm_collect_link.link_data;
let default_config = &state.conf.generic_link.payment_method_collect;
let default_ui_config = default_config.ui_config.clone();
let ui_config_data = common_utils::link_utils::GenericLinkUiConfigFormData {
merchant_name: link_data
.ui_config
.merchant_name
.unwrap_or(default_ui_config.merchant_name),
logo: link_data.ui_config.logo.unwrap_or(default_ui_config.logo),
theme: link_data
.ui_config
.theme
.clone()
.unwrap_or(default_ui_config.theme.clone()),
};
match status {
common_utils::link_utils::PaymentMethodCollectStatus::Initiated => {
// if expired, send back expired status page
if has_expired {
let expired_link_data = services::GenericExpiredLinkData {
title: "Payment collect link has expired".to_string(),
message: "This payment collect link has expired.".to_string(),
theme: link_data.ui_config.theme.unwrap_or(default_ui_config.theme),
};
Ok(services::ApplicationResponse::GenericLinkForm(Box::new(
GenericLinks {
allowed_domains: HashSet::from([]),
data: GenericLinksData::ExpiredLink(expired_link_data),
locale: DEFAULT_LOCALE.to_string(),
},
)))
// else, send back form link
} else {
let customer_id = id_type::CustomerId::try_from(Cow::from(
pm_collect_link.primary_reference.clone(),
))
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "customer_id",
})?;
// Fetch customer
let customer = db
.find_customer_by_customer_id_merchant_id(
&(&state).into(),
&customer_id,
&req.merchant_id,
&key_store,
merchant_account.storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InvalidRequestData {
message: format!(
"Customer [{}] not found for link_id - {}",
pm_collect_link.primary_reference, pm_collect_link.link_id
),
})
.attach_printable(format!(
"customer [{}] not found",
pm_collect_link.primary_reference
))?;
let js_data = payment_methods::PaymentMethodCollectLinkDetails {
publishable_key: Secret::new(merchant_account.publishable_key),
client_secret: link_data.client_secret.clone(),
pm_collect_link_id: pm_collect_link.link_id,
customer_id: customer.customer_id,
session_expiry: pm_collect_link.expiry,
return_url: pm_collect_link.return_url,
ui_config: ui_config_data,
enabled_payment_methods: link_data.enabled_payment_methods,
};
let serialized_css_content = String::new();
let serialized_js_content = format!(
"window.__PM_COLLECT_DETAILS = {}",
js_data
.encode_to_string_of_json()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to serialize PaymentMethodCollectLinkDetails")?
);
let generic_form_data = services::GenericLinkFormData {
js_data: serialized_js_content,
css_data: serialized_css_content,
sdk_url: default_config.sdk_url.to_string(),
html_meta_tags: String::new(),
};
Ok(services::ApplicationResponse::GenericLinkForm(Box::new(
GenericLinks {
allowed_domains: HashSet::from([]),
data: GenericLinksData::PaymentMethodCollect(generic_form_data),
locale: DEFAULT_LOCALE.to_string(),
},
)))
}
}
// Send back status page
status => {
let js_data = payment_methods::PaymentMethodCollectLinkStatusDetails {
pm_collect_link_id: pm_collect_link.link_id,
customer_id: link_data.customer_id,
session_expiry: pm_collect_link.expiry,
return_url: pm_collect_link
.return_url
.as_ref()
.map(|url| url::Url::parse(url))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Failed to parse return URL for payment method collect's status link",
)?,
ui_config: ui_config_data,
status,
};
let serialized_css_content = String::new();
let serialized_js_content = format!(
"window.__PM_COLLECT_DETAILS = {}",
js_data
.encode_to_string_of_json()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Failed to serialize PaymentMethodCollectLinkStatusDetails"
)?
);
let generic_status_data = services::GenericLinkStatusData {
js_data: serialized_js_content,
css_data: serialized_css_content,
};
Ok(services::ApplicationResponse::GenericLinkForm(Box::new(
GenericLinks {
allowed_domains: HashSet::from([]),
data: GenericLinksData::PaymentMethodCollectStatus(generic_status_data),
locale: DEFAULT_LOCALE.to_string(),
},
)))
}
}
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods.rs" role="context" start="1388" end="1392">
fn new(required_fields_config: settings::RequiredFields) -> Self {
Self {
required_fields_config,
}
}
<file_sep path="hyperswitch/crates/router/src/connector/nmi/transformers.rs" role="context" start="454" end="459">
pub enum PaymentMethod {
CardNonThreeDs(Box<CardData>),
CardThreeDs(Box<CardThreeDsData>),
GPay(Box<GooglePayData>),
ApplePay(Box<ApplePayData>),
}
<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/payment_methods.rs<|crate|> router anchor=vault_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.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/payment_methods.rs" role="context" start="1680" end="1680">
.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)
}
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
#[instrument(skip_all)]
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())
<file_sep path="hyperswitch/crates/router/src/core/payment_methods.rs" role="context" start="1815" end="1848">
pub async fn list_customer_payment_method_core(
state: &SessionState,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
customer_id: &id_type::GlobalCustomerId,
) -> RouterResult<api::CustomerPaymentMethodsListResponse> {
let db = &*state.store;
let key_manager_state = &(state).into();
let saved_payment_methods = db
.find_payment_method_by_global_customer_id_merchant_id_status(
key_manager_state,
key_store,
customer_id,
merchant_account.get_id(),
common_enums::PaymentMethodStatus::Active,
None,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
let customer_payment_methods = saved_payment_methods
.into_iter()
.map(ForeignTryFrom::foreign_try_from)
.collect::<Result<Vec<api::CustomerPaymentMethod>, _>>()
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let response = api::CustomerPaymentMethodsListResponse {
customer_payment_methods,
};
Ok(response)
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods.rs" role="context" start="1732" end="1812">
fn get_pm_list_context(
payment_method_type: enums::PaymentMethod,
payment_method: &domain::PaymentMethod,
is_payment_associated: bool,
) -> Result<Option<PaymentMethodListContext>, error_stack::Report<errors::ApiErrorResponse>> {
let payment_method_data = payment_method
.payment_method_data
.clone()
.map(|payment_method_data| payment_method_data.into_inner());
let payment_method_retrieval_context = match payment_method_data {
Some(payment_methods::PaymentMethodsData::Card(card)) => {
Some(PaymentMethodListContext::Card {
card_details: api::CardDetailFromLocker::from(card),
token_data: is_payment_associated.then_some(
storage::PaymentTokenData::permanent_card(
Some(payment_method.get_id().clone()),
payment_method
.locker_id
.as_ref()
.map(|id| id.get_string_repr().to_owned())
.or_else(|| Some(payment_method.get_id().get_string_repr().to_owned())),
payment_method
.locker_id
.as_ref()
.map(|id| id.get_string_repr().to_owned())
.unwrap_or_else(|| {
payment_method.get_id().get_string_repr().to_owned()
}),
),
),
})
}
Some(payment_methods::PaymentMethodsData::BankDetails(bank_details)) => {
let get_bank_account_token_data =
|| -> CustomResult<payment_methods::BankAccountTokenData,errors::ApiErrorResponse> {
let connector_details = bank_details
.connector_details
.first()
.cloned()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to obtain bank account connector details")?;
let payment_method_subtype = payment_method
.get_payment_method_subtype()
.get_required_value("payment_method_subtype")
.attach_printable("PaymentMethodType not found")?;
Ok(payment_methods::BankAccountTokenData {
payment_method_type: payment_method_subtype,
payment_method: payment_method_type,
connector_details,
})
};
// Retrieve the pm_auth connector details so that it can be tokenized
let bank_account_token_data = get_bank_account_token_data()
.inspect_err(|error| logger::error!(?error))
.ok();
bank_account_token_data.map(|data| {
let token_data = storage::PaymentTokenData::AuthBankDebit(data);
PaymentMethodListContext::Bank {
token_data: is_payment_associated.then_some(token_data),
}
})
}
Some(payment_methods::PaymentMethodsData::WalletDetails(_)) | None => {
Some(PaymentMethodListContext::TemporaryToken {
token_data: is_payment_associated.then_some(
storage::PaymentTokenData::temporary_generic(generate_id(
consts::ID_LENGTH,
"token",
)),
),
})
}
};
Ok(payment_method_retrieval_context)
}
<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="1577" end="1610">
fn create_connector_token_details_update(
token_details: payment_methods::ConnectorTokenDetails,
payment_method: &domain::PaymentMethod,
) -> hyperswitch_domain_models::mandates::CommonMandateReference {
let connector_id = token_details.connector_id.clone();
let reference_record =
hyperswitch_domain_models::mandates::ConnectorTokenReferenceRecord::foreign_from(
token_details,
);
let connector_token_details = payment_method.connector_mandate_details.clone();
match connector_token_details {
Some(mut connector_mandate_reference) => {
connector_mandate_reference
.insert_payment_token_reference_record(&connector_id, reference_record);
connector_mandate_reference
}
None => {
let reference_record_hash_map =
std::collections::HashMap::from([(connector_id, reference_record)]);
let payments_mandate_reference =
hyperswitch_domain_models::mandates::PaymentsTokenReference(
reference_record_hash_map,
);
hyperswitch_domain_models::mandates::CommonMandateReference {
payments: Some(payments_mandate_reference),
payouts: None,
}
}
}
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods.rs" role="context" start="882" end="1022">
pub async fn create_payment_method_core(
state: &SessionState,
_request_state: &routes::app::ReqState,
req: api::PaymentMethodCreate,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
profile: &domain::Profile,
) -> RouterResult<api::PaymentMethodResponse> {
use common_utils::ext_traits::ValueExt;
req.validate()?;
let db = &*state.store;
let merchant_id = merchant_account.get_id();
let customer_id = req.customer_id.to_owned();
let key_manager_state = &(state).into();
db.find_customer_by_global_id(
key_manager_state,
&customer_id,
merchant_account.get_id(),
key_store,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)
.attach_printable("Customer not found for the payment method")?;
let payment_method_billing_address = req
.billing
.clone()
.async_map(|billing| cards::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")?
.map(|encoded_address| {
encoded_address.deserialize_inner_value(|value| value.parse_value("Address"))
})
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to parse Payment method billing address")?;
let payment_method_id =
id_type::GlobalPaymentMethodId::generate(&state.conf.cell_information.id)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to generate GlobalPaymentMethodId")?;
let payment_method = create_payment_method_for_intent(
state,
req.metadata.clone(),
&customer_id,
payment_method_id,
merchant_id,
key_store,
merchant_account.storage_scheme,
payment_method_billing_address,
)
.await
.attach_printable("Failed to add Payment method to DB")?;
let payment_method_data = domain::PaymentMethodVaultingData::from(req.payment_method_data)
.populate_bin_details_for_payment_method(state)
.await;
let vaulting_result = vault_payment_method(
state,
&payment_method_data,
merchant_account,
key_store,
None,
&customer_id,
)
.await;
let network_tokenization_resp = network_tokenize_and_vault_the_pmd(
state,
&payment_method_data,
merchant_account,
key_store,
req.network_tokenization.clone(),
profile.is_network_tokenization_enabled,
&customer_id,
)
.await;
let (response, payment_method) = match vaulting_result {
Ok((vaulting_resp, fingerprint_id)) => {
let pm_update = create_pm_additional_data_update(
Some(&payment_method_data),
state,
key_store,
Some(vaulting_resp.vault_id.get_string_repr().clone()),
Some(fingerprint_id),
&payment_method,
None,
network_tokenization_resp,
Some(req.payment_method_type),
Some(req.payment_method_subtype),
)
.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 resp = pm_transforms::generate_payment_method_response(&payment_method, &None)?;
Ok((resp, payment_method))
}
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")?;
Err(e)
}
}?;
Ok(response)
}
<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/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/payment_methods/cards.rs<|crate|> router anchor=get_card_from_hs_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="2869" end="2915">
pub async fn get_card_from_hs_locker<'a>(
state: &'a routes::SessionState,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
card_reference: &'a str,
locker_choice: api_enums::LockerChoice,
) -> errors::CustomResult<Card, errors::VaultError> {
let locker = &state.conf.locker;
let jwekey = &state.conf.jwekey.get_inner();
if !locker.mock_locker {
let request = payment_methods::mk_get_card_request_hs(
jwekey,
locker,
customer_id,
merchant_id,
card_reference,
Some(locker_choice),
state.tenant.tenant_id.clone(),
state.request_id,
)
.await
.change_context(errors::VaultError::FetchCardFailed)
.attach_printable("Making get card request failed")?;
let get_card_resp = call_locker_api::<payment_methods::RetrieveCardResp>(
state,
request,
"get_card_from_locker",
Some(locker_choice),
)
.await
.change_context(errors::VaultError::FetchCardFailed)?;
let retrieve_card_resp = get_card_resp
.payload
.get_required_value("RetrieveCardRespPayload")
.change_context(errors::VaultError::FetchCardFailed)?;
retrieve_card_resp
.card
.get_required_value("Card")
.change_context(errors::VaultError::FetchCardFailed)
} else {
let (get_card_resp, _) = mock_get_card(&*state.store, card_reference).await?;
payment_methods::mk_get_card_response(get_card_resp)
.change_context(errors::VaultError::ResponseDeserializationFailed)
}
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="2868" end="2868">
.transpose()?;
let pm_update = payment_method::PaymentMethodUpdate::ConnectorMandateDetailsUpdate {
connector_mandate_details: connector_mandate_details_value,
};
db.update_payment_method(&(state.into()), key_store, pm, pm_update, storage_scheme)
.await
.change_context(errors::VaultError::UpdateInPaymentMethodDataTableFailed)?;
Ok(())
}
#[instrument(skip_all)]
pub async fn get_card_from_hs_locker<'a>(
state: &'a routes::SessionState,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
card_reference: &'a str,
locker_choice: api_enums::LockerChoice,
) -> errors::CustomResult<Card, errors::VaultError> {
let locker = &state.conf.locker;
let jwekey = &state.conf.jwekey.get_inner();
if !locker.mock_locker {
let request = payment_methods::mk_get_card_request_hs(
jwekey,
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="2959" end="2966">
pub async fn delete_card_from_hs_locker_by_global_id<'a>(
state: &routes::SessionState,
id: &str,
merchant_id: &id_type::MerchantId,
card_reference: &'a str,
) -> errors::RouterResult<payment_methods::DeleteCardResp> {
todo!()
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="2918" end="2954">
pub async fn delete_card_from_hs_locker<'a>(
state: &routes::SessionState,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
card_reference: &'a str,
) -> errors::CustomResult<payment_methods::DeleteCardResp, errors::VaultError> {
let locker = &state.conf.locker;
let jwekey = &state.conf.jwekey.get_inner();
let request = payment_methods::mk_delete_card_request_hs(
jwekey,
locker,
customer_id,
merchant_id,
card_reference,
state.tenant.tenant_id.clone(),
state.request_id,
)
.await
.change_context(errors::VaultError::DeleteCardFailed)
.attach_printable("Making delete card request failed")?;
if !locker.mock_locker {
call_locker_api::<payment_methods::DeleteCardResp>(
state,
request,
"delete_card_from_locker",
Some(api_enums::LockerChoice::HyperswitchCardVault),
)
.await
.change_context(errors::VaultError::DeleteCardFailed)
} else {
Ok(mock_delete_card_hs(&*state.store, card_reference)
.await
.change_context(errors::VaultError::DeleteCardFailed)?)
}
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="2842" end="2867">
pub async fn update_payment_method_connector_mandate_details(
state: &routes::SessionState,
key_store: &domain::MerchantKeyStore,
db: &dyn db::StorageInterface,
pm: domain::PaymentMethod,
connector_mandate_details: Option<CommonMandateReference>,
storage_scheme: MerchantStorageScheme,
) -> errors::CustomResult<(), errors::VaultError> {
let connector_mandate_details_value = 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::VaultError::UpdateInPaymentMethodDataTableFailed
})
})
.transpose()?;
let pm_update = payment_method::PaymentMethodUpdate::ConnectorMandateDetailsUpdate {
connector_mandate_details: connector_mandate_details_value,
};
db.update_payment_method(&(state.into()), key_store, pm, pm_update, storage_scheme)
.await
.change_context(errors::VaultError::UpdateInPaymentMethodDataTableFailed)?;
Ok(())
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="2820" end="2836">
pub async fn update_payment_method_connector_mandate_details(
state: &routes::SessionState,
key_store: &domain::MerchantKeyStore,
db: &dyn db::StorageInterface,
pm: domain::PaymentMethod,
connector_mandate_details: Option<CommonMandateReference>,
storage_scheme: MerchantStorageScheme,
) -> errors::CustomResult<(), errors::VaultError> {
let pm_update = payment_method::PaymentMethodUpdate::ConnectorMandateDetailsUpdate {
connector_mandate_details: connector_mandate_details.map(|cmd| cmd.into()),
};
db.update_payment_method(&(state.into()), key_store, pm, pm_update, storage_scheme)
.await
.change_context(errors::VaultError::UpdateInPaymentMethodDataTableFailed)?;
Ok(())
}
<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="3029" end="3062">
pub async fn mock_get_card<'a>(
db: &dyn db::StorageInterface,
card_id: &'a str,
) -> errors::CustomResult<(payment_methods::GetCardResponse, Option<String>), errors::VaultError> {
let locker_mock_up = db
.find_locker_by_card_id(card_id)
.await
.change_context(errors::VaultError::FetchCardFailed)?;
let add_card_response = payment_methods::AddCardResponse {
card_id: locker_mock_up
.payment_method_id
.unwrap_or(locker_mock_up.card_id),
external_id: locker_mock_up.external_id,
card_fingerprint: locker_mock_up.card_fingerprint.into(),
card_global_fingerprint: locker_mock_up.card_global_fingerprint.into(),
merchant_id: Some(locker_mock_up.merchant_id),
card_number: cards::CardNumber::try_from(locker_mock_up.card_number)
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Invalid card number format from the mock locker")
.map(Some)?,
card_exp_year: Some(locker_mock_up.card_exp_year.into()),
card_exp_month: Some(locker_mock_up.card_exp_month.into()),
name_on_card: locker_mock_up.name_on_card.map(|card| card.into()),
nickname: locker_mock_up.nickname,
customer_id: locker_mock_up.customer_id,
duplicate: locker_mock_up.duplicate,
};
Ok((
payment_methods::GetCardResponse {
card: add_card_response,
},
locker_mock_up.card_cvc,
))
}
<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/core/payment_methods/cards.rs<|crate|> router anchor=get_bank_from_hs_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="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="5597" end="5597">
key_store,
payment_method.clone(),
update_last_used,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update the last_used_at in db")?;
Ok(())
}
#[cfg(feature = "payouts")]
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,
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="5746" end="5803">
pub async fn retrieve_payment_method(
state: routes::SessionState,
pm: api::PaymentMethodId,
key_store: domain::MerchantKeyStore,
merchant_account: domain::MerchantAccount,
) -> errors::RouterResponse<api::PaymentMethodResponse> {
let db = state.store.as_ref();
let pm = db
.find_payment_method(
&((&state).into()),
&key_store,
&pm.payment_method_id,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
let card = if pm.get_payment_method_type() == Some(enums::PaymentMethod::Card) {
let card_detail = if state.conf.locker.locker_enabled {
let card = get_card_from_locker(
&state,
&pm.customer_id,
&pm.merchant_id,
pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error getting card from card vault")?;
payment_methods::get_card_detail(&pm, card)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while getting card details from locker")?
} else {
get_card_details_without_locker_fallback(&pm, &state).await?
};
Some(card_detail)
} else {
None
};
Ok(services::ApplicationResponse::Json(
api::PaymentMethodResponse {
merchant_id: pm.merchant_id.clone(),
customer_id: Some(pm.customer_id.clone()),
payment_method_id: pm.payment_method_id.clone(),
payment_method: pm.get_payment_method_type(),
payment_method_type: pm.get_payment_method_subtype(),
#[cfg(feature = "payouts")]
bank_transfer: None,
card,
metadata: pm.metadata,
created: Some(pm.created_at),
recurring_enabled: false,
installment_payment_enabled: false,
payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]),
last_used_at: Some(pm.last_used_at),
client_secret: pm.client_secret,
},
))
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="5661" end="5738">
async fn create_payment_method_data_in_temp_locker(
state: &routes::SessionState,
payment_token: &str,
card: api::CardDetailFromLocker,
pm: &domain::PaymentMethod,
merchant_key_store: &domain::MerchantKeyStore,
) -> errors::RouterResult<api::CardDetailFromLocker> {
let card_number = card.card_number.clone().get_required_value("card_number")?;
let card_exp_month = card
.expiry_month
.clone()
.expose_option()
.get_required_value("expiry_month")?;
let card_exp_year = card
.expiry_year
.clone()
.expose_option()
.get_required_value("expiry_year")?;
let card_holder_name = card
.card_holder_name
.clone()
.expose_option()
.unwrap_or_default();
let value1 = payment_methods::mk_card_value1(
card_number,
card_exp_year,
card_exp_month,
Some(card_holder_name),
None,
None,
None,
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error getting Value1 for locker")?;
let value2 = payment_methods::mk_card_value2(
None,
None,
None,
Some(pm.customer_id.clone()),
Some(pm.get_id().to_string()),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error getting Value2 for locker")?;
let value1 = vault::VaultPaymentMethod::Card(value1);
let value2 = vault::VaultPaymentMethod::Card(value2);
let value1 = value1
.encode_to_string_of_json()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Wrapped value1 construction failed when saving card to locker")?;
let value2 = value2
.encode_to_string_of_json()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Wrapped value2 construction failed when saving card to locker")?;
let lookup_key = vault::create_tokenize(
state,
value1,
Some(value2),
payment_token.to_string(),
merchant_key_store.key.get_inner(),
)
.await?;
vault::add_delete_tokenized_data_task(
&*state.store,
&lookup_key,
enums::PaymentMethod::Card,
)
.await?;
metrics::TOKENIZED_DATA_COUNT.add(1, &[]);
metrics::TASKS_ADDED_COUNT.add(
1,
router_env::metric_attributes!(("flow", "DeleteTokenizeData")),
);
Ok(card)
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="5572" end="5596">
pub async fn update_last_used_at(
payment_method: &domain::PaymentMethod,
state: &routes::SessionState,
storage_scheme: MerchantStorageScheme,
key_store: &domain::MerchantKeyStore,
) -> errors::RouterResult<()> {
let update_last_used = storage::PaymentMethodUpdate::LastUsedUpdate {
last_used_at: common_utils::date_time::now(),
};
state
.store
.update_payment_method(
&(state.into()),
key_store,
payment_method.clone(),
update_last_used,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update the last_used_at in db")?;
Ok(())
}
<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/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="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="565" end="565">
type Error = error_stack::Report<errors::ApiErrorResponse>;
<file_sep path="hyperswitch/crates/router/src/connector/payone/transformers.rs" role="context" start="117" end="121">
pub struct Card {
card_holder_name: Secret<String>,
card_number: CardNumber,
expiry_date: Secret<String>,
}
<file_sep path="hyperswitch/migrations/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
);
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payment_methods.rs<|crate|> router anchor=create_payment_method_for_intent 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="1521" end="1572">
pub async fn create_payment_method_for_intent(
state: &SessionState,
metadata: Option<common_utils::pii::SecretSerdeValue>,
customer_id: &id_type::GlobalCustomerId,
payment_method_id: id_type::GlobalPaymentMethodId,
merchant_id: &id_type::MerchantId,
key_store: &domain::MerchantKeyStore,
storage_scheme: enums::MerchantStorageScheme,
payment_method_billing_address: Option<
Encryptable<hyperswitch_domain_models::address::Address>,
>,
) -> CustomResult<domain::PaymentMethod, errors::ApiErrorResponse> {
let db = &*state.store;
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(),
id: payment_method_id,
locker_id: None,
payment_method_type: None,
payment_method_subtype: None,
payment_method_data: None,
connector_mandate_details: None,
customer_acceptance: None,
client_secret: None,
status: enums::PaymentMethodStatus::AwaitingData,
network_transaction_id: 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,
locker_fingerprint_id: None,
network_token_locker_id: None,
network_token_payment_method_data: None,
network_token_requestor_reference_id: None,
},
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to add payment method in db")?;
Ok(response)
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods.rs" role="context" start="1520" end="1520">
.collect();
payment_methods::PaymentMethodListResponse {
payment_methods_enabled: response_payment_methods,
customer_payment_methods,
}
}
}
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
#[instrument(skip_all)]
#[allow(clippy::too_many_arguments)]
pub async fn create_payment_method_for_intent(
state: &SessionState,
metadata: Option<common_utils::pii::SecretSerdeValue>,
customer_id: &id_type::GlobalCustomerId,
payment_method_id: id_type::GlobalPaymentMethodId,
merchant_id: &id_type::MerchantId,
key_store: &domain::MerchantKeyStore,
storage_scheme: enums::MerchantStorageScheme,
payment_method_billing_address: Option<
Encryptable<hyperswitch_domain_models::address::Address>,
>,
) -> CustomResult<domain::PaymentMethod, errors::ApiErrorResponse> {
let db = &*state.store;
<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="1577" end="1610">
fn create_connector_token_details_update(
token_details: payment_methods::ConnectorTokenDetails,
payment_method: &domain::PaymentMethod,
) -> hyperswitch_domain_models::mandates::CommonMandateReference {
let connector_id = token_details.connector_id.clone();
let reference_record =
hyperswitch_domain_models::mandates::ConnectorTokenReferenceRecord::foreign_from(
token_details,
);
let connector_token_details = payment_method.connector_mandate_details.clone();
match connector_token_details {
Some(mut connector_mandate_reference) => {
connector_mandate_reference
.insert_payment_token_reference_record(&connector_id, reference_record);
connector_mandate_reference
}
None => {
let reference_record_hash_map =
std::collections::HashMap::from([(connector_id, reference_record)]);
let payments_mandate_reference =
hyperswitch_domain_models::mandates::PaymentsTokenReference(
reference_record_hash_map,
);
hyperswitch_domain_models::mandates::CommonMandateReference {
payments: Some(payments_mandate_reference),
payouts: None,
}
}
}
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods.rs" role="context" start="1494" end="1515">
fn generate_response(
self,
customer_payment_methods: Vec<payment_methods::CustomerPaymentMethod>,
) -> payment_methods::PaymentMethodListResponse {
let response_payment_methods = self
.0
.into_iter()
.map(
|payment_methods_enabled| payment_methods::ResponsePaymentMethodTypes {
payment_method_type: payment_methods_enabled.payment_method_type,
payment_method_subtype: payment_methods_enabled.payment_method_subtype,
required_fields: payment_methods_enabled.required_fields,
extra_information: None,
},
)
.collect();
payment_methods::PaymentMethodListResponse {
payment_methods_enabled: response_payment_methods,
customer_payment_methods,
}
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods.rs" role="context" start="1431" end="1477">
fn get_required_fields(
self,
input: RequiredFieldsInput,
) -> RequiredFieldsForEnabledPaymentMethodTypes {
let required_fields_config = input.required_fields_config;
let required_fields_info = self
.0
.into_iter()
.map(|payment_methods_enabled| {
let required_fields =
required_fields_config.get_required_fields(&payment_methods_enabled);
let required_fields = required_fields
.map(|required_fields| {
let common_required_fields = required_fields
.common
.iter()
.flatten()
.map(ToOwned::to_owned);
// Collect mandate required fields because this is for zero auth mandates only
let mandate_required_fields = required_fields
.mandate
.iter()
.flatten()
.map(ToOwned::to_owned);
// Combine both common and mandate required fields
common_required_fields
.chain(mandate_required_fields)
.collect::<Vec<_>>()
})
.unwrap_or_default();
RequiredFieldsForEnabledPaymentMethod {
required_fields,
payment_method_type: payment_methods_enabled.payment_method,
payment_method_subtype: payment_methods_enabled
.payment_methods_enabled
.payment_method_subtype,
}
})
.collect();
RequiredFieldsForEnabledPaymentMethodTypes(required_fields_info)
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods.rs" role="context" start="1224" end="1284">
pub async fn payment_method_intent_create(
state: &SessionState,
req: api::PaymentMethodIntentCreate,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
) -> RouterResponse<api::PaymentMethodResponse> {
let db = &*state.store;
let merchant_id = merchant_account.get_id();
let customer_id = req.customer_id.to_owned();
let key_manager_state = &(state).into();
db.find_customer_by_global_id(
key_manager_state,
&customer_id,
merchant_account.get_id(),
key_store,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)
.attach_printable("Customer not found for the payment method")?;
let payment_method_billing_address = req
.billing
.clone()
.async_map(|billing| cards::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")?
.map(|encoded_address| {
encoded_address.deserialize_inner_value(|value| value.parse_value("Address"))
})
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to parse Payment method billing address")?;
// create pm entry
let payment_method_id =
id_type::GlobalPaymentMethodId::generate(&state.conf.cell_information.id)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to generate GlobalPaymentMethodId")?;
let payment_method = create_payment_method_for_intent(
state,
req.metadata.clone(),
&customer_id,
payment_method_id,
merchant_id,
key_store,
merchant_account.storage_scheme,
payment_method_billing_address,
)
.await
.attach_printable("Failed to add Payment method to DB")?;
let resp = pm_transforms::generate_payment_method_response(&payment_method, &None)?;
Ok(services::ApplicationResponse::Json(resp))
}
<file_sep path="hyperswitch/crates/router/src/core/payment_methods.rs" role="context" start="882" end="1022">
pub async fn create_payment_method_core(
state: &SessionState,
_request_state: &routes::app::ReqState,
req: api::PaymentMethodCreate,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
profile: &domain::Profile,
) -> RouterResult<api::PaymentMethodResponse> {
use common_utils::ext_traits::ValueExt;
req.validate()?;
let db = &*state.store;
let merchant_id = merchant_account.get_id();
let customer_id = req.customer_id.to_owned();
let key_manager_state = &(state).into();
db.find_customer_by_global_id(
key_manager_state,
&customer_id,
merchant_account.get_id(),
key_store,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)
.attach_printable("Customer not found for the payment method")?;
let payment_method_billing_address = req
.billing
.clone()
.async_map(|billing| cards::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")?
.map(|encoded_address| {
encoded_address.deserialize_inner_value(|value| value.parse_value("Address"))
})
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to parse Payment method billing address")?;
let payment_method_id =
id_type::GlobalPaymentMethodId::generate(&state.conf.cell_information.id)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to generate GlobalPaymentMethodId")?;
let payment_method = create_payment_method_for_intent(
state,
req.metadata.clone(),
&customer_id,
payment_method_id,
merchant_id,
key_store,
merchant_account.storage_scheme,
payment_method_billing_address,
)
.await
.attach_printable("Failed to add Payment method to DB")?;
let payment_method_data = domain::PaymentMethodVaultingData::from(req.payment_method_data)
.populate_bin_details_for_payment_method(state)
.await;
let vaulting_result = vault_payment_method(
state,
&payment_method_data,
merchant_account,
key_store,
None,
&customer_id,
)
.await;
let network_tokenization_resp = network_tokenize_and_vault_the_pmd(
state,
&payment_method_data,
merchant_account,
key_store,
req.network_tokenization.clone(),
profile.is_network_tokenization_enabled,
&customer_id,
)
.await;
let (response, payment_method) = match vaulting_result {
Ok((vaulting_resp, fingerprint_id)) => {
let pm_update = create_pm_additional_data_update(
Some(&payment_method_data),
state,
key_store,
Some(vaulting_resp.vault_id.get_string_repr().clone()),
Some(fingerprint_id),
&payment_method,
None,
network_tokenization_resp,
Some(req.payment_method_type),
Some(req.payment_method_subtype),
)
.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 resp = pm_transforms::generate_payment_method_response(&payment_method, &None)?;
Ok((resp, payment_method))
}
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")?;
Err(e)
}
}?;
Ok(response)
}
<file_sep path="hyperswitch/crates/router/tests/macros.rs" role="context" start="17" end="21">
struct Address {
line1: String,
zip: String,
city: String,
}
<file_sep path="hyperswitch/migrations/2025-02-06-111828_drop_int_id_column_accross_database/up.sql" role="context" start="20" end="36">
------------------------ Payment Attempt -----------------------
ALTER TABLE payment_attempt DROP COLUMN id;
------------------------ Payment Methods -----------------------
ALTER TABLE payment_methods DROP COLUMN IF EXISTS id;
------------------------ Address -----------------------
ALTER TABLE address DROP COLUMN IF EXISTS id;
------------------------ Dispute -----------------------
ALTER TABLE dispute DROP COLUMN IF EXISTS id;
------------------------ Mandate -----------------------
ALTER TABLE mandate DROP COLUMN IF EXISTS id;
------------------------ Refund -----------------------
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/lib.rs<|crate|> router anchor=start_server kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/lib.rs" role="context" start="247" end="317">
pub async fn start_server(conf: settings::Settings<SecuredSecret>) -> ApplicationResult<Server> {
logger::debug!(startup_config=?conf);
let server = conf.server.clone();
let (tx, rx) = oneshot::channel();
let api_client = Box::new(services::ProxyClient::new(&conf.proxy).map_err(|error| {
errors::ApplicationError::ApiClientError(error.current_context().clone())
})?);
let state = Box::pin(AppState::new(conf, tx, api_client)).await;
let request_body_limit = server.request_body_limit;
let server_builder =
actix_web::HttpServer::new(move || mk_app(state.clone(), request_body_limit))
.bind((server.host.as_str(), server.port))?
.workers(server.workers)
.shutdown_timeout(server.shutdown_timeout);
#[cfg(feature = "tls")]
let server = match server.tls {
None => server_builder.run(),
Some(tls_conf) => {
let cert_file =
&mut std::io::BufReader::new(std::fs::File::open(tls_conf.certificate).map_err(
|err| errors::ApplicationError::InvalidConfigurationValueError(err.to_string()),
)?);
let key_file =
&mut std::io::BufReader::new(std::fs::File::open(tls_conf.private_key).map_err(
|err| errors::ApplicationError::InvalidConfigurationValueError(err.to_string()),
)?);
let cert_chain = rustls_pemfile::certs(cert_file)
.collect::<Result<Vec<_>, _>>()
.map_err(|err| {
errors::ApplicationError::InvalidConfigurationValueError(err.to_string())
})?;
let mut keys = rustls_pemfile::pkcs8_private_keys(key_file)
.map(|key| key.map(rustls::pki_types::PrivateKeyDer::Pkcs8))
.collect::<Result<Vec<_>, _>>()
.map_err(|err| {
errors::ApplicationError::InvalidConfigurationValueError(err.to_string())
})?;
// exit if no keys could be parsed
if keys.is_empty() {
return Err(errors::ApplicationError::InvalidConfigurationValueError(
"Could not locate PKCS8 private keys.".into(),
));
}
let config_builder = rustls::ServerConfig::builder().with_no_client_auth();
let config = config_builder
.with_single_cert(cert_chain, keys.remove(0))
.map_err(|err| {
errors::ApplicationError::InvalidConfigurationValueError(err.to_string())
})?;
server_builder
.bind_rustls_0_22(
(tls_conf.host.unwrap_or(server.host).as_str(), tls_conf.port),
config,
)?
.run()
}
};
#[cfg(not(feature = "tls"))]
let server = server_builder.run();
let _task_handle = tokio::spawn(receiver_for_error(rx, server.handle()).in_current_span());
Ok(server)
}
<file_sep path="hyperswitch/crates/router/src/lib.rs" role="context" start="246" end="246">
use actix_web::{
body::MessageBody,
dev::{Server, ServerHandle, ServiceFactory, ServiceRequest},
middleware::ErrorHandlers,
};
use hyperswitch_interfaces::secrets_interface::secret_state::SecuredSecret;
use routes::{AppState, SessionState};
use storage_impl::errors::ApplicationResult;
use tokio::sync::{mpsc, oneshot};
pub use self::env::logger;
pub(crate) use self::macros::*;
use crate::{configs::settings, core::errors};
<file_sep path="hyperswitch/crates/router/src/lib.rs" role="context" start="338" end="340">
async fn stop_server(&mut self) {
let _ = self.stop(true).await;
}
<file_sep path="hyperswitch/crates/router/src/lib.rs" role="context" start="319" end="329">
pub async fn receiver_for_error(rx: oneshot::Receiver<()>, mut server: impl Stop) {
match rx.await {
Ok(_) => {
logger::error!("The redis server failed ");
server.stop_server().await;
}
Err(err) => {
logger::error!("Channel receiver error: {err}");
}
}
}
<file_sep path="hyperswitch/crates/router/src/lib.rs" role="context" start="105" end="239">
pub fn mk_app(
state: AppState,
request_body_limit: usize,
) -> actix_web::App<
impl ServiceFactory<
ServiceRequest,
Config = (),
Response = actix_web::dev::ServiceResponse<impl MessageBody>,
Error = actix_web::Error,
InitError = (),
>,
> {
let mut server_app = get_application_builder(request_body_limit, state.conf.cors.clone());
#[cfg(all(feature = "dummy_connector", feature = "v1"))]
{
use routes::DummyConnector;
server_app = server_app.service(DummyConnector::server(state.clone()));
}
#[cfg(any(feature = "olap", feature = "oltp"))]
{
#[cfg(feature = "olap")]
{
// This is a more specific route as compared to `MerchantConnectorAccount`
// so it is registered before `MerchantConnectorAccount`.
#[cfg(feature = "v1")]
{
server_app = server_app
.service(routes::ProfileNew::server(state.clone()))
.service(routes::Forex::server(state.clone()));
}
server_app = server_app.service(routes::Profile::server(state.clone()));
}
server_app = server_app
.service(routes::Payments::server(state.clone()))
.service(routes::Customers::server(state.clone()))
.service(routes::Configs::server(state.clone()))
.service(routes::MerchantConnectorAccount::server(state.clone()))
.service(routes::RelayWebhooks::server(state.clone()))
.service(routes::Webhooks::server(state.clone()))
.service(routes::Hypersense::server(state.clone()))
.service(routes::Relay::server(state.clone()));
#[cfg(feature = "oltp")]
{
server_app = server_app.service(routes::PaymentMethods::server(state.clone()));
}
#[cfg(all(feature = "v2", feature = "oltp"))]
{
server_app = server_app.service(routes::PaymentMethodSession::server(state.clone()));
}
#[cfg(feature = "v1")]
{
server_app = server_app
.service(routes::Refunds::server(state.clone()))
.service(routes::Mandates::server(state.clone()));
}
}
#[cfg(all(feature = "oltp", any(feature = "v1", feature = "v2"),))]
{
server_app = server_app.service(routes::EphemeralKey::server(state.clone()))
}
#[cfg(all(
feature = "oltp",
any(feature = "v1", feature = "v2"),
not(feature = "customer_v2")
))]
{
server_app = server_app.service(routes::Poll::server(state.clone()))
}
#[cfg(feature = "olap")]
{
server_app = server_app
.service(routes::Organization::server(state.clone()))
.service(routes::MerchantAccount::server(state.clone()))
.service(routes::User::server(state.clone()))
.service(routes::ApiKeys::server(state.clone()))
.service(routes::Routing::server(state.clone()));
#[cfg(feature = "v1")]
{
server_app = server_app
.service(routes::Files::server(state.clone()))
.service(routes::Disputes::server(state.clone()))
.service(routes::Blocklist::server(state.clone()))
.service(routes::Gsm::server(state.clone()))
.service(routes::ApplePayCertificatesMigration::server(state.clone()))
.service(routes::PaymentLink::server(state.clone()))
.service(routes::ConnectorOnboarding::server(state.clone()))
.service(routes::Verify::server(state.clone()))
.service(routes::Analytics::server(state.clone()))
.service(routes::WebhookEvents::server(state.clone()))
.service(routes::FeatureMatrix::server(state.clone()));
}
#[cfg(feature = "v2")]
{
server_app = server_app.service(routes::ProcessTracker::server(state.clone()));
}
}
#[cfg(all(feature = "payouts", feature = "v1"))]
{
server_app = server_app
.service(routes::Payouts::server(state.clone()))
.service(routes::PayoutLink::server(state.clone()));
}
#[cfg(all(
feature = "stripe",
any(feature = "v1", feature = "v2"),
not(feature = "customer_v2")
))]
{
server_app = server_app
.service(routes::StripeApis::server(state.clone()))
.service(routes::Cards::server(state.clone()));
}
#[cfg(all(feature = "recon", feature = "v1"))]
{
server_app = server_app.service(routes::Recon::server(state.clone()));
}
server_app = server_app.service(routes::Cache::server(state.clone()));
server_app = server_app.service(routes::Health::server(state.clone()));
server_app
}
<file_sep path="hyperswitch/crates/router/src/configs/settings.rs" role="context" start="752" end="760">
pub struct Server {
pub port: u16,
pub workers: usize,
pub host: String,
pub request_body_limit: usize,
pub shutdown_timeout: u64,
#[cfg(feature = "tls")]
pub tls: Option<ServerTls>,
}
<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=should_return_ok 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="4298" end="4317">
fn should_return_ok() {
// Arrange
let stripe_shipping_address = create_stripe_shipping_address(
"name".to_string(),
Some("line1".to_string()),
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_ok());
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="4345" end="4367">
fn should_return_err_for_empty_country() {
// Arrange
let stripe_shipping_address = create_stripe_shipping_address(
"name".to_string(),
Some("line1".to_string()),
None,
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.country");
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="4320" end="4342">
fn should_return_err_for_empty_line1() {
// Arrange
let stripe_shipping_address = create_stripe_shipping_address(
"name".to_string(),
None,
Some(CountryAlpha2::AD),
Some("zip".to_string()),
);
let payment_method = &StripePaymentMethodType::AfterpayClearpay;
//Act
let result = validate_shipping_address_against_payment_method(
&Some(stripe_shipping_address),
Some(payment_method),
);
// Assert
assert!(result.is_err());
let missing_fields = get_missing_fields(result.unwrap_err().current_context()).to_owned();
assert_eq!(missing_fields.len(), 1);
assert_eq!(*missing_fields.first().unwrap(), "shipping.address.line1");
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="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="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="991" end="1019">
fn validate_shipping_address_against_payment_method(
shipping_address: &Option<StripeShippingAddress>,
payment_method: Option<&StripePaymentMethodType>,
) -> Result<(), error_stack::Report<errors::ConnectorError>> {
match payment_method {
Some(StripePaymentMethodType::AfterpayClearpay) => match shipping_address {
Some(address) => {
let missing_fields = collect_missing_value_keys!(
("shipping.address.line1", address.line1),
("shipping.address.country", address.country),
("shipping.address.zip", address.zip)
);
if !missing_fields.is_empty() {
return Err(errors::ConnectorError::MissingRequiredFields {
field_names: missing_fields,
}
.into());
}
Ok(())
}
None => Err(errors::ConnectorError::MissingRequiredField {
field_name: "shipping.address",
}
.into()),
},
_ => Ok(()),
}
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="647" end="676">
pub enum StripePaymentMethodType {
Affirm,
AfterpayClearpay,
Alipay,
#[serde(rename = "amazon_pay")]
AmazonPay,
#[serde(rename = "au_becs_debit")]
Becs,
#[serde(rename = "bacs_debit")]
Bacs,
Bancontact,
Blik,
Card,
CustomerBalance,
Eps,
Giropay,
Ideal,
Klarna,
#[serde(rename = "p24")]
Przelewy24,
#[serde(rename = "sepa_debit")]
Sepa,
Sofort,
#[serde(rename = "us_bank_account")]
Ach,
#[serde(rename = "wechat_pay")]
Wechatpay,
#[serde(rename = "cashapp")]
Cashapp,
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/utils.rs<|crate|> router<|connector|> utils anchor=authorize_payment 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="100" end="115">
async fn authorize_payment(
&self,
payment_data: Option<types::PaymentsAuthorizeData>,
payment_info: Option<PaymentInfo>,
) -> Result<types::PaymentsAuthorizeRouterData, Report<ConnectorError>> {
let integration = self.get_data().connector.get_connector_integration();
let request = self.generate_data(
types::PaymentsAuthorizeData {
confirm: true,
capture_method: Some(diesel_models::enums::CaptureMethod::Manual),
..(payment_data.unwrap_or(PaymentAuthorizeType::default().0))
},
payment_info,
);
Box::pin(call_connector(request, integration)).await
}
<file_sep path="hyperswitch/crates/router/tests/connectors/utils.rs" role="context" start="99" end="99">
use error_stack::Report;
use router::{
configs::settings::Settings,
core::{errors::ConnectorError, payments},
db::StorageImpl,
routes,
services::{
self,
connector_integration_interface::{BoxedConnectorIntegrationInterface, ConnectorEnum},
},
types::{self, storage::enums, AccessToken, MinorUnit, PaymentAddress, RouterData},
};
<file_sep path="hyperswitch/crates/router/tests/connectors/utils.rs" role="context" start="132" end="145">
async fn create_connector_pm_token(
&self,
payment_data: Option<types::PaymentMethodTokenizationData>,
payment_info: Option<PaymentInfo>,
) -> Result<types::TokenizationRouterData, Report<ConnectorError>> {
let integration = self.get_data().connector.get_connector_integration();
let request = self.generate_data(
types::PaymentMethodTokenizationData {
..(payment_data.unwrap_or(TokenType::default().0))
},
payment_info,
);
Box::pin(call_connector(request, integration)).await
}
<file_sep path="hyperswitch/crates/router/tests/connectors/utils.rs" role="context" start="117" end="130">
async fn create_connector_customer(
&self,
payment_data: Option<types::ConnectorCustomerData>,
payment_info: Option<PaymentInfo>,
) -> Result<types::ConnectorCustomerRouterData, Report<ConnectorError>> {
let integration = self.get_data().connector.get_connector_integration();
let request = self.generate_data(
types::ConnectorCustomerData {
..(payment_data.unwrap_or(CustomerType::default().0))
},
payment_info,
);
Box::pin(call_connector(request, integration)).await
}
<file_sep path="hyperswitch/crates/router/tests/connectors/utils.rs" role="context" start="75" end="93">
pub fn with_default_billing_name() -> Self {
Self {
address: Some(PaymentAddress::new(
None,
None,
Some(hyperswitch_domain_models::address::Address {
address: Some(hyperswitch_domain_models::address::AddressDetails {
first_name: Some(Secret::new("John".to_string())),
last_name: Some(Secret::new("Doe".to_string())),
..Default::default()
}),
phone: None,
email: None,
}),
None,
)),
..Default::default()
}
}
<file_sep path="hyperswitch/crates/router/tests/connectors/utils.rs" role="context" start="46" end="58">
pub fn construct_connector_data_old(
connector: types::api::BoxedConnector,
connector_name: types::Connector,
get_token: types::api::GetToken,
merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
) -> types::api::ConnectorData {
types::api::ConnectorData {
connector: ConnectorEnum::Old(connector),
connector_name,
get_token,
merchant_connector_id,
}
}
<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="856" end="893">
async fn call_connector<
T: Debug + Clone + 'static,
ResourceCommonData: Debug
+ Clone
+ services::connector_integration_interface::RouterDataConversion<T, Req, Resp>
+ 'static,
Req: Debug + Clone + 'static,
Resp: Debug + Clone + 'static,
>(
request: RouterData<T, Req, Resp>,
integration: BoxedConnectorIntegrationInterface<T, ResourceCommonData, Req, Resp>,
) -> Result<RouterData<T, Req, Resp>, Report<ConnectorError>> {
let conf = Settings::new().unwrap();
let tx: oneshot::Sender<()> = oneshot::channel().0;
let app_state = Box::pin(routes::AppState::with_storage(
conf,
StorageImpl::PostgresqlTest,
tx,
Box::new(services::MockApiClient),
))
.await;
let state = Arc::new(app_state)
.get_session_state(
&common_utils::id_type::TenantId::try_from_string("public".to_string()).unwrap(),
None,
|| {},
)
.unwrap();
services::api::execute_connector_processing_step(
&state,
integration,
&request,
payments::CallConnectorAction::Trigger,
None,
)
.await
}
<file_sep path="hyperswitch/crates/router/tests/connectors/utils.rs" role="context" start="919" end="919">
pub struct PaymentAuthorizeType(pub types::PaymentsAuthorizeData);
<file_sep path="hyperswitch/crates/router/tests/connectors/utils.rs" role="context" start="61" end="72">
pub struct PaymentInfo {
pub address: Option<PaymentAddress>,
pub auth_type: Option<enums::AuthenticationType>,
pub access_token: Option<AccessToken>,
pub connector_meta_data: Option<serde_json::Value>,
pub connector_customer: Option<String>,
pub payment_method_token: Option<String>,
#[cfg(feature = "payouts")]
pub payout_method_data: Option<types::api::PayoutMethodData>,
#[cfg(feature = "payouts")]
pub currency: Option<enums::Currency>,
}
<file_sep path="hyperswitch/crates/router/src/types.rs" role="context" start="126" end="127">
pub type PaymentsAuthorizeRouterData =
RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData>;
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/nmi/transformers.rs<|crate|> router anchor=get_card_details kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/connector/nmi/transformers.rs" role="context" start="122" end="139">
fn get_card_details(
payment_method_data: Option<domain::PaymentMethodData>,
) -> CustomResult<(CardNumber, Secret<String>, Secret<String>), errors::ConnectorError> {
match payment_method_data {
Some(domain::PaymentMethodData::Card(ref card_details)) => Ok((
card_details.card_number.clone(),
utils::CardData::get_card_expiry_month_year_2_digit_with_delimiter(
card_details,
"".to_string(),
)?,
card_details.card_cvc.clone(),
)),
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Nmi"),
)
.into()),
}
}
<file_sep path="hyperswitch/crates/router/src/connector/nmi/transformers.rs" role="context" start="121" end="121">
use cards::CardNumber;
use common_utils::{errors::CustomResult, ext_traits::XmlExt, pii::Email, types::FloatMajorUnit};
use masking::{ExposeInterface, PeekInterface, Secret};
use crate::{
connector::utils::{
self, AddressDetailsData, PaymentsAuthorizeRequestData,
PaymentsCompleteAuthorizeRequestData, RouterData,
},
core::errors,
services,
types::{self, api, domain, storage::enums, transformers::ForeignFrom, ConnectorAuthType},
};
type Error = Report<errors::ConnectorError>;
<file_sep path="hyperswitch/crates/router/src/connector/nmi/transformers.rs" role="context" start="290" end="326">
fn try_from(
item: &NmiRouterData<&types::PaymentsCompleteAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let transaction_type = match item.router_data.request.is_auto_capture()? {
true => TransactionType::Sale,
false => TransactionType::Auth,
};
let auth_type: NmiAuthType = (&item.router_data.connector_auth_type).try_into()?;
let payload_data = item
.router_data
.request
.get_redirect_response_payload()?
.expose();
let three_ds_data: NmiRedirectResponseData = serde_json::from_value(payload_data)
.change_context(errors::ConnectorError::MissingConnectorRedirectionPayload {
field_name: "three_ds_data",
})?;
let (_, _, cvv) = get_card_details(item.router_data.request.payment_method_data.clone())?;
Ok(Self {
amount: item.amount,
transaction_type,
security_key: auth_type.api_key,
orderid: three_ds_data.order_id,
customer_vault_id: three_ds_data.customer_vault_id,
email: item.router_data.request.email.clone(),
cvv,
cardholder_auth: three_ds_data.card_holder_auth,
cavv: three_ds_data.cavv,
xid: three_ds_data.xid,
eci: three_ds_data.eci,
three_ds_version: three_ds_data.three_ds_version,
directory_server_id: three_ds_data.directory_server_id,
})
}
<file_sep path="hyperswitch/crates/router/src/connector/nmi/transformers.rs" role="context" start="161" end="239">
fn try_from(
item: types::ResponseRouterData<
api::PreProcessing,
NmiVaultResponse,
types::PaymentsPreProcessingData,
types::PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let auth_type: NmiAuthType = (&item.data.connector_auth_type).try_into()?;
let amount_data =
item.data
.request
.amount
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "amount",
})?;
let currency_data =
item.data
.request
.currency
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "currency",
})?;
let (response, status) = match item.response.response {
Response::Approved => (
Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::NoResponseId,
redirection_data: Box::new(Some(services::RedirectForm::Nmi {
amount: utils::to_currency_base_unit_asf64(
amount_data,
currency_data.to_owned(),
)?
.to_string(),
currency: currency_data,
customer_vault_id: item
.response
.customer_vault_id
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "customer_vault_id",
})?
.peek()
.to_string(),
public_key: auth_type.public_key.ok_or(
errors::ConnectorError::InvalidConnectorConfig {
config: "public_key",
},
)?,
order_id: item.data.connector_request_reference_id.clone(),
})),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.transactionid),
incremental_authorization_allowed: None,
charges: None,
}),
enums::AttemptStatus::AuthenticationPending,
),
Response::Declined | Response::Error => (
Err(types::ErrorResponse {
code: item.response.response_code,
message: item.response.responsetext.to_owned(),
reason: Some(item.response.responsetext),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(item.response.transactionid),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
}),
enums::AttemptStatus::Failure,
),
};
Ok(Self {
status,
response,
..item.data
})
}
<file_sep path="hyperswitch/crates/router/src/connector/nmi/transformers.rs" role="context" start="95" end="119">
fn try_from(item: &types::PaymentsPreProcessingRouterData) -> Result<Self, Self::Error> {
let auth_type: NmiAuthType = (&item.connector_auth_type).try_into()?;
let (ccnumber, ccexp, cvv) = get_card_details(item.request.payment_method_data.clone())?;
let billing_details = item.get_billing_address()?;
let first_name = billing_details.get_first_name()?;
Ok(Self {
security_key: auth_type.api_key,
ccnumber,
ccexp,
cvv,
first_name: first_name.clone(),
last_name: billing_details
.get_last_name()
.unwrap_or(first_name)
.clone(),
address1: billing_details.line1.clone(),
address2: billing_details.line2.clone(),
city: billing_details.city.clone(),
state: billing_details.state.clone(),
country: billing_details.country,
zip: billing_details.zip.clone(),
customer_vault: CustomerAction::AddCustomer,
})
}
<file_sep path="hyperswitch/crates/router/src/connector/nmi/transformers.rs" role="context" start="61" end="66">
fn from((amount, router_data): (FloatMajorUnit, T)) -> Self {
Self {
amount,
router_data,
}
}
<file_sep path="hyperswitch/crates/router/src/connector/nmi/transformers.rs" role="context" start="462" end="466">
pub struct CardData {
ccnumber: CardNumber,
ccexp: Secret<String>,
cvv: Secret<String>,
}
<file_sep path="hyperswitch/crates/router/src/compatibility/stripe/customers/types.rs" role="context" start="202" end="207">
pub struct PaymentMethodData {
pub id: Option<String>,
pub object: &'static str,
pub card: Option<CardDetails>,
pub created: Option<time::PrimitiveDateTime>,
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/nmi/transformers.rs<|crate|> router anchor=get_card_details kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/connector/nmi/transformers.rs" role="context" start="122" end="139">
fn get_card_details(
payment_method_data: Option<domain::PaymentMethodData>,
) -> CustomResult<(CardNumber, Secret<String>, Secret<String>), errors::ConnectorError> {
match payment_method_data {
Some(domain::PaymentMethodData::Card(ref card_details)) => Ok((
card_details.card_number.clone(),
utils::CardData::get_card_expiry_month_year_2_digit_with_delimiter(
card_details,
"".to_string(),
)?,
card_details.card_cvc.clone(),
)),
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Nmi"),
)
.into()),
}
}
<file_sep path="hyperswitch/crates/router/src/connector/nmi/transformers.rs" role="context" start="121" end="121">
use cards::CardNumber;
use common_utils::{errors::CustomResult, ext_traits::XmlExt, pii::Email, types::FloatMajorUnit};
use masking::{ExposeInterface, PeekInterface, Secret};
use crate::{
connector::utils::{
self, AddressDetailsData, PaymentsAuthorizeRequestData,
PaymentsCompleteAuthorizeRequestData, RouterData,
},
core::errors,
services,
types::{self, api, domain, storage::enums, transformers::ForeignFrom, ConnectorAuthType},
};
type Error = Report<errors::ConnectorError>;
<file_sep path="hyperswitch/crates/router/src/connector/nmi/transformers.rs" role="context" start="290" end="326">
fn try_from(
item: &NmiRouterData<&types::PaymentsCompleteAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let transaction_type = match item.router_data.request.is_auto_capture()? {
true => TransactionType::Sale,
false => TransactionType::Auth,
};
let auth_type: NmiAuthType = (&item.router_data.connector_auth_type).try_into()?;
let payload_data = item
.router_data
.request
.get_redirect_response_payload()?
.expose();
let three_ds_data: NmiRedirectResponseData = serde_json::from_value(payload_data)
.change_context(errors::ConnectorError::MissingConnectorRedirectionPayload {
field_name: "three_ds_data",
})?;
let (_, _, cvv) = get_card_details(item.router_data.request.payment_method_data.clone())?;
Ok(Self {
amount: item.amount,
transaction_type,
security_key: auth_type.api_key,
orderid: three_ds_data.order_id,
customer_vault_id: three_ds_data.customer_vault_id,
email: item.router_data.request.email.clone(),
cvv,
cardholder_auth: three_ds_data.card_holder_auth,
cavv: three_ds_data.cavv,
xid: three_ds_data.xid,
eci: three_ds_data.eci,
three_ds_version: three_ds_data.three_ds_version,
directory_server_id: three_ds_data.directory_server_id,
})
}
<file_sep path="hyperswitch/crates/router/src/connector/nmi/transformers.rs" role="context" start="161" end="239">
fn try_from(
item: types::ResponseRouterData<
api::PreProcessing,
NmiVaultResponse,
types::PaymentsPreProcessingData,
types::PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let auth_type: NmiAuthType = (&item.data.connector_auth_type).try_into()?;
let amount_data =
item.data
.request
.amount
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "amount",
})?;
let currency_data =
item.data
.request
.currency
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "currency",
})?;
let (response, status) = match item.response.response {
Response::Approved => (
Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::NoResponseId,
redirection_data: Box::new(Some(services::RedirectForm::Nmi {
amount: utils::to_currency_base_unit_asf64(
amount_data,
currency_data.to_owned(),
)?
.to_string(),
currency: currency_data,
customer_vault_id: item
.response
.customer_vault_id
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "customer_vault_id",
})?
.peek()
.to_string(),
public_key: auth_type.public_key.ok_or(
errors::ConnectorError::InvalidConnectorConfig {
config: "public_key",
},
)?,
order_id: item.data.connector_request_reference_id.clone(),
})),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.transactionid),
incremental_authorization_allowed: None,
charges: None,
}),
enums::AttemptStatus::AuthenticationPending,
),
Response::Declined | Response::Error => (
Err(types::ErrorResponse {
code: item.response.response_code,
message: item.response.responsetext.to_owned(),
reason: Some(item.response.responsetext),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(item.response.transactionid),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
}),
enums::AttemptStatus::Failure,
),
};
Ok(Self {
status,
response,
..item.data
})
}
<file_sep path="hyperswitch/crates/router/src/connector/nmi/transformers.rs" role="context" start="95" end="119">
fn try_from(item: &types::PaymentsPreProcessingRouterData) -> Result<Self, Self::Error> {
let auth_type: NmiAuthType = (&item.connector_auth_type).try_into()?;
let (ccnumber, ccexp, cvv) = get_card_details(item.request.payment_method_data.clone())?;
let billing_details = item.get_billing_address()?;
let first_name = billing_details.get_first_name()?;
Ok(Self {
security_key: auth_type.api_key,
ccnumber,
ccexp,
cvv,
first_name: first_name.clone(),
last_name: billing_details
.get_last_name()
.unwrap_or(first_name)
.clone(),
address1: billing_details.line1.clone(),
address2: billing_details.line2.clone(),
city: billing_details.city.clone(),
state: billing_details.state.clone(),
country: billing_details.country,
zip: billing_details.zip.clone(),
customer_vault: CustomerAction::AddCustomer,
})
}
<file_sep path="hyperswitch/crates/router/src/connector/nmi/transformers.rs" role="context" start="61" end="66">
fn from((amount, router_data): (FloatMajorUnit, T)) -> Self {
Self {
amount,
router_data,
}
}
<file_sep path="hyperswitch/crates/router/src/connector/nmi/transformers.rs" role="context" start="462" end="466">
pub struct CardData {
ccnumber: CardNumber,
ccexp: Secret<String>,
cvv: Secret<String>,
}
<file_sep path="hyperswitch/crates/router/src/compatibility/stripe/customers/types.rs" role="context" start="202" end="207">
pub struct PaymentMethodData {
pub id: Option<String>,
pub object: &'static str,
pub card: Option<CardDetails>,
pub created: Option<time::PrimitiveDateTime>,
}
<file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="2504" end="2539">
pub enum PaymentMethodData {
#[schema(title = "Card")]
Card(Card),
#[schema(title = "CardRedirect")]
CardRedirect(CardRedirectData),
#[schema(title = "Wallet")]
Wallet(WalletData),
#[schema(title = "PayLater")]
PayLater(PayLaterData),
#[schema(title = "BankRedirect")]
BankRedirect(BankRedirectData),
#[schema(title = "BankDebit")]
BankDebit(BankDebitData),
#[schema(title = "BankTransfer")]
BankTransfer(Box<BankTransferData>),
#[schema(title = "RealTimePayment")]
RealTimePayment(Box<RealTimePaymentData>),
#[schema(title = "Crypto")]
Crypto(CryptoData),
#[schema(title = "MandatePayment")]
MandatePayment,
#[schema(title = "Reward")]
Reward,
#[schema(title = "Upi")]
Upi(UpiData),
#[schema(title = "Voucher")]
Voucher(VoucherData),
#[schema(title = "GiftCard")]
GiftCard(Box<GiftCardData>),
#[schema(title = "CardToken")]
CardToken(CardToken),
#[schema(title = "OpenBanking")]
OpenBanking(OpenBankingData),
#[schema(title = "MobilePayment")]
MobilePayment(MobilePaymentData),
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/workflows/payment_sync.rs<|crate|> router anchor=retry_sync_task kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/workflows/payment_sync.rs" role="context" start="282" end="303">
pub async fn retry_sync_task(
db: &dyn StorageInterface,
connector: String,
merchant_id: common_utils::id_type::MerchantId,
pt: storage::ProcessTracker,
) -> Result<bool, sch_errors::ProcessTrackerError> {
let schedule_time =
get_sync_process_schedule_time(db, &connector, &merchant_id, pt.retry_count + 1).await?;
match schedule_time {
Some(s_time) => {
db.as_scheduler().retry_process(pt, s_time).await?;
Ok(false)
}
None => {
db.as_scheduler()
.finish_process_with_business_status(pt, business_status::RETRIES_EXCEEDED)
.await?;
Ok(true)
}
}
}
<file_sep path="hyperswitch/crates/router/src/workflows/payment_sync.rs" role="context" start="281" end="281">
use common_utils::ext_traits::{OptionExt, StringExt, ValueExt};
use diesel_models::process_tracker::business_status;
use scheduler::{
consumer::{self, types::process_data, workflows::ProcessTrackerWorkflow},
errors as sch_errors, utils as scheduler_utils,
};
use crate::{
consts,
core::{
errors::StorageErrorExt,
payments::{self as payment_flows, operations},
},
db::StorageInterface,
errors,
routes::SessionState,
services,
types::{
api,
storage::{self, enums},
},
utils,
};
<file_sep path="hyperswitch/crates/router/src/workflows/payment_sync.rs" role="context" start="311" end="334">
fn test_get_default_schedule_time() {
let merchant_id =
common_utils::id_type::MerchantId::try_from(std::borrow::Cow::from("-")).unwrap();
let schedule_time_delta = scheduler_utils::get_schedule_time(
process_data::ConnectorPTMapping::default(),
&merchant_id,
0,
)
.unwrap();
let first_retry_time_delta = scheduler_utils::get_schedule_time(
process_data::ConnectorPTMapping::default(),
&merchant_id,
1,
)
.unwrap();
let cpt_default = process_data::ConnectorPTMapping::default().default_mapping;
assert_eq!(
vec![schedule_time_delta, first_retry_time_delta],
vec![
cpt_default.start_after,
cpt_default.frequencies.first().unwrap().0
]
);
}
<file_sep path="hyperswitch/crates/router/src/workflows/payment_sync.rs" role="context" start="249" end="277">
pub async fn get_sync_process_schedule_time(
db: &dyn StorageInterface,
connector: &str,
merchant_id: &common_utils::id_type::MerchantId,
retry_count: i32,
) -> Result<Option<time::PrimitiveDateTime>, errors::ProcessTrackerError> {
let mapping: common_utils::errors::CustomResult<
process_data::ConnectorPTMapping,
errors::StorageError,
> = db
.find_config_by_key(&format!("pt_mapping_{connector}"))
.await
.map(|value| value.config)
.and_then(|config| {
config
.parse_struct("ConnectorPTMapping")
.change_context(errors::StorageError::DeserializationFailed)
});
let mapping = match mapping {
Ok(x) => x,
Err(error) => {
logger::info!(?error, "Redis Mapping Error");
process_data::ConnectorPTMapping::default()
}
};
let time_delta = scheduler_utils::get_schedule_time(mapping, merchant_id, retry_count);
Ok(scheduler_utils::get_time_from_delta(time_delta))
}
<file_sep path="hyperswitch/crates/router/src/workflows/payment_sync.rs" role="context" start="220" end="227">
async fn error_handler<'a>(
&'a self,
state: &'a SessionState,
process: storage::ProcessTracker,
error: sch_errors::ProcessTrackerError,
) -> errors::CustomResult<(), sch_errors::ProcessTrackerError> {
consumer::consumer_error_handler(state.store.as_scheduler(), process, error).await
}
<file_sep path="hyperswitch/crates/router/src/workflows/payment_sync.rs" role="context" start="41" end="218">
async fn execute_workflow<'a>(
&'a self,
state: &'a SessionState,
process: storage::ProcessTracker,
) -> Result<(), sch_errors::ProcessTrackerError> {
let db: &dyn StorageInterface = &*state.store;
let tracking_data: api::PaymentsRetrieveRequest = process
.tracking_data
.clone()
.parse_value("PaymentsRetrieveRequest")?;
let key_manager_state = &state.into();
let key_store = db
.get_merchant_key_store_by_merchant_id(
key_manager_state,
tracking_data
.merchant_id
.as_ref()
.get_required_value("merchant_id")?,
&db.get_master_key().to_vec().into(),
)
.await?;
let merchant_account = db
.find_merchant_account_by_merchant_id(
key_manager_state,
tracking_data
.merchant_id
.as_ref()
.get_required_value("merchant_id")?,
&key_store,
)
.await?;
// TODO: Add support for ReqState in PT flows
let (mut payment_data, _, customer, _, _) =
Box::pin(payment_flows::payments_operation_core::<
api::PSync,
_,
_,
_,
payment_flows::PaymentData<api::PSync>,
>(
state,
state.get_req_state(),
merchant_account.clone(),
None,
key_store.clone(),
operations::PaymentStatus,
tracking_data.clone(),
payment_flows::CallConnectorAction::Trigger,
services::AuthFlow::Client,
None,
hyperswitch_domain_models::payments::HeaderPayload::default(),
None, //Platform merchant account
))
.await?;
let terminal_status = [
enums::AttemptStatus::RouterDeclined,
enums::AttemptStatus::Charged,
enums::AttemptStatus::AutoRefunded,
enums::AttemptStatus::Voided,
enums::AttemptStatus::VoidFailed,
enums::AttemptStatus::CaptureFailed,
enums::AttemptStatus::Failure,
];
match &payment_data.payment_attempt.status {
status if terminal_status.contains(status) => {
state
.store
.as_scheduler()
.finish_process_with_business_status(process, business_status::COMPLETED_BY_PT)
.await?
}
_ => {
let connector = payment_data
.payment_attempt
.connector
.clone()
.ok_or(sch_errors::ProcessTrackerError::MissingRequiredField)?;
let is_last_retry = retry_sync_task(
db,
connector,
payment_data.payment_attempt.merchant_id.clone(),
process,
)
.await?;
// If the payment status is still processing and there is no connector transaction_id
// then change the payment status to failed if all retries exceeded
if is_last_retry
&& payment_data.payment_attempt.status == enums::AttemptStatus::Pending
&& payment_data
.payment_attempt
.connector_transaction_id
.as_ref()
.is_none()
{
let payment_intent_update = hyperswitch_domain_models::payments::payment_intent::PaymentIntentUpdate::PGStatusUpdate { status: api_models::enums::IntentStatus::Failed,updated_by: merchant_account.storage_scheme.to_string(), incremental_authorization_allowed: Some(false) };
let payment_attempt_update =
hyperswitch_domain_models::payments::payment_attempt::PaymentAttemptUpdate::ErrorUpdate {
connector: None,
status: api_models::enums::AttemptStatus::Failure,
error_code: None,
error_message: None,
error_reason: Some(Some(
consts::REQUEST_TIMEOUT_ERROR_MESSAGE_FROM_PSYNC.to_string(),
)),
amount_capturable: Some(common_utils::types::MinorUnit::new(0)),
updated_by: merchant_account.storage_scheme.to_string(),
unified_code: None,
unified_message: None,
connector_transaction_id: None,
payment_method_data: None,
authentication_type: None,
issuer_error_code: None,
issuer_error_message: None,
};
payment_data.payment_attempt = db
.update_payment_attempt_with_attempt_id(
payment_data.payment_attempt,
payment_attempt_update,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
payment_data.payment_intent = db
.update_payment_intent(
&state.into(),
payment_data.payment_intent,
payment_intent_update,
&key_store,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
let profile_id = payment_data
.payment_intent
.profile_id
.as_ref()
.get_required_value("profile_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Could not find profile_id in 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(),
})?;
// Trigger the outgoing webhook to notify the merchant about failed payment
let operation = operations::PaymentStatus;
Box::pin(utils::trigger_payments_webhook(
merchant_account,
business_profile,
&key_store,
payment_data,
customer,
state,
operation,
))
.await
.map_err(|error| logger::warn!(payments_outgoing_webhook_error=?error))
.ok();
}
}
};
Ok(())
}
<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/2022-09-29-084920_create_initial_tables/up.sql" role="context" start="430" end="446">
created_at TIMESTAMP NOT NULL,
last_modified TIMESTAMP NOT NULL,
payment_method "PaymentMethodType" NOT NULL,
payment_method_type "PaymentMethodSubType",
payment_method_issuer VARCHAR(255),
payment_method_issuer_code "PaymentMethodIssuerCode"
);
CREATE TABLE process_tracker (
id VARCHAR(127) PRIMARY KEY,
NAME VARCHAR(255),
tag TEXT [ ] NOT NULL DEFAULT '{}'::TEXT [ ],
runner VARCHAR(255),
retry_count INTEGER NOT NULL,
schedule_time TIMESTAMP,
rule VARCHAR(255) NOT NULL,
tracking_data JSON 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/connector/plaid/transformers.rs<|crate|> router anchor=from kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/connector/plaid/transformers.rs" role="context" start="262" end="276">
fn from(item: PlaidPaymentStatus) -> Self {
match item {
PlaidPaymentStatus::PaymentStatusAuthorising => Self::Authorizing,
PlaidPaymentStatus::PaymentStatusBlocked
| PlaidPaymentStatus::PaymentStatusInsufficientFunds
| PlaidPaymentStatus::PaymentStatusRejected => Self::AuthorizationFailed,
PlaidPaymentStatus::PaymentStatusCancelled => Self::Voided,
PlaidPaymentStatus::PaymentStatusEstablished => Self::Authorized,
PlaidPaymentStatus::PaymentStatusExecuted
| PlaidPaymentStatus::PaymentStatusSettled
| PlaidPaymentStatus::PaymentStatusInitiated => Self::Charged,
PlaidPaymentStatus::PaymentStatusFailed => Self::Failure,
PlaidPaymentStatus::PaymentStatusInputNeeded => Self::AuthenticationPending,
}
}
<file_sep path="hyperswitch/crates/router/src/connector/plaid/transformers.rs" role="context" start="338" end="350">
fn try_from(
item: types::ResponseRouterData<F, PlaidLinkTokenResponse, T, types::PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let session_token = Some(api::OpenBankingSessionToken {
open_banking_session_token: item.response.link_token,
});
Ok(Self {
status: enums::AttemptStatus::AuthenticationPending,
response: Ok(types::PaymentsResponseData::PostProcessingResponse { session_token }),
..item.data
})
}
<file_sep path="hyperswitch/crates/router/src/connector/plaid/transformers.rs" role="context" start="290" end="325">
fn try_from(
item: types::ResponseRouterData<F, PlaidPaymentsResponse, T, types::PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let status = enums::AttemptStatus::from(item.response.status.clone());
Ok(Self {
status,
response: if is_payment_failure(status) {
Err(types::ErrorResponse {
// populating status everywhere as plaid only sends back a status
code: item.response.status.clone().to_string(),
message: item.response.status.clone().to_string(),
reason: Some(item.response.status.to_string()),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(item.response.payment_id),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
})
} else {
Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::ConnectorTransactionId(
item.response.payment_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.payment_id),
incremental_authorization_allowed: None,
charges: None,
})
},
..item.data
})
}
<file_sep path="hyperswitch/crates/router/src/connector/plaid/transformers.rs" role="context" start="233" end="241">
fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
types::ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
client_id: api_key.to_owned(),
secret: key1.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
<file_sep path="hyperswitch/crates/router/src/connector/plaid/transformers.rs" role="context" start="162" end="223">
fn try_from(item: &types::PaymentsPostProcessingRouterData) -> Result<Self, Self::Error> {
match item.request.payment_method_data {
domain::PaymentMethodData::OpenBanking(ref data) => match data {
domain::OpenBankingData::OpenBankingPIS { .. } => {
let headers = item.header_payload.clone();
let platform = headers
.as_ref()
.and_then(|headers| headers.x_client_platform.clone());
let (is_android, is_ios) = match platform {
Some(common_enums::ClientPlatform::Android) => (true, false),
Some(common_enums::ClientPlatform::Ios) => (false, true),
_ => (false, false),
};
Ok(Self {
client_name: "Hyperswitch".to_string(),
country_codes: item
.request
.country
.map(|code| vec![code.to_string()])
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "billing.address.country",
})?,
language: "en".to_string(),
products: vec!["payment_initiation".to_string()],
user: User {
client_user_id: item
.request
.customer_id
.clone()
.map(|id| id.get_string_repr().to_string())
.unwrap_or("default cust".to_string()),
},
payment_initiation: PlaidPaymentInitiation {
payment_id: item
.request
.connector_transaction_id
.clone()
.ok_or(errors::ConnectorError::MissingConnectorTransactionID)?,
},
android_package_name: if is_android {
headers
.as_ref()
.and_then(|headers| headers.x_app_id.clone())
} else {
None
},
redirect_uri: if is_ios {
headers
.as_ref()
.and_then(|headers| headers.x_redirect_uri.clone())
} else {
None
},
})
}
},
_ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()),
}
}
<file_sep path="hyperswitch/crates/router/src/connector/plaid/transformers.rs" role="context" start="379" end="414">
fn try_from(
item: types::ResponseRouterData<F, PlaidSyncResponse, T, types::PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let status = enums::AttemptStatus::from(item.response.status.clone());
Ok(Self {
status,
response: if is_payment_failure(status) {
Err(types::ErrorResponse {
// populating status everywhere as plaid only sends back a status
code: item.response.status.clone().to_string(),
message: item.response.status.clone().to_string(),
reason: Some(item.response.status.to_string()),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(item.response.payment_id),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
})
} else {
Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::ConnectorTransactionId(
item.response.payment_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.payment_id),
incremental_authorization_allowed: None,
charges: None,
})
},
..item.data
})
}
<file_sep path="hyperswitch/crates/router/src/connector/plaid/transformers.rs" role="context" start="247" end="259">
pub enum PlaidPaymentStatus {
PaymentStatusInputNeeded,
PaymentStatusInitiated,
PaymentStatusInsufficientFunds,
PaymentStatusFailed,
PaymentStatusBlocked,
PaymentStatusCancelled,
PaymentStatusExecuted,
PaymentStatusSettled,
PaymentStatusEstablished,
PaymentStatusRejected,
PaymentStatusAuthorising,
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/stripe/transformers.rs<|crate|> router anchor=construct_charge_response 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="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="4254" end="4254">
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,
};
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="4320" end="4342">
fn should_return_err_for_empty_line1() {
// Arrange
let stripe_shipping_address = create_stripe_shipping_address(
"name".to_string(),
None,
Some(CountryAlpha2::AD),
Some("zip".to_string()),
);
let payment_method = &StripePaymentMethodType::AfterpayClearpay;
//Act
let result = validate_shipping_address_against_payment_method(
&Some(stripe_shipping_address),
Some(payment_method),
);
// Assert
assert!(result.is_err());
let missing_fields = get_missing_fields(result.unwrap_err().current_context()).to_owned();
assert_eq!(missing_fields.len(), 1);
assert_eq!(*missing_fields.first().unwrap(), "shipping.address.line1");
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="4298" end="4317">
fn should_return_ok() {
// Arrange
let stripe_shipping_address = create_stripe_shipping_address(
"name".to_string(),
Some("line1".to_string()),
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_ok());
}
<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="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="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/utils.rs" role="context" start="757" end="759">
pub trait SplitPaymentData {
fn get_split_payment_data(&self) -> Option<common_types::payments::SplitPaymentsRequest>;
}
| symbol_neighborhood |
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/stripe/transformers.rs<|crate|> router anchor=deserialize kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="3010" end="3029">
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
#[derive(Deserialize)]
struct Wrapper {
#[serde(rename = "type")]
_ignore: String,
#[serde(flatten, with = "StripeNextActionResponse")]
inner: StripeNextActionResponse,
}
// There is some exception in the stripe next action, it usually sends :
// "next_action": {
// "redirect_to_url": { "return_url": "...", "url": "..." },
// "type": "redirect_to_url"
// },
// But there is a case where it only sends the type and not other field named as it's type
let stripe_next_action_response =
Wrapper::deserialize(deserializer).map_or(Self::NoNextActionBody, |w| w.inner);
Ok(stripe_next_action_response)
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="3009" end="3009">
use api_models::{self, enums as api_enums, payments};
use serde::{Deserialize, Serialize};
use url::Url;
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="3172" end="3184">
fn try_from(
(item, refund_amount): (&types::RefundsRouterData<F>, MinorUnit),
) -> Result<Self, Self::Error> {
let payment_intent = item.request.connector_transaction_id.clone();
Ok(Self {
amount: Some(refund_amount),
payment_intent,
meta_data: StripeMetadata {
order_id: Some(item.request.refund_id.clone()),
is_refund_id_as_reference: Some("true".to_string()),
},
})
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="3033" end="3049">
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
match *self {
Self::CashappHandleRedirectOrDisplayQrCode(ref i) => {
Serialize::serialize(i, serializer)
}
Self::RedirectToUrl(ref i) => Serialize::serialize(i, serializer),
Self::AlipayHandleRedirect(ref i) => Serialize::serialize(i, serializer),
Self::VerifyWithMicrodeposits(ref i) => Serialize::serialize(i, serializer),
Self::WechatPayDisplayQrCode(ref i) => Serialize::serialize(i, serializer),
Self::DisplayBankTransferInstructions(ref i) => Serialize::serialize(i, serializer),
Self::MultibancoDisplayDetails(ref i) => Serialize::serialize(i, serializer),
Self::NoNextActionBody => Serialize::serialize("NoNextActionBody", serializer),
}
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="2985" end="2999">
fn get_url(&self) -> Option<Url> {
match self {
Self::RedirectToUrl(redirect_to_url) | Self::AlipayHandleRedirect(redirect_to_url) => {
Some(redirect_to_url.url.to_owned())
}
Self::WechatPayDisplayQrCode(_) => None,
Self::VerifyWithMicrodeposits(verify_with_microdeposits) => {
Some(verify_with_microdeposits.hosted_verification_url.to_owned())
}
Self::CashappHandleRedirectOrDisplayQrCode(_) => None,
Self::DisplayBankTransferInstructions(_) => None,
Self::MultibancoDisplayDetails(_) => None,
Self::NoNextActionBody => None,
}
}
<file_sep path="hyperswitch/crates/router/src/connector/stripe/transformers.rs" role="context" start="2955" end="2968">
fn foreign_from(latest_attempt: Option<LatestAttempt>) -> Self {
match latest_attempt {
Some(LatestAttempt::PaymentIntentAttempt(attempt)) => attempt
.payment_method_options
.and_then(|payment_method_options| match payment_method_options {
StripePaymentMethodOptions::Card {
network_transaction_id,
..
} => network_transaction_id.map(|network_id| network_id.expose()),
_ => None,
}),
_ => 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="3012" end="3017">
struct Wrapper {
#[serde(rename = "type")]
_ignore: String,
#[serde(flatten, with = "StripeNextActionResponse")]
inner: StripeNextActionResponse,
}
<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/routes/payment_methods.rs<|crate|> router anchor=render_pm_collect_link kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|>
<file_sep path="hyperswitch/crates/router/src/routes/payment_methods.rs" role="context" start="661" end="689">
pub async fn render_pm_collect_link(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<(id_type::MerchantId, String)>,
) -> HttpResponse {
let flow = Flow::PaymentMethodCollectLink;
let (merchant_id, pm_collect_link_id) = path.into_inner();
let payload = payment_methods::PaymentMethodCollectLinkRenderRequest {
merchant_id: merchant_id.clone(),
pm_collect_link_id,
};
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
payment_methods_routes::render_pm_collect_link(
state,
auth.merchant_account,
auth.key_store,
req,
)
},
&auth::MerchantIdAuth(merchant_id),
api_locking::LockAction::NotApplicable,
))
.await
}
<file_sep path="hyperswitch/crates/router/src/routes/payment_methods.rs" role="context" start="660" end="660">
use actix_web::{web, HttpRequest, HttpResponse};
use common_utils::{errors::CustomResult, id_type, transformers::ForeignFrom};
use router_env::{instrument, logger, tracing, Flow};
use super::app::{AppState, SessionState};
use crate::{
core::{
api_locking,
errors::{self, utils::StorageErrorExt},
payment_methods::{self as payment_methods_routes, cards},
},
services::{self, api, authentication as auth, authorization::permissions::Permission},
types::{
api::payment_methods::{self, PaymentMethodId},
domain,
storage::payment_method::PaymentTokenData,
},
};
use crate::{
core::{
customers,
payment_methods::{migration, tokenize},
},
types::api::customers::CustomerRequest,
};
<file_sep path="hyperswitch/crates/router/src/routes/payment_methods.rs" role="context" start="726" end="759">
pub async fn payment_method_update_api(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
json_payload: web::Json<payment_methods::PaymentMethodUpdate>,
) -> HttpResponse {
let flow = Flow::PaymentMethodsUpdate;
let payment_method_id = path.into_inner();
let payload = json_payload.into_inner();
let (auth, _) = match auth::check_client_secret_and_get_auth(req.headers(), &payload) {
Ok((auth, _auth_flow)) => (auth, _auth_flow),
Err(e) => return api::log_and_return_error_response(e),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
cards::update_customer_payment_method(
state,
auth.merchant_account,
req,
&payment_method_id,
auth.key_store,
)
},
&*auth,
api_locking::LockAction::NotApplicable,
))
.await
}
<file_sep path="hyperswitch/crates/router/src/routes/payment_methods.rs" role="context" start="696" end="719">
pub async fn payment_method_retrieve_api(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
) -> HttpResponse {
let flow = Flow::PaymentMethodsRetrieve;
let payload = web::Json(PaymentMethodId {
payment_method_id: path.into_inner(),
})
.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, pm, _| {
cards::retrieve_payment_method(state, pm, auth.key_store, auth.merchant_account)
},
&auth::HeaderAuth(auth::ApiKeyAuth),
api_locking::LockAction::NotApplicable,
))
.await
}
<file_sep path="hyperswitch/crates/router/src/routes/payment_methods.rs" role="context" start="629" end="656">
pub async fn get_total_payment_method_count(
state: web::Data<AppState>,
req: HttpRequest,
) -> HttpResponse {
let flow = Flow::TotalPaymentMethodCount;
Box::pin(api::server_wrap(
flow,
state,
&req,
(),
|state, auth: auth::AuthenticationData, _, _| {
payment_methods_routes::get_total_saved_payment_methods_for_merchant(
state,
auth.merchant_account,
)
},
auth::auth_type(
&auth::V2ApiKeyAuth,
&auth::JWTAuth {
permission: Permission::MerchantCustomerRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
<file_sep path="hyperswitch/crates/router/src/routes/payment_methods.rs" role="context" start="592" end="625">
pub async fn list_customer_payment_method_api(
state: web::Data<AppState>,
customer_id: web::Path<id_type::GlobalCustomerId>,
req: HttpRequest,
query_payload: web::Query<api_models::payment_methods::PaymentMethodListRequest>,
) -> HttpResponse {
let flow = Flow::CustomerPaymentMethodsList;
let payload = query_payload.into_inner();
let customer_id = customer_id.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, _, _| {
payment_methods_routes::list_saved_payment_methods_for_customer(
state,
auth.merchant_account,
auth.key_store,
customer_id.clone(),
)
},
auth::auth_type(
&auth::V2ApiKeyAuth,
&auth::JWTAuth {
permission: Permission::MerchantCustomerRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
<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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.