id stringlengths 11 116 | type stringclasses 1 value | granularity stringclasses 4 values | content stringlengths 16 477k | metadata dict |
|---|---|---|---|---|
fn_clm_router_validate_request_-522700410396971030 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/operations/payment_complete_authorize
// Implementation of CompleteAuthorize for ValidateRequest<F, api::PaymentsRequest, PaymentData<F>>
fn validate_request<'a, 'b>(
&'b self,
request: &api::PaymentsRequest,
merchant_context: &'a domain::MerchantContext,
) -> RouterResult<(
CompleteAuthorizeOperation<'b, F>,
operations::ValidateResult,
)> {
let payment_id = request
.payment_id
.clone()
.ok_or(report!(errors::ApiErrorResponse::PaymentNotFound))?;
let request_merchant_id = request.merchant_id.as_ref();
helpers::validate_merchant_id(
merchant_context.get_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(),
})?;
helpers::validate_payment_method_fields_present(request)?;
let _mandate_type =
helpers::validate_mandate(request, payments::is_operation_confirm(self))?;
helpers::validate_recurring_details_and_token(
&request.recurring_details,
&request.payment_token,
&request.mandate_id,
)?;
Ok((
Box::new(self),
operations::ValidateResult {
merchant_id: merchant_context.get_merchant_account().get_id().to_owned(),
payment_id,
storage_scheme: merchant_context.get_merchant_account().storage_scheme,
requeue: matches!(
request.retry_action,
Some(api_models::enums::RetryAction::Requeue)
),
},
))
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 68,
"total_crates": null
} |
fn_clm_router_make_pm_data_-522700410396971030 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/operations/payment_complete_authorize
// Implementation of CompleteAuthorize for Domain<F, api::PaymentsRequest, PaymentData<F>>
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))
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 29,
"total_crates": null
} |
fn_clm_router_get_or_create_customer_details_-522700410396971030 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/operations/payment_complete_authorize
// Implementation of CompleteAuthorize for Domain<F, api::PaymentsRequest, PaymentData<F>>
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
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 21,
"total_crates": null
} |
fn_clm_router_get_trackers_5183227633886461581 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/operations/payment_capture
// Implementation of PaymentCapture for GetTracker<F, payments::PaymentData<F>, api::PaymentsCaptureRequest>
async fn get_trackers<'a>(
&'a self,
state: &'a SessionState,
payment_id: &api::PaymentIdType,
request: &api::PaymentsCaptureRequest,
merchant_context: &domain::MerchantContext,
_auth_flow: services::AuthFlow,
_header_payload: &hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<
operations::GetTrackerResponse<
'a,
F,
api::PaymentsCaptureRequest,
payments::PaymentData<F>,
>,
> {
let db = &*state.store;
let key_manager_state = &state.into();
let merchant_id = merchant_context.get_merchant_account().get_id();
let storage_scheme = merchant_context.get_merchant_account().storage_scheme;
let (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,
merchant_context.get_merchant_key_store(),
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
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().as_str(),
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
payment_attempt
.amount_to_capture
.update_value(request.amount_to_capture);
let capture_method = payment_attempt
.capture_method
.get_required_value("capture_method")?;
helpers::validate_status_with_capture_method(payment_intent.status, capture_method)?;
if !*payment_attempt
.is_overcapture_enabled
.unwrap_or_default()
.deref()
{
helpers::validate_amount_to_capture(
payment_attempt.amount_capturable.get_amount_as_i64(),
request
.amount_to_capture
.map(|capture_amount| capture_amount.get_amount_as_i64()),
)?;
}
helpers::validate_capture_method(capture_method)?;
let multiple_capture_data = if capture_method == enums::CaptureMethod::ManualMultiple {
let amount_to_capture = request
.amount_to_capture
.get_required_value("amount_to_capture")?;
helpers::validate_amount_to_capture(
payment_attempt.amount_capturable.get_amount_as_i64(),
Some(amount_to_capture.get_amount_as_i64()),
)?;
let previous_captures = db
.find_all_captures_by_merchant_id_payment_id_authorized_attempt_id(
&payment_attempt.merchant_id,
&payment_attempt.payment_id,
&payment_attempt.attempt_id,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
let capture = db
.insert_capture(
payment_attempt
.make_new_capture(amount_to_capture, enums::CaptureStatus::Started)?,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::DuplicatePayment {
payment_id: payment_id.clone(),
})?;
Some(MultipleCaptureData::new_for_create(
previous_captures,
capture,
))
} else {
None
};
currency = payment_attempt.currency.get_required_value("currency")?;
amount = payment_attempt.get_total_amount().into();
let shipping_address = helpers::get_address_by_id(
state,
payment_intent.shipping_address_id.clone(),
merchant_context.get_merchant_key_store(),
&payment_intent.payment_id,
merchant_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let billing_address = helpers::get_address_by_id(
state,
payment_intent.billing_address_id.clone(),
merchant_context.get_merchant_key_store(),
&payment_intent.payment_id,
merchant_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let payment_method_billing = helpers::get_address_by_id(
state,
payment_attempt.payment_method_billing_address_id.clone(),
merchant_context.get_merchant_key_store(),
&payment_intent.payment_id,
merchant_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
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_context.get_merchant_account().get_id(),
mcd,
)
.await
})
.await
.transpose()?;
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,
merchant_context.get_merchant_key_store(),
profile_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
let payment_data = payments::PaymentData {
flow: PhantomData,
payment_intent,
payment_attempt,
currency,
force_sync: None,
all_keys_required: None,
amount,
email: None,
mandate_id: None,
mandate_connector: None,
setup_mandate: None,
customer_acceptance: None,
token: None,
token_data: None,
address: core_types::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: None,
payment_method_data: None,
payment_method_token: None,
payment_method_info: None,
refunds: vec![],
disputes: vec![],
attempts: None,
sessions_token: vec![],
card_cvc: None,
creds_identifier,
pm_token: None,
connector_customer_id: None,
recurring_mandate_payment_data: None,
ephemeral_key: None,
multiple_capture_data,
redirect_response: None,
surcharge_details: None,
frm_message: None,
payment_link_data: None,
incremental_authorization_details: None,
authorizations: vec![],
authentication: None,
recurring_details: None,
poll_config: None,
tax_data: None,
session_id: None,
service_details: None,
card_testing_guard_data: None,
vault_operation: None,
threeds_method_comp_ind: None,
whole_connector_response: None,
is_manual_retry_enabled: None,
is_l2_l3_enabled: false,
};
let get_trackers_response = operations::GetTrackerResponse {
operation: Box::new(self),
customer_details: None,
payment_data,
business_profile,
mandate_type: None,
};
Ok(get_trackers_response)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 191,
"total_crates": null
} |
fn_clm_router_update_trackers_5183227633886461581 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/operations/payment_capture
// Implementation of PaymentCapture for UpdateTracker<F, payments::PaymentData<F>, api::PaymentsCaptureRequest>
async fn update_trackers<'b>(
&'b self,
db: &'b SessionState,
req_state: ReqState,
mut payment_data: payments::PaymentData<F>,
_customer: Option<domain::Customer>,
storage_scheme: enums::MerchantStorageScheme,
_updated_customer: Option<storage::CustomerUpdate>,
_mechant_key_store: &domain::MerchantKeyStore,
_frm_suggestion: Option<FrmSuggestion>,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<(PaymentCaptureOperation<'b, F>, payments::PaymentData<F>)>
where
F: 'b + Send,
{
payment_data.payment_attempt = if payment_data.multiple_capture_data.is_some()
|| payment_data.payment_attempt.amount_to_capture.is_some()
{
let multiple_capture_count = payment_data
.multiple_capture_data
.as_ref()
.map(|multiple_capture_data| multiple_capture_data.get_captures_count())
.transpose()?;
let amount_to_capture = payment_data.payment_attempt.amount_to_capture;
db.store
.update_payment_attempt_with_attempt_id(
payment_data.payment_attempt,
storage::PaymentAttemptUpdate::CaptureUpdate {
amount_to_capture,
multiple_capture_count,
updated_by: storage_scheme.to_string(),
},
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::InternalServerError)?
} else {
payment_data.payment_attempt
};
let capture_amount = payment_data.payment_attempt.amount_to_capture;
let multiple_capture_count = payment_data.payment_attempt.multiple_capture_count;
req_state
.event_context
.event(AuditEvent::new(AuditEventType::PaymentCapture {
capture_amount,
multiple_capture_count,
}))
.with(payment_data.to_event())
.emit();
Ok((Box::new(self), payment_data))
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 89,
"total_crates": null
} |
fn_clm_router_validate_request_5183227633886461581 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/operations/payment_capture
// Implementation of PaymentCapture for ValidateRequest<F, api::PaymentsCaptureRequest, payments::PaymentData<F>>
fn validate_request<'a, 'b>(
&'b self,
request: &api::PaymentsCaptureRequest,
merchant_context: &'a domain::MerchantContext,
) -> RouterResult<(PaymentCaptureOperation<'b, F>, operations::ValidateResult)> {
Ok((
Box::new(self),
operations::ValidateResult {
merchant_id: merchant_context.get_merchant_account().get_id().to_owned(),
payment_id: api::PaymentIdType::PaymentIntentId(request.payment_id.to_owned()),
storage_scheme: merchant_context.get_merchant_account().storage_scheme,
requeue: false,
},
))
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 46,
"total_crates": null
} |
fn_clm_router_get_trackers_1193279926401257270 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/operations/payment_create
// Implementation of PaymentCreate for GetTracker<F, PaymentData<F>, api::PaymentsRequest>
async fn get_trackers<'a>(
&'a self,
state: &'a SessionState,
payment_id: &api::PaymentIdType,
request: &api::PaymentsRequest,
merchant_context: &domain::MerchantContext,
_auth_flow: services::AuthFlow,
header_payload: &hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsRequest, PaymentData<F>>>
{
let db = &*state.store;
let key_manager_state = &state.into();
let ephemeral_key = Self::get_ephemeral_key(request, state, merchant_context).await;
let merchant_id = merchant_context.get_merchant_account().get_id();
let storage_scheme = merchant_context.get_merchant_account().storage_scheme;
let money @ (amount, currency) = payments_create_request_validation(request)?;
let payment_id = payment_id
.get_payment_intent_id()
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
#[cfg(feature = "v1")]
helpers::validate_business_details(
request.business_country,
request.business_label.as_ref(),
merchant_context,
)?;
// If profile id is not passed, get it from the business_country and business_label
#[cfg(feature = "v1")]
let profile_id = core_utils::get_profile_id_from_business_details(
key_manager_state,
request.business_country,
request.business_label.as_ref(),
merchant_context,
request.profile_id.as_ref(),
&*state.store,
true,
)
.await?;
// Profile id will be mandatory in v2 in the request / headers
#[cfg(feature = "v2")]
let profile_id = request
.profile_id
.clone()
.get_required_value("profile_id")
.attach_printable("Profile id is a mandatory parameter")?;
// TODO: eliminate a redundant db call to fetch the business profile
// Validate whether profile_id passed in request is valid and is linked to the merchant
let business_profile = if let Some(business_profile) =
core_utils::validate_and_get_business_profile(
db,
key_manager_state,
merchant_context.get_merchant_key_store(),
Some(&profile_id),
merchant_id,
)
.await?
{
business_profile
} else {
db.find_business_profile_by_profile_id(
key_manager_state,
merchant_context.get_merchant_key_store(),
&profile_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?
};
let customer_acceptance = request.customer_acceptance.clone();
let recurring_details = request.recurring_details.clone();
let mandate_type = m_helpers::get_mandate_type(
request.mandate_data.clone(),
request.off_session,
request.setup_future_usage,
request.customer_acceptance.clone(),
request.payment_token.clone(),
request.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,
} = helpers::get_token_pm_type_mandate_details(
state,
request,
mandate_type,
merchant_context,
None,
None,
)
.await?;
helpers::validate_allowed_payment_method_types_request(
state,
&profile_id,
merchant_context,
request.allowed_payment_method_types.clone(),
)
.await?;
let customer_details = helpers::get_customer_details_from_request(request);
let shipping_address = helpers::create_or_find_address_for_payment_by_request(
state,
request.shipping.as_ref(),
None,
merchant_id,
customer_details.customer_id.as_ref(),
merchant_context.get_merchant_key_store(),
&payment_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let billing_address = helpers::create_or_find_address_for_payment_by_request(
state,
request.billing.as_ref(),
None,
merchant_id,
customer_details.customer_id.as_ref(),
merchant_context.get_merchant_key_store(),
&payment_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let payment_method_billing_address =
helpers::create_or_find_address_for_payment_by_request(
state,
request
.payment_method_data
.as_ref()
.and_then(|pmd| pmd.billing.as_ref()),
None,
merchant_id,
customer_details.customer_id.as_ref(),
merchant_context.get_merchant_key_store(),
&payment_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let browser_info = request
.browser_info
.clone()
.as_ref()
.map(Encode::encode_to_value)
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "browser_info",
})?;
let attempt_id = if core_utils::is_merchant_enabled_for_payment_id_as_connector_request_id(
&state.conf,
merchant_id,
) {
payment_id.get_string_repr().to_string()
} else {
payment_id.get_attempt_id(1)
};
let session_expiry =
common_utils::date_time::now().saturating_add(time::Duration::seconds(
request.session_expiry.map(i64::from).unwrap_or(
business_profile
.session_expiry
.unwrap_or(consts::DEFAULT_SESSION_EXPIRY),
),
));
let payment_link_data = match request.payment_link {
Some(true) => {
let merchant_name = merchant_context
.get_merchant_account()
.merchant_name
.clone()
.map(|name| name.into_inner().peek().to_owned())
.unwrap_or_default();
let default_domain_name = state.base_url.clone();
let (payment_link_config, domain_name) =
payment_link::get_payment_link_config_based_on_priority(
request.payment_link_config.clone(),
business_profile.payment_link_config.clone(),
merchant_name,
default_domain_name,
request.payment_link_config_id.clone(),
)?;
create_payment_link(
request,
payment_link_config,
merchant_id,
payment_id.clone(),
db,
amount,
request.description.clone(),
profile_id.clone(),
domain_name,
session_expiry,
header_payload.locale.clone(),
)
.await?
}
_ => None,
};
let payment_intent_new = Self::make_payment_intent(
state,
&payment_id,
merchant_context,
money,
request,
shipping_address
.as_ref()
.map(|address| address.address_id.clone()),
payment_link_data.clone(),
billing_address
.as_ref()
.map(|address| address.address_id.clone()),
attempt_id,
profile_id.clone(),
session_expiry,
&business_profile,
request.is_payment_id_from_merchant,
)
.await?;
let (payment_attempt_new, additional_payment_data) = Self::make_payment_attempt(
&payment_id,
merchant_id,
&merchant_context.get_merchant_account().organization_id,
money,
payment_method,
payment_method_type,
request,
browser_info,
state,
payment_method_billing_address
.as_ref()
.map(|address| address.address_id.clone()),
&payment_method_info,
merchant_context.get_merchant_key_store(),
profile_id,
&customer_acceptance,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let payment_intent = db
.insert_payment_intent(
key_manager_state,
payment_intent_new,
merchant_context.get_merchant_key_store(),
storage_scheme,
)
.await
.to_duplicate_response(errors::ApiErrorResponse::DuplicatePayment {
payment_id: payment_id.clone(),
})?;
if let Some(order_details) = &request.order_details {
helpers::validate_order_details_amount(
order_details.to_owned(),
payment_intent.amount,
false,
)?;
}
#[cfg(feature = "v1")]
let mut payment_attempt = db
.insert_payment_attempt(payment_attempt_new, storage_scheme)
.await
.to_duplicate_response(errors::ApiErrorResponse::DuplicatePayment {
payment_id: payment_id.clone(),
})?;
#[cfg(feature = "v2")]
let payment_attempt = db
.insert_payment_attempt(
key_manager_state,
merchant_key_store,
payment_attempt_new,
storage_scheme,
)
.await
.to_duplicate_response(errors::ApiErrorResponse::DuplicatePayment {
payment_id: payment_id.clone(),
})?;
let mandate_details_present = payment_attempt.mandate_details.is_some();
helpers::validate_mandate_data_and_future_usage(
request.setup_future_usage,
mandate_details_present,
)?;
// connector mandate reference update history
let mandate_id = request
.mandate_id
.as_ref()
.or_else(|| {
request.recurring_details
.as_ref()
.and_then(|recurring_details| match recurring_details {
RecurringDetails::MandateId(id) => Some(id),
_ => None,
})
})
.async_and_then(|mandate_id| async {
let mandate = db
.find_mandate_by_merchant_id_mandate_id(merchant_id, mandate_id, storage_scheme)
.await
.to_not_found_response(errors::ApiErrorResponse::MandateNotFound);
Some(mandate.and_then(|mandate_obj| {
match (
mandate_obj.network_transaction_id,
mandate_obj.connector_mandate_ids,
) {
(_, Some(connector_mandate_id)) => connector_mandate_id
.parse_value("ConnectorMandateId")
.change_context(errors::ApiErrorResponse::MandateNotFound)
.map(|connector_id: api_models::payments::ConnectorMandateReferenceId| {
api_models::payments::MandateIds {
mandate_id: Some(mandate_obj.mandate_id),
mandate_reference_id: Some(api_models::payments::MandateReferenceId::ConnectorMandateId(
api_models::payments::ConnectorMandateReferenceId::new(
connector_id.get_connector_mandate_id(),
connector_id.get_payment_method_id(),
None,
None,
connector_id.get_connector_mandate_request_reference_id(),
)
))
}
}),
(Some(network_tx_id), _) => Ok(api_models::payments::MandateIds {
mandate_id: Some(mandate_obj.mandate_id),
mandate_reference_id: Some(
api_models::payments::MandateReferenceId::NetworkMandateId(
network_tx_id,
),
),
}),
(_, _) => Ok(api_models::payments::MandateIds {
mandate_id: Some(mandate_obj.mandate_id),
mandate_reference_id: None,
}),
}
}))
})
.await
.transpose()?;
let mandate_id = if mandate_id.is_none() {
request
.recurring_details
.as_ref()
.and_then(|recurring_details| match recurring_details {
RecurringDetails::ProcessorPaymentToken(token) => {
Some(api_models::payments::MandateIds {
mandate_id: None,
mandate_reference_id: Some(
api_models::payments::MandateReferenceId::ConnectorMandateId(
api_models::payments::ConnectorMandateReferenceId::new(
Some(token.processor_payment_token.clone()),
None,
None,
None,
None,
),
),
),
})
}
_ => None,
})
} else {
mandate_id
};
let operation = payments::if_not_create_change_operation::<_, F>(
payment_intent.status,
request.confirm,
self,
);
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_context.get_merchant_account().get_id(),
mcd,
)
.await
})
.await
.transpose()?;
// The operation merges mandate data from both request and payment_attempt
let setup_mandate = mandate_data;
let surcharge_details = request.surcharge_details.map(|request_surcharge_details| {
payments::types::SurchargeDetails::from((&request_surcharge_details, &payment_attempt))
});
let payment_method_data_after_card_bin_call = request
.payment_method_data
.as_ref()
.and_then(|payment_method_data_from_request| {
payment_method_data_from_request
.payment_method_data
.as_ref()
})
.zip(additional_payment_data)
.map(|(payment_method_data, additional_payment_data)| {
payment_method_data.apply_additional_payment_data(additional_payment_data)
})
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Card cobadge check failed due to an invalid card network regex")?;
let additional_pm_data_from_locker = if let Some(ref pm) = payment_method_info {
let card_detail_from_locker: Option<api::CardDetailFromLocker> = pm
.payment_method_data
.clone()
.map(|x| x.into_inner().expose())
.and_then(|v| {
v.parse_value("PaymentMethodsData")
.map_err(|err| {
router_env::logger::info!(
"PaymentMethodsData deserialization failed: {:?}",
err
)
})
.ok()
})
.and_then(|pmd| match pmd {
PaymentMethodsData::Card(crd) => Some(api::CardDetailFromLocker::from(crd)),
_ => None,
});
card_detail_from_locker.map(|card_details| {
let additional_data = card_details.into();
api_models::payments::AdditionalPaymentData::Card(Box::new(additional_data))
})
} else {
None
};
// Only set `payment_attempt.payment_method_data` if `additional_pm_data_from_locker` is not None
if let Some(additional_pm_data) = additional_pm_data_from_locker.as_ref() {
payment_attempt.payment_method_data = Some(
Encode::encode_to_value(additional_pm_data)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to encode additional pm data")?,
);
}
let amount = payment_attempt.get_total_amount().into();
payment_attempt.connector_mandate_detail =
Some(DieselConnectorMandateReferenceId::foreign_from(
api_models::payments::ConnectorMandateReferenceId::new(
None,
None,
None, // update_history
None, // mandate_metadata
Some(common_utils::generate_id_with_len(
consts::CONNECTOR_MANDATE_REQUEST_REFERENCE_ID_LENGTH,
)), // connector_mandate_request_reference_id
),
));
let address = PaymentAddress::new(
shipping_address.as_ref().map(From::from),
billing_address.as_ref().map(From::from),
payment_method_billing_address.as_ref().map(From::from),
business_profile.use_billing_as_payment_method_billing,
);
let payment_method_data_billing = request
.payment_method_data
.as_ref()
.and_then(|pmd| pmd.payment_method_data.as_ref())
.and_then(|payment_method_data_billing| {
payment_method_data_billing.get_billing_address()
})
.map(From::from);
let unified_address =
address.unify_with_payment_method_data_billing(payment_method_data_billing);
let payment_data = PaymentData {
flow: PhantomData,
payment_intent,
payment_attempt,
currency,
amount,
email: request.email.clone(),
mandate_id: mandate_id.clone(),
mandate_connector,
setup_mandate,
customer_acceptance,
token,
address: unified_address,
token_data: None,
confirm: request.confirm,
payment_method_data: payment_method_data_after_card_bin_call.map(Into::into),
payment_method_token: None,
payment_method_info,
refunds: vec![],
disputes: vec![],
attempts: None,
force_sync: None,
all_keys_required: 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,
multiple_capture_data: None,
redirect_response: None,
surcharge_details,
frm_message: None,
payment_link_data,
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: None,
whole_connector_response: None,
is_manual_retry_enabled: None,
is_l2_l3_enabled: business_profile.is_l2_l3_enabled,
};
let get_trackers_response = operations::GetTrackerResponse {
operation,
customer_details: Some(customer_details),
payment_data,
business_profile,
mandate_type,
};
Ok(get_trackers_response)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 439,
"total_crates": null
} |
fn_clm_router_make_payment_attempt_1193279926401257270 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/operations/payment_create
// Inherent implementation for PaymentCreate
pub async fn make_payment_attempt(
payment_id: &common_utils::id_type::PaymentId,
merchant_id: &common_utils::id_type::MerchantId,
organization_id: &common_utils::id_type::OrganizationId,
money: (api::Amount, enums::Currency),
payment_method: Option<enums::PaymentMethod>,
payment_method_type: Option<enums::PaymentMethodType>,
request: &api::PaymentsRequest,
browser_info: Option<serde_json::Value>,
state: &SessionState,
optional_payment_method_billing_address_id: Option<String>,
payment_method_info: &Option<domain::PaymentMethod>,
key_store: &domain::MerchantKeyStore,
profile_id: common_utils::id_type::ProfileId,
customer_acceptance: &Option<common_payments_types::CustomerAcceptance>,
storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<(
storage::PaymentAttemptNew,
Option<api_models::payments::AdditionalPaymentData>,
)> {
let payment_method_data =
request
.payment_method_data
.as_ref()
.and_then(|payment_method_data_request| {
payment_method_data_request.payment_method_data.as_ref()
});
let created_at @ modified_at @ last_synced = Some(common_utils::date_time::now());
let status = helpers::payment_attempt_status_fsm(payment_method_data, request.confirm);
let (amount, currency) = (money.0, Some(money.1));
let mut additional_pm_data = request
.payment_method_data
.as_ref()
.and_then(|payment_method_data_request| {
payment_method_data_request.payment_method_data.clone()
})
.async_map(|payment_method_data| async {
helpers::get_additional_payment_data(
&payment_method_data.into(),
&*state.store,
&profile_id,
)
.await
})
.await
.transpose()?
.flatten();
if additional_pm_data.is_none() {
// If recurring payment is made using payment_method_id, then fetch payment_method_data from retrieved payment_method object
additional_pm_data = payment_method_info.as_ref().and_then(|pm_info| {
pm_info
.payment_method_data
.clone()
.map(|x| x.into_inner().expose())
.and_then(|v| {
serde_json::from_value::<PaymentMethodsData>(v)
.map_err(|err| {
logger::error!(
"Unable to deserialize payment methods data: {:?}",
err
)
})
.ok()
})
.and_then(|pmd| match pmd {
PaymentMethodsData::Card(card) => {
Some(api_models::payments::AdditionalPaymentData::Card(Box::new(
api::CardDetailFromLocker::from(card).into(),
)))
}
PaymentMethodsData::WalletDetails(wallet) => match payment_method_type {
Some(enums::PaymentMethodType::ApplePay) => {
Some(api_models::payments::AdditionalPaymentData::Wallet {
apple_pay: api::payments::ApplepayPaymentMethod::try_from(
wallet,
)
.inspect_err(|err| {
logger::error!(
"Unable to transform PaymentMethodDataWalletInfo to ApplepayPaymentMethod: {:?}",
err
)
})
.ok(),
google_pay: None,
samsung_pay: None,
})
}
Some(enums::PaymentMethodType::GooglePay) => {
Some(api_models::payments::AdditionalPaymentData::Wallet {
apple_pay: None,
google_pay: Some(wallet.into()),
samsung_pay: None,
})
}
Some(enums::PaymentMethodType::SamsungPay) => {
Some(api_models::payments::AdditionalPaymentData::Wallet {
apple_pay: None,
google_pay: None,
samsung_pay: Some(wallet.into()),
})
}
_ => None,
},
_ => None,
})
.or_else(|| match payment_method_type {
Some(enums::PaymentMethodType::Paypal) => {
Some(api_models::payments::AdditionalPaymentData::Wallet {
apple_pay: None,
google_pay: None,
samsung_pay: None,
})
}
_ => None,
})
});
};
let additional_pm_data_value = additional_pm_data
.as_ref()
.map(Encode::encode_to_value)
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to encode additional pm data")?;
let attempt_id = if core_utils::is_merchant_enabled_for_payment_id_as_connector_request_id(
&state.conf,
merchant_id,
) {
payment_id.get_string_repr().to_owned()
} else {
payment_id.get_attempt_id(1)
};
if request.mandate_data.as_ref().is_some_and(|mandate_data| {
mandate_data.update_mandate_id.is_some() && mandate_data.mandate_type.is_some()
}) {
Err(errors::ApiErrorResponse::InvalidRequestData {message:"Only one field out of 'mandate_type' and 'update_mandate_id' was expected, found both".to_string()})?
}
let mandate_data = if let Some(update_id) = request
.mandate_data
.as_ref()
.and_then(|inner| inner.update_mandate_id.clone())
{
let mandate_details = MandateDetails {
update_mandate_id: Some(update_id),
};
Some(mandate_details)
} else {
None
};
let payment_method_type = Option::<enums::PaymentMethodType>::foreign_from((
payment_method_type,
additional_pm_data.as_ref(),
payment_method,
));
// TODO: remove once https://github.com/juspay/hyperswitch/issues/7421 is fixed
let payment_method_billing_address_id = match optional_payment_method_billing_address_id {
None => payment_method_info
.as_ref()
.and_then(|pm_info| pm_info.payment_method_billing_address.as_ref())
.map(|address| {
address.clone().deserialize_inner_value(|value| {
value.parse_value::<api_models::payments::Address>("Address")
})
})
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.ok()
.flatten()
.async_map(|addr| async move {
helpers::create_or_find_address_for_payment_by_request(
state,
Some(addr.get_inner()),
None,
merchant_id,
payment_method_info
.as_ref()
.map(|pmd_info| pmd_info.customer_id.clone())
.as_ref(),
key_store,
payment_id,
storage_scheme,
)
.await
})
.await
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)?
.flatten()
.map(|address| address.address_id),
address_id => address_id,
};
let is_stored_credential = helpers::is_stored_credential(
&request.recurring_details,
&request.payment_token,
request.mandate_id.is_some(),
request.is_stored_credential,
);
Ok((
storage::PaymentAttemptNew {
payment_id: payment_id.to_owned(),
merchant_id: merchant_id.to_owned(),
attempt_id,
status,
currency,
payment_method,
capture_method: request.capture_method,
capture_on: request.capture_on,
confirm: request.confirm.unwrap_or(false),
created_at,
modified_at,
last_synced,
authentication_type: request.authentication_type,
browser_info,
payment_experience: request.payment_experience,
payment_method_type,
payment_method_data: additional_pm_data_value,
amount_to_capture: request.amount_to_capture,
payment_token: request.payment_token.clone(),
mandate_id: request.mandate_id.clone(),
business_sub_label: request.business_sub_label.clone(),
mandate_details: request
.mandate_data
.as_ref()
.and_then(|inner| inner.mandate_type.clone().map(Into::into)),
external_three_ds_authentication_attempted: None,
mandate_data,
payment_method_billing_address_id,
net_amount: hyperswitch_domain_models::payments::payment_attempt::NetAmount::from_payments_request(
request,
MinorUnit::from(amount),
),
save_to_locker: None,
connector: None,
error_message: None,
offer_amount: None,
payment_method_id: payment_method_info
.as_ref()
.map(|pm_info| pm_info.get_id().clone()),
cancellation_reason: None,
error_code: None,
connector_metadata: None,
straight_through_algorithm: None,
preprocessing_step_id: None,
error_reason: None,
connector_response_reference_id: None,
multiple_capture_count: None,
amount_capturable: MinorUnit::new(i64::default()),
updated_by: String::default(),
authentication_data: None,
encoded_data: None,
merchant_connector_id: None,
unified_code: None,
unified_message: None,
fingerprint_id: None,
authentication_connector: None,
authentication_id: None,
client_source: None,
client_version: None,
customer_acceptance: customer_acceptance
.clone()
.map(|customer_acceptance| customer_acceptance.encode_to_value())
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to serialize customer_acceptance")?
.map(Secret::new),
organization_id: organization_id.clone(),
profile_id,
connector_mandate_detail: None,
request_extended_authorization: None,
extended_authorization_applied: None,
capture_before: None,
card_discovery: None,
processor_merchant_id: merchant_id.to_owned(),
created_by: None,
setup_future_usage_applied: request.setup_future_usage,
routing_approach: Some(common_enums::RoutingApproach::default()),
connector_request_reference_id: None,
network_transaction_id:None,
network_details:None,
is_stored_credential,
authorized_amount: None,
},
additional_pm_data,
))
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 231,
"total_crates": null
} |
fn_clm_router_make_payment_intent_1193279926401257270 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/operations/payment_create
// Inherent implementation for PaymentCreate
async fn make_payment_intent(
state: &SessionState,
payment_id: &common_utils::id_type::PaymentId,
merchant_context: &domain::MerchantContext,
money: (api::Amount, enums::Currency),
request: &api::PaymentsRequest,
shipping_address_id: Option<String>,
payment_link_data: Option<api_models::payments::PaymentLinkResponse>,
billing_address_id: Option<String>,
active_attempt_id: String,
profile_id: common_utils::id_type::ProfileId,
session_expiry: PrimitiveDateTime,
business_profile: &domain::Profile,
is_payment_id_from_merchant: bool,
) -> RouterResult<storage::PaymentIntent> {
let created_at @ modified_at @ last_synced = common_utils::date_time::now();
let status = helpers::payment_intent_status_fsm(
request
.payment_method_data
.as_ref()
.and_then(|request_payment_method_data| {
request_payment_method_data.payment_method_data.as_ref()
}),
request.confirm,
);
let client_secret = payment_id.generate_client_secret();
let (amount, currency) = (money.0, Some(money.1));
let order_details = request
.get_order_details_as_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to convert order details to value")?;
let 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")?;
let connector_metadata = request
.get_connector_metadata_as_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error converting connector_metadata to Value")?;
let feature_metadata = request
.get_feature_metadata_as_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error converting feature_metadata to Value")?;
let payment_link_id = payment_link_data.map(|pl_data| pl_data.payment_link_id);
let request_incremental_authorization =
core_utils::get_request_incremental_authorization_value(
request.request_incremental_authorization,
request.capture_method,
)?;
let split_payments = request.split_payments.clone();
// Derivation of directly supplied Customer data in our Payment Create Request
let raw_customer_details = if request.customer_id.is_none()
&& (request.name.is_some()
|| request.email.is_some()
|| request.phone.is_some()
|| request.phone_country_code.is_some())
{
Some(CustomerData {
name: request.name.clone(),
phone: request.phone.clone(),
email: request.email.clone(),
phone_country_code: request.phone_country_code.clone(),
tax_registration_id: None,
})
} else {
None
};
let is_payment_processor_token_flow = request.recurring_details.as_ref().and_then(
|recurring_details| match recurring_details {
RecurringDetails::ProcessorPaymentToken(_) => Some(true),
_ => None,
},
);
let key = merchant_context
.get_merchant_key_store()
.key
.get_inner()
.peek();
let identifier = Identifier::Merchant(
merchant_context
.get_merchant_key_store()
.merchant_id
.clone(),
);
let key_manager_state: KeyManagerState = state.into();
let shipping_details_encoded = request
.shipping
.clone()
.map(|shipping| Encode::encode_to_value(&shipping).map(Secret::new))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encode billing details to serde_json::Value")?;
let billing_details_encoded = request
.billing
.clone()
.map(|billing| Encode::encode_to_value(&billing).map(Secret::new))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encode billing details to serde_json::Value")?;
let customer_details_encoded = raw_customer_details
.map(|customer| Encode::encode_to_value(&customer).map(Secret::new))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encode shipping details to serde_json::Value")?;
let encrypted_data = domain::types::crypto_operation(
&key_manager_state,
type_name!(storage::PaymentIntent),
domain::types::CryptoOperation::BatchEncrypt(
FromRequestEncryptablePaymentIntent::to_encryptable(
FromRequestEncryptablePaymentIntent {
shipping_details: shipping_details_encoded,
billing_details: billing_details_encoded,
customer_details: customer_details_encoded,
},
),
),
identifier.clone(),
key,
)
.await
.and_then(|val| val.try_into_batchoperation())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt data")?;
let encrypted_data = FromRequestEncryptablePaymentIntent::from_encryptable(encrypted_data)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt the payment intent data")?;
let skip_external_tax_calculation = request.skip_external_tax_calculation;
let tax_details = request
.order_tax_amount
.map(|tax_amount| diesel_models::TaxDetails {
default: Some(diesel_models::DefaultTax {
order_tax_amount: tax_amount,
}),
payment_method_type: None,
});
let force_3ds_challenge_trigger = request
.force_3ds_challenge
.unwrap_or(business_profile.force_3ds_challenge);
Ok(storage::PaymentIntent {
payment_id: payment_id.to_owned(),
merchant_id: merchant_context.get_merchant_account().get_id().to_owned(),
status,
amount: MinorUnit::from(amount),
currency,
description: request.description.clone(),
created_at,
modified_at,
last_synced: Some(last_synced),
client_secret: Some(client_secret),
setup_future_usage: request.setup_future_usage,
off_session: request.off_session,
return_url: request.return_url.as_ref().map(|a| a.to_string()),
shipping_address_id,
billing_address_id,
statement_descriptor_name: request.statement_descriptor_name.clone(),
statement_descriptor_suffix: request.statement_descriptor_suffix.clone(),
metadata: request.metadata.clone(),
business_country: request.business_country,
business_label: request.business_label.clone(),
active_attempt: hyperswitch_domain_models::RemoteStorageObject::ForeignID(
active_attempt_id,
),
order_details,
amount_captured: None,
customer_id: request.get_customer_id().cloned(),
connector_id: None,
allowed_payment_method_types,
connector_metadata,
feature_metadata,
attempt_count: 1,
profile_id: Some(profile_id),
merchant_decision: None,
payment_link_id,
payment_confirm_source: None,
surcharge_applicable: None,
updated_by: merchant_context
.get_merchant_account()
.storage_scheme
.to_string(),
request_incremental_authorization,
incremental_authorization_allowed: None,
authorization_count: None,
fingerprint_id: None,
session_expiry: Some(session_expiry),
request_external_three_ds_authentication: request
.request_external_three_ds_authentication,
split_payments,
frm_metadata: request.frm_metadata.clone(),
billing_details: encrypted_data.billing_details,
customer_details: encrypted_data.customer_details,
merchant_order_reference_id: request.merchant_order_reference_id.clone(),
shipping_details: encrypted_data.shipping_details,
is_payment_processor_token_flow,
organization_id: merchant_context
.get_merchant_account()
.organization_id
.clone(),
shipping_cost: request.shipping_cost,
tax_details,
skip_external_tax_calculation,
request_extended_authorization: request.request_extended_authorization,
psd2_sca_exemption_type: request.psd2_sca_exemption_type,
processor_merchant_id: merchant_context.get_merchant_account().get_id().to_owned(),
created_by: None,
force_3ds_challenge: request.force_3ds_challenge,
force_3ds_challenge_trigger: Some(force_3ds_challenge_trigger),
is_iframe_redirection_enabled: request
.is_iframe_redirection_enabled
.or(business_profile.is_iframe_redirection_enabled),
is_payment_id_from_merchant: Some(is_payment_id_from_merchant),
payment_channel: request.payment_channel.clone(),
order_date: request.order_date,
discount_amount: request.discount_amount,
duty_amount: request.duty_amount,
tax_status: request.tax_status,
shipping_amount_tax: request.shipping_amount_tax,
enable_partial_authorization: request.enable_partial_authorization,
enable_overcapture: request.enable_overcapture,
mit_category: request.mit_category,
})
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 209,
"total_crates": null
} |
fn_clm_router_validate_request_1193279926401257270 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/operations/payment_create
// Implementation of PaymentCreate for ValidateRequest<F, api::PaymentsRequest, PaymentData<F>>
fn validate_request<'a, 'b>(
&'b self,
request: &api::PaymentsRequest,
merchant_context: &'a domain::MerchantContext,
) -> RouterResult<(PaymentCreateOperation<'b, F>, operations::ValidateResult)> {
helpers::validate_customer_information(request)?;
if let Some(amount) = request.amount {
helpers::validate_max_amount(amount)?;
}
if let Some(session_expiry) = &request.session_expiry {
helpers::validate_session_expiry(session_expiry.to_owned())?;
}
if let Some(payment_link) = &request.payment_link {
if *payment_link {
helpers::validate_payment_link_request(request)?;
}
};
let payment_id = request.payment_id.clone().ok_or(error_stack::report!(
errors::ApiErrorResponse::PaymentNotFound
))?;
let request_merchant_id = request.merchant_id.as_ref();
helpers::validate_merchant_id(
merchant_context.get_merchant_account().get_id(),
request_merchant_id,
)
.change_context(errors::ApiErrorResponse::MerchantAccountNotFound)?;
helpers::validate_request_amount_and_amount_to_capture(
request.amount,
request.amount_to_capture,
request.surcharge_details,
)
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "amount_to_capture".to_string(),
expected_format: "amount_to_capture lesser than amount".to_string(),
})?;
helpers::validate_amount_to_capture_and_capture_method(None, request)?;
helpers::validate_card_data(
request
.payment_method_data
.as_ref()
.and_then(|pmd| pmd.payment_method_data.clone()),
)?;
helpers::validate_payment_method_fields_present(request)?;
let mandate_type =
helpers::validate_mandate(request, payments::is_operation_confirm(self))?;
helpers::validate_recurring_details_and_token(
&request.recurring_details,
&request.payment_token,
&request.mandate_id,
)?;
request.validate_stored_credential().change_context(
errors::ApiErrorResponse::InvalidRequestData {
message:
"is_stored_credential should be true when reusing stored payment method data"
.to_string(),
},
)?;
helpers::validate_overcapture_request(
&request.enable_overcapture,
&request.capture_method,
)?;
request.validate_mit_request().change_context(
errors::ApiErrorResponse::InvalidRequestData {
message:
"`mit_category` requires both: (1) `off_session = true`, and (2) `recurring_details`."
.to_string(),
},
)?;
if request.confirm.unwrap_or(false) {
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,
&request.payment_token,
&request.ctp_service_details,
)?;
helpers::validate_customer_id_mandatory_cases(
request.setup_future_usage.is_some(),
request.customer_id.as_ref().or(request
.customer
.as_ref()
.map(|customer| customer.id.clone())
.as_ref()),
)?;
}
if request.split_payments.is_some() {
let amount = request.amount.get_required_value("amount")?;
helpers::validate_platform_request_for_marketplace(
amount,
request.split_payments.clone(),
)?;
};
let _request_straight_through: Option<api::routing::StraightThroughAlgorithm> = request
.routing
.clone()
.map(|val| val.parse_value("RoutingAlgorithm"))
.transpose()
.change_context(errors::ApiErrorResponse::InvalidRequestData {
message: "Invalid straight through routing rules format".to_string(),
})
.attach_printable("Invalid straight through routing rules format")?;
Ok((
Box::new(self),
operations::ValidateResult {
merchant_id: merchant_context.get_merchant_account().get_id().to_owned(),
payment_id,
storage_scheme: merchant_context.get_merchant_account().storage_scheme,
requeue: matches!(
request.retry_action,
Some(api_models::enums::RetryAction::Requeue)
),
},
))
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 154,
"total_crates": null
} |
fn_clm_router_update_trackers_1193279926401257270 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/operations/payment_create
// Implementation of PaymentCreate for UpdateTracker<F, PaymentData<F>, api::PaymentsRequest>
async fn update_trackers<'b>(
&'b self,
state: &'b SessionState,
req_state: ReqState,
mut payment_data: PaymentData<F>,
customer: Option<domain::Customer>,
storage_scheme: enums::MerchantStorageScheme,
_updated_customer: Option<storage::CustomerUpdate>,
key_store: &domain::MerchantKeyStore,
_frm_suggestion: Option<FrmSuggestion>,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<(PaymentCreateOperation<'b, F>, PaymentData<F>)>
where
F: 'b + Send,
{
let status = match payment_data.payment_intent.status {
IntentStatus::RequiresPaymentMethod => match payment_data.payment_method_data {
Some(_) => Some(IntentStatus::RequiresConfirmation),
_ => None,
},
IntentStatus::RequiresConfirmation => {
if let Some(true) = payment_data.confirm {
//TODO: do this later, request validation should happen before
Some(IntentStatus::Processing)
} else {
None
}
}
_ => None,
};
let payment_token = payment_data.token.clone();
let connector = payment_data.payment_attempt.connector.clone();
let straight_through_algorithm = payment_data
.payment_attempt
.straight_through_algorithm
.clone();
let authorized_amount = payment_data.payment_attempt.get_total_amount();
let merchant_connector_id = payment_data.payment_attempt.merchant_connector_id.clone();
let surcharge_amount = payment_data
.surcharge_details
.as_ref()
.map(|surcharge_details| surcharge_details.surcharge_amount);
let tax_amount = payment_data
.surcharge_details
.as_ref()
.map(|surcharge_details| surcharge_details.tax_on_surcharge_amount);
let routing_approach = payment_data.payment_attempt.routing_approach.clone();
let is_stored_credential = helpers::is_stored_credential(
&payment_data.recurring_details,
&payment_data.pm_token,
payment_data.mandate_id.is_some(),
payment_data.payment_attempt.is_stored_credential,
);
payment_data.payment_attempt = state
.store
.update_payment_attempt_with_attempt_id(
payment_data.payment_attempt,
storage::PaymentAttemptUpdate::UpdateTrackers {
payment_token,
connector,
straight_through_algorithm,
amount_capturable: match payment_data.confirm.unwrap_or(true) {
true => Some(authorized_amount),
false => None,
},
surcharge_amount,
tax_amount,
updated_by: storage_scheme.to_string(),
merchant_connector_id,
routing_approach,
is_stored_credential,
},
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
let customer_id = payment_data.payment_intent.customer_id.clone();
let raw_customer_details = customer
.map(|customer| CustomerData::foreign_try_from(customer.clone()))
.transpose()?;
let key_manager_state = state.into();
// Updation of Customer Details for the cases where both customer_id and specific customer
// details are provided in Payment Create Request
let customer_details = raw_customer_details
.clone()
.async_map(|customer_details| {
create_encrypted_data(&key_manager_state, key_store, customer_details)
})
.await
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt customer details")?;
payment_data.payment_intent = state
.store
.update_payment_intent(
&state.into(),
payment_data.payment_intent,
storage::PaymentIntentUpdate::PaymentCreateUpdate {
return_url: None,
status,
customer_id,
shipping_address_id: None,
billing_address_id: None,
customer_details,
updated_by: storage_scheme.to_string(),
},
key_store,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
req_state
.event_context
.event(AuditEvent::new(AuditEventType::PaymentCreate))
.with(payment_data.to_event())
.emit();
// payment_data.mandate_id = response.and_then(|router_data| router_data.request.mandate_id);
Ok((
payments::is_confirm(self, payment_data.confirm),
payment_data,
))
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 135,
"total_crates": null
} |
fn_clm_router_get_trackers_6217211736591887322 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/operations/payment_cancel
// Implementation of PaymentCancel for GetTracker<F, PaymentData<F>, api::PaymentsCancelRequest>
async fn get_trackers<'a>(
&'a self,
state: &'a SessionState,
payment_id: &api::PaymentIdType,
request: &api::PaymentsCancelRequest,
merchant_context: &domain::MerchantContext,
_auth_flow: services::AuthFlow,
_header_payload: &hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<
operations::GetTrackerResponse<'a, F, api::PaymentsCancelRequest, PaymentData<F>>,
> {
let db = &*state.store;
let key_manager_state = &state.into();
let merchant_id = merchant_context.get_merchant_account().get_id();
let storage_scheme = merchant_context.get_merchant_account().storage_scheme;
let payment_id = payment_id
.get_payment_intent_id()
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
let payment_intent = db
.find_payment_intent_by_payment_id_merchant_id(
key_manager_state,
&payment_id,
merchant_id,
merchant_context.get_merchant_key_store(),
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
helpers::validate_payment_status_against_not_allowed_statuses(
payment_intent.status,
&[
enums::IntentStatus::Failed,
enums::IntentStatus::Succeeded,
enums::IntentStatus::Cancelled,
enums::IntentStatus::Processing,
enums::IntentStatus::RequiresMerchantAction,
],
"cancel",
)?;
let mut 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().as_str(),
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
let shipping_address = helpers::get_address_by_id(
state,
payment_intent.shipping_address_id.clone(),
merchant_context.get_merchant_key_store(),
&payment_intent.payment_id,
merchant_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let billing_address = helpers::get_address_by_id(
state,
payment_intent.billing_address_id.clone(),
merchant_context.get_merchant_key_store(),
&payment_intent.payment_id,
merchant_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let payment_method_billing = helpers::get_address_by_id(
state,
payment_attempt.payment_method_billing_address_id.clone(),
merchant_context.get_merchant_key_store(),
&payment_intent.payment_id,
merchant_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let currency = payment_attempt.currency.get_required_value("currency")?;
let amount = payment_attempt.get_total_amount().into();
payment_attempt
.cancellation_reason
.clone_from(&request.cancellation_reason);
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_context.get_merchant_account().get_id(),
mcd,
)
.await
})
.await
.transpose()?;
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,
merchant_context.get_merchant_key_store(),
profile_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
let payment_data = PaymentData {
flow: PhantomData,
payment_intent,
payment_attempt,
currency,
amount,
email: None,
mandate_id: None,
mandate_connector: None,
setup_mandate: None,
customer_acceptance: None,
token: None,
token_data: None,
address: core_types::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: None,
payment_method_data: None,
payment_method_token: None,
payment_method_info: None,
force_sync: None,
all_keys_required: None,
refunds: vec![],
disputes: vec![],
attempts: None,
sessions_token: vec![],
card_cvc: None,
creds_identifier,
pm_token: None,
connector_customer_id: None,
recurring_mandate_payment_data: None,
ephemeral_key: None,
multiple_capture_data: None,
redirect_response: None,
surcharge_details: None,
frm_message: None,
payment_link_data: None,
incremental_authorization_details: None,
authorizations: vec![],
authentication: None,
recurring_details: None,
poll_config: None,
tax_data: None,
session_id: None,
service_details: None,
card_testing_guard_data: None,
vault_operation: None,
threeds_method_comp_ind: None,
whole_connector_response: None,
is_manual_retry_enabled: None,
is_l2_l3_enabled: false,
};
let get_trackers_response = operations::GetTrackerResponse {
operation: Box::new(self),
customer_details: None,
payment_data,
business_profile,
mandate_type: None,
};
Ok(get_trackers_response)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 153,
"total_crates": null
} |
fn_clm_router_update_trackers_6217211736591887322 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/operations/payment_cancel
// Implementation of PaymentCancel for UpdateTracker<F, PaymentData<F>, api::PaymentsCancelRequest>
async fn update_trackers<'b>(
&'b self,
state: &'b SessionState,
req_state: ReqState,
mut payment_data: PaymentData<F>,
_customer: Option<domain::Customer>,
storage_scheme: enums::MerchantStorageScheme,
_updated_customer: Option<storage::CustomerUpdate>,
key_store: &domain::MerchantKeyStore,
_frm_suggestion: Option<FrmSuggestion>,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<(PaymentCancelOperation<'b, F>, PaymentData<F>)>
where
F: 'b + Send,
{
let cancellation_reason = payment_data.payment_attempt.cancellation_reason.clone();
let (intent_status_update, attempt_status_update) =
if payment_data.payment_intent.status != enums::IntentStatus::RequiresCapture {
let payment_intent_update = storage::PaymentIntentUpdate::PGStatusUpdate {
status: enums::IntentStatus::Cancelled,
updated_by: storage_scheme.to_string(),
incremental_authorization_allowed: None,
feature_metadata: payment_data
.payment_intent
.feature_metadata
.clone()
.map(masking::Secret::new),
};
(Some(payment_intent_update), enums::AttemptStatus::Voided)
} else {
(None, enums::AttemptStatus::VoidInitiated)
};
if let Some(payment_intent_update) = intent_status_update {
payment_data.payment_intent = state
.store
.update_payment_intent(
&state.into(),
payment_data.payment_intent,
payment_intent_update,
key_store,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
}
state
.store
.update_payment_attempt_with_attempt_id(
payment_data.payment_attempt.clone(),
storage::PaymentAttemptUpdate::VoidUpdate {
status: attempt_status_update,
cancellation_reason: cancellation_reason.clone(),
updated_by: storage_scheme.to_string(),
},
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
req_state
.event_context
.event(AuditEvent::new(AuditEventType::PaymentCancelled {
cancellation_reason,
}))
.with(payment_data.to_event())
.emit();
Ok((Box::new(self), payment_data))
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 95,
"total_crates": null
} |
fn_clm_router_validate_request_6217211736591887322 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/operations/payment_cancel
// Implementation of PaymentCancel for ValidateRequest<F, api::PaymentsCancelRequest, PaymentData<F>>
fn validate_request<'a, 'b>(
&'b self,
request: &api::PaymentsCancelRequest,
merchant_context: &'a domain::MerchantContext,
) -> RouterResult<(PaymentCancelOperation<'b, F>, operations::ValidateResult)> {
Ok((
Box::new(self),
operations::ValidateResult {
merchant_id: merchant_context.get_merchant_account().get_id().to_owned(),
payment_id: api::PaymentIdType::PaymentIntentId(request.payment_id.to_owned()),
storage_scheme: merchant_context.get_merchant_account().storage_scheme,
requeue: false,
},
))
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 46,
"total_crates": null
} |
fn_clm_router_get_trackers_-322264693709528005 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/operations/payment_confirm
// Implementation of PaymentConfirm for GetTracker<F, PaymentData<F>, api::PaymentsRequest>
async fn get_trackers<'a>(
&'a self,
state: &'a SessionState,
payment_id: &api::PaymentIdType,
request: &api::PaymentsRequest,
merchant_context: &domain::MerchantContext,
auth_flow: services::AuthFlow,
header_payload: &hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsRequest, PaymentData<F>>>
{
let key_manager_state = &state.into();
let merchant_id = merchant_context.get_merchant_account().get_id();
let storage_scheme = merchant_context.get_merchant_account().storage_scheme;
let (currency, amount);
let payment_id = payment_id
.get_payment_intent_id()
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
// Stage 1
let store = &*state.store;
let m_merchant_id = merchant_id.clone();
// Parallel calls - level 0
let mut payment_intent = store
.find_payment_intent_by_payment_id_merchant_id(
key_manager_state,
&payment_id,
&m_merchant_id,
merchant_context.get_merchant_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
if let Some(order_details) = &request.order_details {
helpers::validate_order_details_amount(
order_details.to_owned(),
payment_intent.amount,
false,
)?;
}
helpers::validate_customer_access(&payment_intent, auth_flow, request)?;
if [
Some(common_enums::PaymentSource::Webhook),
Some(common_enums::PaymentSource::ExternalAuthenticator),
]
.contains(&header_payload.payment_confirm_source)
{
helpers::validate_payment_status_against_not_allowed_statuses(
payment_intent.status,
&[
storage_enums::IntentStatus::Cancelled,
storage_enums::IntentStatus::Succeeded,
storage_enums::IntentStatus::Processing,
storage_enums::IntentStatus::RequiresCapture,
storage_enums::IntentStatus::RequiresMerchantAction,
],
"confirm",
)?;
} else {
helpers::validate_payment_status_against_not_allowed_statuses(
payment_intent.status,
&[
storage_enums::IntentStatus::Cancelled,
storage_enums::IntentStatus::Succeeded,
storage_enums::IntentStatus::Processing,
storage_enums::IntentStatus::RequiresCapture,
storage_enums::IntentStatus::RequiresMerchantAction,
storage_enums::IntentStatus::RequiresCustomerAction,
],
"confirm",
)?;
}
helpers::authenticate_client_secret(request.client_secret.as_ref(), &payment_intent)?;
let customer_details = helpers::get_customer_details_from_request(request);
// Stage 2
let attempt_id = payment_intent.active_attempt.get_id();
let profile_id = payment_intent
.profile_id
.clone()
.get_required_value("profile_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("'profile_id' not set in payment intent")?;
let store = state.store.clone();
let key_manager_state_clone = key_manager_state.clone();
let key_store_clone = merchant_context.get_merchant_key_store().clone();
let business_profile_fut = tokio::spawn(
async move {
store
.find_business_profile_by_profile_id(
&key_manager_state_clone,
&key_store_clone,
&profile_id,
)
.map(|business_profile_result| {
business_profile_result.to_not_found_response(
errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
},
)
})
.await
}
.in_current_span(),
);
let store = state.store.clone();
let m_payment_id = payment_intent.payment_id.clone();
let m_merchant_id = merchant_id.clone();
let payment_attempt_fut = tokio::spawn(
async move {
store
.find_payment_attempt_by_payment_id_merchant_id_attempt_id(
&m_payment_id,
&m_merchant_id,
attempt_id.as_str(),
storage_scheme,
)
.map(|x| x.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound))
.await
}
.in_current_span(),
);
let m_merchant_id = merchant_id.clone();
let m_request_shipping = request.shipping.clone();
let m_payment_intent_shipping_address_id = payment_intent.shipping_address_id.clone();
let m_payment_intent_payment_id = payment_intent.payment_id.clone();
let m_customer_details_customer_id = customer_details.customer_id.clone();
let m_payment_intent_customer_id = payment_intent.customer_id.clone();
let m_key_store = merchant_context.get_merchant_key_store().clone();
let session_state = state.clone();
let shipping_address_fut = tokio::spawn(
async move {
helpers::create_or_update_address_for_payment_by_request(
&session_state,
m_request_shipping.as_ref(),
m_payment_intent_shipping_address_id.as_deref(),
&m_merchant_id,
m_payment_intent_customer_id
.as_ref()
.or(m_customer_details_customer_id.as_ref()),
&m_key_store,
&m_payment_intent_payment_id,
storage_scheme,
)
.await
}
.in_current_span(),
);
let m_merchant_id = merchant_id.clone();
let m_request_billing = request.billing.clone();
let m_customer_details_customer_id = customer_details.customer_id.clone();
let m_payment_intent_customer_id = payment_intent.customer_id.clone();
let m_payment_intent_billing_address_id = payment_intent.billing_address_id.clone();
let m_payment_intent_payment_id = payment_intent.payment_id.clone();
let m_key_store = merchant_context.get_merchant_key_store().clone();
let session_state = state.clone();
let billing_address_fut = tokio::spawn(
async move {
helpers::create_or_update_address_for_payment_by_request(
&session_state,
m_request_billing.as_ref(),
m_payment_intent_billing_address_id.as_deref(),
&m_merchant_id,
m_payment_intent_customer_id
.as_ref()
.or(m_customer_details_customer_id.as_ref()),
&m_key_store,
&m_payment_intent_payment_id,
storage_scheme,
)
.await
}
.in_current_span(),
);
let m_merchant_id = merchant_id.clone();
let store = state.clone().store;
let m_request_merchant_connector_details = request.merchant_connector_details.clone();
let config_update_fut = tokio::spawn(
async move {
m_request_merchant_connector_details
.async_map(|mcd| async {
helpers::insert_merchant_connector_creds_to_config(
store.as_ref(),
&m_merchant_id,
mcd,
)
.await
})
.map(|x| x.transpose())
.await
}
.in_current_span(),
);
// Based on whether a retry can be performed or not, fetch relevant entities
let (mut payment_attempt, shipping_address, billing_address, business_profile) =
match payment_intent.status {
api_models::enums::IntentStatus::RequiresCustomerAction
| api_models::enums::IntentStatus::RequiresMerchantAction
| api_models::enums::IntentStatus::RequiresPaymentMethod
| api_models::enums::IntentStatus::RequiresConfirmation => {
// Normal payment
// Parallel calls - level 1
let (payment_attempt, shipping_address, billing_address, business_profile, _) =
tokio::try_join!(
utils::flatten_join_error(payment_attempt_fut),
utils::flatten_join_error(shipping_address_fut),
utils::flatten_join_error(billing_address_fut),
utils::flatten_join_error(business_profile_fut),
utils::flatten_join_error(config_update_fut)
)?;
(
payment_attempt,
shipping_address,
billing_address,
business_profile,
)
}
_ => {
// Retry payment
let (
mut payment_attempt,
shipping_address,
billing_address,
business_profile,
_,
) = tokio::try_join!(
utils::flatten_join_error(payment_attempt_fut),
utils::flatten_join_error(shipping_address_fut),
utils::flatten_join_error(billing_address_fut),
utils::flatten_join_error(business_profile_fut),
utils::flatten_join_error(config_update_fut)
)?;
let attempt_type = helpers::get_attempt_type(
&payment_intent,
&payment_attempt,
business_profile.is_manual_retry_enabled,
"confirm",
)?;
// 3
(payment_intent, payment_attempt) = attempt_type
.modify_payment_intent_and_payment_attempt(
request,
payment_intent,
payment_attempt,
state,
merchant_context.get_merchant_key_store(),
storage_scheme,
)
.await?;
(
payment_attempt,
shipping_address,
billing_address,
business_profile,
)
}
};
payment_intent.order_details = request
.get_order_details_as_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to convert order details to value")?
.or(payment_intent.order_details);
payment_intent.setup_future_usage = request
.setup_future_usage
.or(payment_intent.setup_future_usage);
payment_intent.psd2_sca_exemption_type = request
.psd2_sca_exemption_type
.or(payment_intent.psd2_sca_exemption_type);
let browser_info = request
.browser_info
.clone()
.or(payment_attempt.browser_info)
.as_ref()
.map(Encode::encode_to_value)
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "browser_info",
})?;
let customer_acceptance = request.customer_acceptance.clone().or(payment_attempt
.customer_acceptance
.clone()
.map(|customer_acceptance| {
customer_acceptance
.expose()
.parse_value("CustomerAcceptance")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while deserializing customer_acceptance")
})
.transpose()?);
let recurring_details = request.recurring_details.clone();
helpers::validate_card_data(
request
.payment_method_data
.as_ref()
.and_then(|pmd| pmd.payment_method_data.clone()),
)?;
payment_attempt.browser_info = browser_info;
payment_attempt.payment_experience = request
.payment_experience
.or(payment_attempt.payment_experience);
payment_attempt.capture_method = request.capture_method.or(payment_attempt.capture_method);
payment_attempt.customer_acceptance = request
.customer_acceptance
.clone()
.map(|customer_acceptance| customer_acceptance.encode_to_value())
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while encoding customer_acceptance to value")?
.map(masking::Secret::new)
.or(payment_attempt.customer_acceptance);
currency = payment_attempt.currency.get_required_value("currency")?;
amount = payment_attempt.get_total_amount().into();
helpers::validate_customer_id_mandatory_cases(
request.setup_future_usage.is_some(),
payment_intent
.customer_id
.as_ref()
.or(customer_details.customer_id.as_ref()),
)?;
let creds_identifier = request
.merchant_connector_details
.as_ref()
.map(|mcd| mcd.creds_identifier.to_owned());
payment_intent.shipping_address_id =
shipping_address.as_ref().map(|i| i.address_id.clone());
payment_intent.billing_address_id = billing_address.as_ref().map(|i| i.address_id.clone());
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);
payment_intent.frm_metadata = request.frm_metadata.clone().or(payment_intent.frm_metadata);
payment_intent.request_incremental_authorization = request
.request_incremental_authorization
.map(|request_incremental_authorization| {
core_utils::get_request_incremental_authorization_value(
Some(request_incremental_authorization),
payment_attempt.capture_method,
)
})
.unwrap_or(Ok(payment_intent.request_incremental_authorization))?;
payment_intent.enable_partial_authorization = request
.enable_partial_authorization
.or(payment_intent.enable_partial_authorization);
payment_attempt.business_sub_label = request
.business_sub_label
.clone()
.or(payment_attempt.business_sub_label);
let n_request_payment_method_data = request
.payment_method_data
.as_ref()
.and_then(|pmd| pmd.payment_method_data.clone());
let store = state.clone().store;
let profile_id = payment_intent
.profile_id
.clone()
.get_required_value("profile_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("'profile_id' not set in payment intent")?;
let additional_pm_data_fut = tokio::spawn(
async move {
Ok(n_request_payment_method_data
.async_map(|payment_method_data| async move {
helpers::get_additional_payment_data(
&payment_method_data.into(),
store.as_ref(),
&profile_id,
)
.await
})
.await)
}
.in_current_span(),
);
let n_payment_method_billing_address_id =
payment_attempt.payment_method_billing_address_id.clone();
let n_request_payment_method_billing_address = request
.payment_method_data
.as_ref()
.and_then(|pmd| pmd.billing.clone());
let m_payment_intent_customer_id = payment_intent.customer_id.clone();
let m_payment_intent_payment_id = payment_intent.payment_id.clone();
let m_key_store = merchant_context.get_merchant_key_store().clone();
let m_customer_details_customer_id = customer_details.customer_id.clone();
let m_merchant_id = merchant_id.clone();
let session_state = state.clone();
let payment_method_billing_future = tokio::spawn(
async move {
helpers::create_or_update_address_for_payment_by_request(
&session_state,
n_request_payment_method_billing_address.as_ref(),
n_payment_method_billing_address_id.as_deref(),
&m_merchant_id,
m_payment_intent_customer_id
.as_ref()
.or(m_customer_details_customer_id.as_ref()),
&m_key_store,
&m_payment_intent_payment_id,
storage_scheme,
)
.await
}
.in_current_span(),
);
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.or(request.payment_method),
)
.change_context(errors::ApiErrorResponse::MandateValidationFailed {
reason: "Expected one out of recurring_details and mandate_data but got both".into(),
})?;
let m_state = state.clone();
let m_mandate_type = mandate_type;
let m_merchant_context = merchant_context.clone();
let m_request = request.clone();
let payment_intent_customer_id = payment_intent.customer_id.clone();
let mandate_details_fut = tokio::spawn(
async move {
Box::pin(helpers::get_token_pm_type_mandate_details(
&m_state,
&m_request,
m_mandate_type,
&m_merchant_context,
None,
payment_intent_customer_id.as_ref(),
))
.await
}
.in_current_span(),
);
// Parallel calls - level 2
let (mandate_details, additional_pm_info, payment_method_billing) = tokio::try_join!(
utils::flatten_join_error(mandate_details_fut),
utils::flatten_join_error(additional_pm_data_fut),
utils::flatten_join_error(payment_method_billing_future),
)?;
let additional_pm_data = additional_pm_info.transpose()?.flatten();
let m_helpers::MandateGenericData {
token,
payment_method,
payment_method_type,
mandate_data,
recurring_mandate_payment_data,
mandate_connector,
payment_method_info,
} = mandate_details;
let token = token.or_else(|| payment_attempt.payment_token.clone());
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, payment_method_info) = if let Some(token) = token.clone() {
let token_data = helpers::retrieve_payment_token_data(
state,
token,
payment_method.or(payment_attempt.payment_method),
)
.await?;
let payment_method_info = helpers::retrieve_payment_method_from_db_with_token_data(
state,
merchant_context.get_merchant_key_store(),
&token_data,
storage_scheme,
)
.await?;
(Some(token_data), payment_method_info)
} else {
(None, payment_method_info)
};
let additional_pm_data_from_locker = if let Some(ref pm) = payment_method_info {
let card_detail_from_locker: Option<api::CardDetailFromLocker> = pm
.payment_method_data
.clone()
.map(|x| x.into_inner().expose())
.and_then(|v| {
v.parse_value("PaymentMethodsData")
.map_err(|err| {
router_env::logger::info!(
"PaymentMethodsData deserialization failed: {:?}",
err
)
})
.ok()
})
.and_then(|pmd| match pmd {
PaymentMethodsData::Card(crd) => Some(api::CardDetailFromLocker::from(crd)),
_ => None,
});
card_detail_from_locker.map(|card_details| {
let additional_data = card_details.into();
api_models::payments::AdditionalPaymentData::Card(Box::new(additional_data))
})
} else {
None
};
// Only set `payment_attempt.payment_method_data` if `additional_pm_data_from_locker` is not None
if let Some(additional_pm_data) = additional_pm_data_from_locker.as_ref() {
payment_attempt.payment_method_data = Some(
Encode::encode_to_value(additional_pm_data)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to encode additional pm data")?,
);
}
payment_attempt.payment_method = payment_method.or(payment_attempt.payment_method);
let payment_method_type = Option::<api_models::enums::PaymentMethodType>::foreign_from((
payment_method_type,
additional_pm_data.as_ref(),
payment_method,
));
payment_attempt.payment_method_type = payment_method_type
.or(payment_attempt.payment_method_type)
.or(payment_method_info
.as_ref()
.and_then(|pm_info| pm_info.get_payment_method_subtype()));
// The operation merges mandate data from both request and payment_attempt
let setup_mandate = mandate_data.map(|mut sm| {
sm.mandate_type = payment_attempt.mandate_details.clone().or(sm.mandate_type);
sm.update_mandate_id = payment_attempt
.mandate_data
.clone()
.and_then(|mandate| mandate.update_mandate_id)
.or(sm.update_mandate_id);
sm
});
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 payment_method_data_after_card_bin_call = request
.payment_method_data
.as_ref()
.and_then(|request_payment_method_data| {
request_payment_method_data.payment_method_data.as_ref()
})
.zip(additional_pm_data)
.map(|(payment_method_data, additional_payment_data)| {
payment_method_data.apply_additional_payment_data(additional_payment_data)
})
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Card cobadge check failed due to an invalid card network regex")?;
payment_attempt.payment_method_billing_address_id = payment_method_billing
.as_ref()
.map(|payment_method_billing| payment_method_billing.address_id.clone());
let 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,
);
let payment_method_data_billing = request
.payment_method_data
.as_ref()
.and_then(|pmd| pmd.payment_method_data.as_ref())
.and_then(|payment_method_data_billing| {
payment_method_data_billing.get_billing_address()
})
.map(From::from);
let unified_address =
address.unify_with_payment_method_data_billing(payment_method_data_billing);
// If processor_payment_token is passed in request then populating the same in PaymentData
let mandate_id = request
.recurring_details
.as_ref()
.and_then(|recurring_details| match recurring_details {
api_models::mandates::RecurringDetails::ProcessorPaymentToken(token) => {
payment_intent.is_payment_processor_token_flow = Some(true);
Some(api_models::payments::MandateIds {
mandate_id: None,
mandate_reference_id: Some(
api_models::payments::MandateReferenceId::ConnectorMandateId(
ConnectorMandateReferenceId::new(
Some(token.processor_payment_token.clone()), // connector_mandate_id
None, // payment_method_id
None, // update_history
None, // mandate_metadata
None, // connector_mandate_request_reference_id
),
),
),
})
}
_ => None,
});
let pmt_order_tax_amount = payment_intent.tax_details.clone().and_then(|tax| {
if tax.payment_method_type.clone().map(|a| a.pmt) == payment_attempt.payment_method_type
{
tax.payment_method_type.map(|a| a.order_tax_amount)
} else {
None
}
});
let order_tax_amount = pmt_order_tax_amount.or_else(|| {
payment_intent
.tax_details
.clone()
.and_then(|tax| tax.default.map(|a| a.order_tax_amount))
});
payment_attempt
.net_amount
.set_order_tax_amount(order_tax_amount);
payment_attempt.connector_mandate_detail = Some(
DieselConnectorMandateReferenceId::foreign_from(ConnectorMandateReferenceId::new(
None,
None,
None, // update_history
None, // mandate_metadata
Some(common_utils::generate_id_with_len(
consts::CONNECTOR_MANDATE_REQUEST_REFERENCE_ID_LENGTH,
)), // connector_mandate_request_reference_id
)),
);
let payment_data = PaymentData {
flow: PhantomData,
payment_intent,
payment_attempt,
currency,
amount,
email: request.email.clone(),
mandate_id: mandate_id.clone(),
mandate_connector,
setup_mandate,
customer_acceptance,
token,
address: unified_address,
token_data,
confirm: request.confirm,
payment_method_data: payment_method_data_after_card_bin_call.map(Into::into),
payment_method_token: None,
payment_method_info,
force_sync: None,
all_keys_required: 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: None,
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: request.ctp_service_details.clone(),
card_testing_guard_data: None,
vault_operation: None,
threeds_method_comp_ind: None,
whole_connector_response: None,
is_manual_retry_enabled: business_profile.is_manual_retry_enabled,
is_l2_l3_enabled: business_profile.is_l2_l3_enabled,
};
let get_trackers_response = operations::GetTrackerResponse {
operation: Box::new(self),
customer_details: Some(customer_details),
payment_data,
business_profile,
mandate_type,
};
Ok(get_trackers_response)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 675,
"total_crates": null
} |
fn_clm_router_update_trackers_-322264693709528005 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/operations/payment_confirm
// Implementation of PaymentConfirm for UpdateTracker<F, PaymentData<F>, api::PaymentsRequest>
async fn update_trackers<'b>(
&'b self,
state: &'b SessionState,
req_state: ReqState,
mut payment_data: PaymentData<F>,
customer: Option<domain::Customer>,
storage_scheme: storage_enums::MerchantStorageScheme,
updated_customer: Option<storage::CustomerUpdate>,
key_store: &domain::MerchantKeyStore,
frm_suggestion: Option<FrmSuggestion>,
header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<(
BoxedOperation<'b, F, api::PaymentsRequest, PaymentData<F>>,
PaymentData<F>,
)>
where
F: 'b + Send,
{
let payment_method = payment_data.payment_attempt.payment_method;
let browser_info = payment_data.payment_attempt.browser_info.clone();
let frm_message = payment_data.frm_message.clone();
let capture_method = payment_data.payment_attempt.capture_method;
let default_status_result = (
storage_enums::IntentStatus::Processing,
storage_enums::AttemptStatus::Pending,
(None, None),
);
let status_handler_for_frm_results = |frm_suggestion: FrmSuggestion| match frm_suggestion {
FrmSuggestion::FrmCancelTransaction => (
storage_enums::IntentStatus::Failed,
storage_enums::AttemptStatus::Failure,
frm_message.map_or((None, None), |fraud_check| {
(
Some(Some(fraud_check.frm_status.to_string())),
Some(fraud_check.frm_reason.map(|reason| reason.to_string())),
)
}),
),
FrmSuggestion::FrmManualReview => (
storage_enums::IntentStatus::RequiresMerchantAction,
storage_enums::AttemptStatus::Unresolved,
(None, None),
),
FrmSuggestion::FrmAuthorizeTransaction => (
storage_enums::IntentStatus::RequiresCapture,
storage_enums::AttemptStatus::Authorized,
(None, None),
),
};
let status_handler_for_authentication_results =
|authentication: &storage::Authentication| {
if authentication.authentication_status.is_failed() {
(
storage_enums::IntentStatus::Failed,
storage_enums::AttemptStatus::Failure,
(
Some(Some("EXTERNAL_AUTHENTICATION_FAILURE".to_string())),
Some(Some("external authentication failure".to_string())),
),
)
} else if authentication.is_separate_authn_required() {
(
storage_enums::IntentStatus::RequiresCustomerAction,
storage_enums::AttemptStatus::AuthenticationPending,
(None, None),
)
} else {
default_status_result.clone()
}
};
let (intent_status, attempt_status, (error_code, error_message)) =
match (frm_suggestion, payment_data.authentication.as_ref()) {
(Some(frm_suggestion), _) => status_handler_for_frm_results(frm_suggestion),
(_, Some(authentication_details)) => status_handler_for_authentication_results(
&authentication_details.authentication,
),
_ => default_status_result,
};
let connector = payment_data.payment_attempt.connector.clone();
let merchant_connector_id = payment_data.payment_attempt.merchant_connector_id.clone();
let connector_request_reference_id = payment_data
.payment_attempt
.connector_request_reference_id
.clone();
let straight_through_algorithm = payment_data
.payment_attempt
.straight_through_algorithm
.clone();
let payment_token = payment_data.token.clone();
let payment_method_type = payment_data.payment_attempt.payment_method_type;
let profile_id = payment_data
.payment_intent
.profile_id
.as_ref()
.get_required_value("profile_id")
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let payment_experience = payment_data.payment_attempt.payment_experience;
let additional_pm_data = payment_data
.payment_method_data
.as_ref()
.async_map(|payment_method_data| async {
helpers::get_additional_payment_data(payment_method_data, &*state.store, profile_id)
.await
})
.await
.transpose()?
.flatten();
let encoded_additional_pm_data = additional_pm_data
.as_ref()
.map(Encode::encode_to_value)
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to encode additional pm data")?;
let customer_details = payment_data.payment_intent.customer_details.clone();
let business_sub_label = payment_data.payment_attempt.business_sub_label.clone();
let authentication_type = payment_data.payment_attempt.authentication_type;
let (shipping_address_id, billing_address_id, payment_method_billing_address_id) = (
payment_data.payment_intent.shipping_address_id.clone(),
payment_data.payment_intent.billing_address_id.clone(),
payment_data
.payment_attempt
.payment_method_billing_address_id
.clone(),
);
let customer_id = customer.clone().map(|c| c.customer_id);
let return_url = payment_data.payment_intent.return_url.take();
let setup_future_usage = payment_data.payment_intent.setup_future_usage;
let business_label = payment_data.payment_intent.business_label.clone();
let business_country = payment_data.payment_intent.business_country;
let description = payment_data.payment_intent.description.take();
let statement_descriptor_name =
payment_data.payment_intent.statement_descriptor_name.take();
let statement_descriptor_suffix = payment_data
.payment_intent
.statement_descriptor_suffix
.take();
let order_details = payment_data.payment_intent.order_details.clone();
let metadata = payment_data.payment_intent.metadata.clone();
let frm_metadata = payment_data.payment_intent.frm_metadata.clone();
let client_source = header_payload
.client_source
.clone()
.or(payment_data.payment_attempt.client_source.clone());
let client_version = header_payload
.client_version
.clone()
.or(payment_data.payment_attempt.client_version.clone());
let m_payment_data_payment_attempt = payment_data.payment_attempt.clone();
let m_payment_method_id =
payment_data
.payment_attempt
.payment_method_id
.clone()
.or(payment_data
.payment_method_info
.as_ref()
.map(|payment_method| payment_method.payment_method_id.clone()));
let m_browser_info = browser_info.clone();
let m_connector = connector.clone();
let m_capture_method = capture_method;
let m_payment_token = payment_token.clone();
let m_additional_pm_data = encoded_additional_pm_data
.clone()
.or(payment_data.payment_attempt.payment_method_data.clone());
let m_business_sub_label = business_sub_label.clone();
let m_straight_through_algorithm = straight_through_algorithm.clone();
let m_error_code = error_code.clone();
let m_error_message = error_message.clone();
let m_fingerprint_id = payment_data.payment_attempt.fingerprint_id.clone();
let m_db = state.clone().store;
let surcharge_amount = payment_data
.surcharge_details
.as_ref()
.map(|surcharge_details| surcharge_details.surcharge_amount);
let tax_amount = payment_data
.surcharge_details
.as_ref()
.map(|surcharge_details| surcharge_details.tax_on_surcharge_amount);
let (
external_three_ds_authentication_attempted,
authentication_connector,
authentication_id,
) = match payment_data.authentication.as_ref() {
Some(authentication_store) => (
Some(
authentication_store
.authentication
.is_separate_authn_required(),
),
authentication_store
.authentication
.authentication_connector
.clone(),
Some(
authentication_store
.authentication
.authentication_id
.clone(),
),
),
None => (None, None, None),
};
let card_discovery = payment_data.get_card_discovery_for_card_payment_method();
let is_stored_credential = helpers::is_stored_credential(
&payment_data.recurring_details,
&payment_data.pm_token,
payment_data.mandate_id.is_some(),
payment_data.payment_attempt.is_stored_credential,
);
let payment_attempt_fut = tokio::spawn(
async move {
m_db.update_payment_attempt_with_attempt_id(
m_payment_data_payment_attempt,
storage::PaymentAttemptUpdate::ConfirmUpdate {
currency: payment_data.currency,
status: attempt_status,
payment_method,
authentication_type,
capture_method: m_capture_method,
browser_info: m_browser_info,
connector: m_connector,
payment_token: m_payment_token,
payment_method_data: m_additional_pm_data,
payment_method_type,
payment_experience,
business_sub_label: m_business_sub_label,
straight_through_algorithm: m_straight_through_algorithm,
error_code: m_error_code,
error_message: m_error_message,
updated_by: storage_scheme.to_string(),
merchant_connector_id,
external_three_ds_authentication_attempted,
authentication_connector,
authentication_id,
payment_method_billing_address_id,
fingerprint_id: m_fingerprint_id,
payment_method_id: m_payment_method_id,
client_source,
client_version,
customer_acceptance: payment_data.payment_attempt.customer_acceptance,
net_amount:
hyperswitch_domain_models::payments::payment_attempt::NetAmount::new(
payment_data.payment_attempt.net_amount.get_order_amount(),
payment_data.payment_intent.shipping_cost,
payment_data
.payment_attempt
.net_amount
.get_order_tax_amount(),
surcharge_amount,
tax_amount,
),
connector_mandate_detail: payment_data
.payment_attempt
.connector_mandate_detail,
card_discovery,
routing_approach: payment_data.payment_attempt.routing_approach,
connector_request_reference_id,
network_transaction_id: payment_data
.payment_attempt
.network_transaction_id
.clone(),
is_stored_credential,
request_extended_authorization: payment_data
.payment_attempt
.request_extended_authorization,
},
storage_scheme,
)
.map(|x| x.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound))
.await
}
.in_current_span(),
);
let billing_address = payment_data.address.get_payment_billing();
let key_manager_state = state.into();
let billing_details = billing_address
.async_map(|billing_details| {
create_encrypted_data(&key_manager_state, key_store, billing_details)
})
.await
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt billing details")?;
let shipping_address = payment_data.address.get_shipping();
let shipping_details = shipping_address
.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 m_payment_data_payment_intent = payment_data.payment_intent.clone();
let m_customer_id = customer_id.clone();
let m_shipping_address_id = shipping_address_id.clone();
let m_billing_address_id = billing_address_id.clone();
let m_return_url = return_url.clone();
let m_business_label = business_label.clone();
let m_description = description.clone();
let m_statement_descriptor_name = statement_descriptor_name.clone();
let m_statement_descriptor_suffix = statement_descriptor_suffix.clone();
let m_order_details = order_details.clone();
let m_metadata = metadata.clone();
let m_frm_metadata = frm_metadata.clone();
let m_db = state.clone().store;
let m_storage_scheme = storage_scheme.to_string();
let session_expiry = m_payment_data_payment_intent.session_expiry;
let m_key_store = key_store.clone();
let key_manager_state = state.into();
let is_payment_processor_token_flow =
payment_data.payment_intent.is_payment_processor_token_flow;
let payment_intent_fut = tokio::spawn(
async move {
m_db.update_payment_intent(
&key_manager_state,
m_payment_data_payment_intent,
storage::PaymentIntentUpdate::Update(Box::new(PaymentIntentUpdateFields {
amount: payment_data.payment_intent.amount,
currency: payment_data.currency,
setup_future_usage,
status: intent_status,
customer_id: m_customer_id,
shipping_address_id: m_shipping_address_id,
billing_address_id: m_billing_address_id,
return_url: m_return_url,
business_country,
business_label: m_business_label,
description: m_description,
statement_descriptor_name: m_statement_descriptor_name,
statement_descriptor_suffix: m_statement_descriptor_suffix,
order_details: m_order_details,
metadata: m_metadata,
payment_confirm_source: header_payload.payment_confirm_source,
updated_by: m_storage_scheme,
fingerprint_id: None,
session_expiry,
request_external_three_ds_authentication: None,
frm_metadata: m_frm_metadata,
customer_details,
merchant_order_reference_id: None,
billing_details,
shipping_details,
is_payment_processor_token_flow,
tax_details: None,
force_3ds_challenge: payment_data.payment_intent.force_3ds_challenge,
is_iframe_redirection_enabled: payment_data
.payment_intent
.is_iframe_redirection_enabled,
is_confirm_operation: true, // Indicates that this is a confirm operation
payment_channel: payment_data.payment_intent.payment_channel,
feature_metadata: payment_data
.payment_intent
.feature_metadata
.clone()
.map(masking::Secret::new),
tax_status: payment_data.payment_intent.tax_status,
discount_amount: payment_data.payment_intent.discount_amount,
order_date: payment_data.payment_intent.order_date,
shipping_amount_tax: payment_data.payment_intent.shipping_amount_tax,
duty_amount: payment_data.payment_intent.duty_amount,
enable_partial_authorization: payment_data
.payment_intent
.enable_partial_authorization,
enable_overcapture: payment_data.payment_intent.enable_overcapture,
})),
&m_key_store,
storage_scheme,
)
.map(|x| x.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound))
.await
}
.in_current_span(),
);
let customer_fut =
if let Some((updated_customer, customer)) = updated_customer.zip(customer) {
let m_customer_merchant_id = customer.merchant_id.to_owned();
let m_key_store = key_store.clone();
let m_updated_customer = updated_customer.clone();
let session_state = state.clone();
let m_db = session_state.store.clone();
let key_manager_state = state.into();
tokio::spawn(
async move {
let m_customer_customer_id = customer.customer_id.to_owned();
m_db.update_customer_by_customer_id_merchant_id(
&key_manager_state,
m_customer_customer_id,
m_customer_merchant_id,
customer,
m_updated_customer,
&m_key_store,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update CustomerConnector in customer")?;
Ok::<_, error_stack::Report<errors::ApiErrorResponse>>(())
}
.in_current_span(),
)
} else {
tokio::spawn(
async move { Ok::<_, error_stack::Report<errors::ApiErrorResponse>>(()) }
.in_current_span(),
)
};
let (payment_intent, payment_attempt, _) = tokio::try_join!(
utils::flatten_join_error(payment_intent_fut),
utils::flatten_join_error(payment_attempt_fut),
utils::flatten_join_error(customer_fut)
)?;
payment_data.payment_intent = payment_intent;
payment_data.payment_attempt = payment_attempt;
let client_src = payment_data.payment_attempt.client_source.clone();
let client_ver = payment_data.payment_attempt.client_version.clone();
let frm_message = payment_data.frm_message.clone();
req_state
.event_context
.event(AuditEvent::new(AuditEventType::PaymentConfirm {
client_src,
client_ver,
frm_message: Box::new(frm_message),
}))
.with(payment_data.to_event())
.emit();
Ok((Box::new(self), payment_data))
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 369,
"total_crates": null
} |
fn_clm_router_call_unified_authentication_service_if_eligible_-322264693709528005 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/operations/payment_confirm
// Implementation of PaymentConfirm for Domain<F, api::PaymentsRequest, PaymentData<F>>
async fn call_unified_authentication_service_if_eligible<'a>(
&'a self,
state: &SessionState,
payment_data: &mut PaymentData<F>,
should_continue_confirm_transaction: &mut bool,
connector_call_type: &ConnectorCallType,
business_profile: &domain::Profile,
key_store: &domain::MerchantKeyStore,
mandate_type: Option<api_models::payments::MandateTransactionType>,
) -> CustomResult<(), errors::ApiErrorResponse> {
let unified_authentication_service_flow =
helpers::decide_action_for_unified_authentication_service(
state,
key_store,
business_profile,
payment_data,
connector_call_type,
mandate_type,
)
.await?;
if let Some(unified_authentication_service_flow) = unified_authentication_service_flow {
match unified_authentication_service_flow {
helpers::UnifiedAuthenticationServiceFlow::ClickToPayInitiate => {
let authentication_product_ids = business_profile
.authentication_product_ids
.clone()
.ok_or(errors::ApiErrorResponse::PreconditionFailed {
message: "authentication_product_ids is not configured in business profile"
.to_string(),
})?;
let click_to_pay_mca_id = authentication_product_ids
.get_click_to_pay_connector_account_id()
.change_context(errors::ApiErrorResponse::MissingRequiredField {
field_name: "authentication_product_ids",
})?;
let key_manager_state = &(state).into();
let merchant_id = &business_profile.merchant_id;
let connector_mca = state
.store
.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
key_manager_state,
merchant_id,
&click_to_pay_mca_id,
key_store,
)
.await
.to_not_found_response(
errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: click_to_pay_mca_id.get_string_repr().to_string(),
},
)?;
let authentication_id =
common_utils::id_type::AuthenticationId::generate_authentication_id(consts::AUTHENTICATION_ID_PREFIX);
let payment_method = payment_data.payment_attempt.payment_method.ok_or(
errors::ApiErrorResponse::MissingRequiredField {
field_name: "payment_method",
},
)?;
ClickToPay::pre_authentication(
state,
&payment_data.payment_attempt.merchant_id,
Some(&payment_data.payment_intent.payment_id),
payment_data.payment_method_data.as_ref(),
payment_data.payment_attempt.payment_method_type,
&helpers::MerchantConnectorAccountType::DbVal(Box::new(connector_mca.clone())),
&connector_mca.connector_name,
&authentication_id,
payment_method,
payment_data.payment_intent.amount,
payment_data.payment_intent.currency,
payment_data.service_details.clone(),
None,
None,
None,
None
)
.await?;
payment_data.payment_attempt.authentication_id = Some(authentication_id.clone());
let response = ClickToPay::post_authentication(
state,
business_profile,
Some(&payment_data.payment_intent.payment_id),
&helpers::MerchantConnectorAccountType::DbVal(Box::new(connector_mca.clone())),
&connector_mca.connector_name,
&authentication_id,
payment_method,
&payment_data.payment_intent.merchant_id,
None
)
.await?;
let (network_token, authentication_status) = match response.response.clone() {
Ok(unified_authentication_service::UasAuthenticationResponseData::PostAuthentication {
authentication_details,
}) => {
let token_details = authentication_details.token_details.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Missing authentication_details.token_details")?;
(Some(
hyperswitch_domain_models::payment_method_data::NetworkTokenData {
token_number: token_details.payment_token,
token_exp_month: token_details
.token_expiration_month,
token_exp_year: token_details
.token_expiration_year,
token_cryptogram: authentication_details
.dynamic_data_details
.and_then(|data| data.dynamic_data_value),
card_issuer: None,
card_network: None,
card_type: None,
card_issuing_country: None,
bank_code: None,
nick_name: None,
eci: authentication_details.eci,
}),common_enums::AuthenticationStatus::Success)
},
Ok(unified_authentication_service::UasAuthenticationResponseData::PreAuthentication { .. })
| Ok(unified_authentication_service::UasAuthenticationResponseData::Confirmation {})
| Ok(unified_authentication_service::UasAuthenticationResponseData::Authentication { .. }) => Err(errors::ApiErrorResponse::InternalServerError).attach_printable("unexpected response received from unified authentication service")?,
Err(_) => (None, common_enums::AuthenticationStatus::Failed)
};
payment_data.payment_attempt.payment_method =
Some(common_enums::PaymentMethod::Card);
payment_data.payment_method_data = network_token
.clone()
.map(domain::PaymentMethodData::NetworkToken);
let authentication = uas_utils::create_new_authentication(
state,
payment_data.payment_attempt.merchant_id.clone(),
Some(connector_mca.connector_name.to_string()),
business_profile.get_id().clone(),
Some(payment_data.payment_intent.get_id().clone()),
Some(click_to_pay_mca_id.to_owned()),
&authentication_id,
payment_data.service_details.clone(),
authentication_status,
network_token.clone(),
payment_data.payment_attempt.organization_id.clone(),
payment_data.payment_intent.force_3ds_challenge,
payment_data.payment_intent.psd2_sca_exemption_type,
None,
None,
None,
None,
None,
None,
None
)
.await?;
let authentication_store = hyperswitch_domain_models::router_request_types::authentication::AuthenticationStore {
cavv: network_token.and_then(|token| token.token_cryptogram),
authentication
};
payment_data.authentication = Some(authentication_store);
},
helpers::UnifiedAuthenticationServiceFlow::ExternalAuthenticationInitiate {
acquirer_details,
..
} => {
let (authentication_connector, three_ds_connector_account) =
authentication::utils::get_authentication_connector_data(state, key_store, business_profile, None).await?;
let authentication_connector_name = authentication_connector.to_string();
let authentication_id =
common_utils::id_type::AuthenticationId::generate_authentication_id(consts::AUTHENTICATION_ID_PREFIX);
let (acquirer_bin, acquirer_merchant_id, acquirer_country_code) = if let Some(details) = &acquirer_details {
(
Some(details.acquirer_bin.clone()),
Some(details.acquirer_merchant_id.clone()),
details.acquirer_country_code.clone(),
)
} else {
(None, None, None)
};
let authentication = uas_utils::create_new_authentication(
state,
business_profile.merchant_id.clone(),
Some(authentication_connector_name.clone()),
business_profile.get_id().to_owned(),
Some(payment_data.payment_intent.payment_id.clone()),
Some(three_ds_connector_account
.get_mca_id()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error while finding mca_id from merchant_connector_account")?),
&authentication_id,
payment_data.service_details.clone(),
common_enums::AuthenticationStatus::Started,
None,
payment_data.payment_attempt.organization_id.clone(),
payment_data.payment_intent.force_3ds_challenge,
payment_data.payment_intent.psd2_sca_exemption_type,
acquirer_bin,
acquirer_merchant_id,
acquirer_country_code,
None,
None,
None,
None,
)
.await?;
let acquirer_configs = authentication
.profile_acquirer_id
.clone()
.and_then(|acquirer_id| {
business_profile
.acquirer_config_map.as_ref()
.and_then(|acquirer_config_map| acquirer_config_map.0.get(&acquirer_id).cloned())
});
let metadata: Option<ThreeDsMetaData> = three_ds_connector_account
.get_metadata()
.map(|metadata| {
metadata
.expose()
.parse_value("ThreeDsMetaData")
.attach_printable("Error while parsing ThreeDsMetaData")
})
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let merchant_country_code = authentication.acquirer_country_code.clone();
let return_url = helpers::create_authorize_url(
&state.base_url,
&payment_data.payment_attempt.clone(),
payment_data.payment_attempt.connector.as_ref().get_required_value("connector")?,
);
let notification_url = Some(url::Url::parse(&return_url))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to parse webhook url")?;
let merchant_details = Some(unified_authentication_service::MerchantDetails {
merchant_id: Some(authentication.merchant_id.get_string_repr().to_string()),
merchant_name: acquirer_configs.clone().map(|detail| detail.merchant_name.clone()).or(metadata.clone().and_then(|metadata| metadata.merchant_name)),
merchant_category_code: business_profile.merchant_category_code.or(metadata.clone().and_then(|metadata| metadata.merchant_category_code)),
endpoint_prefix: metadata.clone().and_then(|metadata| metadata.endpoint_prefix),
three_ds_requestor_url: business_profile.authentication_connector_details.clone().map(|details| details.three_ds_requestor_url),
three_ds_requestor_id: metadata.clone().and_then(|metadata| metadata.three_ds_requestor_id),
three_ds_requestor_name: metadata.clone().and_then(|metadata| metadata.three_ds_requestor_name),
merchant_country_code: merchant_country_code.map(common_types::payments::MerchantCountryCode::new),
notification_url,
});
let domain_address = payment_data.address.get_payment_method_billing();
let pre_auth_response = uas_utils::types::ExternalAuthentication::pre_authentication(
state,
&payment_data.payment_attempt.merchant_id,
Some(&payment_data.payment_intent.payment_id),
payment_data.payment_method_data.as_ref(),
payment_data.payment_attempt.payment_method_type,
&three_ds_connector_account,
&authentication_connector_name,
&authentication.authentication_id,
payment_data.payment_attempt.payment_method.ok_or(
errors::ApiErrorResponse::InternalServerError
).attach_printable("payment_method not found in payment_attempt")?,
payment_data.payment_intent.amount,
payment_data.payment_intent.currency,
payment_data.service_details.clone(),
merchant_details.as_ref(),
domain_address,
authentication.acquirer_bin.clone(),
authentication.acquirer_merchant_id.clone(),
)
.await?;
let updated_authentication = uas_utils::utils::external_authentication_update_trackers(
state,
pre_auth_response,
authentication.clone(),
acquirer_details,
key_store,
None,
None,
None,
None,
).await?;
let authentication_store = hyperswitch_domain_models::router_request_types::authentication::AuthenticationStore {
cavv: None, // since in case of pre_authentication cavv is not present
authentication: updated_authentication.clone(),
};
payment_data.authentication = Some(authentication_store.clone());
if updated_authentication.is_separate_authn_required()
|| updated_authentication.authentication_status.is_failed()
{
*should_continue_confirm_transaction = false;
let default_poll_config = types::PollConfig::default();
let default_config_str = default_poll_config
.encode_to_string_of_json()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error while stringifying default poll config")?;
// raise error if authentication_connector is not present since it should we be present in the current flow
let authentication_connector = updated_authentication.authentication_connector
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("authentication_connector not found in updated_authentication")?;
let poll_config = state
.store
.find_config_by_key_unwrap_or(
&types::PollConfig::get_poll_config_key(
authentication_connector.clone(),
),
Some(default_config_str),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("The poll config was not found in the DB")?;
let poll_config: types::PollConfig = poll_config
.config
.parse_struct("PollConfig")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error while parsing PollConfig")?;
payment_data.poll_config = Some(poll_config)
}
},
helpers::UnifiedAuthenticationServiceFlow::ExternalAuthenticationPostAuthenticate {authentication_id} => {
let (authentication_connector, three_ds_connector_account) =
authentication::utils::get_authentication_connector_data(state, key_store, business_profile, None).await?;
let is_pull_mechanism_enabled =
utils::check_if_pull_mechanism_for_external_3ds_enabled_from_connector_metadata(
three_ds_connector_account
.get_metadata()
.map(|metadata| metadata.expose()),
);
let authentication = state
.store
.find_authentication_by_merchant_id_authentication_id(
&business_profile.merchant_id,
&authentication_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| format!("Error while fetching authentication record with authentication_id {}", authentication_id.get_string_repr()))?;
let updated_authentication = if !authentication.authentication_status.is_terminal_status() && is_pull_mechanism_enabled {
let post_auth_response = uas_utils::types::ExternalAuthentication::post_authentication(
state,
business_profile,
Some(&payment_data.payment_intent.payment_id),
&three_ds_connector_account,
&authentication_connector.to_string(),
&authentication.authentication_id,
payment_data.payment_attempt.payment_method.ok_or(
errors::ApiErrorResponse::InternalServerError
).attach_printable("payment_method not found in payment_attempt")?,
&payment_data.payment_intent.merchant_id,
Some(&authentication),
).await?;
uas_utils::utils::external_authentication_update_trackers(
state,
post_auth_response,
authentication,
None,
key_store,
None,
None,
None,
None,
).await?
} else {
authentication
};
let tokenized_data = if updated_authentication.authentication_status.is_success() {
Some(crate::core::payment_methods::vault::get_tokenized_data(state, authentication_id.get_string_repr(), false, key_store.key.get_inner()).await?)
} else {
None
};
let authentication_store = hyperswitch_domain_models::router_request_types::authentication::AuthenticationStore {
cavv: tokenized_data.map(|tokenized_data| masking::Secret::new(tokenized_data.value1)),
authentication: updated_authentication
};
payment_data.authentication = Some(authentication_store.clone());
//If authentication is not successful, skip the payment connector flows and mark the payment as failure
if authentication_store.authentication.authentication_status
!= api_models::enums::AuthenticationStatus::Success
{
*should_continue_confirm_transaction = false;
}
},
}
}
Ok(())
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 315,
"total_crates": null
} |
fn_clm_router_apply_three_ds_authentication_strategy_-322264693709528005 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/operations/payment_confirm
// Implementation of PaymentConfirm for Domain<F, api::PaymentsRequest, PaymentData<F>>
async fn apply_three_ds_authentication_strategy<'a>(
&'a self,
state: &SessionState,
payment_data: &mut PaymentData<F>,
business_profile: &domain::Profile,
) -> CustomResult<(), errors::ApiErrorResponse> {
// If the business profile has a three_ds_decision_rule_algorithm, we will use it to determine the 3DS strategy (authentication_type, exemption_type and force_three_ds_challenge)
if let Some(three_ds_decision_rule) =
business_profile.three_ds_decision_rule_algorithm.clone()
{
// Parse the three_ds_decision_rule to get the algorithm_id
let algorithm_id = three_ds_decision_rule
.parse_value::<api::routing::RoutingAlgorithmRef>("RoutingAlgorithmRef")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Could not decode profile routing algorithm ref")?
.algorithm_id
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("No algorithm_id found in three_ds_decision_rule_algorithm")?;
// get additional card info from payment data
let additional_card_info = payment_data
.payment_attempt
.payment_method_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")?
.and_then(|additional_payment_method_data| {
additional_payment_method_data.get_additional_card_info()
});
// get acquirer details from business profile based on card network
let acquirer_config = additional_card_info.as_ref().and_then(|card_info| {
card_info
.card_network
.clone()
.and_then(|network| business_profile.get_acquirer_details_from_network(network))
});
let country = business_profile
.merchant_country_code
.as_ref()
.map(|country_code| {
country_code.validate_and_get_country_from_merchant_country_code()
})
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error while parsing country from merchant country code")?;
// get three_ds_decision_rule_output using algorithm_id and payment data
let decision = three_ds_decision_rule::get_three_ds_decision_rule_output(
state,
&business_profile.merchant_id,
api_models::three_ds_decision_rule::ThreeDsDecisionRuleExecuteRequest {
routing_id: algorithm_id,
payment: api_models::three_ds_decision_rule::PaymentData {
amount: payment_data.payment_intent.amount,
currency: payment_data
.payment_intent
.currency
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("currency is not set in payment intent")?,
},
payment_method: Some(
api_models::three_ds_decision_rule::PaymentMethodMetaData {
card_network: additional_card_info
.as_ref()
.and_then(|info| info.card_network.clone()),
},
),
issuer: Some(api_models::three_ds_decision_rule::IssuerData {
name: additional_card_info
.as_ref()
.and_then(|info| info.card_issuer.clone()),
country: additional_card_info
.as_ref()
.map(|info| info.card_issuing_country.clone().parse_enum("Country"))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Error while getting country enum from issuer country",
)?,
}),
customer_device: None,
acquirer: acquirer_config.as_ref().map(|acquirer| {
api_models::three_ds_decision_rule::AcquirerData {
country,
fraud_rate: Some(acquirer.acquirer_fraud_rate),
}
}),
},
)
.await?;
logger::info!("Three DS Decision Rule Output: {:?}", decision);
// We should update authentication_type from the Three DS Decision if it is not already set
if payment_data.payment_attempt.authentication_type.is_none() {
payment_data.payment_attempt.authentication_type =
Some(common_enums::AuthenticationType::foreign_from(decision));
}
// We should update psd2_sca_exemption_type from the Three DS Decision
payment_data.payment_intent.psd2_sca_exemption_type = decision.foreign_into();
// We should update force_3ds_challenge from the Three DS Decision
payment_data.payment_intent.force_3ds_challenge =
decision.should_force_3ds_challenge().then_some(true);
}
Ok(())
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 105,
"total_crates": null
} |
fn_clm_router_validate_request_-322264693709528005 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/operations/payment_confirm
// Implementation of PaymentConfirm for ValidateRequest<F, api::PaymentsRequest, PaymentData<F>>
fn validate_request<'a, 'b>(
&'b self,
request: &api::PaymentsRequest,
merchant_context: &'a domain::MerchantContext,
) -> RouterResult<(PaymentConfirmOperation<'b, F>, operations::ValidateResult)> {
helpers::validate_customer_information(request)?;
if let Some(amount) = request.amount {
helpers::validate_max_amount(amount)?;
}
let request_merchant_id = request.merchant_id.as_ref();
helpers::validate_merchant_id(
merchant_context.get_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(),
})?;
helpers::validate_payment_method_fields_present(request)?;
let _mandate_type =
helpers::validate_mandate(request, payments::is_operation_confirm(self))?;
helpers::validate_recurring_details_and_token(
&request.recurring_details,
&request.payment_token,
&request.mandate_id,
)?;
request.validate_stored_credential().change_context(
errors::ApiErrorResponse::InvalidRequestData {
message:
"is_stored_credential should be true when reusing stored payment method data"
.to_string(),
},
)?;
let payment_id = request
.payment_id
.clone()
.ok_or(report!(errors::ApiErrorResponse::PaymentNotFound))?;
let _request_straight_through: Option<api::routing::StraightThroughAlgorithm> = request
.routing
.clone()
.map(|val| val.parse_value("RoutingAlgorithm"))
.transpose()
.change_context(errors::ApiErrorResponse::InvalidRequestData {
message: "Invalid straight through routing rules format".to_string(),
})
.attach_printable("Invalid straight through routing rules format")?;
Ok((
Box::new(self),
operations::ValidateResult {
merchant_id: merchant_context.get_merchant_account().get_id().to_owned(),
payment_id,
storage_scheme: merchant_context.get_merchant_account().storage_scheme,
requeue: matches!(
request.retry_action,
Some(api_models::enums::RetryAction::Requeue)
),
},
))
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 92,
"total_crates": null
} |
fn_clm_router_get_trackers_-193513852164633139 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/operations/proxy_payments_intent
// Implementation of PaymentProxyIntent for GetTracker<F, PaymentConfirmData<F>, ProxyPaymentsRequest>
async fn get_trackers<'a>(
&'a self,
state: &'a SessionState,
payment_id: &common_utils::id_type::GlobalPaymentId,
request: &ProxyPaymentsRequest,
merchant_context: &domain::MerchantContext,
_profile: &domain::Profile,
header_payload: &hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<operations::GetTrackerResponse<PaymentConfirmData<F>>> {
let db = &*state.store;
let key_manager_state = &state.into();
let storage_scheme = merchant_context.get_merchant_account().storage_scheme;
let payment_intent = db
.find_payment_intent_by_id(
key_manager_state,
payment_id,
merchant_context.get_merchant_key_store(),
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
self.validate_status_for_operation(payment_intent.status)?;
let cell_id = state.conf.cell_information.id.clone();
let batch_encrypted_data = domain_types::crypto_operation(
key_manager_state,
common_utils::type_name!(hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt),
domain_types::CryptoOperation::BatchEncrypt(
hyperswitch_domain_models::payments::payment_attempt::FromRequestEncryptablePaymentAttempt::to_encryptable(
hyperswitch_domain_models::payments::payment_attempt::FromRequestEncryptablePaymentAttempt {
payment_method_billing_address: None,
},
),
),
common_utils::types::keymanager::Identifier::Merchant(merchant_context.get_merchant_account().get_id().to_owned()),
merchant_context.get_merchant_key_store().key.peek(),
)
.await
.and_then(|val| val.try_into_batchoperation())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while encrypting payment intent details".to_string())?;
let encrypted_data =
hyperswitch_domain_models::payments::payment_attempt::FromRequestEncryptablePaymentAttempt::from_encryptable(batch_encrypted_data)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while encrypting payment intent details")?;
let payment_attempt = match payment_intent.active_attempt_id.clone() {
Some(ref active_attempt_id) => db
.find_payment_attempt_by_id(
key_manager_state,
merchant_context.get_merchant_key_store(),
active_attempt_id,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::PaymentNotFound)
.attach_printable("Could not find payment attempt")?,
None => {
let payment_attempt_domain_model: hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt =
hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt::proxy_create_domain_model(
&payment_intent,
cell_id,
storage_scheme,
request,
encrypted_data
)
.await?;
db.insert_payment_attempt(
key_manager_state,
merchant_context.get_merchant_key_store(),
payment_attempt_domain_model,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Could not insert payment attempt")?
}
};
let processor_payment_token = request.recurring_details.processor_payment_token.clone();
let payment_address = hyperswitch_domain_models::payment_address::PaymentAddress::new(
payment_intent
.shipping_address
.clone()
.map(|address| address.into_inner()),
payment_intent
.billing_address
.clone()
.map(|address| address.into_inner()),
payment_attempt
.payment_method_billing_address
.clone()
.map(|address| address.into_inner()),
Some(true),
);
let mandate_data_input = api_models::payments::MandateIds {
mandate_id: None,
mandate_reference_id: Some(
api_models::payments::MandateReferenceId::ConnectorMandateId(
api_models::payments::ConnectorMandateReferenceId::new(
Some(processor_payment_token),
None,
None,
None,
None,
),
),
),
};
let payment_data = PaymentConfirmData {
flow: std::marker::PhantomData,
payment_intent,
payment_attempt,
payment_method_data: Some(PaymentMethodData::MandatePayment),
payment_address,
mandate_data: Some(mandate_data_input),
payment_method: None,
merchant_connector_details: None,
external_vault_pmd: None,
webhook_url: None,
};
let get_trackers_response = operations::GetTrackerResponse { payment_data };
Ok(get_trackers_response)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 135,
"total_crates": null
} |
fn_clm_router_update_trackers_-193513852164633139 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/operations/proxy_payments_intent
// Implementation of PaymentProxyIntent for UpdateTracker<F, PaymentConfirmData<F>, ProxyPaymentsRequest>
async fn update_trackers<'b>(
&'b self,
state: &'b SessionState,
_req_state: ReqState,
mut payment_data: PaymentConfirmData<F>,
_customer: Option<domain::Customer>,
storage_scheme: storage_enums::MerchantStorageScheme,
_updated_customer: Option<storage::CustomerUpdate>,
key_store: &domain::MerchantKeyStore,
_frm_suggestion: Option<api_models::enums::FrmSuggestion>,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<(BoxedConfirmOperation<'b, F>, PaymentConfirmData<F>)>
where
F: 'b + Send,
{
let db = &*state.store;
let key_manager_state = &state.into();
let intent_status = common_enums::IntentStatus::Processing;
let attempt_status = common_enums::AttemptStatus::Pending;
let connector = payment_data
.payment_attempt
.connector
.clone()
.get_required_value("connector")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Connector is none when constructing response")?;
let merchant_connector_id = Some(
payment_data
.payment_attempt
.merchant_connector_id
.clone()
.get_required_value("merchant_connector_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Merchant connector id is none when constructing response")?,
);
let payment_intent_update =
hyperswitch_domain_models::payments::payment_intent::PaymentIntentUpdate::ConfirmIntent {
status: intent_status,
updated_by: storage_scheme.to_string(),
active_attempt_id: Some(payment_data.payment_attempt.id.clone()),
};
let authentication_type = payment_data
.payment_intent
.authentication_type
.unwrap_or_default();
let connector_request_reference_id = payment_data
.payment_attempt
.connector_request_reference_id
.clone();
let connector_response_reference_id = payment_data
.payment_attempt
.connector_response_reference_id
.clone();
let payment_attempt_update = hyperswitch_domain_models::payments::payment_attempt::PaymentAttemptUpdate::ConfirmIntent {
status: attempt_status,
updated_by: storage_scheme.to_string(),
connector,
merchant_connector_id,
authentication_type,
connector_request_reference_id,
connector_response_reference_id,
};
let updated_payment_intent = db
.update_payment_intent(
key_manager_state,
payment_data.payment_intent.clone(),
payment_intent_update,
key_store,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to update payment intent")?;
payment_data.payment_intent = updated_payment_intent;
let updated_payment_attempt = db
.update_payment_attempt(
key_manager_state,
key_store,
payment_data.payment_attempt.clone(),
payment_attempt_update,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to update payment attempt")?;
payment_data.payment_attempt = updated_payment_attempt;
Ok((Box::new(self), payment_data))
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 107,
"total_crates": null
} |
fn_clm_router_to_domain_-193513852164633139 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/operations/proxy_payments_intent
// Implementation of PaymentProxyIntent for Operation<F, ProxyPaymentsRequest>
fn to_domain(&self) -> RouterResult<&dyn Domain<F, ProxyPaymentsRequest, Self::Data>> {
Ok(self)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 92,
"total_crates": null
} |
fn_clm_router_to_update_tracker_-193513852164633139 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/operations/proxy_payments_intent
// Implementation of PaymentProxyIntent for Operation<F, ProxyPaymentsRequest>
fn to_update_tracker(
&self,
) -> RouterResult<&(dyn UpdateTracker<F, Self::Data, ProxyPaymentsRequest> + Send + Sync)> {
Ok(self)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 56,
"total_crates": null
} |
fn_clm_router_update_tracker_-193513852164633139 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/operations/proxy_payments_intent
// Implementation of PaymentProxyIntent for PostUpdateTracker<F, PaymentConfirmData<F>, types::PaymentsAuthorizeData>
async fn update_tracker<'b>(
&'b self,
state: &'b SessionState,
mut payment_data: PaymentConfirmData<F>,
response: types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>,
key_store: &domain::MerchantKeyStore,
storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<PaymentConfirmData<F>>
where
F: 'b + Send + Sync,
types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>:
hyperswitch_domain_models::router_data::TrackerPostUpdateObjects<
F,
types::PaymentsAuthorizeData,
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)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 50,
"total_crates": null
} |
fn_clm_router_get_trackers_-1949759077308537089 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/operations/payment_update_intent
// Implementation of PaymentUpdateIntent for GetTracker<F, payments::PaymentIntentData<F>, PaymentsUpdateIntentRequest>
async fn get_trackers<'a>(
&'a self,
state: &'a SessionState,
payment_id: &common_utils::id_type::GlobalPaymentId,
request: &PaymentsUpdateIntentRequest,
merchant_context: &domain::MerchantContext,
profile: &domain::Profile,
_header_payload: &hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<operations::GetTrackerResponse<payments::PaymentIntentData<F>>> {
let db = &*state.store;
if let Some(routing_algorithm_id) = request.routing_algorithm_id.as_ref() {
helpers::validate_routing_id_with_profile_id(
db,
routing_algorithm_id,
profile.get_id(),
)
.await?;
}
let key_manager_state = &state.into();
let storage_scheme = merchant_context.get_merchant_account().storage_scheme;
let payment_intent = db
.find_payment_intent_by_id(
key_manager_state,
payment_id,
merchant_context.get_merchant_key_store(),
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
self.validate_status_for_operation(payment_intent.status)?;
let PaymentsUpdateIntentRequest {
amount_details,
routing_algorithm_id,
capture_method,
authentication_type,
billing,
shipping,
customer_present,
description,
return_url,
setup_future_usage,
apply_mit_exemption,
statement_descriptor,
order_details,
allowed_payment_method_types,
metadata,
connector_metadata,
feature_metadata,
payment_link_config,
request_incremental_authorization,
session_expiry,
frm_metadata,
request_external_three_ds_authentication,
set_active_attempt_id,
enable_partial_authorization,
} = request.clone();
let batch_encrypted_data = domain_types::crypto_operation(
key_manager_state,
common_utils::type_name!(hyperswitch_domain_models::payments::PaymentIntent),
domain_types::CryptoOperation::BatchEncrypt(
hyperswitch_domain_models::payments::FromRequestEncryptablePaymentIntent::to_encryptable(
hyperswitch_domain_models::payments::FromRequestEncryptablePaymentIntent {
shipping_address: shipping.map(|address| address.encode_to_value()).transpose().change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed to encode shipping address")?.map(masking::Secret::new),
billing_address: billing.map(|address| address.encode_to_value()).transpose().change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed to encode billing address")?.map(masking::Secret::new),
customer_details: None,
},
),
),
common_utils::types::keymanager::Identifier::Merchant(merchant_context.get_merchant_account().get_id().to_owned()),
merchant_context.get_merchant_key_store().key.peek(),
)
.await
.and_then(|val| val.try_into_batchoperation())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while encrypting payment intent details".to_string())?;
let decrypted_payment_intent =
hyperswitch_domain_models::payments::FromRequestEncryptablePaymentIntent::from_encryptable(batch_encrypted_data)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while encrypting payment intent details")?;
let order_details = order_details.clone().map(|order_details| {
order_details
.into_iter()
.map(|order_detail| {
masking::Secret::new(
diesel_models::types::OrderDetailsWithAmount::convert_from(order_detail),
)
})
.collect()
});
let session_expiry = session_expiry.map(|expiry| {
payment_intent
.created_at
.saturating_add(time::Duration::seconds(i64::from(expiry)))
});
let updated_amount_details = match amount_details {
Some(details) => payment_intent.amount_details.update_from_request(&details),
None => payment_intent.amount_details,
};
let active_attempt_id = set_active_attempt_id
.map(|active_attempt_req| match active_attempt_req {
UpdateActiveAttempt::Set(global_attempt_id) => Some(global_attempt_id),
UpdateActiveAttempt::Unset => None,
})
.unwrap_or(payment_intent.active_attempt_id);
let payment_intent = hyperswitch_domain_models::payments::PaymentIntent {
amount_details: updated_amount_details,
description: description.or(payment_intent.description),
return_url: return_url.or(payment_intent.return_url),
metadata: metadata.or(payment_intent.metadata),
statement_descriptor: statement_descriptor.or(payment_intent.statement_descriptor),
modified_at: common_utils::date_time::now(),
order_details,
connector_metadata: connector_metadata.or(payment_intent.connector_metadata),
feature_metadata: (feature_metadata
.map(FeatureMetadata::convert_from)
.or(payment_intent.feature_metadata)),
updated_by: storage_scheme.to_string(),
request_incremental_authorization: request_incremental_authorization
.unwrap_or(payment_intent.request_incremental_authorization),
session_expiry: session_expiry.unwrap_or(payment_intent.session_expiry),
request_external_three_ds_authentication: request_external_three_ds_authentication
.unwrap_or(payment_intent.request_external_three_ds_authentication),
frm_metadata: frm_metadata.or(payment_intent.frm_metadata),
billing_address: decrypted_payment_intent
.billing_address
.as_ref()
.map(|data| {
data.clone()
.deserialize_inner_value(|value| value.parse_value("Address"))
})
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to decode billing address")?,
shipping_address: decrypted_payment_intent
.shipping_address
.as_ref()
.map(|data| {
data.clone()
.deserialize_inner_value(|value| value.parse_value("Address"))
})
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to decode shipping address")?,
capture_method: capture_method.unwrap_or(payment_intent.capture_method),
authentication_type: authentication_type.or(payment_intent.authentication_type),
payment_link_config: payment_link_config
.map(ApiModelToDieselModelConvertor::convert_from)
.or(payment_intent.payment_link_config),
apply_mit_exemption: apply_mit_exemption.unwrap_or(payment_intent.apply_mit_exemption),
customer_present: customer_present.unwrap_or(payment_intent.customer_present),
routing_algorithm_id: routing_algorithm_id.or(payment_intent.routing_algorithm_id),
allowed_payment_method_types: allowed_payment_method_types
.or(payment_intent.allowed_payment_method_types),
active_attempt_id,
enable_partial_authorization: enable_partial_authorization
.or(payment_intent.enable_partial_authorization),
..payment_intent
};
let payment_data = payments::PaymentIntentData {
flow: PhantomData,
payment_intent,
client_secret: None,
sessions_token: vec![],
vault_session_details: None,
connector_customer_id: None,
};
let get_trackers_response = operations::GetTrackerResponse { payment_data };
Ok(get_trackers_response)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 223,
"total_crates": null
} |
fn_clm_router_to_domain_-1949759077308537089 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/operations/payment_update_intent
// Implementation of PaymentUpdateIntent for Operation<F, PaymentsUpdateIntentRequest>
fn to_domain(&self) -> RouterResult<&dyn Domain<F, PaymentsUpdateIntentRequest, Self::Data>> {
Ok(self)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 92,
"total_crates": null
} |
fn_clm_router_update_trackers_-1949759077308537089 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/operations/payment_update_intent
// Implementation of PaymentUpdateIntent for UpdateTracker<F, payments::PaymentIntentData<F>, PaymentsUpdateIntentRequest>
async fn update_trackers<'b>(
&'b self,
state: &'b SessionState,
_req_state: ReqState,
mut payment_data: payments::PaymentIntentData<F>,
_customer: Option<domain::Customer>,
storage_scheme: enums::MerchantStorageScheme,
_updated_customer: Option<storage::CustomerUpdate>,
key_store: &domain::MerchantKeyStore,
_frm_suggestion: Option<FrmSuggestion>,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<(
PaymentsUpdateIntentOperation<'b, F>,
payments::PaymentIntentData<F>,
)>
where
F: 'b + Send,
{
let db = &*state.store;
let key_manager_state = &state.into();
let intent = payment_data.payment_intent.clone();
let payment_intent_update =
PaymentIntentUpdate::UpdateIntent(Box::new(PaymentIntentUpdateFields {
amount: Some(intent.amount_details.order_amount),
currency: Some(intent.amount_details.currency),
shipping_cost: intent.amount_details.shipping_cost,
skip_external_tax_calculation: Some(
intent.amount_details.skip_external_tax_calculation,
),
skip_surcharge_calculation: Some(intent.amount_details.skip_surcharge_calculation),
surcharge_amount: intent.amount_details.surcharge_amount,
tax_on_surcharge: intent.amount_details.tax_on_surcharge,
routing_algorithm_id: intent.routing_algorithm_id,
capture_method: Some(intent.capture_method),
authentication_type: intent.authentication_type,
billing_address: intent.billing_address,
shipping_address: intent.shipping_address,
customer_present: Some(intent.customer_present),
description: intent.description,
return_url: intent.return_url,
setup_future_usage: Some(intent.setup_future_usage),
apply_mit_exemption: Some(intent.apply_mit_exemption),
statement_descriptor: intent.statement_descriptor,
order_details: intent.order_details,
allowed_payment_method_types: intent.allowed_payment_method_types,
metadata: intent.metadata,
connector_metadata: intent
.connector_metadata
.map(|cm| cm.encode_to_value())
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to serialize connector_metadata")?
.map(masking::Secret::new),
feature_metadata: intent.feature_metadata,
payment_link_config: intent.payment_link_config,
request_incremental_authorization: Some(intent.request_incremental_authorization),
session_expiry: Some(intent.session_expiry),
frm_metadata: intent.frm_metadata,
request_external_three_ds_authentication: Some(
intent.request_external_three_ds_authentication,
),
updated_by: intent.updated_by,
tax_details: intent.amount_details.tax_details,
active_attempt_id: Some(intent.active_attempt_id),
force_3ds_challenge: intent.force_3ds_challenge,
is_iframe_redirection_enabled: intent.is_iframe_redirection_enabled,
enable_partial_authorization: intent.enable_partial_authorization,
}));
let new_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("Could not update Intent")?;
payment_data.payment_intent = new_payment_intent;
Ok((Box::new(self), payment_data))
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 87,
"total_crates": null
} |
fn_clm_router_to_update_tracker_-1949759077308537089 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/operations/payment_update_intent
// Implementation of PaymentUpdateIntent for Operation<F, PaymentsUpdateIntentRequest>
fn to_update_tracker(
&self,
) -> RouterResult<&(dyn UpdateTracker<F, Self::Data, PaymentsUpdateIntentRequest> + Send + Sync)>
{
Ok(self)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 56,
"total_crates": null
} |
fn_clm_router_to_get_tracker_-1949759077308537089 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/operations/payment_update_intent
// Implementation of PaymentUpdateIntent for Operation<F, PaymentsUpdateIntentRequest>
fn to_get_tracker(
&self,
) -> RouterResult<&(dyn GetTracker<F, Self::Data, PaymentsUpdateIntentRequest> + Send + Sync)>
{
Ok(self)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 44,
"total_crates": null
} |
fn_clm_router_get_trackers_-8528062731674934239 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/operations/payments_extend_authorization
// Implementation of PaymentExtendAuthorization for GetTracker<F, PaymentData<F>, api::PaymentsExtendAuthorizationRequest>
async fn get_trackers<'a>(
&'a self,
state: &'a SessionState,
payment_id: &api::PaymentIdType,
_request: &api::PaymentsExtendAuthorizationRequest,
merchant_context: &domain::MerchantContext,
_auth_flow: services::AuthFlow,
_header_payload: &hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<
operations::GetTrackerResponse<
'a,
F,
api::PaymentsExtendAuthorizationRequest,
PaymentData<F>,
>,
> {
let db = &*state.store;
let key_manager_state = &state.into();
let merchant_id = merchant_context.get_merchant_account().get_id();
let storage_scheme = merchant_context.get_merchant_account().storage_scheme;
let payment_id = payment_id
.get_payment_intent_id()
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
let payment_intent = db
.find_payment_intent_by_payment_id_merchant_id(
key_manager_state,
&payment_id,
merchant_id,
merchant_context.get_merchant_key_store(),
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
helpers::validate_payment_status_against_allowed_statuses(
payment_intent.status,
&[
enums::IntentStatus::RequiresCapture,
enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture,
],
"extend authorization",
)?;
let 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().as_str(),
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
if !payment_attempt
.request_extended_authorization
.is_some_and(|request_extended_authorization| request_extended_authorization.is_true())
{
Err(errors::ApiErrorResponse::PreconditionFailed {
message:
"You cannot extend the authorization for this payment because authorization extension is not enabled.".to_owned(),
})?
}
let shipping_address = helpers::get_address_by_id(
state,
payment_intent.shipping_address_id.clone(),
merchant_context.get_merchant_key_store(),
&payment_intent.payment_id,
merchant_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let billing_address = helpers::get_address_by_id(
state,
payment_intent.billing_address_id.clone(),
merchant_context.get_merchant_key_store(),
&payment_intent.payment_id,
merchant_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let payment_method_billing = helpers::get_address_by_id(
state,
payment_attempt.payment_method_billing_address_id.clone(),
merchant_context.get_merchant_key_store(),
&payment_intent.payment_id,
merchant_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let currency = payment_attempt.currency.get_required_value("currency")?;
let amount = payment_attempt.get_total_amount().into();
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,
merchant_context.get_merchant_key_store(),
profile_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
let payment_data = PaymentData {
flow: PhantomData,
payment_intent,
payment_attempt,
currency,
amount,
email: None,
mandate_id: None,
mandate_connector: None,
setup_mandate: None,
customer_acceptance: None,
token: None,
token_data: None,
address: core_types::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: None,
payment_method_data: None,
payment_method_token: None,
payment_method_info: None,
force_sync: None,
all_keys_required: None,
refunds: vec![],
disputes: vec![],
attempts: None,
sessions_token: vec![],
card_cvc: None,
creds_identifier: None,
pm_token: None,
connector_customer_id: None,
recurring_mandate_payment_data: None,
ephemeral_key: None,
multiple_capture_data: None,
redirect_response: None,
surcharge_details: None,
frm_message: None,
payment_link_data: None,
incremental_authorization_details: None,
authorizations: vec![],
authentication: None,
recurring_details: None,
poll_config: None,
tax_data: None,
session_id: None,
service_details: None,
card_testing_guard_data: None,
vault_operation: None,
threeds_method_comp_ind: None,
whole_connector_response: None,
is_manual_retry_enabled: None,
is_l2_l3_enabled: false,
};
let get_trackers_response = operations::GetTrackerResponse {
operation: Box::new(self),
customer_details: None,
payment_data,
business_profile,
mandate_type: None,
};
Ok(get_trackers_response)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 139,
"total_crates": null
} |
fn_clm_router_update_trackers_-8528062731674934239 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/operations/payments_extend_authorization
// Implementation of PaymentExtendAuthorization for UpdateTracker<F, PaymentData<F>, api::PaymentsExtendAuthorizationRequest>
async fn update_trackers<'b>(
&'b self,
_state: &'b SessionState,
_req_state: ReqState,
payment_data: PaymentData<F>,
_customer: Option<domain::Customer>,
_storage_scheme: enums::MerchantStorageScheme,
_updated_customer: Option<storage::CustomerUpdate>,
_key_store: &domain::MerchantKeyStore,
_frm_suggestion: Option<FrmSuggestion>,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<(PaymentExtendAuthorizationOperation<'b, F>, PaymentData<F>)>
where
F: 'b + Send,
{
Ok((Box::new(self), payment_data))
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 61,
"total_crates": null
} |
fn_clm_router_validate_request_-8528062731674934239 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/operations/payments_extend_authorization
// Implementation of PaymentExtendAuthorization for ValidateRequest<F, api::PaymentsExtendAuthorizationRequest, PaymentData<F>>
fn validate_request<'a, 'b>(
&'b self,
request: &api::PaymentsExtendAuthorizationRequest,
merchant_context: &'a domain::MerchantContext,
) -> RouterResult<(
PaymentExtendAuthorizationOperation<'b, F>,
operations::ValidateResult,
)> {
Ok((
Box::new(self),
operations::ValidateResult {
merchant_id: merchant_context.get_merchant_account().get_id().to_owned(),
payment_id: api::PaymentIdType::PaymentIntentId(request.payment_id.to_owned()),
storage_scheme: merchant_context.get_merchant_account().storage_scheme,
requeue: false,
},
))
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 46,
"total_crates": null
} |
fn_clm_router_make_pm_data_-8528062731674934239 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/operations/payments_extend_authorization
// Implementation of PaymentExtendAuthorization for Domain<F, api::PaymentsExtendAuthorizationRequest, PaymentData<F>>
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<(
PaymentExtendAuthorizationOperation<'a, F>,
Option<domain::PaymentMethodData>,
Option<String>,
)> {
Ok((Box::new(self), None, None))
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 25,
"total_crates": null
} |
fn_clm_router_get_or_create_customer_details_-8528062731674934239 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/operations/payments_extend_authorization
// Implementation of PaymentExtendAuthorization for Domain<F, api::PaymentsExtendAuthorizationRequest, PaymentData<F>>
async fn get_or_create_customer_details<'a>(
&'a self,
_state: &SessionState,
_payment_data: &mut PaymentData<F>,
_request: Option<payments::CustomerDetails>,
_merchant_key_store: &domain::MerchantKeyStore,
_storage_scheme: enums::MerchantStorageScheme,
) -> errors::CustomResult<
(
PaymentExtendAuthorizationOperation<'a, F>,
Option<domain::Customer>,
),
errors::StorageError,
> {
Ok((Box::new(self), None))
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 19,
"total_crates": null
} |
fn_clm_router_get_trackers_-5721314855364615868 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/operations/payment_update
// Implementation of PaymentUpdate for GetTracker<F, PaymentData<F>, api::PaymentsRequest>
async fn get_trackers<'a>(
&'a self,
state: &'a SessionState,
payment_id: &api::PaymentIdType,
request: &api::PaymentsRequest,
merchant_context: &domain::MerchantContext,
auth_flow: services::AuthFlow,
_header_payload: &hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsRequest, PaymentData<F>>>
{
let (mut payment_intent, mut payment_attempt, currency): (_, _, storage_enums::Currency);
let payment_id = payment_id
.get_payment_intent_id()
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
let merchant_id = merchant_context.get_merchant_account().get_id();
let storage_scheme = merchant_context.get_merchant_account().storage_scheme;
let db = &*state.store;
let key_manager_state = &state.into();
helpers::allow_payment_update_enabled_for_client_auth(merchant_id, state, auth_flow)
.await?;
payment_intent = db
.find_payment_intent_by_payment_id_merchant_id(
key_manager_state,
&payment_id,
merchant_id,
merchant_context.get_merchant_key_store(),
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
// TODO (#7195): Add platform merchant account validation once publishable key auth is solved
if let Some(order_details) = &request.order_details {
helpers::validate_order_details_amount(
order_details.to_owned(),
payment_intent.amount,
false,
)?;
}
payment_intent.setup_future_usage = request
.setup_future_usage
.or(payment_intent.setup_future_usage);
helpers::validate_customer_access(&payment_intent, auth_flow, request)?;
helpers::validate_card_data(
request
.payment_method_data
.as_ref()
.and_then(|pmd| pmd.payment_method_data.clone()),
)?;
helpers::validate_payment_status_against_allowed_statuses(
payment_intent.status,
&[
storage_enums::IntentStatus::RequiresPaymentMethod,
storage_enums::IntentStatus::RequiresConfirmation,
],
"update",
)?;
helpers::authenticate_client_secret(request.client_secret.as_ref(), &payment_intent)?;
payment_intent.order_details = request
.get_order_details_as_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to convert order details to value")?
.or(payment_intent.order_details);
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().as_str(),
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
let customer_acceptance = request.customer_acceptance.clone();
let recurring_details = request.recurring_details.clone();
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.or(request.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_context,
None,
payment_intent.customer_id.as_ref(),
))
.await?;
helpers::validate_amount_to_capture_and_capture_method(Some(&payment_attempt), request)?;
helpers::validate_request_amount_and_amount_to_capture(
request.amount,
request.amount_to_capture,
request
.surcharge_details
.or(payment_attempt.get_surcharge_details()),
)
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "amount_to_capture".to_string(),
expected_format: "amount_to_capture lesser than or equal to amount".to_string(),
})?;
currency = request
.currency
.or(payment_attempt.currency)
.get_required_value("currency")?;
payment_attempt.payment_method = payment_method.or(payment_attempt.payment_method);
payment_attempt.payment_method_type =
payment_method_type.or(payment_attempt.payment_method_type);
let customer_details = helpers::get_customer_details_from_request(request);
let amount = request
.amount
.unwrap_or_else(|| payment_attempt.net_amount.get_order_amount().into());
if request.confirm.unwrap_or(false) {
helpers::validate_customer_id_mandatory_cases(
request.setup_future_usage.is_some(),
payment_intent
.customer_id
.as_ref()
.or(customer_details.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.as_deref(),
merchant_id,
payment_intent
.customer_id
.as_ref()
.or(customer_details.customer_id.as_ref()),
merchant_context.get_merchant_key_store(),
&payment_intent.payment_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let billing_address = helpers::create_or_update_address_for_payment_by_request(
state,
request.billing.as_ref(),
payment_intent.billing_address_id.as_deref(),
merchant_id,
payment_intent
.customer_id
.as_ref()
.or(customer_details.customer_id.as_ref()),
merchant_context.get_merchant_key_store(),
&payment_intent.payment_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let payment_method_billing = helpers::create_or_update_address_for_payment_by_request(
state,
request
.payment_method_data
.as_ref()
.and_then(|pmd| pmd.billing.as_ref()),
payment_attempt.payment_method_billing_address_id.as_deref(),
merchant_id,
payment_intent
.customer_id
.as_ref()
.or(customer_details.customer_id.as_ref()),
merchant_context.get_merchant_key_store(),
&payment_intent.payment_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
payment_intent.shipping_address_id = shipping_address.clone().map(|x| x.address_id);
payment_intent.billing_address_id = billing_address.clone().map(|x| x.address_id);
payment_attempt.payment_method_billing_address_id = payment_method_billing
.as_ref()
.map(|payment_method_billing| payment_method_billing.address_id.clone());
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);
payment_intent.frm_metadata = request.frm_metadata.clone().or(payment_intent.frm_metadata);
payment_intent.psd2_sca_exemption_type = request
.psd2_sca_exemption_type
.or(payment_intent.psd2_sca_exemption_type);
Self::populate_payment_intent_with_request(&mut payment_intent, request);
let token = token.or_else(|| payment_attempt.payment_token.clone());
if request.confirm.unwrap_or(false) {
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) = token.clone() {
Some(helpers::retrieve_payment_token_data(state, token, payment_method).await?)
} else {
None
};
let mandate_id = request
.mandate_id
.as_ref()
.or_else(|| {
request.recurring_details
.as_ref()
.and_then(|recurring_details| match recurring_details {
RecurringDetails::MandateId(id) => Some(id),
_ => None,
})
})
.async_and_then(|mandate_id| async {
let mandate = db
.find_mandate_by_merchant_id_mandate_id(merchant_id, mandate_id, merchant_context.get_merchant_account().storage_scheme)
.await
.change_context(errors::ApiErrorResponse::MandateNotFound);
Some(mandate.and_then(|mandate_obj| {
match (
mandate_obj.network_transaction_id,
mandate_obj.connector_mandate_ids,
) {
(Some(network_tx_id), _) => Ok(api_models::payments::MandateIds {
mandate_id: Some(mandate_obj.mandate_id),
mandate_reference_id: Some(
api_models::payments::MandateReferenceId::NetworkMandateId(
network_tx_id,
),
),
}),
(_, Some(connector_mandate_id)) => connector_mandate_id
.parse_value("ConnectorMandateId")
.change_context(errors::ApiErrorResponse::MandateNotFound)
.map(|connector_id: api_models::payments::ConnectorMandateReferenceId| {
api_models::payments::MandateIds {
mandate_id: Some(mandate_obj.mandate_id),
mandate_reference_id: Some(api_models::payments::MandateReferenceId::ConnectorMandateId(
api_models::payments::ConnectorMandateReferenceId::new(
connector_id.get_connector_mandate_id(), // connector_mandate_id
connector_id.get_payment_method_id(), // payment_method_id
None, // update_history
connector_id.get_mandate_metadata(), // mandate_metadata
connector_id.get_connector_mandate_request_reference_id() // connector_mandate_request_reference_id
)
))
}
}),
(_, _) => Ok(api_models::payments::MandateIds {
mandate_id: Some(mandate_obj.mandate_id),
mandate_reference_id: None,
}),
}
}))
})
.await
.transpose()?;
let (next_operation, amount): (PaymentUpdateOperation<'a, F>, _) =
if request.confirm.unwrap_or(false) {
let amount = {
let amount = request
.amount
.map(Into::into)
.unwrap_or(payment_attempt.net_amount.get_order_amount());
payment_attempt.net_amount.set_order_amount(amount);
payment_intent.amount = amount;
let surcharge_amount = request
.surcharge_details
.as_ref()
.map(RequestSurchargeDetails::get_total_surcharge_amount)
.or(payment_attempt.get_total_surcharge_amount());
amount + surcharge_amount.unwrap_or_default()
};
(Box::new(operations::PaymentConfirm), amount.into())
} else {
(Box::new(self), amount)
};
payment_intent.status = if request
.payment_method_data
.as_ref()
.is_some_and(|payment_method_data| payment_method_data.payment_method_data.is_some())
{
if request.confirm.unwrap_or(false) {
payment_intent.status
} else {
storage_enums::IntentStatus::RequiresConfirmation
}
} else {
storage_enums::IntentStatus::RequiresPaymentMethod
};
payment_intent.request_external_three_ds_authentication = request
.request_external_three_ds_authentication
.or(payment_intent.request_external_three_ds_authentication);
payment_intent.merchant_order_reference_id = request
.merchant_order_reference_id
.clone()
.or(payment_intent.merchant_order_reference_id);
Self::populate_payment_attempt_with_request(&mut payment_attempt, request);
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_context.get_merchant_account().get_id(),
mcd,
)
.await
})
.await
.transpose()?;
// 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,
merchant_context.get_merchant_key_store(),
profile_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
let surcharge_details = request.surcharge_details.map(|request_surcharge_details| {
payments::types::SurchargeDetails::from((&request_surcharge_details, &payment_attempt))
});
payment_intent.force_3ds_challenge = request
.force_3ds_challenge
.or(payment_intent.force_3ds_challenge);
payment_intent.payment_channel = request
.payment_channel
.clone()
.or(payment_intent.payment_channel);
payment_intent.enable_partial_authorization = request
.enable_partial_authorization
.or(payment_intent.enable_partial_authorization);
helpers::validate_overcapture_request(
&request.enable_overcapture,
&payment_attempt.capture_method,
)?;
payment_intent.enable_overcapture = request.enable_overcapture;
let payment_data = PaymentData {
flow: PhantomData,
payment_intent,
payment_attempt,
currency,
amount,
email: request.email.clone(),
mandate_id,
mandate_connector,
token,
token_data,
setup_mandate,
customer_acceptance,
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_token: None,
payment_method_info,
force_sync: None,
all_keys_required: 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: None,
surcharge_details,
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: None,
whole_connector_response: None,
is_manual_retry_enabled: None,
is_l2_l3_enabled: business_profile.is_l2_l3_enabled,
};
let get_trackers_response = operations::GetTrackerResponse {
operation: next_operation,
customer_details: Some(customer_details),
payment_data,
business_profile,
mandate_type,
};
Ok(get_trackers_response)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 451,
"total_crates": null
} |
fn_clm_router_foreign_try_from_-5721314855364615868 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/operations/payment_update
// Implementation of CustomerData for ForeignTryFrom<domain::Customer>
fn foreign_try_from(value: domain::Customer) -> Result<Self, Self::Error> {
Ok(Self {
name: value.name.map(|name| name.into_inner()),
email: value.email.map(Email::from),
phone: value.phone.map(|ph| ph.into_inner()),
phone_country_code: value.phone_country_code,
tax_registration_id: value
.tax_registration_id
.map(|tax_registration_id| tax_registration_id.into_inner()),
})
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 442,
"total_crates": null
} |
fn_clm_router_update_trackers_-5721314855364615868 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/operations/payment_update
// Implementation of PaymentUpdate for UpdateTracker<F, PaymentData<F>, api::PaymentsRequest>
async fn update_trackers<'b>(
&'b self,
state: &'b SessionState,
req_state: ReqState,
mut payment_data: PaymentData<F>,
customer: Option<domain::Customer>,
storage_scheme: storage_enums::MerchantStorageScheme,
_updated_customer: Option<storage::CustomerUpdate>,
key_store: &domain::MerchantKeyStore,
_frm_suggestion: Option<FrmSuggestion>,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<(PaymentUpdateOperation<'b, F>, PaymentData<F>)>
where
F: 'b + Send,
{
let is_payment_method_unavailable =
payment_data.payment_attempt.payment_method_id.is_none()
&& payment_data.payment_intent.status
== storage_enums::IntentStatus::RequiresPaymentMethod;
let payment_method = payment_data.payment_attempt.payment_method;
let get_attempt_status = || {
if is_payment_method_unavailable {
storage_enums::AttemptStatus::PaymentMethodAwaited
} else {
storage_enums::AttemptStatus::ConfirmationAwaited
}
};
let profile_id = payment_data
.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 additional_pm_data = payment_data
.payment_method_data
.as_ref()
.async_map(|payment_method_data| async {
helpers::get_additional_payment_data(payment_method_data, &*state.store, profile_id)
.await
})
.await
.transpose()?
.flatten();
let encoded_pm_data = additional_pm_data
.as_ref()
.map(Encode::encode_to_value)
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to encode additional pm data")?;
let business_sub_label = payment_data.payment_attempt.business_sub_label.clone();
let payment_method_type = payment_data.payment_attempt.payment_method_type;
let payment_experience = payment_data.payment_attempt.payment_experience;
let amount_to_capture = payment_data.payment_attempt.amount_to_capture;
let capture_method = payment_data.payment_attempt.capture_method;
let payment_method_billing_address_id = payment_data
.payment_attempt
.payment_method_billing_address_id
.clone();
let surcharge_amount = payment_data
.surcharge_details
.as_ref()
.map(|surcharge_details| surcharge_details.surcharge_amount);
let tax_amount = payment_data
.surcharge_details
.as_ref()
.map(|surcharge_details| surcharge_details.tax_on_surcharge_amount);
let network_transaction_id = payment_data.payment_attempt.network_transaction_id.clone();
payment_data.payment_attempt = state
.store
.update_payment_attempt_with_attempt_id(
payment_data.payment_attempt,
storage::PaymentAttemptUpdate::Update {
currency: payment_data.currency,
status: get_attempt_status(),
authentication_type: None,
payment_method,
payment_token: payment_data.token.clone(),
payment_method_data: encoded_pm_data,
payment_experience,
payment_method_type,
business_sub_label,
amount_to_capture,
capture_method,
fingerprint_id: None,
payment_method_billing_address_id,
updated_by: storage_scheme.to_string(),
network_transaction_id,
net_amount:
hyperswitch_domain_models::payments::payment_attempt::NetAmount::new(
payment_data.amount.into(),
None,
None,
surcharge_amount,
tax_amount,
),
},
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
let customer_id = customer.clone().map(|c| c.customer_id);
let intent_status = {
let current_intent_status = payment_data.payment_intent.status;
if is_payment_method_unavailable {
storage_enums::IntentStatus::RequiresPaymentMethod
} else if !payment_data.confirm.unwrap_or(true)
|| current_intent_status == storage_enums::IntentStatus::RequiresCustomerAction
{
storage_enums::IntentStatus::RequiresConfirmation
} else {
payment_data.payment_intent.status
}
};
let (shipping_address, billing_address) = (
payment_data.payment_intent.shipping_address_id.clone(),
payment_data.payment_intent.billing_address_id.clone(),
);
let customer_details = payment_data.payment_intent.customer_details.clone();
let return_url = payment_data.payment_intent.return_url.clone();
let setup_future_usage = payment_data.payment_intent.setup_future_usage;
let business_label = payment_data.payment_intent.business_label.clone();
let business_country = payment_data.payment_intent.business_country;
let description = payment_data.payment_intent.description.clone();
let statement_descriptor_name = payment_data
.payment_intent
.statement_descriptor_name
.clone();
let statement_descriptor_suffix = payment_data
.payment_intent
.statement_descriptor_suffix
.clone();
let key_manager_state = state.into();
let billing_details = payment_data
.address
.get_payment_billing()
.async_map(|billing_details| {
create_encrypted_data(&key_manager_state, key_store, billing_details)
})
.await
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt billing details")?;
let shipping_details = payment_data
.address
.get_shipping()
.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 order_details = payment_data.payment_intent.order_details.clone();
let metadata = payment_data.payment_intent.metadata.clone();
let frm_metadata = payment_data.payment_intent.frm_metadata.clone();
let session_expiry = payment_data.payment_intent.session_expiry;
let merchant_order_reference_id = payment_data
.payment_intent
.merchant_order_reference_id
.clone();
payment_data.payment_intent = state
.store
.update_payment_intent(
&state.into(),
payment_data.payment_intent.clone(),
storage::PaymentIntentUpdate::Update(Box::new(PaymentIntentUpdateFields {
amount: payment_data.amount.into(),
currency: payment_data.currency,
setup_future_usage,
status: intent_status,
customer_id: customer_id.clone(),
shipping_address_id: shipping_address,
billing_address_id: billing_address,
return_url,
business_country,
business_label,
description,
statement_descriptor_name,
statement_descriptor_suffix,
order_details,
metadata,
payment_confirm_source: None,
updated_by: storage_scheme.to_string(),
fingerprint_id: None,
session_expiry,
request_external_three_ds_authentication: payment_data
.payment_intent
.request_external_three_ds_authentication,
frm_metadata,
customer_details,
merchant_order_reference_id,
billing_details,
shipping_details,
is_payment_processor_token_flow: None,
tax_details: None,
force_3ds_challenge: payment_data.payment_intent.force_3ds_challenge,
is_iframe_redirection_enabled: payment_data
.payment_intent
.is_iframe_redirection_enabled,
is_confirm_operation: false, // this is not a confirm operation
payment_channel: payment_data.payment_intent.payment_channel,
feature_metadata: payment_data
.payment_intent
.feature_metadata
.clone()
.map(masking::Secret::new),
tax_status: payment_data.payment_intent.tax_status,
discount_amount: payment_data.payment_intent.discount_amount,
order_date: payment_data.payment_intent.order_date,
shipping_amount_tax: payment_data.payment_intent.shipping_amount_tax,
duty_amount: payment_data.payment_intent.duty_amount,
enable_partial_authorization: payment_data
.payment_intent
.enable_partial_authorization,
enable_overcapture: payment_data.payment_intent.enable_overcapture,
})),
key_store,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
let amount = payment_data.amount;
req_state
.event_context
.event(AuditEvent::new(AuditEventType::PaymentUpdate { amount }))
.with(payment_data.to_event())
.emit();
Ok((
payments::is_confirm(self, payment_data.confirm),
payment_data,
))
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 207,
"total_crates": null
} |
fn_clm_router_validate_request_-5721314855364615868 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/operations/payment_update
// Implementation of PaymentUpdate for ValidateRequest<F, api::PaymentsRequest, PaymentData<F>>
fn validate_request<'a, 'b>(
&'b self,
request: &api::PaymentsRequest,
merchant_context: &'a domain::MerchantContext,
) -> RouterResult<(PaymentUpdateOperation<'b, F>, operations::ValidateResult)> {
helpers::validate_customer_information(request)?;
if let Some(amount) = request.amount {
helpers::validate_max_amount(amount)?;
}
if let Some(session_expiry) = &request.session_expiry {
helpers::validate_session_expiry(session_expiry.to_owned())?;
}
let payment_id = request
.payment_id
.clone()
.ok_or(report!(errors::ApiErrorResponse::PaymentNotFound))?;
let request_merchant_id = request.merchant_id.as_ref();
helpers::validate_merchant_id(
merchant_context.get_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(),
})?;
helpers::validate_request_amount_and_amount_to_capture(
request.amount,
request.amount_to_capture,
request.surcharge_details,
)
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "amount_to_capture".to_string(),
expected_format: "amount_to_capture lesser than or equal to amount".to_string(),
})?;
helpers::validate_payment_method_fields_present(request)?;
let _mandate_type = helpers::validate_mandate(request, false)?;
helpers::validate_recurring_details_and_token(
&request.recurring_details,
&request.payment_token,
&request.mandate_id,
)?;
let _request_straight_through: Option<api::routing::StraightThroughAlgorithm> = request
.routing
.clone()
.map(|val| val.parse_value("RoutingAlgorithm"))
.transpose()
.change_context(errors::ApiErrorResponse::InvalidRequestData {
message: "Invalid straight through routing rules format".to_string(),
})
.attach_printable("Invalid straight through routing rules format")?;
Ok((
Box::new(self),
operations::ValidateResult {
merchant_id: merchant_context.get_merchant_account().get_id().to_owned(),
payment_id,
storage_scheme: merchant_context.get_merchant_account().storage_scheme,
requeue: matches!(
request.retry_action,
Some(api_models::enums::RetryAction::Requeue)
),
},
))
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 96,
"total_crates": null
} |
fn_clm_router_payments_dynamic_tax_calculation_-5721314855364615868 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/operations/payment_update
// Implementation of PaymentUpdate for Domain<F, api::PaymentsRequest, PaymentData<F>>
async fn payments_dynamic_tax_calculation<'a>(
&'a self,
state: &SessionState,
payment_data: &mut PaymentData<F>,
_connector_call_type: &ConnectorCallType,
business_profile: &domain::Profile,
merchant_context: &domain::MerchantContext,
) -> 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,
merchant_context.get_merchant_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_context,
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,
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(())
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 59,
"total_crates": null
} |
fn_clm_router_foreign_from_-7954479622253803623 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/routing/transformers
// Implementation of types::PaymentMethodFilters for ForeignFrom<settings::PaymentMethodFilters>
fn foreign_from(from: settings::PaymentMethodFilters) -> Self {
let iter_map = from
.0
.into_iter()
.map(|(key, val)| (key.foreign_into(), val.foreign_into()))
.collect::<HashMap<_, _>>();
Self(iter_map)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 222,
"total_crates": null
} |
fn_clm_router_new_-7976063767929341634 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/routing/utils
// Inherent implementation for RoutingEventsWrapper<Req>
pub fn new(
tenant_id: id_type::TenantId,
request_id: Option<RequestId>,
payment_id: String,
profile_id: id_type::ProfileId,
merchant_id: id_type::MerchantId,
flow: String,
request: Option<Req>,
parse_response: bool,
log_event: bool,
) -> Self {
Self {
tenant_id,
request_id,
payment_id,
profile_id,
merchant_id,
flow,
request,
parse_response,
log_event,
routing_event: None,
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 14463,
"total_crates": null
} |
fn_clm_router_try_from_-7976063767929341634 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/routing/utils
// Implementation of UpdateContractEventResponse for TryFrom<&ir_client::contract_routing_client::UpdateContractResponse>
fn try_from(
value: &ir_client::contract_routing_client::UpdateContractResponse,
) -> Result<Self, Self::Error> {
Ok(Self {
status: match value.status {
0 => ContractUpdationStatusEventResponse::ContractUpdationSucceeded,
1 => ContractUpdationStatusEventResponse::ContractUpdationFailed,
_ => {
return Err(errors::RoutingError::GenericNotFoundError {
field: "unknown updation status from dynamic routing service".to_string(),
})
}
},
})
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 2659,
"total_crates": null
} |
fn_clm_router_from_-7976063767929341634 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/routing/utils
// Implementation of ContractLabelInformationEventRequest for From<&api_routing::LabelInformation>
fn from(value: &api_routing::LabelInformation) -> Self {
Self {
label: value.label.clone(),
target_count: value.target_count,
target_time: value.target_time,
current_count: 1,
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 2602,
"total_crates": null
} |
fn_clm_router_get_error_message_-7976063767929341634 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/routing/utils
// Implementation of or_types::ErrorResponse for DecisionEngineErrorsInterface
fn get_error_message(&self) -> String {
self.error_message.clone()
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 196,
"total_crates": null
} |
fn_clm_router_extract_de_output_connectors_-7976063767929341634 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/routing/utils
/// Custom deserializer for output from decision_engine, this is required as untagged enum is
/// stored but the enum requires tagged deserialization, hence deserializing it into specific
/// variants
pub fn extract_de_output_connectors(
output_value: serde_json::Value,
) -> RoutingResult<Vec<ConnectorInfo>> {
const SINGLE: &str = "straight_through";
const PRIORITY: &str = "priority";
const VOLUME_SPLIT: &str = "volume_split";
const VOLUME_SPLIT_PRIORITY: &str = "volume_split_priority";
let obj = output_value.as_object().ok_or_else(|| {
logger::error!("decision_engine_euclid_error: output is not a JSON object");
errors::RoutingError::OpenRouterError("Expected output to be a JSON object".into())
})?;
let type_str = obj.get("type").and_then(|v| v.as_str()).ok_or_else(|| {
logger::error!("decision_engine_euclid_error: missing or invalid 'type' in output");
errors::RoutingError::OpenRouterError("Missing or invalid 'type' field in output".into())
})?;
match type_str {
SINGLE => {
let connector_value = obj.get("connector").ok_or_else(|| {
logger::error!(
"decision_engine_euclid_error: missing 'connector' field for type=single"
);
errors::RoutingError::OpenRouterError(
"Missing 'connector' field for single output".into(),
)
})?;
let connector: ConnectorInfo = serde_json::from_value(connector_value.clone())
.map_err(|e| {
logger::error!(
?e,
"decision_engine_euclid_error: Failed to parse single connector"
);
errors::RoutingError::OpenRouterError(
"Failed to deserialize single connector".into(),
)
})?;
Ok(vec![connector])
}
PRIORITY => {
let connectors_value = obj.get("connectors").ok_or_else(|| {
logger::error!(
"decision_engine_euclid_error: missing 'connectors' field for type=priority"
);
errors::RoutingError::OpenRouterError(
"Missing 'connectors' field for priority output".into(),
)
})?;
let connectors: Vec<ConnectorInfo> = serde_json::from_value(connectors_value.clone())
.map_err(|e| {
logger::error!(
?e,
"decision_engine_euclid_error: Failed to parse connectors for priority"
);
errors::RoutingError::OpenRouterError(
"Failed to deserialize priority connectors".into(),
)
})?;
Ok(connectors)
}
VOLUME_SPLIT => {
let splits_value = obj.get("splits").ok_or_else(|| {
logger::error!(
"decision_engine_euclid_error: missing 'splits' field for type=volume_split"
);
errors::RoutingError::OpenRouterError(
"Missing 'splits' field for volume_split output".into(),
)
})?;
// Transform each {connector, split} into {output, split}
let fixed_splits: Vec<_> = splits_value
.as_array()
.ok_or_else(|| {
logger::error!("decision_engine_euclid_error: 'splits' is not an array");
errors::RoutingError::OpenRouterError("'splits' field must be an array".into())
})?
.iter()
.map(|entry| {
let mut entry_map = entry.as_object().cloned().ok_or_else(|| {
logger::error!(
"decision_engine_euclid_error: invalid split entry in volume_split"
);
errors::RoutingError::OpenRouterError(
"Invalid entry in splits array".into(),
)
})?;
if let Some(connector) = entry_map.remove("connector") {
entry_map.insert("output".to_string(), connector);
}
Ok::<_, error_stack::Report<errors::RoutingError>>(serde_json::Value::Object(
entry_map,
))
})
.collect::<Result<Vec<_>, _>>()?;
let splits: Vec<VolumeSplit<ConnectorInfo>> =
serde_json::from_value(serde_json::Value::Array(fixed_splits)).map_err(|e| {
logger::error!(
?e,
"decision_engine_euclid_error: Failed to parse volume_split"
);
errors::RoutingError::OpenRouterError(
"Failed to deserialize volume_split connectors".into(),
)
})?;
Ok(splits.into_iter().map(|s| s.output).collect())
}
VOLUME_SPLIT_PRIORITY => {
let splits_value = obj.get("splits").ok_or_else(|| {
logger::error!("decision_engine_euclid_error: missing 'splits' field for type=volume_split_priority");
errors::RoutingError::OpenRouterError("Missing 'splits' field for volume_split_priority output".into())
})?;
// Transform each {connector: [...], split} into {output: [...], split}
let fixed_splits: Vec<_> = splits_value
.as_array()
.ok_or_else(|| {
logger::error!("decision_engine_euclid_error: 'splits' is not an array");
errors::RoutingError::OpenRouterError("'splits' field must be an array".into())
})?
.iter()
.map(|entry| {
let mut entry_map = entry.as_object().cloned().ok_or_else(|| {
logger::error!("decision_engine_euclid_error: invalid split entry in volume_split_priority");
errors::RoutingError::OpenRouterError("Invalid entry in splits array".into())
})?;
if let Some(connector) = entry_map.remove("connector") {
entry_map.insert("output".to_string(), connector);
}
Ok::<_, error_stack::Report<errors::RoutingError>>(serde_json::Value::Object(entry_map))
})
.collect::<Result<Vec<_>, _>>()?;
let splits: Vec<VolumeSplit<Vec<ConnectorInfo>>> =
serde_json::from_value(serde_json::Value::Array(fixed_splits)).map_err(|e| {
logger::error!(
?e,
"decision_engine_euclid_error: Failed to parse volume_split_priority"
);
errors::RoutingError::OpenRouterError(
"Failed to deserialize volume_split_priority connectors".into(),
)
})?;
Ok(splits.into_iter().flat_map(|s| s.output).collect())
}
other => {
logger::error!(type_str=%other, "decision_engine_euclid_error: unknown output type");
Err(
errors::RoutingError::OpenRouterError(format!("Unknown output type: {other}"))
.into(),
)
}
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 181,
"total_crates": null
} |
fn_clm_router_foreign_try_from_6221549246093910141 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/flows/complete_authorize_flow
// Implementation of types::PaymentsCaptureData for ForeignTryFrom<types::RouterData<F, types::CompleteAuthorizeData, types::PaymentsResponseData>>
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,
})
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 442,
"total_crates": null
} |
fn_clm_router_add_access_token_6221549246093910141 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/flows/complete_authorize_flow
// Implementation of types::RouterData<
api::CompleteAuthorize,
types::CompleteAuthorizeData,
types::PaymentsResponseData,
> for Feature<api::CompleteAuthorize, types::CompleteAuthorizeData>
async fn add_access_token<'a>(
&self,
state: &SessionState,
connector: &api::ConnectorData,
merchant_context: &domain::MerchantContext,
creds_identifier: Option<&str>,
) -> RouterResult<types::AddAccessTokenResult> {
Box::pin(access_token::add_access_token(
state,
connector,
merchant_context,
self,
creds_identifier,
))
.await
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 84,
"total_crates": null
} |
fn_clm_router_preprocessing_steps_6221549246093910141 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/flows/complete_authorize_flow
// Implementation of types::RouterData<
api::CompleteAuthorize,
types::CompleteAuthorizeData,
types::PaymentsResponseData,
> for Feature<api::CompleteAuthorize, types::CompleteAuthorizeData>
async fn preprocessing_steps<'a>(
self,
state: &SessionState,
connector: &api::ConnectorData,
) -> RouterResult<Self> {
complete_authorize_preprocessing_steps(state, &self, true, connector).await
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 49,
"total_crates": null
} |
fn_clm_router_construct_router_data_6221549246093910141 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/flows/complete_authorize_flow
// Implementation of PaymentData<api::CompleteAuthorize> for ConstructFlowSpecificData<
api::CompleteAuthorize,
types::CompleteAuthorizeData,
types::PaymentsResponseData,
>
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
merchant_context: &domain::MerchantContext,
customer: &Option<domain::Customer>,
merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
) -> RouterResult<
types::RouterData<
api::CompleteAuthorize,
types::CompleteAuthorizeData,
types::PaymentsResponseData,
>,
> {
todo!()
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 47,
"total_crates": null
} |
fn_clm_router_decide_flows_6221549246093910141 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/flows/complete_authorize_flow
// Implementation of types::RouterData<
api::CompleteAuthorize,
types::CompleteAuthorizeData,
types::PaymentsResponseData,
> for Feature<api::CompleteAuthorize, types::CompleteAuthorizeData>
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,
_return_raw_connector_response: Option<bool>,
) -> 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,
None,
)
.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)
}
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 41,
"total_crates": null
} |
fn_clm_router_add_access_token_5286937453533156372 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/flows/cancel_post_capture_flow
// Implementation of types::RouterData<
api::PostCaptureVoid,
types::PaymentsCancelPostCaptureData,
types::PaymentsResponseData,
> for Feature<api::PostCaptureVoid, types::PaymentsCancelPostCaptureData>
async fn add_access_token<'a>(
&self,
state: &SessionState,
connector: &api::ConnectorData,
merchant_context: &domain::MerchantContext,
creds_identifier: Option<&str>,
) -> RouterResult<types::AddAccessTokenResult> {
Box::pin(access_token::add_access_token(
state,
connector,
merchant_context,
self,
creds_identifier,
))
.await
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 84,
"total_crates": null
} |
fn_clm_router_construct_router_data_5286937453533156372 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/flows/cancel_post_capture_flow
// Implementation of PaymentData<api::PostCaptureVoid> for ConstructFlowSpecificData<
api::PostCaptureVoid,
types::PaymentsCancelPostCaptureData,
types::PaymentsResponseData,
>
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
merchant_context: &domain::MerchantContext,
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
_payment_method: Option<common_enums::PaymentMethod>,
_payment_method_type: Option<common_enums::PaymentMethodType>,
) -> RouterResult<types::PaymentsCancelPostCaptureRouterData> {
Box::pin(transformers::construct_payment_router_data::<
api::PostCaptureVoid,
types::PaymentsCancelPostCaptureData,
>(
state,
self.clone(),
connector_id,
merchant_context,
customer,
merchant_connector_account,
merchant_recipient_data,
header_payload,
None,
None,
))
.await
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 51,
"total_crates": null
} |
fn_clm_router_decide_flows_5286937453533156372 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/flows/cancel_post_capture_flow
// Implementation of types::RouterData<
api::PostCaptureVoid,
types::PaymentsCancelPostCaptureData,
types::PaymentsResponseData,
> for Feature<api::PostCaptureVoid, types::PaymentsCancelPostCaptureData>
async fn decide_flows<'a>(
self,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
connector_request: Option<services::Request>,
_business_profile: &domain::Profile,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
_return_raw_connector_response: Option<bool>,
) -> RouterResult<Self> {
metrics::PAYMENT_CANCEL_COUNT.add(
1,
router_env::metric_attributes!(("connector", connector.connector_name.to_string())),
);
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::PostCaptureVoid,
types::PaymentsCancelPostCaptureData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
let resp = services::execute_connector_processing_step(
state,
connector_integration,
&self,
call_connector_action,
connector_request,
None,
)
.await
.to_payment_failed_response()?;
Ok(resp)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 31,
"total_crates": null
} |
fn_clm_router_build_flow_specific_connector_request_5286937453533156372 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/flows/cancel_post_capture_flow
// Implementation of types::RouterData<
api::PostCaptureVoid,
types::PaymentsCancelPostCaptureData,
types::PaymentsResponseData,
> for Feature<api::PostCaptureVoid, types::PaymentsCancelPostCaptureData>
async fn build_flow_specific_connector_request(
&mut self,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
) -> RouterResult<(Option<services::Request>, bool)> {
let request = match call_connector_action {
payments::CallConnectorAction::Trigger => {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::PostCaptureVoid,
types::PaymentsCancelPostCaptureData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
connector_integration
.build_request(self, &state.conf.connectors)
.to_payment_failed_response()?
}
_ => None,
};
Ok((request, true))
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 29,
"total_crates": null
} |
fn_clm_router_get_payment_method_data_7754123510831908882 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/flows/setup_mandate_flow
// Implementation of types::SetupMandateRequestData for mandate::MandateBehaviour
fn get_payment_method_data(&self) -> domain::payments::PaymentMethodData {
self.payment_method_data.clone()
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 94,
"total_crates": null
} |
fn_clm_router_call_unified_connector_service_7754123510831908882 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/flows/setup_mandate_flow
// Implementation of types::SetupMandateRouterData for Feature<api::SetupMandate, types::SetupMandateRequestData>
async fn call_unified_connector_service<'a>(
&mut self,
state: &SessionState,
header_payload: &domain_payments::HeaderPayload,
lineage_ids: grpc_client::LineageIds,
#[cfg(feature = "v1")] merchant_connector_account: helpers::MerchantConnectorAccountType,
#[cfg(feature = "v2")]
merchant_connector_account: domain::MerchantConnectorAccountTypeDetails,
merchant_context: &domain::MerchantContext,
unified_connector_service_execution_mode: enums::ExecutionMode,
) -> RouterResult<()> {
let client = state
.grpc_client
.unified_connector_service_client
.clone()
.ok_or(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to fetch Unified Connector Service client")?;
let payment_register_request =
payments_grpc::PaymentServiceRegisterRequest::foreign_try_from(&*self)
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to construct Payment Setup Mandate Request")?;
let connector_auth_metadata = build_unified_connector_service_auth_metadata(
merchant_connector_account,
merchant_context,
)
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to construct request metadata")?;
let merchant_reference_id = header_payload
.x_reference_id
.clone()
.map(|id| id_type::PaymentReferenceId::from_str(id.as_str()))
.transpose()
.inspect_err(|err| logger::warn!(error=?err, "Invalid Merchant ReferenceId found"))
.ok()
.flatten()
.map(ucs_types::UcsReferenceId::Payment);
let header_payload = state
.get_grpc_headers_ucs(unified_connector_service_execution_mode)
.external_vault_proxy_metadata(None)
.merchant_reference_id(merchant_reference_id)
.lineage_ids(lineage_ids);
let updated_router_data = Box::pin(ucs_logging_wrapper(
self.clone(),
state,
payment_register_request,
header_payload,
|mut router_data, payment_register_request, grpc_headers| async move {
let response = client
.payment_setup_mandate(
payment_register_request,
connector_auth_metadata,
grpc_headers,
)
.await
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to Setup Mandate payment")?;
let payment_register_response = response.into_inner();
let (router_data_response, status_code) =
handle_unified_connector_service_response_for_payment_register(
payment_register_response.clone(),
)
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to deserialize UCS response")?;
let router_data_response = router_data_response.map(|(response, status)| {
router_data.status = status;
response
});
router_data.response = router_data_response;
router_data.connector_http_status_code = Some(status_code);
Ok((router_data, payment_register_response))
},
))
.await?;
// Copy back the updated data
*self = updated_router_data;
Ok(())
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 88,
"total_crates": null
} |
fn_clm_router_add_access_token_7754123510831908882 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/flows/setup_mandate_flow
// Implementation of types::SetupMandateRouterData for Feature<api::SetupMandate, types::SetupMandateRequestData>
async fn add_access_token<'a>(
&self,
state: &SessionState,
connector: &api::ConnectorData,
merchant_context: &domain::MerchantContext,
creds_identifier: Option<&str>,
) -> RouterResult<types::AddAccessTokenResult> {
Box::pin(access_token::add_access_token(
state,
connector,
merchant_context,
self,
creds_identifier,
))
.await
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 84,
"total_crates": null
} |
fn_clm_router_construct_router_data_7754123510831908882 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/flows/setup_mandate_flow
// Implementation of hyperswitch_domain_models::payments::PaymentConfirmData<api::SetupMandate> for ConstructFlowSpecificData<
api::SetupMandate,
types::SetupMandateRequestData,
types::PaymentsResponseData,
>
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
merchant_context: &domain::MerchantContext,
customer: &Option<domain::Customer>,
merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<domain_payments::HeaderPayload>,
) -> RouterResult<types::SetupMandateRouterData> {
Box::pin(
transformers::construct_payment_router_data_for_setup_mandate(
state,
self.clone(),
connector_id,
merchant_context,
customer,
merchant_connector_account,
merchant_recipient_data,
header_payload,
),
)
.await
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 53,
"total_crates": null
} |
fn_clm_router_preprocessing_steps_7754123510831908882 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/flows/setup_mandate_flow
// Implementation of types::SetupMandateRouterData for Feature<api::SetupMandate, types::SetupMandateRequestData>
async fn preprocessing_steps<'a>(
self,
state: &SessionState,
connector: &api::ConnectorData,
) -> RouterResult<Self> {
setup_mandate_preprocessing_steps(state, &self, true, connector).await
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 49,
"total_crates": null
} |
fn_clm_router_add_access_token_883126423496542212 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/flows/approve_flow
// Implementation of types::RouterData<api::Approve, types::PaymentsApproveData, types::PaymentsResponseData> for Feature<api::Approve, types::PaymentsApproveData>
async fn add_access_token<'a>(
&self,
state: &SessionState,
connector: &api::ConnectorData,
merchant_context: &domain::MerchantContext,
creds_identifier: Option<&str>,
) -> RouterResult<types::AddAccessTokenResult> {
Box::pin(access_token::add_access_token(
state,
connector,
merchant_context,
self,
creds_identifier,
))
.await
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 84,
"total_crates": null
} |
fn_clm_router_construct_router_data_883126423496542212 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/flows/approve_flow
// Implementation of PaymentData<api::Approve> for ConstructFlowSpecificData<api::Approve, types::PaymentsApproveData, types::PaymentsResponseData>
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
merchant_context: &domain::MerchantContext,
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
_payment_method: Option<common_enums::PaymentMethod>,
_payment_method_type: Option<common_enums::PaymentMethodType>,
) -> RouterResult<types::PaymentsApproveRouterData> {
Box::pin(transformers::construct_payment_router_data::<
api::Approve,
types::PaymentsApproveData,
>(
state,
self.clone(),
connector_id,
merchant_context,
customer,
merchant_connector_account,
merchant_recipient_data,
header_payload,
None,
None,
))
.await
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 51,
"total_crates": null
} |
fn_clm_router_decide_flows_883126423496542212 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/flows/approve_flow
// Implementation of types::RouterData<api::Approve, types::PaymentsApproveData, types::PaymentsResponseData> for Feature<api::Approve, types::PaymentsApproveData>
async fn decide_flows<'a>(
self,
_state: &SessionState,
_connector: &api::ConnectorData,
_call_connector_action: payments::CallConnectorAction,
_connector_request: Option<services::Request>,
_business_profile: &domain::Profile,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
_return_raw_connector_response: Option<bool>,
) -> RouterResult<Self> {
Err(ApiErrorResponse::NotImplemented {
message: NotImplementedMessage::Reason("Flow not supported".to_string()),
}
.into())
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 29,
"total_crates": null
} |
fn_clm_router_build_flow_specific_connector_request_883126423496542212 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/flows/approve_flow
// Implementation of types::RouterData<api::Approve, types::PaymentsApproveData, types::PaymentsResponseData> for Feature<api::Approve, types::PaymentsApproveData>
async fn build_flow_specific_connector_request(
&mut self,
_state: &SessionState,
_connector: &api::ConnectorData,
_call_connector_action: payments::CallConnectorAction,
) -> RouterResult<(Option<services::Request>, bool)> {
Err(ApiErrorResponse::NotImplemented {
message: NotImplementedMessage::Reason("Flow not supported".to_string()),
}
.into())
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 29,
"total_crates": null
} |
fn_clm_router_add_access_token_-6710354682619637456 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/flows/update_metadata_flow
// Implementation of types::RouterData<
api::UpdateMetadata,
types::PaymentsUpdateMetadataData,
types::PaymentsResponseData,
> for Feature<api::UpdateMetadata, types::PaymentsUpdateMetadataData>
async fn add_access_token<'a>(
&self,
state: &SessionState,
connector: &api::ConnectorData,
merchant_context: &domain::MerchantContext,
creds_identifier: Option<&str>,
) -> RouterResult<types::AddAccessTokenResult> {
Box::pin(access_token::add_access_token(
state,
connector,
merchant_context,
self,
creds_identifier,
))
.await
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 84,
"total_crates": null
} |
fn_clm_router_construct_router_data_-6710354682619637456 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/flows/update_metadata_flow
// Implementation of PaymentData<api::UpdateMetadata> for ConstructFlowSpecificData<
api::UpdateMetadata,
types::PaymentsUpdateMetadataData,
types::PaymentsResponseData,
>
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
merchant_context: &domain::MerchantContext,
customer: &Option<domain::Customer>,
merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
) -> RouterResult<types::PaymentsUpdateMetadataRouterData> {
todo!()
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 47,
"total_crates": null
} |
fn_clm_router_decide_flows_-6710354682619637456 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/flows/update_metadata_flow
// Implementation of types::RouterData<
api::UpdateMetadata,
types::PaymentsUpdateMetadataData,
types::PaymentsResponseData,
> for Feature<api::UpdateMetadata, types::PaymentsUpdateMetadataData>
async fn decide_flows<'a>(
self,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
connector_request: Option<services::Request>,
_business_profile: &domain::Profile,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
return_raw_connector_response: Option<bool>,
) -> RouterResult<Self> {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::UpdateMetadata,
types::PaymentsUpdateMetadataData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
let resp = services::execute_connector_processing_step(
state,
connector_integration,
&self,
call_connector_action,
connector_request,
return_raw_connector_response,
)
.await
.to_payment_failed_response()?;
Ok(resp)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 29,
"total_crates": null
} |
fn_clm_router_build_flow_specific_connector_request_-6710354682619637456 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/flows/update_metadata_flow
// Implementation of types::RouterData<
api::UpdateMetadata,
types::PaymentsUpdateMetadataData,
types::PaymentsResponseData,
> for Feature<api::UpdateMetadata, types::PaymentsUpdateMetadataData>
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::UpdateMetadata,
types::PaymentsUpdateMetadataData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
connector_integration
.build_request(self, &state.conf.connectors)
.to_payment_failed_response()?
}
_ => None,
};
Ok((request, true))
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 29,
"total_crates": null
} |
fn_clm_router_call_unified_connector_service_with_external_vault_proxy_-7952569934817741737 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/flows/external_proxy_flow
// Implementation of types::ExternalVaultProxyPaymentsRouterData for Feature<api::ExternalVaultProxy, types::ExternalVaultProxyPaymentsData>
async fn call_unified_connector_service_with_external_vault_proxy<'a>(
&mut self,
state: &SessionState,
header_payload: &domain_payments::HeaderPayload,
lineage_ids: grpc_client::LineageIds,
merchant_connector_account: domain::MerchantConnectorAccountTypeDetails,
external_vault_merchant_connector_account: domain::MerchantConnectorAccountTypeDetails,
merchant_context: &domain::MerchantContext,
unified_connector_service_execution_mode: enums::ExecutionMode,
) -> RouterResult<()> {
let client = state
.grpc_client
.unified_connector_service_client
.clone()
.ok_or(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to fetch Unified Connector Service client")?;
let payment_authorize_request =
payments_grpc::PaymentServiceAuthorizeRequest::foreign_try_from(&*self)
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to construct Payment Authorize Request")?;
let connector_auth_metadata =
unified_connector_service::build_unified_connector_service_auth_metadata(
merchant_connector_account,
merchant_context,
)
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to construct request metadata")?;
let external_vault_proxy_metadata =
unified_connector_service::build_unified_connector_service_external_vault_proxy_metadata(
external_vault_merchant_connector_account
)
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to construct external vault proxy metadata")?;
let merchant_order_reference_id = header_payload
.x_reference_id
.clone()
.map(|id| id_type::PaymentReferenceId::from_str(id.as_str()))
.transpose()
.inspect_err(|err| logger::warn!(error=?err, "Invalid Merchant ReferenceId found"))
.ok()
.flatten()
.map(ucs_types::UcsReferenceId::Payment);
let headers_builder = state
.get_grpc_headers_ucs(unified_connector_service_execution_mode)
.external_vault_proxy_metadata(Some(external_vault_proxy_metadata))
.merchant_reference_id(merchant_order_reference_id)
.lineage_ids(lineage_ids);
let updated_router_data = Box::pin(ucs_logging_wrapper(
self.clone(),
state,
payment_authorize_request.clone(),
headers_builder,
|mut router_data, payment_authorize_request, grpc_headers| async move {
let response = client
.payment_authorize(
payment_authorize_request,
connector_auth_metadata,
grpc_headers,
)
.await
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to authorize payment")?;
let payment_authorize_response = response.into_inner();
let (router_data_response, status_code) =
unified_connector_service::handle_unified_connector_service_response_for_payment_authorize(
payment_authorize_response.clone(),
)
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to deserialize UCS response")?;
let router_data_response = router_data_response.map(|(response, status)|{
router_data.status = status;
response
});
router_data.response = router_data_response;
router_data.raw_connector_response = payment_authorize_response
.raw_connector_response
.clone()
.map(masking::Secret::new);
router_data.connector_http_status_code = Some(status_code);
Ok((router_data, payment_authorize_response))
}
)).await?;
// Copy back the updated data
*self = updated_router_data;
Ok(())
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 91,
"total_crates": null
} |
fn_clm_router_add_access_token_-7952569934817741737 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/flows/external_proxy_flow
// Implementation of types::ExternalVaultProxyPaymentsRouterData for Feature<api::ExternalVaultProxy, types::ExternalVaultProxyPaymentsData>
async fn add_access_token<'a>(
&self,
state: &SessionState,
connector: &api::ConnectorData,
merchant_context: &domain::MerchantContext,
creds_identifier: Option<&str>,
) -> RouterResult<types::AddAccessTokenResult> {
access_token::add_access_token(state, connector, merchant_context, self, creds_identifier)
.await
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 82,
"total_crates": null
} |
fn_clm_router_construct_router_data_-7952569934817741737 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/flows/external_proxy_flow
// Implementation of PaymentConfirmData<api::ExternalVaultProxy> for ConstructFlowSpecificData<
api::ExternalVaultProxy,
types::ExternalVaultProxyPaymentsData,
types::PaymentsResponseData,
>
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
merchant_context: &domain::MerchantContext,
customer: &Option<domain::Customer>,
merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<domain_payments::HeaderPayload>,
) -> RouterResult<
types::RouterData<
api::ExternalVaultProxy,
types::ExternalVaultProxyPaymentsData,
types::PaymentsResponseData,
>,
> {
Box::pin(
transformers::construct_external_vault_proxy_payment_router_data(
state,
self.clone(),
connector_id,
merchant_context,
customer,
merchant_connector_account,
merchant_recipient_data,
header_payload,
),
)
.await
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 53,
"total_crates": null
} |
fn_clm_router_build_flow_specific_connector_request_-7952569934817741737 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/flows/external_proxy_flow
// Implementation of types::ExternalVaultProxyPaymentsRouterData for Feature<api::ExternalVaultProxy, types::ExternalVaultProxyPaymentsData>
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 => {
connector
.connector
.validate_connector_against_payment_request(
self.request.capture_method,
self.payment_method,
self.request.payment_method_type,
)
.to_payment_failed_response()?;
// Check if the connector supports mandate payment
// if the payment_method_type does not support mandate for the given connector, downgrade the setup future usage to on session
if self.request.setup_future_usage
== Some(diesel_models::enums::FutureUsage::OffSession)
&& !self
.request
.payment_method_type
.and_then(|payment_method_type| {
state
.conf
.mandates
.supported_payment_methods
.0
.get(&enums::PaymentMethod::from(payment_method_type))
.and_then(|supported_pm_for_mandates| {
supported_pm_for_mandates.0.get(&payment_method_type).map(
|supported_connector_for_mandates| {
supported_connector_for_mandates
.connector_list
.contains(&connector.connector_name)
},
)
})
})
.unwrap_or(false)
{
// downgrade the setup future usage to on session
self.request.setup_future_usage =
Some(diesel_models::enums::FutureUsage::OnSession);
};
// External vault proxy doesn't use regular payment method validation
// Skip mandate payment validation for external vault proxy
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::ExternalVaultProxy,
types::ExternalVaultProxyPaymentsData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
metrics::EXECUTE_PRETASK_COUNT.add(
1,
router_env::metric_attributes!(
("connector", connector.connector_name.to_string()),
("flow", format!("{:?}", api::ExternalVaultProxy)),
),
);
logger::debug!(completed_pre_tasks=?true);
// External vault proxy always proceeds
Ok((
connector_integration
.build_request(self, &state.conf.connectors)
.to_payment_failed_response()?,
true,
))
}
_ => Ok((None, true)),
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 51,
"total_crates": null
} |
fn_clm_router_preprocessing_steps_-7952569934817741737 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/flows/external_proxy_flow
// Implementation of types::ExternalVaultProxyPaymentsRouterData for Feature<api::ExternalVaultProxy, types::ExternalVaultProxyPaymentsData>
async fn preprocessing_steps<'a>(
self,
state: &SessionState,
connector: &api::ConnectorData,
) -> RouterResult<Self> {
todo!()
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 47,
"total_crates": null
} |
fn_clm_router_add_access_token_9181400992718385718 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/flows/incremental_authorization_flow
// Implementation of types::RouterData<
api::IncrementalAuthorization,
types::PaymentsIncrementalAuthorizationData,
types::PaymentsResponseData,
> for Feature<api::IncrementalAuthorization, types::PaymentsIncrementalAuthorizationData>
async fn add_access_token<'a>(
&self,
state: &SessionState,
connector: &api::ConnectorData,
merchant_context: &domain::MerchantContext,
creds_identifier: Option<&str>,
) -> RouterResult<types::AddAccessTokenResult> {
Box::pin(access_token::add_access_token(
state,
connector,
merchant_context,
self,
creds_identifier,
))
.await
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 84,
"total_crates": null
} |
fn_clm_router_construct_router_data_9181400992718385718 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/flows/incremental_authorization_flow
// Implementation of PaymentData<api::IncrementalAuthorization> for ConstructFlowSpecificData<
api::IncrementalAuthorization,
types::PaymentsIncrementalAuthorizationData,
types::PaymentsResponseData,
>
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
merchant_context: &domain::MerchantContext,
customer: &Option<domain::Customer>,
merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
) -> RouterResult<types::PaymentsIncrementalAuthorizationRouterData> {
todo!()
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 47,
"total_crates": null
} |
fn_clm_router_decide_flows_9181400992718385718 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/flows/incremental_authorization_flow
// Implementation of types::RouterData<
api::IncrementalAuthorization,
types::PaymentsIncrementalAuthorizationData,
types::PaymentsResponseData,
> for Feature<api::IncrementalAuthorization, types::PaymentsIncrementalAuthorizationData>
async fn decide_flows<'a>(
self,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
connector_request: Option<services::Request>,
_business_profile: &domain::Profile,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
_return_raw_connector_response: Option<bool>,
) -> RouterResult<Self> {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::IncrementalAuthorization,
types::PaymentsIncrementalAuthorizationData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
let resp = services::execute_connector_processing_step(
state,
connector_integration,
&self,
call_connector_action,
connector_request,
None,
)
.await
.to_payment_failed_response()?;
Ok(resp)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 29,
"total_crates": null
} |
fn_clm_router_build_flow_specific_connector_request_9181400992718385718 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/flows/incremental_authorization_flow
// Implementation of types::RouterData<
api::IncrementalAuthorization,
types::PaymentsIncrementalAuthorizationData,
types::PaymentsResponseData,
> for Feature<api::IncrementalAuthorization, types::PaymentsIncrementalAuthorizationData>
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::IncrementalAuthorization,
types::PaymentsIncrementalAuthorizationData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
connector_integration
.build_request(self, &state.conf.connectors)
.to_payment_failed_response()?
}
_ => None,
};
Ok((request, true))
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 29,
"total_crates": null
} |
fn_clm_router_add_access_token_9157555930035817544 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/flows/extend_authorization_flow
// Implementation of types::RouterData<
api::ExtendAuthorization,
types::PaymentsExtendAuthorizationData,
types::PaymentsResponseData,
> for Feature<api::ExtendAuthorization, types::PaymentsExtendAuthorizationData>
async fn add_access_token<'a>(
&self,
state: &SessionState,
connector: &api::ConnectorData,
merchant_context: &domain::MerchantContext,
creds_identifier: Option<&str>,
) -> RouterResult<types::AddAccessTokenResult> {
Box::pin(access_token::add_access_token(
state,
connector,
merchant_context,
self,
creds_identifier,
))
.await
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 84,
"total_crates": null
} |
fn_clm_router_construct_router_data_9157555930035817544 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/flows/extend_authorization_flow
// Implementation of PaymentData<api::ExtendAuthorization> for ConstructFlowSpecificData<
api::ExtendAuthorization,
types::PaymentsExtendAuthorizationData,
types::PaymentsResponseData,
>
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
merchant_context: &domain::MerchantContext,
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
_payment_method: Option<common_enums::PaymentMethod>,
_payment_method_type: Option<common_enums::PaymentMethodType>,
) -> RouterResult<types::PaymentsExtendAuthorizationRouterData> {
Box::pin(transformers::construct_payment_router_data::<
api::ExtendAuthorization,
types::PaymentsExtendAuthorizationData,
>(
state,
self.clone(),
connector_id,
merchant_context,
customer,
merchant_connector_account,
merchant_recipient_data,
header_payload,
None,
None,
))
.await
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 51,
"total_crates": null
} |
fn_clm_router_decide_flows_9157555930035817544 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/flows/extend_authorization_flow
// Implementation of types::RouterData<
api::ExtendAuthorization,
types::PaymentsExtendAuthorizationData,
types::PaymentsResponseData,
> for Feature<api::ExtendAuthorization, types::PaymentsExtendAuthorizationData>
async fn decide_flows<'a>(
self,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
connector_request: Option<services::Request>,
_business_profile: &domain::Profile,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
_return_raw_connector_response: Option<bool>,
) -> RouterResult<Self> {
metrics::PAYMENT_EXTEND_AUTHORIZATION_COUNT.add(
1,
router_env::metric_attributes!(("connector", connector.connector_name.to_string())),
);
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::ExtendAuthorization,
types::PaymentsExtendAuthorizationData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
let resp = services::execute_connector_processing_step(
state,
connector_integration,
&self,
call_connector_action,
connector_request,
None,
)
.await
.to_payment_failed_response()?;
Ok(resp)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 31,
"total_crates": null
} |
fn_clm_router_build_flow_specific_connector_request_9157555930035817544 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/flows/extend_authorization_flow
// Implementation of types::RouterData<
api::ExtendAuthorization,
types::PaymentsExtendAuthorizationData,
types::PaymentsResponseData,
> for Feature<api::ExtendAuthorization, types::PaymentsExtendAuthorizationData>
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::ExtendAuthorization,
types::PaymentsExtendAuthorizationData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
connector_integration
.build_request(self, &state.conf.connectors)
.to_payment_failed_response()?
}
_ => None,
};
Ok((request, true))
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 29,
"total_crates": null
} |
fn_clm_router_create_applepay_session_token_874664424121257062 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/flows/session_flow
async fn create_applepay_session_token(
state: &routes::SessionState,
router_data: &types::PaymentsSessionRouterData,
connector: &api::ConnectorData,
business_profile: &domain::Profile,
header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<types::PaymentsSessionRouterData> {
let delayed_response = is_session_response_delayed(state, connector);
if delayed_response {
let delayed_response_apple_pay_session =
Some(payment_types::ApplePaySessionResponse::NoSessionResponse(
api_models::payments::NullObject,
));
create_apple_pay_session_response(
router_data,
delayed_response_apple_pay_session,
None, // Apple pay payment request will be none for delayed session response
connector.connector_name.to_string(),
delayed_response,
payment_types::NextActionCall::Confirm,
header_payload,
)
} else {
// Get the apple pay metadata
let apple_pay_metadata =
helpers::get_applepay_metadata(router_data.connector_meta_data.clone())
.attach_printable(
"Failed to to fetch apple pay certificates during session call",
)?;
// Get payment request data , apple pay session request and merchant keys
let (
payment_request_data,
apple_pay_session_request_optional,
apple_pay_merchant_cert,
apple_pay_merchant_cert_key,
apple_pay_merchant_identifier,
merchant_business_country,
merchant_configured_domain_optional,
) = match apple_pay_metadata {
payment_types::ApplepaySessionTokenMetadata::ApplePayCombined(
apple_pay_combined_metadata,
) => match apple_pay_combined_metadata {
payment_types::ApplePayCombinedMetadata::Simplified {
payment_request_data,
session_token_data,
} => {
logger::info!("Apple pay simplified flow");
let merchant_identifier = state
.conf
.applepay_merchant_configs
.get_inner()
.common_merchant_identifier
.clone()
.expose();
let merchant_business_country = session_token_data.merchant_business_country;
let apple_pay_session_request = get_session_request_for_simplified_apple_pay(
merchant_identifier.clone(),
session_token_data.clone(),
);
let apple_pay_merchant_cert = state
.conf
.applepay_decrypt_keys
.get_inner()
.apple_pay_merchant_cert
.clone();
let apple_pay_merchant_cert_key = state
.conf
.applepay_decrypt_keys
.get_inner()
.apple_pay_merchant_cert_key
.clone();
(
payment_request_data,
Ok(apple_pay_session_request),
apple_pay_merchant_cert,
apple_pay_merchant_cert_key,
merchant_identifier,
merchant_business_country,
Some(session_token_data.initiative_context),
)
}
payment_types::ApplePayCombinedMetadata::Manual {
payment_request_data,
session_token_data,
} => {
logger::info!("Apple pay manual flow");
let apple_pay_session_request = get_session_request_for_manual_apple_pay(
session_token_data.clone(),
header_payload.x_merchant_domain.clone(),
);
let merchant_business_country = session_token_data.merchant_business_country;
(
payment_request_data,
apple_pay_session_request,
session_token_data.certificate.clone(),
session_token_data.certificate_keys,
session_token_data.merchant_identifier,
merchant_business_country,
session_token_data.initiative_context,
)
}
},
payment_types::ApplepaySessionTokenMetadata::ApplePay(apple_pay_metadata) => {
logger::info!("Apple pay manual flow");
let apple_pay_session_request = get_session_request_for_manual_apple_pay(
apple_pay_metadata.session_token_data.clone(),
header_payload.x_merchant_domain.clone(),
);
let merchant_business_country = apple_pay_metadata
.session_token_data
.merchant_business_country;
(
apple_pay_metadata.payment_request_data,
apple_pay_session_request,
apple_pay_metadata.session_token_data.certificate.clone(),
apple_pay_metadata
.session_token_data
.certificate_keys
.clone(),
apple_pay_metadata.session_token_data.merchant_identifier,
merchant_business_country,
apple_pay_metadata.session_token_data.initiative_context,
)
}
};
// Get amount info for apple pay
let amount_info = get_apple_pay_amount_info(
payment_request_data.label.as_str(),
router_data.request.to_owned(),
)?;
let required_billing_contact_fields = if business_profile
.always_collect_billing_details_from_wallet_connector
.unwrap_or(false)
{
Some(payment_types::ApplePayBillingContactFields(vec![
payment_types::ApplePayAddressParameters::PostalAddress,
]))
} else if business_profile
.collect_billing_details_from_wallet_connector
.unwrap_or(false)
{
let billing_variants = enums::FieldType::get_billing_variants();
is_dynamic_fields_required(
&state.conf.required_fields,
enums::PaymentMethod::Wallet,
enums::PaymentMethodType::ApplePay,
connector.connector_name,
billing_variants,
)
.then_some(payment_types::ApplePayBillingContactFields(vec![
payment_types::ApplePayAddressParameters::PostalAddress,
]))
} else {
None
};
let required_shipping_contact_fields = if business_profile
.always_collect_shipping_details_from_wallet_connector
.unwrap_or(false)
{
Some(payment_types::ApplePayShippingContactFields(vec![
payment_types::ApplePayAddressParameters::PostalAddress,
payment_types::ApplePayAddressParameters::Phone,
payment_types::ApplePayAddressParameters::Email,
]))
} else if business_profile
.collect_shipping_details_from_wallet_connector
.unwrap_or(false)
{
let shipping_variants = enums::FieldType::get_shipping_variants();
is_dynamic_fields_required(
&state.conf.required_fields,
enums::PaymentMethod::Wallet,
enums::PaymentMethodType::ApplePay,
connector.connector_name,
shipping_variants,
)
.then_some(payment_types::ApplePayShippingContactFields(vec![
payment_types::ApplePayAddressParameters::PostalAddress,
payment_types::ApplePayAddressParameters::Phone,
payment_types::ApplePayAddressParameters::Email,
]))
} else {
None
};
// If collect_shipping_details_from_wallet_connector is false, we check if
// collect_billing_details_from_wallet_connector is true. If it is, then we pass the Email and Phone in
// ApplePayShippingContactFields as it is a required parameter and ApplePayBillingContactFields
// does not contain Email and Phone.
let required_shipping_contact_fields_updated = if required_billing_contact_fields.is_some()
&& required_shipping_contact_fields.is_none()
{
Some(payment_types::ApplePayShippingContactFields(vec![
payment_types::ApplePayAddressParameters::Phone,
payment_types::ApplePayAddressParameters::Email,
]))
} else {
required_shipping_contact_fields
};
// Get apple pay payment request
let applepay_payment_request = get_apple_pay_payment_request(
amount_info,
payment_request_data,
router_data.request.to_owned(),
apple_pay_merchant_identifier.as_str(),
merchant_business_country,
required_billing_contact_fields,
required_shipping_contact_fields_updated,
)?;
let apple_pay_session_response = match (
header_payload.browser_name.clone(),
header_payload.x_client_platform.clone(),
) {
(Some(common_enums::BrowserName::Safari), Some(common_enums::ClientPlatform::Web))
| (None, None) => {
let apple_pay_session_request = apple_pay_session_request_optional
.attach_printable("Failed to obtain apple pay session request")?;
let applepay_session_request = build_apple_pay_session_request(
state,
apple_pay_session_request.clone(),
apple_pay_merchant_cert.clone(),
apple_pay_merchant_cert_key.clone(),
)?;
let response = services::call_connector_api(
state,
applepay_session_request,
"create_apple_pay_session_token",
)
.await;
let updated_response = match (
response.as_ref().ok(),
header_payload.x_merchant_domain.clone(),
) {
(Some(Err(error)), Some(_)) => {
logger::error!(
"Retry apple pay session call with the merchant configured domain {error:?}"
);
let merchant_configured_domain = merchant_configured_domain_optional
.get_required_value("apple pay domain")
.attach_printable("Failed to get domain for apple pay session call")?;
let apple_pay_retry_session_request =
payment_types::ApplepaySessionRequest {
initiative_context: merchant_configured_domain,
..apple_pay_session_request
};
let applepay_retry_session_request = build_apple_pay_session_request(
state,
apple_pay_retry_session_request,
apple_pay_merchant_cert,
apple_pay_merchant_cert_key,
)?;
services::call_connector_api(
state,
applepay_retry_session_request,
"create_apple_pay_session_token",
)
.await
}
_ => response,
};
// logging the error if present in session call response
log_session_response_if_error(&updated_response);
updated_response
.ok()
.and_then(|apple_pay_res| {
apple_pay_res
.map(|res| {
let response: Result<
payment_types::NoThirdPartySdkSessionResponse,
Report<common_utils::errors::ParsingError>,
> = res.response.parse_struct("NoThirdPartySdkSessionResponse");
// logging the parsing failed error
if let Err(error) = response.as_ref() {
logger::error!(?error);
};
response.ok()
})
.ok()
})
.flatten()
}
_ => {
logger::debug!("Skipping apple pay session call based on the browser name");
None
}
};
let session_response =
apple_pay_session_response.map(payment_types::ApplePaySessionResponse::NoThirdPartySdk);
create_apple_pay_session_response(
router_data,
session_response,
Some(applepay_payment_request),
connector.connector_name.to_string(),
delayed_response,
payment_types::NextActionCall::Confirm,
header_payload,
)
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 155,
"total_crates": null
} |
fn_clm_router_create_gpay_session_token_874664424121257062 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/flows/session_flow
fn create_gpay_session_token(
state: &routes::SessionState,
router_data: &types::PaymentsSessionRouterData,
connector: &api::ConnectorData,
business_profile: &domain::Profile,
) -> RouterResult<types::PaymentsSessionRouterData> {
// connector_wallet_details is being parse into admin types to check specifically if google_pay field is present
// this is being done because apple_pay details from metadata is also being filled into connector_wallets_details
let google_pay_wallets_details = router_data
.connector_wallets_details
.clone()
.parse_value::<admin_types::ConnectorWalletDetails>("ConnectorWalletDetails")
.change_context(errors::ConnectorError::NoConnectorWalletDetails)
.attach_printable(format!(
"cannot parse connector_wallets_details from the given value {:?}",
router_data.connector_wallets_details
))
.map_err(|err| {
logger::debug!(
"Failed to parse connector_wallets_details for google_pay flow: {:?}",
err
);
})
.ok()
.and_then(|connector_wallets_details| connector_wallets_details.google_pay);
let connector_metadata = router_data.connector_meta_data.clone();
let delayed_response = is_session_response_delayed(state, connector);
if delayed_response {
Ok(types::PaymentsSessionRouterData {
response: Ok(types::PaymentsResponseData::SessionResponse {
session_token: payment_types::SessionToken::GooglePay(Box::new(
payment_types::GpaySessionTokenResponse::ThirdPartyResponse(
payment_types::GooglePayThirdPartySdk {
delayed_session_token: true,
connector: connector.connector_name.to_string(),
sdk_next_action: payment_types::SdkNextAction {
next_action: payment_types::NextActionCall::Confirm,
},
},
),
)),
}),
..router_data.clone()
})
} else {
let is_billing_details_required = is_billing_address_required_to_be_collected_from_wallet(
state,
connector,
business_profile,
enums::PaymentMethodType::GooglePay,
);
let required_amount_type = StringMajorUnitForConnector;
let google_pay_amount = required_amount_type
.convert(
router_data.request.minor_amount,
router_data.request.currency,
)
.change_context(errors::ApiErrorResponse::PreconditionFailed {
message: "Failed to convert amount to string major unit for googlePay".to_string(),
})?;
let session_data = router_data.request.clone();
let transaction_info = payment_types::GpayTransactionInfo {
country_code: session_data.country.unwrap_or_default(),
currency_code: router_data.request.currency,
total_price_status: "Final".to_string(),
total_price: google_pay_amount,
};
let required_shipping_contact_fields =
is_shipping_address_required_to_be_collected_form_wallet(
state,
connector,
business_profile,
enums::PaymentMethodType::GooglePay,
);
if google_pay_wallets_details.is_some() {
let gpay_data = router_data
.connector_wallets_details
.clone()
.parse_value::<payment_types::GooglePayWalletDetails>("GooglePayWalletDetails")
.change_context(errors::ConnectorError::NoConnectorWalletDetails)
.attach_printable(format!(
"cannot parse gpay connector_wallets_details from the given value {:?}",
router_data.connector_wallets_details
))
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "connector_wallets_details".to_string(),
expected_format: "gpay_connector_wallets_details_format".to_string(),
})?;
let payment_types::GooglePayProviderDetails::GooglePayMerchantDetails(gpay_info) =
gpay_data.google_pay.provider_details.clone();
let gpay_allowed_payment_methods = get_allowed_payment_methods_from_cards(
gpay_data,
&gpay_info.merchant_info.tokenization_specification,
is_billing_details_required,
)?;
Ok(types::PaymentsSessionRouterData {
response: Ok(types::PaymentsResponseData::SessionResponse {
session_token: payment_types::SessionToken::GooglePay(Box::new(
payment_types::GpaySessionTokenResponse::GooglePaySession(
payment_types::GooglePaySessionResponse {
merchant_info: payment_types::GpayMerchantInfo {
merchant_name: gpay_info.merchant_info.merchant_name,
merchant_id: gpay_info.merchant_info.merchant_id,
},
allowed_payment_methods: vec![gpay_allowed_payment_methods],
transaction_info,
connector: connector.connector_name.to_string(),
sdk_next_action: payment_types::SdkNextAction {
next_action: payment_types::NextActionCall::Confirm,
},
delayed_session_token: false,
secrets: None,
shipping_address_required: required_shipping_contact_fields,
// We pass Email as a required field irrespective of
// collect_billing_details_from_wallet_connector or
// collect_shipping_details_from_wallet_connector as it is common to both.
email_required: required_shipping_contact_fields
|| is_billing_details_required,
shipping_address_parameters:
api_models::payments::GpayShippingAddressParameters {
phone_number_required: required_shipping_contact_fields,
},
},
),
)),
}),
..router_data.clone()
})
} else {
let billing_address_parameters = is_billing_details_required.then_some(
payment_types::GpayBillingAddressParameters {
phone_number_required: is_billing_details_required,
format: payment_types::GpayBillingAddressFormat::FULL,
},
);
let gpay_data = connector_metadata
.clone()
.parse_value::<payment_types::GpaySessionTokenData>("GpaySessionTokenData")
.change_context(errors::ConnectorError::NoConnectorMetaData)
.attach_printable(format!(
"cannot parse gpay metadata from the given value {connector_metadata:?}"
))
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "connector_metadata".to_string(),
expected_format: "gpay_metadata_format".to_string(),
})?;
let gpay_allowed_payment_methods = gpay_data
.data
.allowed_payment_methods
.into_iter()
.map(
|allowed_payment_methods| payment_types::GpayAllowedPaymentMethods {
parameters: payment_types::GpayAllowedMethodsParameters {
billing_address_required: Some(is_billing_details_required),
billing_address_parameters: billing_address_parameters.clone(),
..allowed_payment_methods.parameters
},
..allowed_payment_methods
},
)
.collect();
Ok(types::PaymentsSessionRouterData {
response: Ok(types::PaymentsResponseData::SessionResponse {
session_token: payment_types::SessionToken::GooglePay(Box::new(
payment_types::GpaySessionTokenResponse::GooglePaySession(
payment_types::GooglePaySessionResponse {
merchant_info: gpay_data.data.merchant_info,
allowed_payment_methods: gpay_allowed_payment_methods,
transaction_info,
connector: connector.connector_name.to_string(),
sdk_next_action: payment_types::SdkNextAction {
next_action: payment_types::NextActionCall::Confirm,
},
delayed_session_token: false,
secrets: None,
shipping_address_required: required_shipping_contact_fields,
// We pass Email as a required field irrespective of
// collect_billing_details_from_wallet_connector or
// collect_shipping_details_from_wallet_connector as it is common to both.
email_required: required_shipping_contact_fields
|| is_billing_details_required,
shipping_address_parameters:
api_models::payments::GpayShippingAddressParameters {
phone_number_required: required_shipping_contact_fields,
},
},
),
)),
}),
..router_data.clone()
})
}
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 105,
"total_crates": null
} |
fn_clm_router_create_amazon_pay_session_token_874664424121257062 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/flows/session_flow
async fn create_amazon_pay_session_token(
router_data: &types::PaymentsSessionRouterData,
state: &routes::SessionState,
) -> RouterResult<types::PaymentsSessionRouterData> {
let amazon_pay_session_token_data = router_data
.connector_wallets_details
.clone()
.parse_value::<payment_types::AmazonPaySessionTokenData>("AmazonPaySessionTokenData")
.change_context(errors::ApiErrorResponse::MissingRequiredField {
field_name: "merchant_id or store_id",
})?;
let amazon_pay_metadata = amazon_pay_session_token_data.data;
let merchant_id = amazon_pay_metadata.merchant_id;
let store_id = amazon_pay_metadata.store_id;
let amazonpay_supported_currencies =
payments::cards::list_countries_currencies_for_connector_payment_method_util(
state.conf.pm_filters.clone(),
enums::Connector::Amazonpay,
enums::PaymentMethodType::AmazonPay,
)
.await
.currencies;
// currently supports only the US region hence USD is the only supported currency
payment_types::AmazonPayDeliveryOptions::validate_currency(
router_data.request.currency,
amazonpay_supported_currencies.clone(),
)
.change_context(errors::ApiErrorResponse::CurrencyNotSupported {
message: "USD is the only supported currency.".to_string(),
})?;
let ledger_currency = router_data.request.currency;
// currently supports only the 'automatic' capture_method
let payment_intent = payment_types::AmazonPayPaymentIntent::AuthorizeWithCapture;
let required_amount_type = StringMajorUnitForConnector;
let total_tax_amount = required_amount_type
.convert(
router_data.request.order_tax_amount.unwrap_or_default(),
router_data.request.currency,
)
.change_context(errors::ApiErrorResponse::AmountConversionFailed {
amount_type: "StringMajorUnit",
})?;
let total_base_amount = required_amount_type
.convert(
router_data.request.minor_amount,
router_data.request.currency,
)
.change_context(errors::ApiErrorResponse::AmountConversionFailed {
amount_type: "StringMajorUnit",
})?;
let delivery_options_request = router_data
.request
.metadata
.clone()
.and_then(|metadata| {
metadata
.expose()
.get("delivery_options")
.and_then(|value| value.as_array().cloned())
})
.ok_or(errors::ApiErrorResponse::MissingRequiredField {
field_name: "metadata.delivery_options",
})?;
let mut delivery_options =
payment_types::AmazonPayDeliveryOptions::parse_delivery_options_request(
&delivery_options_request,
)
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "delivery_options".to_string(),
expected_format: r#""delivery_options": [{"id": String, "price": {"amount": Number, "currency_code": String}, "shipping_method":{"shipping_method_name": String, "shipping_method_code": String}, "is_default": Boolean}]"#.to_string(),
})?;
let default_amount = payment_types::AmazonPayDeliveryOptions::get_default_delivery_amount(
delivery_options.clone(),
)
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "is_default",
})?;
for option in &delivery_options {
payment_types::AmazonPayDeliveryOptions::validate_currency(
option.price.currency_code,
amazonpay_supported_currencies.clone(),
)
.change_context(errors::ApiErrorResponse::CurrencyNotSupported {
message: "USD is the only supported currency.".to_string(),
})?;
}
payment_types::AmazonPayDeliveryOptions::insert_display_amount(
&mut delivery_options,
router_data.request.currency,
)
.change_context(errors::ApiErrorResponse::AmountConversionFailed {
amount_type: "StringMajorUnit",
})?;
let total_shipping_amount = match router_data.request.shipping_cost {
Some(shipping_cost) => {
if shipping_cost == default_amount {
required_amount_type
.convert(shipping_cost, router_data.request.currency)
.change_context(errors::ApiErrorResponse::AmountConversionFailed {
amount_type: "StringMajorUnit",
})?
} else {
return Err(errors::ApiErrorResponse::InvalidDataValue {
field_name: "shipping_cost",
})
.attach_printable(format!(
"Provided shipping_cost ({shipping_cost}) does not match the default delivery amount ({default_amount})"
));
}
}
None => {
return Err(errors::ApiErrorResponse::MissingRequiredField {
field_name: "shipping_cost",
}
.into());
}
};
Ok(types::PaymentsSessionRouterData {
response: Ok(types::PaymentsResponseData::SessionResponse {
session_token: payment_types::SessionToken::AmazonPay(Box::new(
payment_types::AmazonPaySessionTokenResponse {
merchant_id,
ledger_currency,
store_id,
payment_intent,
total_shipping_amount,
total_tax_amount,
total_base_amount,
delivery_options,
},
)),
}),
..router_data.clone()
})
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 85,
"total_crates": null
} |
fn_clm_router_add_access_token_874664424121257062 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/flows/session_flow
// Implementation of types::PaymentsSessionRouterData for Feature<api::Session, types::PaymentsSessionData>
async fn add_access_token<'a>(
&self,
state: &routes::SessionState,
connector: &api::ConnectorData,
merchant_context: &domain::MerchantContext,
creds_identifier: Option<&str>,
) -> RouterResult<types::AddAccessTokenResult> {
Box::pin(access_token::add_access_token(
state,
connector,
merchant_context,
self,
creds_identifier,
))
.await
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 84,
"total_crates": null
} |
fn_clm_router_construct_router_data_874664424121257062 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/flows/session_flow
// Implementation of PaymentData<api::Session> for ConstructFlowSpecificData<api::Session, types::PaymentsSessionData, types::PaymentsResponseData>
async fn construct_router_data<'a>(
&self,
state: &routes::SessionState,
connector_id: &str,
merchant_context: &domain::MerchantContext,
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
payment_method: Option<common_enums::PaymentMethod>,
payment_method_type: Option<common_enums::PaymentMethodType>,
) -> RouterResult<types::PaymentsSessionRouterData> {
Box::pin(transformers::construct_payment_router_data::<
api::Session,
types::PaymentsSessionData,
>(
state,
self.clone(),
connector_id,
merchant_context,
customer,
merchant_connector_account,
merchant_recipient_data,
header_payload,
payment_method,
payment_method_type,
))
.await
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 51,
"total_crates": null
} |
fn_clm_router_add_access_token_-2771427405472014672 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/flows/cancel_flow
// Implementation of types::RouterData<api::Void, types::PaymentsCancelData, types::PaymentsResponseData> for Feature<api::Void, types::PaymentsCancelData>
async fn add_access_token<'a>(
&self,
state: &SessionState,
connector: &api::ConnectorData,
merchant_context: &domain::MerchantContext,
creds_identifier: Option<&str>,
) -> RouterResult<types::AddAccessTokenResult> {
Box::pin(access_token::add_access_token(
state,
connector,
merchant_context,
self,
creds_identifier,
))
.await
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 84,
"total_crates": null
} |
fn_clm_router_construct_router_data_-2771427405472014672 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/flows/cancel_flow
// Implementation of hyperswitch_domain_models::payments::PaymentCancelData<api::Void> for ConstructFlowSpecificData<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
merchant_context: &domain::MerchantContext,
customer: &Option<domain::Customer>,
merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
) -> RouterResult<types::PaymentsCancelRouterData> {
Box::pin(transformers::construct_router_data_for_cancel(
state,
self.clone(),
connector_id,
merchant_context,
customer,
merchant_connector_account,
merchant_recipient_data,
header_payload,
))
.await
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 53,
"total_crates": null
} |
fn_clm_router_decide_flows_-2771427405472014672 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/flows/cancel_flow
// Implementation of types::RouterData<api::Void, types::PaymentsCancelData, types::PaymentsResponseData> for Feature<api::Void, types::PaymentsCancelData>
async fn decide_flows<'a>(
self,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
connector_request: Option<services::Request>,
_business_profile: &domain::Profile,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
_return_raw_connector_response: Option<bool>,
) -> RouterResult<Self> {
metrics::PAYMENT_CANCEL_COUNT.add(
1,
router_env::metric_attributes!(("connector", connector.connector_name.to_string())),
);
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::Void,
types::PaymentsCancelData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
let resp = services::execute_connector_processing_step(
state,
connector_integration,
&self,
call_connector_action,
connector_request,
None,
)
.await
.to_payment_failed_response()?;
Ok(resp)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 31,
"total_crates": null
} |
fn_clm_router_build_flow_specific_connector_request_-2771427405472014672 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/flows/cancel_flow
// Implementation of types::RouterData<api::Void, types::PaymentsCancelData, types::PaymentsResponseData> for Feature<api::Void, types::PaymentsCancelData>
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::Void,
types::PaymentsCancelData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
connector_integration
.build_request(self, &state.conf.connectors)
.to_payment_failed_response()?
}
_ => None,
};
Ok((request, true))
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 29,
"total_crates": null
} |
fn_clm_router_call_unified_connector_service_2066038552921865240 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/flows/psync_flow
// Implementation of types::RouterData<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> for Feature<api::PSync, types::PaymentsSyncData>
async fn call_unified_connector_service<'a>(
&mut self,
state: &SessionState,
header_payload: &domain_payments::HeaderPayload,
lineage_ids: grpc_client::LineageIds,
#[cfg(feature = "v1")] merchant_connector_account: helpers::MerchantConnectorAccountType,
#[cfg(feature = "v2")]
merchant_connector_account: domain::MerchantConnectorAccountTypeDetails,
merchant_context: &domain::MerchantContext,
unified_connector_service_execution_mode: enums::ExecutionMode,
) -> RouterResult<()> {
let connector_name = self.connector.clone();
let connector_enum = common_enums::connector_enums::Connector::from_str(&connector_name)
.change_context(ApiErrorResponse::IncorrectConnectorNameGiven)?;
let is_ucs_psync_disabled = state
.conf
.grpc_client
.unified_connector_service
.as_ref()
.is_some_and(|config| {
config
.ucs_psync_disabled_connectors
.contains(&connector_enum)
});
if is_ucs_psync_disabled {
logger::info!(
"UCS PSync call disabled for connector: {}, skipping UCS call",
connector_name
);
return Ok(());
}
let client = state
.grpc_client
.unified_connector_service_client
.clone()
.ok_or(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to fetch Unified Connector Service client")?;
let payment_get_request = payments_grpc::PaymentServiceGetRequest::foreign_try_from(&*self)
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to construct Payment Get Request")?;
let connector_auth_metadata = build_unified_connector_service_auth_metadata(
merchant_connector_account,
merchant_context,
)
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to construct request metadata")?;
let merchant_reference_id = header_payload
.x_reference_id
.clone()
.map(|id| id_type::PaymentReferenceId::from_str(id.as_str()))
.transpose()
.inspect_err(|err| logger::warn!(error=?err, "Invalid Merchant ReferenceId found"))
.ok()
.flatten()
.map(ucs_types::UcsReferenceId::Payment);
let header_payload = state
.get_grpc_headers_ucs(unified_connector_service_execution_mode)
.external_vault_proxy_metadata(None)
.merchant_reference_id(merchant_reference_id)
.lineage_ids(lineage_ids);
let updated_router_data = Box::pin(ucs_logging_wrapper(
self.clone(),
state,
payment_get_request,
header_payload,
|mut router_data, payment_get_request, grpc_headers| async move {
let response = client
.payment_get(payment_get_request, connector_auth_metadata, grpc_headers)
.await
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get payment")?;
let payment_get_response = response.into_inner();
let (router_data_response, status_code) =
handle_unified_connector_service_response_for_payment_get(
payment_get_response.clone(),
)
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to deserialize UCS response")?;
let router_data_response = router_data_response.map(|(response, status)| {
router_data.status = status;
response
});
router_data.response = router_data_response;
router_data.raw_connector_response = payment_get_response
.raw_connector_response
.clone()
.map(Secret::new);
router_data.connector_http_status_code = Some(status_code);
Ok((router_data, payment_get_response))
},
))
.await?;
// Copy back the updated data
*self = updated_router_data;
Ok(())
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 104,
"total_crates": null
} |
fn_clm_router_add_access_token_2066038552921865240 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/flows/psync_flow
// Implementation of types::RouterData<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> for Feature<api::PSync, types::PaymentsSyncData>
async fn add_access_token<'a>(
&self,
state: &SessionState,
connector: &api::ConnectorData,
merchant_context: &domain::MerchantContext,
creds_identifier: Option<&str>,
) -> RouterResult<types::AddAccessTokenResult> {
Box::pin(access_token::add_access_token(
state,
connector,
merchant_context,
self,
creds_identifier,
))
.await
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 84,
"total_crates": null
} |
fn_clm_router_construct_router_data_2066038552921865240 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/flows/psync_flow
// Implementation of hyperswitch_domain_models::payments::PaymentStatusData<api::PSync> for ConstructFlowSpecificData<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
merchant_context: &domain::MerchantContext,
customer: &Option<domain::Customer>,
merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<domain_payments::HeaderPayload>,
) -> RouterResult<
types::RouterData<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>,
> {
Box::pin(transformers::construct_router_data_for_psync(
state,
self.clone(),
connector_id,
merchant_context,
customer,
merchant_connector_account,
merchant_recipient_data,
header_payload,
))
.await
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 53,
"total_crates": null
} |
fn_clm_router_execute_connector_processing_step_for_each_capture_2066038552921865240 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/flows/psync_flow
// Implementation of types::RouterData<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> for RouterDataPSync
async fn execute_connector_processing_step_for_each_capture(
&self,
state: &SessionState,
pending_connector_capture_id_list: Vec<String>,
call_connector_action: payments::CallConnectorAction,
connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::PSync,
types::PaymentsSyncData,
types::PaymentsResponseData,
>,
return_raw_connector_response: Option<bool>,
) -> RouterResult<Self> {
let mut capture_sync_response_map = HashMap::new();
if let payments::CallConnectorAction::HandleResponse(_) = call_connector_action {
// webhook consume flow, only call connector once. Since there will only be a single event in every webhook
let resp = services::execute_connector_processing_step(
state,
connector_integration,
self,
call_connector_action.clone(),
None,
return_raw_connector_response,
)
.await
.to_payment_failed_response()?;
Ok(resp)
} else {
// in trigger, call connector for every capture_id
for connector_capture_id in pending_connector_capture_id_list {
// TEMPORARY FIX: remove the clone on router data after removing this function as an impl on trait RouterDataPSync
// TRACKING ISSUE: https://github.com/juspay/hyperswitch/issues/4644
let mut cloned_router_data = self.clone();
cloned_router_data.request.connector_transaction_id =
types::ResponseId::ConnectorTransactionId(connector_capture_id.clone());
let resp = services::execute_connector_processing_step(
state,
connector_integration.clone_box(),
&cloned_router_data,
call_connector_action.clone(),
None,
return_raw_connector_response,
)
.await
.to_payment_failed_response()?;
match resp.response {
Err(err) => {
capture_sync_response_map.insert(connector_capture_id, types::CaptureSyncResponse::Error {
code: err.code,
message: err.message,
reason: err.reason,
status_code: err.status_code,
amount: None,
});
},
Ok(types::PaymentsResponseData::MultipleCaptureResponse { capture_sync_response_list })=> {
capture_sync_response_map.extend(capture_sync_response_list.into_iter());
}
_ => Err(ApiErrorResponse::PreconditionFailed { message: "Response type must be PaymentsResponseData::MultipleCaptureResponse for payment sync".into() })?,
};
}
let mut cloned_router_data = self.clone();
cloned_router_data.response =
Ok(types::PaymentsResponseData::MultipleCaptureResponse {
capture_sync_response_list: capture_sync_response_map,
});
Ok(cloned_router_data)
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 43,
"total_crates": null
} |
fn_clm_router_decide_flows_2066038552921865240 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/flows/psync_flow
// Implementation of types::RouterData<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> for Feature<api::PSync, types::PaymentsSyncData>
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: domain_payments::HeaderPayload,
return_raw_connector_response: Option<bool>,
) -> RouterResult<Self> {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::PSync,
types::PaymentsSyncData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
let capture_sync_method_result = connector_integration
.get_multiple_capture_sync_method()
.to_payment_failed_response();
match (self.request.sync_type.clone(), capture_sync_method_result) {
(
types::SyncRequestType::MultipleCaptureSync(pending_connector_capture_id_list),
Ok(services::CaptureSyncMethod::Individual),
) => {
let mut new_router_data = self
.execute_connector_processing_step_for_each_capture(
state,
pending_connector_capture_id_list,
call_connector_action,
connector_integration,
return_raw_connector_response,
)
.await?;
// Initiating Integrity checks
let integrity_result = helpers::check_integrity_based_on_flow(
&new_router_data.request,
&new_router_data.response,
);
new_router_data.integrity_check = integrity_result;
Ok(new_router_data)
}
(types::SyncRequestType::MultipleCaptureSync(_), Err(err)) => Err(err),
_ => {
// for bulk sync of captures, above logic needs to be handled at connector end
let mut new_router_data = services::execute_connector_processing_step(
state,
connector_integration,
&self,
call_connector_action,
connector_request,
return_raw_connector_response,
)
.await
.to_payment_failed_response()?;
// Initiating Integrity checks
let integrity_result = helpers::check_integrity_based_on_flow(
&new_router_data.request,
&new_router_data.response,
);
new_router_data.integrity_check = integrity_result;
Ok(new_router_data)
}
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 41,
"total_crates": null
} |
fn_clm_router_add_access_token_-5987471418390413719 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/flows/reject_flow
// Implementation of types::RouterData<api::Reject, types::PaymentsRejectData, types::PaymentsResponseData> for Feature<api::Reject, types::PaymentsRejectData>
async fn add_access_token<'a>(
&self,
state: &SessionState,
connector: &api::ConnectorData,
merchant_context: &domain::MerchantContext,
creds_identifier: Option<&str>,
) -> RouterResult<types::AddAccessTokenResult> {
Box::pin(access_token::add_access_token(
state,
connector,
merchant_context,
self,
creds_identifier,
))
.await
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 84,
"total_crates": null
} |
fn_clm_router_construct_router_data_-5987471418390413719 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/flows/reject_flow
// Implementation of PaymentData<api::Reject> for ConstructFlowSpecificData<api::Reject, types::PaymentsRejectData, types::PaymentsResponseData>
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
merchant_context: &domain::MerchantContext,
customer: &Option<domain::Customer>,
merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
) -> RouterResult<types::PaymentsRejectRouterData> {
todo!()
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 47,
"total_crates": null
} |
fn_clm_router_decide_flows_-5987471418390413719 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/flows/reject_flow
// Implementation of types::RouterData<api::Reject, types::PaymentsRejectData, types::PaymentsResponseData> for Feature<api::Reject, types::PaymentsRejectData>
async fn decide_flows<'a>(
self,
_state: &SessionState,
_connector: &api::ConnectorData,
_call_connector_action: payments::CallConnectorAction,
_connector_request: Option<services::Request>,
_business_profile: &domain::Profile,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
_return_raw_connector_response: Option<bool>,
) -> RouterResult<Self> {
Err(ApiErrorResponse::NotImplemented {
message: NotImplementedMessage::Reason("Flow not supported".to_string()),
}
.into())
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 29,
"total_crates": null
} |
fn_clm_router_build_flow_specific_connector_request_-5987471418390413719 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/flows/reject_flow
// Implementation of types::RouterData<api::Reject, types::PaymentsRejectData, types::PaymentsResponseData> for Feature<api::Reject, types::PaymentsRejectData>
async fn build_flow_specific_connector_request(
&mut self,
_state: &SessionState,
_connector: &api::ConnectorData,
_call_connector_action: payments::CallConnectorAction,
) -> RouterResult<(Option<services::Request>, bool)> {
Err(ApiErrorResponse::NotImplemented {
message: NotImplementedMessage::Reason("Flow not supported".to_string()),
}
.into())
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 29,
"total_crates": null
} |
fn_clm_router_add_access_token_-7801497263982683577 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/flows/session_update_flow
// Implementation of types::RouterData<
api::SdkSessionUpdate,
types::SdkPaymentsSessionUpdateData,
types::PaymentsResponseData,
> for Feature<api::SdkSessionUpdate, types::SdkPaymentsSessionUpdateData>
async fn add_access_token<'a>(
&self,
state: &SessionState,
connector: &api::ConnectorData,
merchant_context: &domain::MerchantContext,
creds_identifier: Option<&str>,
) -> RouterResult<types::AddAccessTokenResult> {
Box::pin(access_token::add_access_token(
state,
connector,
merchant_context,
self,
creds_identifier,
))
.await
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 84,
"total_crates": null
} |
fn_clm_router_construct_router_data_-7801497263982683577 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/flows/session_update_flow
// Implementation of PaymentData<api::SdkSessionUpdate> for ConstructFlowSpecificData<
api::SdkSessionUpdate,
types::SdkPaymentsSessionUpdateData,
types::PaymentsResponseData,
>
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
merchant_context: &domain::MerchantContext,
customer: &Option<domain::Customer>,
merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
_merchant_recipient_data: Option<types::MerchantRecipientData>,
_header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
) -> RouterResult<types::SdkSessionUpdateRouterData> {
todo!()
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 47,
"total_crates": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.