id stringlengths 11 116 | type stringclasses 1 value | granularity stringclasses 4 values | content stringlengths 16 477k | metadata dict |
|---|---|---|---|---|
fn_clm_router_health_check_locker_-3899550709035071783 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/health_check
// Implementation of app::SessionState for HealthCheckInterface
async fn health_check_locker(
&self,
) -> CustomResult<HealthState, errors::HealthCheckLockerError> {
let locker = &self.conf.locker;
if !locker.mock_locker {
let mut url = locker.host_rs.to_owned();
url.push_str(consts::LOCKER_HEALTH_CALL_PATH);
let request = services::Request::new(services::Method::Get, &url);
services::call_connector_api(self, request, "health_check_for_locker")
.await
.change_context(errors::HealthCheckLockerError::FailedToCallLocker)?
.map_err(|_| {
error_stack::report!(errors::HealthCheckLockerError::FailedToCallLocker)
})?;
Ok(HealthState::Running)
} else {
Ok(HealthState::NotApplicable)
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 23,
"total_crates": null
} |
fn_clm_router_apple_pay_certificates_migration_-2756590359081229520 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/apple_pay_certificates_migration
pub async fn apple_pay_certificates_migration(
state: SessionState,
req: &apple_pay_certificates_migration::ApplePayCertificatesMigrationRequest,
) -> CustomResult<
services::ApplicationResponse<
apple_pay_certificates_migration::ApplePayCertificatesMigrationResponse,
>,
errors::ApiErrorResponse,
> {
let db = state.store.as_ref();
let merchant_id_list = &req.merchant_ids;
let mut migration_successful_merchant_ids = vec![];
let mut migration_failed_merchant_ids = vec![];
let key_manager_state = &(&state).into();
for merchant_id in merchant_id_list {
let key_store = state
.store
.get_merchant_key_store_by_merchant_id(
key_manager_state,
merchant_id,
&state.store.get_master_key().to_vec().into(),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let merchant_connector_accounts = db
.find_merchant_connector_account_by_merchant_id_and_disabled_list(
key_manager_state,
merchant_id,
true,
&key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::InternalServerError)?;
let mut mca_to_update = vec![];
for connector_account in merchant_connector_accounts {
let connector_apple_pay_metadata =
helpers::get_applepay_metadata(connector_account.clone().metadata)
.map_err(|error| {
logger::error!(
"Apple pay metadata parsing failed for {:?} in certificates migrations api {:?}",
connector_account.clone().connector_name,
error
)
})
.ok();
if let Some(apple_pay_metadata) = connector_apple_pay_metadata {
let encrypted_apple_pay_metadata = domain_types::crypto_operation(
&(&state).into(),
type_name!(storage::MerchantConnectorAccount),
domain_types::CryptoOperation::Encrypt(Secret::new(
serde_json::to_value(apple_pay_metadata)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to serialize apple pay metadata as JSON")?,
)),
Identifier::Merchant(merchant_id.clone()),
key_store.key.get_inner().peek(),
)
.await
.and_then(|val| val.try_into_operation())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt connector apple pay metadata")?;
let updated_mca =
storage::MerchantConnectorAccountUpdate::ConnectorWalletDetailsUpdate {
connector_wallets_details: encrypted_apple_pay_metadata,
};
mca_to_update.push((connector_account, updated_mca.into()));
}
}
let merchant_connector_accounts_update = db
.update_multiple_merchant_connector_accounts(mca_to_update)
.await;
match merchant_connector_accounts_update {
Ok(_) => {
logger::debug!(
"Merchant connector accounts updated for merchant id {merchant_id:?}"
);
migration_successful_merchant_ids.push(merchant_id.clone());
}
Err(error) => {
logger::debug!(
"Merchant connector accounts update failed with error {error} for merchant id {merchant_id:?}");
migration_failed_merchant_ids.push(merchant_id.clone());
}
};
}
Ok(services::api::ApplicationResponse::Json(
apple_pay_certificates_migration::ApplePayCertificatesMigrationResponse {
migration_successful: migration_successful_merchant_ids,
migration_failed: migration_failed_merchant_ids,
},
))
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 85,
"total_crates": null
} |
fn_clm_router_get_three_ds_decision_rule_output_6018817534058495741 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/three_ds_decision_rule
pub async fn get_three_ds_decision_rule_output(
state: &SessionState,
merchant_id: &common_utils::id_type::MerchantId,
request: api_models::three_ds_decision_rule::ThreeDsDecisionRuleExecuteRequest,
) -> errors::RouterResult<common_types::three_ds_decision_rule_engine::ThreeDSDecision> {
let db = state.store.as_ref();
// Retrieve the rule from database
let routing_algorithm = db
.find_routing_algorithm_by_algorithm_id_merchant_id(&request.routing_id, merchant_id)
.await
.to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?;
let algorithm: Algorithm = routing_algorithm
.algorithm_data
.parse_value("Algorithm")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error parsing program from three_ds_decision rule algorithm")?;
let program: ast::Program<ThreeDSDecisionRule> = algorithm
.data
.parse_value("Program<ThreeDSDecisionRule>")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error parsing program from three_ds_decision rule algorithm")?;
// Construct backend input from request
let backend_input = dsl_inputs::BackendInput::foreign_from(request.clone());
// Initialize interpreter with the rule program
let interpreter = backend::VirInterpreterBackend::with_program(program)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error initializing DSL interpreter backend")?;
// Execute the rule
let result = interpreter
.execute(backend_input)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error executing 3DS decision rule")?;
// Apply PSD2 validations to the decision
let final_decision =
utils::apply_psd2_validations_during_execute(result.get_output().get_decision(), &request);
Ok(final_decision)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 56,
"total_crates": null
} |
fn_clm_router_execute_three_ds_decision_rule_6018817534058495741 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/three_ds_decision_rule
pub async fn execute_three_ds_decision_rule(
state: SessionState,
merchant_context: MerchantContext,
request: api_models::three_ds_decision_rule::ThreeDsDecisionRuleExecuteRequest,
) -> RouterResponse<api_models::three_ds_decision_rule::ThreeDsDecisionRuleExecuteResponse> {
let decision = get_three_ds_decision_rule_output(
&state,
merchant_context.get_merchant_account().get_id(),
request.clone(),
)
.await?;
// Construct response
let response =
api_models::three_ds_decision_rule::ThreeDsDecisionRuleExecuteResponse { decision };
Ok(services::ApplicationResponse::Json(response))
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 23,
"total_crates": null
} |
fn_clm_router_validate_7488359987517968518 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/relay
// Implementation of relay_api_models::RelayRefundRequestData for Validate
fn validate(&self) -> Result<(), Self::Error> {
fp_utils::when(self.amount.get_amount_as_i64() <= 0, || {
Err(errors::ApiErrorResponse::PreconditionFailed {
message: "Amount should be greater than 0".to_string(),
})
})?;
Ok(())
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 215,
"total_crates": null
} |
fn_clm_router_relay_retrieve_7488359987517968518 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/relay
pub async fn relay_retrieve(
state: SessionState,
merchant_context: domain::MerchantContext,
profile_id_optional: Option<id_type::ProfileId>,
req: relay_api_models::RelayRetrieveRequest,
) -> RouterResponse<relay_api_models::RelayResponse> {
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
let merchant_id = merchant_context.get_merchant_account().get_id();
let relay_id = &req.id;
let profile_id_from_auth_layer = profile_id_optional.get_required_value("ProfileId")?;
db.find_business_profile_by_merchant_id_profile_id(
key_manager_state,
merchant_context.get_merchant_key_store(),
merchant_id,
&profile_id_from_auth_layer,
)
.await
.change_context(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id_from_auth_layer.get_string_repr().to_owned(),
})?;
let relay_record_result = db
.find_relay_by_id(
key_manager_state,
merchant_context.get_merchant_key_store(),
relay_id,
)
.await;
let relay_record = match relay_record_result {
Err(error) => {
if error.current_context().is_db_not_found() {
Err(error).change_context(errors::ApiErrorResponse::GenericNotFoundError {
message: "relay not found".to_string(),
})?
} else {
Err(error)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("error while fetch relay record")?
}
}
Ok(relay) => relay,
};
#[cfg(feature = "v1")]
let connector_account = db
.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
key_manager_state,
merchant_id,
&relay_record.connector_id,
merchant_context.get_merchant_key_store(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: relay_record.connector_id.get_string_repr().to_string(),
})?;
#[cfg(feature = "v2")]
let connector_account = db
.find_merchant_connector_account_by_id(
key_manager_state,
&relay_record.connector_id,
merchant_context.get_merchant_key_store(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: relay_record.connector_id.get_string_repr().to_string(),
})?;
let relay_response = match relay_record.relay_type {
common_enums::RelayType::Refund => {
if should_call_connector_for_relay_refund_status(&relay_record, req.force_sync) {
let relay_response = sync_relay_refund_with_gateway(
&state,
&merchant_context,
&relay_record,
connector_account,
)
.await?;
db.update_relay(
key_manager_state,
merchant_context.get_merchant_key_store(),
relay_record,
relay_response,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update the relay record")?
} else {
relay_record
}
}
};
let response = relay_api_models::RelayResponse::from(relay_response);
Ok(hyperswitch_domain_models::api::ApplicationResponse::Json(
response,
))
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 88,
"total_crates": null
} |
fn_clm_router_relay_7488359987517968518 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/relay
pub async fn relay<T: RelayInterface>(
state: SessionState,
merchant_context: domain::MerchantContext,
profile_id_optional: Option<id_type::ProfileId>,
req: RelayRequestInner<T>,
) -> RouterResponse<relay_api_models::RelayResponse> {
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
let merchant_id = merchant_context.get_merchant_account().get_id();
let connector_id = &req.connector_id;
let profile_id_from_auth_layer = profile_id_optional.get_required_value("ProfileId")?;
let profile = db
.find_business_profile_by_merchant_id_profile_id(
key_manager_state,
merchant_context.get_merchant_key_store(),
merchant_id,
&profile_id_from_auth_layer,
)
.await
.change_context(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id_from_auth_layer.get_string_repr().to_owned(),
})?;
#[cfg(feature = "v1")]
let connector_account = db
.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
key_manager_state,
merchant_id,
connector_id,
merchant_context.get_merchant_key_store(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: connector_id.get_string_repr().to_string(),
})?;
#[cfg(feature = "v2")]
let connector_account = db
.find_merchant_connector_account_by_id(
key_manager_state,
connector_id,
merchant_context.get_merchant_key_store(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: connector_id.get_string_repr().to_string(),
})?;
T::validate_relay_request(&req.data)?;
let relay_domain = T::get_domain_models(req, merchant_id, profile.get_id());
let relay_record = db
.insert_relay(
key_manager_state,
merchant_context.get_merchant_key_store(),
relay_domain,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to insert a relay record in db")?;
let relay_response = T::process_relay(
&state,
merchant_context.clone(),
connector_account,
&relay_record,
)
.await
.attach_printable("Failed to process relay")?;
let relay_update_record = db
.update_relay(
key_manager_state,
merchant_context.get_merchant_key_store(),
relay_record,
relay_response,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let response = T::generate_response(relay_update_record)
.attach_printable("Failed to generate relay response")?;
Ok(hyperswitch_domain_models::api::ApplicationResponse::Json(
response,
))
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 85,
"total_crates": null
} |
fn_clm_router_generate_response_7488359987517968518 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/relay
// Implementation of RelayRefund for RelayInterface
fn generate_response(value: relay::Relay) -> RouterResult<api_models::relay::RelayResponse> {
let error = value
.error_code
.zip(value.error_message)
.map(
|(error_code, error_message)| api_models::relay::RelayError {
code: error_code,
message: error_message,
},
);
let data =
api_models::relay::RelayData::from(value.request_data.get_required_value("RelayData")?);
Ok(api_models::relay::RelayResponse {
id: value.id,
status: value.status,
error,
connector_resource_id: value.connector_resource_id,
connector_id: value.connector_id,
profile_id: value.profile_id,
relay_type: value.relay_type,
data: Some(data),
connector_reference_id: value.connector_reference_id,
})
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 73,
"total_crates": null
} |
fn_clm_router_sync_relay_refund_with_gateway_7488359987517968518 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/relay
pub async fn sync_relay_refund_with_gateway(
state: &SessionState,
merchant_context: &domain::MerchantContext,
relay_record: &relay::Relay,
connector_account: domain::MerchantConnectorAccount,
) -> RouterResult<relay::RelayUpdate> {
let connector_id = &relay_record.connector_id;
let merchant_id = merchant_context.get_merchant_account().get_id();
#[cfg(feature = "v1")]
let connector_name = &connector_account.connector_name;
#[cfg(feature = "v2")]
let connector_name = &connector_account.connector_name.to_string();
let connector_data: api::ConnectorData = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
connector_name,
api::GetToken::Connector,
Some(connector_id.clone()),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get the connector")?;
let router_data = utils::construct_relay_refund_router_data(
state,
merchant_id,
&connector_account,
relay_record,
)
.await?;
let connector_integration: services::BoxedRefundConnectorIntegrationInterface<
api::RSync,
hyperswitch_domain_models::router_request_types::RefundsData,
hyperswitch_domain_models::router_response_types::RefundsResponseData,
> = connector_data.connector.get_connector_integration();
let router_data_res = services::execute_connector_processing_step(
state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.to_refund_failed_response()?;
let relay_response = relay::RelayUpdate::from(router_data_res.response);
Ok(relay_response)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 37,
"total_crates": null
} |
fn_clm_router_foreign_from_4082165272400305752 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/mandate
// Implementation of Option<types::MandateReference> for ForeignFrom<Result<types::PaymentsResponseData, types::ErrorResponse>>
fn foreign_from(resp: Result<types::PaymentsResponseData, types::ErrorResponse>) -> Self {
match resp {
Ok(types::PaymentsResponseData::TransactionResponse {
mandate_reference, ..
}) => *mandate_reference,
_ => None,
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 212,
"total_crates": null
} |
fn_clm_router_mandate_procedure_4082165272400305752 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/mandate
pub async fn mandate_procedure<F, FData>(
state: &SessionState,
resp: &types::RouterData<F, FData, types::PaymentsResponseData>,
customer_id: &Option<id_type::CustomerId>,
pm_id: Option<String>,
merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
storage_scheme: MerchantStorageScheme,
payment_id: &id_type::PaymentId,
) -> errors::RouterResult<Option<String>>
where
FData: MandateBehaviour,
{
let Ok(ref response) = resp.response else {
return Ok(None);
};
match resp.request.get_mandate_id() {
Some(mandate_id) => {
let Some(ref mandate_id) = mandate_id.mandate_id else {
return Ok(None);
};
let orig_mandate = state
.store
.find_mandate_by_merchant_id_mandate_id(
&resp.merchant_id,
mandate_id,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?;
let mandate = match orig_mandate.mandate_type {
storage_enums::MandateType::SingleUse => state
.store
.update_mandate_by_merchant_id_mandate_id(
&resp.merchant_id,
mandate_id,
storage::MandateUpdate::StatusUpdate {
mandate_status: storage_enums::MandateStatus::Revoked,
},
orig_mandate,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::MandateUpdateFailed),
storage_enums::MandateType::MultiUse => state
.store
.update_mandate_by_merchant_id_mandate_id(
&resp.merchant_id,
mandate_id,
storage::MandateUpdate::CaptureAmountUpdate {
amount_captured: Some(
orig_mandate.amount_captured.unwrap_or(0)
+ resp.request.get_amount(),
),
},
orig_mandate,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::MandateUpdateFailed),
}?;
metrics::SUBSEQUENT_MANDATE_PAYMENT.add(
1,
router_env::metric_attributes!(("connector", mandate.connector)),
);
Ok(Some(mandate_id.clone()))
}
None => {
let Some(_mandate_details) = resp.request.get_setup_mandate_details() else {
return Ok(None);
};
let (mandate_reference, network_txn_id) = match &response {
types::PaymentsResponseData::TransactionResponse {
mandate_reference,
network_txn_id,
..
} => (mandate_reference.clone(), network_txn_id.clone()),
_ => (Box::new(None), None),
};
let mandate_ids = (*mandate_reference)
.as_ref()
.map(|md| {
md.encode_to_value()
.change_context(errors::ApiErrorResponse::MandateSerializationFailed)
.map(masking::Secret::new)
})
.transpose()?;
let Some(new_mandate_data) = payment_helper::generate_mandate(
resp.merchant_id.clone(),
payment_id.to_owned(),
resp.connector.clone(),
resp.request.get_setup_mandate_details().cloned(),
customer_id,
pm_id.get_required_value("payment_method_id")?,
mandate_ids,
network_txn_id,
get_insensitive_payment_method_data_if_exists(resp),
*mandate_reference,
merchant_connector_id,
)?
else {
return Ok(None);
};
let connector = new_mandate_data.connector.clone();
logger::debug!("{:?}", new_mandate_data);
let res_mandate_id = new_mandate_data.mandate_id.clone();
state
.store
.insert_mandate(new_mandate_data, storage_scheme)
.await
.to_duplicate_response(errors::ApiErrorResponse::DuplicateMandate)?;
metrics::MANDATE_COUNT.add(1, router_env::metric_attributes!(("connector", connector)));
Ok(Some(res_mandate_id))
}
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 78,
"total_crates": null
} |
fn_clm_router_revoke_mandate_4082165272400305752 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/mandate
pub async fn revoke_mandate(
state: SessionState,
merchant_context: domain::MerchantContext,
req: mandates::MandateId,
) -> RouterResponse<mandates::MandateRevokedResponse> {
let db = state.store.as_ref();
let mandate = db
.find_mandate_by_merchant_id_mandate_id(
merchant_context.get_merchant_account().get_id(),
&req.mandate_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?;
match mandate.mandate_status {
common_enums::MandateStatus::Active
| common_enums::MandateStatus::Inactive
| common_enums::MandateStatus::Pending => {
let profile_id =
helpers::get_profile_id_for_mandate(&state, &merchant_context, mandate.clone())
.await?;
let merchant_connector_account = payment_helper::get_merchant_connector_account(
&state,
merchant_context.get_merchant_account().get_id(),
None,
merchant_context.get_merchant_key_store(),
&profile_id,
&mandate.connector.clone(),
mandate.merchant_connector_id.as_ref(),
)
.await?;
let connector_data = ConnectorData::get_connector_by_name(
&state.conf.connectors,
&mandate.connector,
GetToken::Connector,
mandate.merchant_connector_id.clone(),
)?;
let connector_integration: services::BoxedMandateRevokeConnectorIntegrationInterface<
types::api::MandateRevoke,
types::MandateRevokeRequestData,
types::MandateRevokeResponseData,
> = connector_data.connector.get_connector_integration();
let router_data = utils::construct_mandate_revoke_router_data(
&state,
merchant_connector_account,
&merchant_context,
mandate.clone(),
)
.await?;
let response = services::execute_connector_processing_step(
&state,
connector_integration,
&router_data,
CallConnectorAction::Trigger,
None,
None,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?;
match response.response {
Ok(_) => {
let update_mandate = db
.update_mandate_by_merchant_id_mandate_id(
merchant_context.get_merchant_account().get_id(),
&req.mandate_id,
storage::MandateUpdate::StatusUpdate {
mandate_status: storage::enums::MandateStatus::Revoked,
},
mandate,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?;
Ok(services::ApplicationResponse::Json(
mandates::MandateRevokedResponse {
mandate_id: update_mandate.mandate_id,
status: update_mandate.mandate_status,
error_code: None,
error_message: None,
},
))
}
Err(err) => Err(errors::ApiErrorResponse::ExternalConnectorError {
code: err.code,
message: err.message,
connector: mandate.connector,
status_code: err.status_code,
reason: err.reason,
}
.into()),
}
}
common_enums::MandateStatus::Revoked => {
Err(errors::ApiErrorResponse::MandateValidationFailed {
reason: "Mandate has already been revoked".to_string(),
}
.into())
}
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 73,
"total_crates": null
} |
fn_clm_router_get_customer_mandates_4082165272400305752 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/mandate
pub async fn get_customer_mandates(
state: SessionState,
merchant_context: domain::MerchantContext,
customer_id: id_type::CustomerId,
) -> RouterResponse<Vec<mandates::MandateResponse>> {
let mandates = state
.store
.find_mandate_by_merchant_id_customer_id(
merchant_context.get_merchant_account().get_id(),
&customer_id,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| {
format!(
"Failed while finding mandate: merchant_id: {:?}, customer_id: {:?}",
merchant_context.get_merchant_account().get_id(),
customer_id,
)
})?;
if mandates.is_empty() {
Err(report!(errors::ApiErrorResponse::MandateNotFound).attach_printable("No Mandate found"))
} else {
let mut response_vec = Vec::with_capacity(mandates.len());
for mandate in mandates {
response_vec.push(
mandates::MandateResponse::from_db_mandate(
&state,
merchant_context.get_merchant_key_store().clone(),
mandate,
merchant_context.get_merchant_account(),
)
.await?,
);
}
Ok(services::ApplicationResponse::Json(response_vec))
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 43,
"total_crates": null
} |
fn_clm_router_update_connector_mandate_id_4082165272400305752 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/mandate
pub async fn update_connector_mandate_id(
db: &dyn StorageInterface,
merchant_id: &id_type::MerchantId,
mandate_ids_opt: Option<String>,
payment_method_id: Option<String>,
resp: Result<types::PaymentsResponseData, types::ErrorResponse>,
storage_scheme: MerchantStorageScheme,
) -> RouterResponse<mandates::MandateResponse> {
let mandate_details = Option::foreign_from(resp);
let connector_mandate_id = mandate_details
.clone()
.map(|md| {
md.encode_to_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
.map(masking::Secret::new)
})
.transpose()?;
//Ignore updation if the payment_attempt mandate_id or connector_mandate_id is not present
if let Some((mandate_id, connector_id)) = mandate_ids_opt.zip(connector_mandate_id) {
let mandate = db
.find_mandate_by_merchant_id_mandate_id(merchant_id, &mandate_id, storage_scheme)
.await
.change_context(errors::ApiErrorResponse::MandateNotFound)?;
let update_mandate_details = match payment_method_id {
Some(pmd_id) => storage::MandateUpdate::ConnectorMandateIdUpdate {
connector_mandate_id: mandate_details
.and_then(|mandate_reference| mandate_reference.connector_mandate_id),
connector_mandate_ids: Some(connector_id),
payment_method_id: pmd_id,
original_payment_id: None,
},
None => storage::MandateUpdate::ConnectorReferenceUpdate {
connector_mandate_ids: Some(connector_id),
},
};
// only update the connector_mandate_id if existing is none
if mandate.connector_mandate_id.is_none() {
db.update_mandate_by_merchant_id_mandate_id(
merchant_id,
&mandate_id,
update_mandate_details,
mandate,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::MandateUpdateFailed)?;
}
}
Ok(services::ApplicationResponse::StatusOk)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 41,
"total_crates": null
} |
fn_clm_router_new_-4825863129539560043 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/utils
// Inherent implementation for Object
pub fn new(profile_id: &'static str) -> Self {
Self {
profile_id: Some(
common_utils::id_type::ProfileId::try_from(std::borrow::Cow::from(
profile_id,
))
.expect("invalid profile ID"),
),
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 14467,
"total_crates": null
} |
fn_clm_router_construct_refund_router_data_-4825863129539560043 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/utils
pub async fn construct_refund_router_data<'a, F>(
state: &'a SessionState,
connector_id: &str,
merchant_context: &domain::MerchantContext,
money: (MinorUnit, enums::Currency),
payment_intent: &'a storage::PaymentIntent,
payment_attempt: &storage::PaymentAttempt,
refund: &'a diesel_refund::Refund,
creds_identifier: Option<String>,
split_refunds: Option<router_request_types::SplitRefundsRequest>,
) -> RouterResult<types::RefundsRouterData<F>> {
let profile_id = payment_intent
.profile_id
.as_ref()
.get_required_value("profile_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("profile_id is not set in payment_intent")?;
let merchant_connector_account = helpers::get_merchant_connector_account(
state,
merchant_context.get_merchant_account().get_id(),
creds_identifier.as_deref(),
merchant_context.get_merchant_key_store(),
profile_id,
connector_id,
payment_attempt.merchant_connector_id.as_ref(),
)
.await?;
let auth_type: types::ConnectorAuthType = merchant_connector_account
.get_connector_account_details()
.parse_value("ConnectorAuthType")
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let status = payment_attempt.status;
let (payment_amount, currency) = money;
let payment_method = payment_attempt
.payment_method
.get_required_value("payment_method")
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let merchant_connector_account_id_or_connector_name = payment_attempt
.merchant_connector_id
.as_ref()
.map(|mca_id| mca_id.get_string_repr())
.unwrap_or(connector_id);
let webhook_url = Some(helpers::create_webhook_url(
&state.base_url.clone(),
merchant_context.get_merchant_account().get_id(),
merchant_connector_account_id_or_connector_name,
));
let test_mode: Option<bool> = merchant_connector_account.is_test_mode_on();
let supported_connector = &state
.conf
.multiple_api_version_supported_connectors
.supported_connectors;
let connector_enum = Connector::from_str(connector_id)
.change_context(errors::ConnectorError::InvalidConnectorName)
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "connector",
})
.attach_printable_lazy(|| format!("unable to parse connector name {connector_id:?}"))?;
let connector_api_version = if supported_connector.contains(&connector_enum) {
state
.store
.find_config_by_key(&format!("connector_api_version_{connector_id}"))
.await
.map(|value| value.config)
.ok()
} else {
None
};
let browser_info: Option<types::BrowserInformation> = payment_attempt
.browser_info
.clone()
.map(|b| b.parse_value("BrowserInformation"))
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "browser_info",
})?;
let connector_refund_id = refund.get_optional_connector_refund_id().cloned();
let capture_method = payment_attempt.capture_method;
let braintree_metadata = payment_intent
.connector_metadata
.clone()
.map(|cm| {
cm.parse_value::<api_models::payments::ConnectorMetadata>("ConnectorMetadata")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed parsing ConnectorMetadata")
})
.transpose()?
.and_then(|cm| cm.braintree);
let merchant_account_id = braintree_metadata
.as_ref()
.and_then(|braintree| braintree.merchant_account_id.clone());
let merchant_config_currency =
braintree_metadata.and_then(|braintree| braintree.merchant_config_currency);
let additional_payment_method_data: Option<api_models::payments::AdditionalPaymentData> =
payment_attempt
.payment_method_data
.clone()
.and_then(|value| match serde_json::from_value(value) {
Ok(data) => Some(data),
Err(e) => {
router_env::logger::error!("Failed to deserialize payment_method_data: {}", e);
None
}
});
let router_data = types::RouterData {
flow: PhantomData,
merchant_id: merchant_context.get_merchant_account().get_id().clone(),
customer_id: payment_intent.customer_id.to_owned(),
tenant_id: state.tenant.tenant_id.clone(),
connector: connector_id.to_string(),
payment_id: payment_attempt.payment_id.get_string_repr().to_owned(),
attempt_id: payment_attempt.attempt_id.clone(),
status,
payment_method,
payment_method_type: payment_attempt.payment_method_type,
connector_auth_type: auth_type,
description: None,
// Does refund need shipping/billing address ?
address: PaymentAddress::default(),
auth_type: payment_attempt.authentication_type.unwrap_or_default(),
connector_meta_data: merchant_connector_account.get_metadata(),
connector_wallets_details: merchant_connector_account.get_connector_wallets_details(),
amount_captured: payment_intent
.amount_captured
.map(|amt| amt.get_amount_as_i64()),
payment_method_status: None,
minor_amount_captured: payment_intent.amount_captured,
request: types::RefundsData {
refund_id: refund.refund_id.clone(),
connector_transaction_id: refund.get_connector_transaction_id().clone(),
refund_amount: refund.refund_amount.get_amount_as_i64(),
minor_refund_amount: refund.refund_amount,
currency,
payment_amount: payment_amount.get_amount_as_i64(),
minor_payment_amount: payment_amount,
webhook_url,
connector_metadata: payment_attempt.connector_metadata.clone(),
refund_connector_metadata: refund.metadata.clone(),
reason: refund.refund_reason.clone(),
connector_refund_id: connector_refund_id.clone(),
browser_info,
split_refunds,
integrity_object: None,
refund_status: refund.refund_status,
merchant_account_id,
merchant_config_currency,
capture_method,
additional_payment_method_data,
},
response: Ok(types::RefundsResponseData {
connector_refund_id: connector_refund_id.unwrap_or_default(),
refund_status: refund.refund_status,
}),
access_token: None,
session_token: None,
reference_id: None,
payment_method_token: None,
connector_customer: None,
recurring_mandate_payment_data: None,
preprocessing_id: None,
connector_request_reference_id: refund.refund_id.clone(),
#[cfg(feature = "payouts")]
payout_method_data: None,
#[cfg(feature = "payouts")]
quote_id: None,
test_mode,
payment_method_balance: None,
connector_api_version,
connector_http_status_code: None,
external_latency: None,
apple_pay_flow: None,
frm_metadata: None,
refund_id: Some(refund.refund_id.clone()),
dispute_id: None,
connector_response: None,
integrity_check: Ok(()),
additional_merchant_data: None,
header_payload: None,
connector_mandate_request_reference_id: None,
authentication_id: None,
psd2_sca_exemption_type: None,
raw_connector_response: None,
is_payment_id_from_merchant: None,
l2_l3_data: None,
minor_amount_capturable: None,
authorized_amount: None,
};
Ok(router_data)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 177,
"total_crates": null
} |
fn_clm_router_construct_payout_router_data_-4825863129539560043 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/utils
pub async fn construct_payout_router_data<'a, F>(
state: &SessionState,
connector_data: &api::ConnectorData,
merchant_context: &domain::MerchantContext,
payout_data: &mut PayoutData,
) -> RouterResult<types::PayoutsRouterData<F>> {
let merchant_connector_account = payout_data
.merchant_connector_account
.clone()
.get_required_value("merchant_connector_account")?;
let connector_name = connector_data.connector_name;
let connector_auth_type: types::ConnectorAuthType = merchant_connector_account
.get_connector_account_details()
.parse_value("ConnectorAuthType")
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let billing = payout_data.billing_address.to_owned();
let billing_address = billing.map(api_models::payments::Address::from);
let address = PaymentAddress::new(None, billing_address.map(From::from), None, None);
let test_mode: Option<bool> = merchant_connector_account.is_test_mode_on();
let payouts = &payout_data.payouts;
let payout_attempt = &payout_data.payout_attempt;
let customer_details = &payout_data.customer_details;
let connector_label = format!(
"{}_{}",
payout_data.profile_id.get_string_repr(),
connector_name
);
let connector_customer_id = customer_details
.as_ref()
.and_then(|c| c.connector_customer.as_ref())
.and_then(|connector_customer_value| {
connector_customer_value
.clone()
.expose()
.get(connector_label)
.cloned()
})
.and_then(|id| serde_json::from_value::<String>(id).ok());
let vendor_details: Option<PayoutVendorAccountDetails> =
match api_models::enums::PayoutConnectors::try_from(connector_name.to_owned()).map_err(
|err| report!(errors::ApiErrorResponse::InternalServerError).attach_printable(err),
)? {
api_models::enums::PayoutConnectors::Stripe => {
payout_data.payouts.metadata.to_owned().and_then(|meta| {
let val = meta
.peek()
.to_owned()
.parse_value("PayoutVendorAccountDetails")
.ok();
val
})
}
_ => None,
};
let webhook_url = helpers::create_webhook_url(
&state.base_url,
&merchant_context.get_merchant_account().get_id().to_owned(),
merchant_connector_account
.get_mca_id()
.get_required_value("merchant_connector_id")?
.get_string_repr(),
);
let connector_transfer_method_id =
payout_helpers::should_create_connector_transfer_method(&*payout_data, connector_data)?;
let browser_info = payout_data.browser_info.to_owned();
let router_data = types::RouterData {
flow: PhantomData,
merchant_id: merchant_context.get_merchant_account().get_id().to_owned(),
customer_id: customer_details.to_owned().map(|c| c.customer_id),
tenant_id: state.tenant.tenant_id.clone(),
connector_customer: connector_customer_id,
connector: connector_name.to_string(),
payment_id: common_utils::id_type::PaymentId::get_irrelevant_id("payout")
.get_string_repr()
.to_owned(),
attempt_id: "".to_string(),
status: enums::AttemptStatus::Failure,
payment_method: enums::PaymentMethod::default(),
payment_method_type: None,
connector_auth_type,
description: None,
address,
auth_type: enums::AuthenticationType::default(),
connector_meta_data: merchant_connector_account.get_metadata(),
connector_wallets_details: merchant_connector_account.get_connector_wallets_details(),
amount_captured: None,
minor_amount_captured: None,
payment_method_status: None,
request: types::PayoutsData {
payout_id: payouts.payout_id.clone(),
amount: payouts.amount.get_amount_as_i64(),
minor_amount: payouts.amount,
connector_payout_id: payout_attempt.connector_payout_id.clone(),
destination_currency: payouts.destination_currency,
source_currency: payouts.source_currency,
entity_type: payouts.entity_type.to_owned(),
payout_type: payouts.payout_type,
vendor_details,
priority: payouts.priority,
customer_details: customer_details
.to_owned()
.map(|c| payments::CustomerDetails {
customer_id: Some(c.customer_id),
name: c.name.map(Encryptable::into_inner),
email: c.email.map(Email::from),
phone: c.phone.map(Encryptable::into_inner),
phone_country_code: c.phone_country_code,
tax_registration_id: c.tax_registration_id.map(Encryptable::into_inner),
}),
connector_transfer_method_id,
webhook_url: Some(webhook_url),
browser_info,
payout_connector_metadata: payout_attempt.payout_connector_metadata.to_owned(),
},
response: Ok(types::PayoutsResponseData::default()),
access_token: None,
session_token: None,
reference_id: None,
payment_method_token: None,
recurring_mandate_payment_data: None,
preprocessing_id: None,
connector_request_reference_id: payout_attempt.payout_attempt_id.clone(),
payout_method_data: payout_data.payout_method_data.to_owned(),
quote_id: None,
test_mode,
payment_method_balance: None,
connector_api_version: None,
connector_http_status_code: None,
external_latency: None,
apple_pay_flow: None,
frm_metadata: None,
refund_id: None,
dispute_id: None,
connector_response: None,
integrity_check: Ok(()),
additional_merchant_data: None,
header_payload: None,
connector_mandate_request_reference_id: None,
authentication_id: None,
psd2_sca_exemption_type: None,
raw_connector_response: None,
is_payment_id_from_merchant: None,
l2_l3_data: None,
minor_amount_capturable: None,
authorized_amount: None,
};
Ok(router_data)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 164,
"total_crates": null
} |
fn_clm_router_validate_and_get_business_profile_-4825863129539560043 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/utils
/// Validate whether the profile_id exists and is associated with the merchant_id
pub async fn validate_and_get_business_profile(
db: &dyn StorageInterface,
key_manager_state: &KeyManagerState,
merchant_key_store: &domain::MerchantKeyStore,
profile_id: Option<&common_utils::id_type::ProfileId>,
merchant_id: &common_utils::id_type::MerchantId,
) -> RouterResult<Option<domain::Profile>> {
profile_id
.async_map(|profile_id| async {
db.find_business_profile_by_merchant_id_profile_id(
key_manager_state,
merchant_key_store,
merchant_id,
profile_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})
})
.await
.transpose()
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 103,
"total_crates": null
} |
fn_clm_router_validate_iban_-4825863129539560043 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/utils
fn validate_iban(iban: &Secret<String>) -> RouterResult<()> {
let iban_str = iban.peek();
if iban_str.len() > consts::IBAN_MAX_LENGTH || iban_str.len() < consts::IBAN_MIN_LENGTH {
return Err(errors::ApiErrorResponse::InvalidRequestData {
message: format!(
"IBAN length must be between {} and {} characters",
consts::IBAN_MIN_LENGTH,
consts::IBAN_MAX_LENGTH
),
}
.into());
}
if iban.peek().len() > consts::IBAN_MAX_LENGTH {
return Err(errors::ApiErrorResponse::InvalidRequestData {
message: "IBAN length must be up to 34 characters".to_string(),
}
.into());
}
let pattern = Regex::new(r"^[A-Z0-9]*$")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed to create regex pattern")?;
let mut iban = iban.peek().to_string();
if !pattern.is_match(iban.as_str()) {
return Err(errors::ApiErrorResponse::InvalidRequestData {
message: "IBAN data must be alphanumeric".to_string(),
}
.into());
}
// MOD check
let first_4 = iban.chars().take(4).collect::<String>();
iban.push_str(first_4.as_str());
let len = iban.len();
let rearranged_iban = iban
.chars()
.rev()
.take(len - 4)
.collect::<String>()
.chars()
.rev()
.collect::<String>();
let mut result = String::new();
rearranged_iban.chars().for_each(|c| {
if c.is_ascii_uppercase() {
let digit = (u32::from(c) - u32::from('A')) + 10;
result.push_str(&format!("{digit:02}"));
} else {
result.push(c);
}
});
let num = result
.parse::<u128>()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed to validate IBAN")?;
if num % 97 != 1 {
return Err(errors::ApiErrorResponse::InvalidRequestData {
message: "Invalid IBAN".to_string(),
}
.into());
}
Ok(())
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 90,
"total_crates": null
} |
fn_clm_router_new_6770424081242400472 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/admin
// Implementation of None for ProfileWrapper
pub fn new(profile: domain::Profile) -> Self {
Self { profile }
}
| {
"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_from_6770424081242400472 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/admin
// Implementation of pm_auth_types::RecipientCreateRequest for From<&types::MerchantAccountData>
fn from(data: &types::MerchantAccountData) -> Self {
let (name, account_data) = match data {
types::MerchantAccountData::Iban { iban, name, .. } => (
name.clone(),
pm_auth_types::RecipientAccountData::Iban(iban.clone()),
),
types::MerchantAccountData::Bacs {
account_number,
sort_code,
name,
..
} => (
name.clone(),
pm_auth_types::RecipientAccountData::Bacs {
sort_code: sort_code.clone(),
account_number: account_number.clone(),
},
),
types::MerchantAccountData::FasterPayments {
account_number,
sort_code,
name,
..
} => (
name.clone(),
pm_auth_types::RecipientAccountData::FasterPayments {
sort_code: sort_code.clone(),
account_number: account_number.clone(),
},
),
types::MerchantAccountData::Sepa { iban, name, .. } => (
name.clone(),
pm_auth_types::RecipientAccountData::Sepa(iban.clone()),
),
types::MerchantAccountData::SepaInstant { iban, name, .. } => (
name.clone(),
pm_auth_types::RecipientAccountData::SepaInstant(iban.clone()),
),
types::MerchantAccountData::Elixir {
account_number,
iban,
name,
..
} => (
name.clone(),
pm_auth_types::RecipientAccountData::Elixir {
account_number: account_number.clone(),
iban: iban.clone(),
},
),
types::MerchantAccountData::Bankgiro { number, name, .. } => (
name.clone(),
pm_auth_types::RecipientAccountData::Bankgiro(number.clone()),
),
types::MerchantAccountData::Plusgiro { number, name, .. } => (
name.clone(),
pm_auth_types::RecipientAccountData::Plusgiro(number.clone()),
),
};
Self {
name,
account_data,
address: None,
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 2648,
"total_crates": null
} |
fn_clm_router_get_merchant_account_6770424081242400472 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/admin
pub async fn get_merchant_account(
state: SessionState,
req: api::MerchantId,
_profile_id: Option<id_type::ProfileId>,
) -> RouterResponse<api::MerchantAccountResponse> {
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
let key_store = db
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&req.merchant_id,
&db.get_master_key().to_vec().into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
let merchant_account = db
.find_merchant_account_by_merchant_id(key_manager_state, &req.merchant_id, &key_store)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
Ok(service_api::ApplicationResponse::Json(
api::MerchantAccountResponse::foreign_try_from(merchant_account)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to construct response")?,
))
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 2577,
"total_crates": null
} |
fn_clm_router_create_domain_model_from_request_6770424081242400472 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/admin
// Implementation of api::ProfileCreate for ProfileCreateBridge
async fn create_domain_model_from_request(
self,
state: &SessionState,
key_store: &domain::MerchantKeyStore,
merchant_id: &id_type::MerchantId,
) -> RouterResult<domain::Profile> {
if let Some(session_expiry) = &self.session_expiry {
helpers::validate_session_expiry(session_expiry.to_owned())?;
}
// Generate a unique profile id
// TODO: the profile_id should be generated from the profile_name
let profile_id = common_utils::generate_profile_id_of_default_length();
let profile_name = self.profile_name;
let current_time = date_time::now();
let webhook_details = self.webhook_details.map(ForeignInto::foreign_into);
let payment_response_hash_key = self
.payment_response_hash_key
.unwrap_or(common_utils::crypto::generate_cryptographically_secure_random_string(64));
let payment_link_config = self.payment_link_config.map(ForeignInto::foreign_into);
let key_manager_state = state.into();
let outgoing_webhook_custom_http_headers = self
.outgoing_webhook_custom_http_headers
.async_map(|headers| {
cards::create_encrypted_data(&key_manager_state, key_store, headers)
})
.await
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt outgoing webhook custom HTTP headers")?;
let payout_link_config = self
.payout_link_config
.map(|payout_conf| match payout_conf.config.validate() {
Ok(_) => Ok(payout_conf.foreign_into()),
Err(e) => Err(error_stack::report!(
errors::ApiErrorResponse::InvalidRequestData {
message: e.to_string()
}
)),
})
.transpose()?;
let key = key_store.key.clone().into_inner();
let key_manager_state = state.into();
let card_testing_secret_key = Some(Secret::new(utils::generate_id(
consts::FINGERPRINT_SECRET_LENGTH,
"fs",
)));
let card_testing_guard_config = self
.card_testing_guard_config
.map(CardTestingGuardConfig::foreign_from)
.or(Some(CardTestingGuardConfig::default()));
Ok(domain::Profile::from(domain::ProfileSetter {
id: profile_id,
merchant_id: merchant_id.clone(),
profile_name,
created_at: current_time,
modified_at: current_time,
return_url: self.return_url,
enable_payment_response_hash: self.enable_payment_response_hash.unwrap_or(true),
payment_response_hash_key: Some(payment_response_hash_key),
redirect_to_merchant_with_http_post: self
.redirect_to_merchant_with_http_post
.unwrap_or(true),
webhook_details,
metadata: self.metadata,
is_recon_enabled: false,
applepay_verified_domains: self.applepay_verified_domains,
payment_link_config,
session_expiry: self
.session_expiry
.map(i64::from)
.or(Some(common_utils::consts::DEFAULT_SESSION_EXPIRY)),
authentication_connector_details: self
.authentication_connector_details
.map(ForeignInto::foreign_into),
payout_link_config,
is_connector_agnostic_mit_enabled: self.is_connector_agnostic_mit_enabled,
is_extended_card_info_enabled: None,
extended_card_info_config: None,
use_billing_as_payment_method_billing: self
.use_billing_as_payment_method_billing
.or(Some(true)),
collect_shipping_details_from_wallet_connector: self
.collect_shipping_details_from_wallet_connector_if_required
.or(Some(false)),
collect_billing_details_from_wallet_connector: self
.collect_billing_details_from_wallet_connector_if_required
.or(Some(false)),
outgoing_webhook_custom_http_headers,
always_collect_billing_details_from_wallet_connector: self
.always_collect_billing_details_from_wallet_connector,
always_collect_shipping_details_from_wallet_connector: self
.always_collect_shipping_details_from_wallet_connector,
routing_algorithm_id: None,
frm_routing_algorithm_id: None,
payout_routing_algorithm_id: None,
order_fulfillment_time: self
.order_fulfillment_time
.map(|order_fulfillment_time| order_fulfillment_time.into_inner())
.or(Some(common_utils::consts::DEFAULT_ORDER_FULFILLMENT_TIME)),
order_fulfillment_time_origin: self.order_fulfillment_time_origin,
default_fallback_routing: None,
should_collect_cvv_during_payment: None,
tax_connector_id: self.tax_connector_id,
is_tax_connector_enabled: self.is_tax_connector_enabled,
is_network_tokenization_enabled: self.is_network_tokenization_enabled,
is_click_to_pay_enabled: self.is_click_to_pay_enabled,
authentication_product_ids: self.authentication_product_ids,
three_ds_decision_manager_config: None,
card_testing_guard_config,
card_testing_secret_key: card_testing_secret_key
.async_lift(|inner| async {
domain_types::crypto_operation(
&key_manager_state,
common_utils::type_name!(domain::Profile),
domain_types::CryptoOperation::EncryptOptional(inner),
km_types::Identifier::Merchant(key_store.merchant_id.clone()),
key.peek(),
)
.await
.and_then(|val| val.try_into_optionaloperation())
})
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("error while generating card testing secret key")?,
is_clear_pan_retries_enabled: self.is_clear_pan_retries_enabled.unwrap_or_default(),
is_debit_routing_enabled: self.is_debit_routing_enabled.unwrap_or_default(),
merchant_business_country: self.merchant_business_country,
revenue_recovery_retry_algorithm_type: None,
revenue_recovery_retry_algorithm_data: None,
is_iframe_redirection_enabled: None,
is_external_vault_enabled: self.is_external_vault_enabled,
external_vault_connector_details: self
.external_vault_connector_details
.map(ForeignInto::foreign_into),
merchant_category_code: self.merchant_category_code,
merchant_country_code: self.merchant_country_code,
split_txns_enabled: self.split_txns_enabled.unwrap_or_default(),
billing_processor_id: self.billing_processor_id,
}))
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 138,
"total_crates": null
} |
fn_clm_router_create_merchant_account_6770424081242400472 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/admin
pub async fn create_merchant_account(
state: SessionState,
req: api::MerchantAccountCreate,
org_data_from_auth: Option<authentication::AuthenticationDataWithOrg>,
) -> RouterResponse<api::MerchantAccountResponse> {
#[cfg(feature = "keymanager_create")]
use common_utils::{keymanager, types::keymanager::EncryptionTransferRequest};
let db = state.store.as_ref();
let key = services::generate_aes256_key()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to generate aes 256 key")?;
let master_key = db.get_master_key();
let key_manager_state: &KeyManagerState = &(&state).into();
let merchant_id = req.get_merchant_reference_id();
let identifier = km_types::Identifier::Merchant(merchant_id.clone());
#[cfg(feature = "keymanager_create")]
{
use base64::Engine;
use crate::consts::BASE64_ENGINE;
if key_manager_state.enabled {
keymanager::transfer_key_to_key_manager(
key_manager_state,
EncryptionTransferRequest {
identifier: identifier.clone(),
key: BASE64_ENGINE.encode(key),
},
)
.await
.change_context(errors::ApiErrorResponse::DuplicateMerchantAccount)
.attach_printable("Failed to insert key to KeyManager")?;
}
}
let key_store = domain::MerchantKeyStore {
merchant_id: merchant_id.clone(),
key: domain_types::crypto_operation(
key_manager_state,
type_name!(domain::MerchantKeyStore),
domain_types::CryptoOperation::Encrypt(key.to_vec().into()),
identifier.clone(),
master_key,
)
.await
.and_then(|val| val.try_into_operation())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to decrypt data from key store")?,
created_at: date_time::now(),
};
let domain_merchant_account = req
.create_domain_model_from_request(
&state,
key_store.clone(),
&merchant_id,
org_data_from_auth,
)
.await?;
let key_manager_state = &(&state).into();
db.insert_merchant_key_store(
key_manager_state,
key_store.clone(),
&master_key.to_vec().into(),
)
.await
.to_duplicate_response(errors::ApiErrorResponse::DuplicateMerchantAccount)?;
let merchant_account = db
.insert_merchant(key_manager_state, domain_merchant_account, &key_store)
.await
.to_duplicate_response(errors::ApiErrorResponse::DuplicateMerchantAccount)?;
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(domain::Context(
merchant_account.clone(),
key_store.clone(),
)));
add_publishable_key_to_decision_service(&state, &merchant_context);
insert_merchant_configs(db, &merchant_id).await?;
Ok(service_api::ApplicationResponse::Json(
api::MerchantAccountResponse::foreign_try_from(merchant_account)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while generating response")?,
))
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 123,
"total_crates": null
} |
fn_clm_router_sync_onboarding_status_-6090421623747606806 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/connector_onboarding
pub async fn sync_onboarding_status(
state: SessionState,
user_from_token: auth::UserFromToken,
request: api::OnboardingSyncRequest,
_req_state: ReqState,
) -> RouterResponse<api::OnboardingStatus> {
utils::check_if_connector_exists(&state, &request.connector_id, &user_from_token.merchant_id)
.await?;
let connector_onboarding_conf = state.conf.connector_onboarding.get_inner();
let is_enabled = utils::is_enabled(request.connector, connector_onboarding_conf);
let tracking_id =
utils::get_tracking_id_from_configs(&state, &request.connector_id, request.connector)
.await?;
match (is_enabled, request.connector) {
(Some(true), enums::Connector::Paypal) => {
let status = Box::pin(paypal::sync_merchant_onboarding_status(
state.clone(),
tracking_id,
))
.await?;
if let api::OnboardingStatus::PayPal(api::PayPalOnboardingStatus::Success(
ref paypal_onboarding_data,
)) = status
{
let connector_onboarding_conf = state.conf.connector_onboarding.get_inner();
let auth_details = oss_types::ConnectorAuthType::SignatureKey {
api_key: connector_onboarding_conf.paypal.client_secret.clone(),
key1: connector_onboarding_conf.paypal.client_id.clone(),
api_secret: Secret::new(
paypal_onboarding_data.payer_id.get_string_repr().to_owned(),
),
};
let update_mca_data = paypal::update_mca(
&state,
user_from_token.merchant_id,
request.connector_id.to_owned(),
auth_details,
)
.await?;
return Ok(ApplicationResponse::Json(api::OnboardingStatus::PayPal(
api::PayPalOnboardingStatus::ConnectorIntegrated(Box::new(update_mca_data)),
)));
}
Ok(ApplicationResponse::Json(status))
}
_ => Err(ApiErrorResponse::FlowNotSupported {
flow: "Connector onboarding".to_string(),
connector: request.connector.to_string(),
}
.into()),
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 56,
"total_crates": null
} |
fn_clm_router_get_action_url_-6090421623747606806 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/connector_onboarding
pub async fn get_action_url(
state: SessionState,
user_from_token: auth::UserFromToken,
request: api::ActionUrlRequest,
_req_state: ReqState,
) -> RouterResponse<api::ActionUrlResponse> {
utils::check_if_connector_exists(&state, &request.connector_id, &user_from_token.merchant_id)
.await?;
let connector_onboarding_conf = state.conf.connector_onboarding.get_inner();
let is_enabled = utils::is_enabled(request.connector, connector_onboarding_conf);
let tracking_id =
utils::get_tracking_id_from_configs(&state, &request.connector_id, request.connector)
.await?;
match (is_enabled, request.connector) {
(Some(true), enums::Connector::Paypal) => {
let action_url = Box::pin(paypal::get_action_url_from_paypal(
state,
tracking_id,
request.return_url,
))
.await?;
Ok(ApplicationResponse::Json(api::ActionUrlResponse::PayPal(
api::PayPalActionUrlResponse { action_url },
)))
}
_ => Err(ApiErrorResponse::FlowNotSupported {
flow: "Connector onboarding".to_string(),
connector: request.connector.to_string(),
}
.into()),
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 32,
"total_crates": null
} |
fn_clm_router_reset_tracking_id_-6090421623747606806 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/connector_onboarding
pub async fn reset_tracking_id(
state: SessionState,
user_from_token: auth::UserFromToken,
request: api::ResetTrackingIdRequest,
_req_state: ReqState,
) -> RouterResponse<()> {
utils::check_if_connector_exists(&state, &request.connector_id, &user_from_token.merchant_id)
.await?;
utils::set_tracking_id_in_configs(&state, &request.connector_id, request.connector).await?;
Ok(ApplicationResponse::StatusOk)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 14,
"total_crates": null
} |
fn_clm_router_perform_locking_action_8629356370946668334 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/api_locking
// Implementation of None for LockAction
pub async fn perform_locking_action<A>(
self,
state: &A,
merchant_id: common_utils::id_type::MerchantId,
) -> RouterResult<()>
where
A: SessionStateInfo,
{
match self {
Self::HoldMultiple { inputs } => {
let lock_retries = inputs
.iter()
.find_map(|input| input.override_lock_retries)
.unwrap_or(state.conf().lock_settings.lock_retries);
let request_id = state.get_request_id();
let redis_lock_expiry_seconds =
state.conf().lock_settings.redis_lock_expiry_seconds;
let redis_conn = state
.store()
.get_redis_conn()
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let redis_key_values = inputs
.iter()
.map(|input| input.get_redis_locking_key(&merchant_id))
.map(|key| (RedisKey::from(key.as_str()), request_id.clone()))
.collect::<Vec<_>>();
let delay_between_retries_in_milliseconds = state
.conf()
.lock_settings
.delay_between_retries_in_milliseconds;
for _retry in 0..lock_retries {
let results: Vec<redis::SetGetReply<_>> = redis_conn
.set_multiple_keys_if_not_exists_and_get_values(
&redis_key_values,
Some(i64::from(redis_lock_expiry_seconds)),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let lock_aqcuired = results.iter().all(|res| {
// each redis value must match the request_id
// if even 1 does match, the lock is not acquired
*res.get_value() == request_id
});
if lock_aqcuired {
logger::info!("Lock acquired for locking inputs {:?}", inputs);
return Ok(());
} else {
actix_time::sleep(tokio::time::Duration::from_millis(u64::from(
delay_between_retries_in_milliseconds,
)))
.await;
}
}
Err(report!(errors::ApiErrorResponse::ResourceBusy))
}
Self::Hold { input } => {
let redis_conn = state
.store()
.get_redis_conn()
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let redis_locking_key = input.get_redis_locking_key(&merchant_id);
let delay_between_retries_in_milliseconds = state
.conf()
.lock_settings
.delay_between_retries_in_milliseconds;
let redis_lock_expiry_seconds =
state.conf().lock_settings.redis_lock_expiry_seconds;
let lock_retries = input
.override_lock_retries
.unwrap_or(state.conf().lock_settings.lock_retries);
for _retry in 0..lock_retries {
let redis_lock_result = redis_conn
.set_key_if_not_exists_with_expiry(
&redis_locking_key.as_str().into(),
state.get_request_id(),
Some(i64::from(redis_lock_expiry_seconds)),
)
.await;
match redis_lock_result {
Ok(redis::SetnxReply::KeySet) => {
logger::info!("Lock acquired for locking input {:?}", input);
tracing::Span::current()
.record("redis_lock_acquired", redis_locking_key);
return Ok(());
}
Ok(redis::SetnxReply::KeyNotSet) => {
logger::info!(
"Lock busy by other request when tried for locking input {:?}",
input
);
actix_time::sleep(tokio::time::Duration::from_millis(u64::from(
delay_between_retries_in_milliseconds,
)))
.await;
}
Err(err) => {
return Err(err)
.change_context(errors::ApiErrorResponse::InternalServerError)
}
}
}
Err(report!(errors::ApiErrorResponse::ResourceBusy))
}
Self::QueueWithOk | Self::Drop | Self::NotApplicable => Ok(()),
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 117,
"total_crates": null
} |
fn_clm_router_free_lock_action_8629356370946668334 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/api_locking
// Implementation of None for LockAction
pub async fn free_lock_action<A>(
self,
state: &A,
merchant_id: common_utils::id_type::MerchantId,
) -> RouterResult<()>
where
A: SessionStateInfo,
{
match self {
Self::HoldMultiple { inputs } => {
let redis_conn = state
.store()
.get_redis_conn()
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let redis_locking_keys = inputs
.iter()
.map(|input| RedisKey::from(input.get_redis_locking_key(&merchant_id).as_str()))
.collect::<Vec<_>>();
let request_id = state.get_request_id();
let values = redis_conn
.get_multiple_keys::<String>(&redis_locking_keys)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let invalid_request_id_list = values
.iter()
.filter(|redis_value| **redis_value != request_id)
.flatten()
.collect::<Vec<_>>();
if !invalid_request_id_list.is_empty() {
logger::error!(
"The request_id which acquired the lock is not equal to the request_id requesting for releasing the lock.
Current request_id: {:?},
Redis request_ids : {:?}",
request_id,
invalid_request_id_list
);
Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable("The request_id which acquired the lock is not equal to the request_id requesting for releasing the lock")
} else {
Ok(())
}?;
let delete_result = redis_conn
.delete_multiple_keys(&redis_locking_keys)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let is_key_not_deleted = delete_result
.into_iter()
.any(|delete_reply| delete_reply.is_key_not_deleted());
if is_key_not_deleted {
Err(errors::ApiErrorResponse::InternalServerError).attach_printable(
"Status release lock called but key is not found in redis",
)
} else {
logger::info!("Lock freed for locking inputs {:?}", inputs);
Ok(())
}
}
Self::Hold { input } => {
let redis_conn = state
.store()
.get_redis_conn()
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let redis_locking_key = input.get_redis_locking_key(&merchant_id);
match redis_conn
.get_key::<Option<String>>(&redis_locking_key.as_str().into())
.await
{
Ok(val) => {
if val == state.get_request_id() {
match redis_conn
.delete_key(&redis_locking_key.as_str().into())
.await
{
Ok(redis::types::DelReply::KeyDeleted) => {
logger::info!("Lock freed for locking input {:?}", input);
tracing::Span::current()
.record("redis_lock_released", redis_locking_key);
Ok(())
}
Ok(redis::types::DelReply::KeyNotDeleted) => {
Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Status release lock called but key is not found in redis",
)
}
Err(error) => Err(error)
.change_context(errors::ApiErrorResponse::InternalServerError),
}
} else {
Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable("The request_id which acquired the lock is not equal to the request_id requesting for releasing the lock")
}
}
Err(error) => {
Err(error).change_context(errors::ApiErrorResponse::InternalServerError)
}
}
}
Self::QueueWithOk | Self::Drop | Self::NotApplicable => Ok(()),
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 101,
"total_crates": null
} |
fn_clm_router_get_redis_locking_key_8629356370946668334 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/api_locking
// Inherent implementation for LockingInput
fn get_redis_locking_key(&self, merchant_id: &common_utils::id_type::MerchantId) -> String {
format!(
"{}_{}_{}_{}",
API_LOCK_PREFIX,
merchant_id.get_string_repr(),
self.api_identifier,
self.unique_locking_key
)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 20,
"total_crates": null
} |
fn_clm_router_list_chat_conversations_-4781845038534438114 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/chat
pub async fn list_chat_conversations(
state: SessionState,
user_from_token: auth::UserFromToken,
req: chat_api::ChatListRequest,
) -> CustomResult<ApplicationResponse<chat_api::ChatListResponse>, ChatErrors> {
let role_info = roles::RoleInfo::from_role_id_org_id_tenant_id(
&state,
&user_from_token.role_id,
&user_from_token.org_id,
user_from_token
.tenant_id
.as_ref()
.unwrap_or(&state.tenant.tenant_id),
)
.await
.change_context(ChatErrors::InternalServerError)
.attach_printable("Failed to retrieve role information")?;
if !role_info.is_internal() {
return Err(error_stack::Report::new(ChatErrors::UnauthorizedAccess)
.attach_printable("Only internal roles are allowed for this operation"));
}
let db = state.store.as_ref();
let hyperswitch_ai_interactions = db
.list_hyperswitch_ai_interactions(
req.merchant_id,
req.limit.unwrap_or(consts::DEFAULT_LIST_LIMIT),
req.offset.unwrap_or(consts::DEFAULT_LIST_OFFSET),
)
.await
.change_context(ChatErrors::InternalServerError)
.attach_printable("Error when fetching hyperswitch_ai_interactions")?;
let encryption_key = state.conf.chat.get_inner().encryption_key.clone().expose();
let key = match hex::decode(&encryption_key) {
Ok(key) => key,
Err(e) => {
router_env::logger::error!("Failed to decode encryption key: {}", e);
encryption_key.as_bytes().to_vec()
}
};
let mut conversations = Vec::new();
for interaction in hyperswitch_ai_interactions {
let user_query_encrypted = interaction
.user_query
.ok_or(ChatErrors::InternalServerError)
.attach_printable("Missing user_query field in hyperswitch_ai_interaction")?;
let response_encrypted = interaction
.response
.ok_or(ChatErrors::InternalServerError)
.attach_printable("Missing response field in hyperswitch_ai_interaction")?;
let user_query_decrypted_bytes = GcmAes256
.decode_message(&key, user_query_encrypted.into_inner())
.change_context(ChatErrors::InternalServerError)
.attach_printable("Failed to decrypt user query")?;
let response_decrypted_bytes = GcmAes256
.decode_message(&key, response_encrypted.into_inner())
.change_context(ChatErrors::InternalServerError)
.attach_printable("Failed to decrypt response")?;
let user_query_decrypted = String::from_utf8(user_query_decrypted_bytes)
.change_context(ChatErrors::InternalServerError)
.attach_printable("Failed to convert decrypted user query to string")?;
let response_decrypted = serde_json::from_slice(&response_decrypted_bytes)
.change_context(ChatErrors::InternalServerError)
.attach_printable("Failed to deserialize decrypted response")?;
conversations.push(chat_api::ChatConversation {
id: interaction.id,
session_id: interaction.session_id,
user_id: interaction.user_id,
merchant_id: interaction.merchant_id,
profile_id: interaction.profile_id,
org_id: interaction.org_id,
role_id: interaction.role_id,
user_query: user_query_decrypted.into(),
response: response_decrypted,
database_query: interaction.database_query,
interaction_status: interaction.interaction_status,
created_at: interaction.created_at,
});
}
return Ok(ApplicationResponse::Json(chat_api::ChatListResponse {
conversations,
}));
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 97,
"total_crates": null
} |
fn_clm_router_get_data_from_hyperswitch_ai_workflow_-4781845038534438114 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/chat
pub async fn get_data_from_hyperswitch_ai_workflow(
state: SessionState,
user_from_token: auth::UserFromToken,
req: chat_api::ChatRequest,
session_id: Option<&str>,
) -> CustomResult<ApplicationResponse<chat_api::ChatResponse>, ChatErrors> {
let role_info = roles::RoleInfo::from_role_id_org_id_tenant_id(
&state,
&user_from_token.role_id,
&user_from_token.org_id,
user_from_token
.tenant_id
.as_ref()
.unwrap_or(&state.tenant.tenant_id),
)
.await
.change_context(ChatErrors::InternalServerError)
.attach_printable("Failed to retrieve role information")?;
let url = format!(
"{}/webhook",
state.conf.chat.get_inner().hyperswitch_ai_host
);
let request_id = state
.get_request_id()
.unwrap_or_else(|| uuid::Uuid::new_v4().to_string());
let request_body = chat_domain::HyperswitchAiDataRequest {
query: chat_domain::GetDataMessage {
message: req.message.clone(),
},
org_id: user_from_token.org_id.clone(),
merchant_id: user_from_token.merchant_id.clone(),
profile_id: user_from_token.profile_id.clone(),
entity_type: role_info.get_entity_type(),
};
logger::info!("Request for AI service: {:?}", request_body);
let mut request_builder = RequestBuilder::new()
.method(Method::Post)
.url(&url)
.attach_default_headers()
.header(consts::X_REQUEST_ID, &request_id)
.set_body(RequestContent::Json(Box::new(request_body.clone())));
if let Some(session_id) = session_id {
request_builder = request_builder.header(consts::X_CHAT_SESSION_ID, session_id);
}
let request = request_builder.build();
let response = http_client::send_request(
&state.conf.proxy,
request,
Some(consts::REQUEST_TIME_OUT_FOR_AI_SERVICE),
)
.await
.change_context(ChatErrors::InternalServerError)
.attach_printable("Error when sending request to AI service")?
.json::<chat_api::ChatResponse>()
.await
.change_context(ChatErrors::InternalServerError)
.attach_printable("Error when deserializing response from AI service")?;
let response_to_return = response.clone();
tokio::spawn(
async move {
let new_hyperswitch_ai_interaction = utils::chat::construct_hyperswitch_ai_interaction(
&state,
&user_from_token,
&req,
&response,
&request_id,
)
.await;
match new_hyperswitch_ai_interaction {
Ok(interaction) => {
let db = state.store.as_ref();
if let Err(e) = db.insert_hyperswitch_ai_interaction(interaction).await {
logger::error!("Failed to insert hyperswitch_ai_interaction: {:?}", e);
}
}
Err(e) => {
logger::error!("Failed to construct hyperswitch_ai_interaction: {:?}", e);
}
}
}
.in_current_span(),
);
Ok(ApplicationResponse::Json(response_to_return))
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 87,
"total_crates": null
} |
fn_clm_router_foreign_try_from_8118401249331794696 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/pm_auth
// Implementation of PlaidAuthType for ForeignTryFrom<&types::ConnectorAuthType>
fn foreign_try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
types::ConnectorAuthType::BodyKey { api_key, key1 } => {
Ok::<Self, errors::ConnectorError>(Self {
client_id: api_key.to_owned(),
secret: key1.to_owned(),
})
}
_ => Err(errors::ConnectorError::FailedToObtainAuthType),
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 432,
"total_crates": null
} |
fn_clm_router_retrieve_payment_method_from_auth_service_8118401249331794696 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/pm_auth
pub async fn retrieve_payment_method_from_auth_service(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
auth_token: &payment_methods::BankAccountTokenData,
payment_intent: &PaymentIntent,
_customer: &Option<domain::Customer>,
) -> RouterResult<Option<(domain::PaymentMethodData, enums::PaymentMethod)>> {
let db = state.store.as_ref();
let connector = PaymentAuthConnectorData::get_connector_by_name(
auth_token.connector_details.connector.as_str(),
)?;
let key_manager_state = &state.into();
let merchant_account = db
.find_merchant_account_by_merchant_id(
key_manager_state,
&payment_intent.merchant_id,
key_store,
)
.await
.to_not_found_response(ApiErrorResponse::MerchantAccountNotFound)?;
#[cfg(feature = "v1")]
let mca = db
.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
key_manager_state,
&payment_intent.merchant_id,
&auth_token.connector_details.mca_id,
key_store,
)
.await
.to_not_found_response(ApiErrorResponse::MerchantConnectorAccountNotFound {
id: auth_token
.connector_details
.mca_id
.get_string_repr()
.to_string()
.clone(),
})
.attach_printable(
"error while fetching merchant_connector_account from merchant_id and connector name",
)?;
let auth_type = pm_auth_helpers::get_connector_auth_type(mca)?;
let BankAccountAccessCreds::AccessToken(access_token) =
&auth_token.connector_details.access_token;
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(domain::Context(
merchant_account.clone(),
key_store.clone(),
)));
let bank_account_creds = get_bank_account_creds(
connector,
&merchant_context,
&auth_token.connector_details.connector,
access_token,
auth_type,
state,
Some(auth_token.connector_details.account_id.clone()),
)
.await?;
let bank_account = bank_account_creds
.credentials
.iter()
.find(|acc| {
acc.payment_method_type == auth_token.payment_method_type
&& acc.payment_method == auth_token.payment_method
})
.ok_or(ApiErrorResponse::InternalServerError)
.attach_printable("Bank account details not found")?;
if let (Some(balance), Some(currency)) = (bank_account.balance, payment_intent.currency) {
let required_conversion = util_types::FloatMajorUnitForConnector;
let converted_amount = required_conversion
.convert_back(balance, currency)
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Could not convert FloatMajorUnit to MinorUnit")?;
if converted_amount < payment_intent.amount {
return Err((ApiErrorResponse::PreconditionFailed {
message: "selected bank account has insufficient balance".to_string(),
})
.into());
}
}
let mut bank_type = None;
if let Some(account_type) = bank_account.account_type.clone() {
bank_type = common_enums::BankType::from_str(account_type.as_str())
.map_err(|error| logger::error!(%error,"unable to parse account_type {account_type:?}"))
.ok();
}
let payment_method_data = match &bank_account.account_details {
pm_auth_types::PaymentMethodTypeDetails::Ach(ach) => {
domain::PaymentMethodData::BankDebit(domain::BankDebitData::AchBankDebit {
account_number: ach.account_number.clone(),
routing_number: ach.routing_number.clone(),
bank_name: None,
bank_type,
bank_holder_type: None,
card_holder_name: None,
bank_account_holder_name: None,
})
}
pm_auth_types::PaymentMethodTypeDetails::Bacs(bacs) => {
domain::PaymentMethodData::BankDebit(domain::BankDebitData::BacsBankDebit {
account_number: bacs.account_number.clone(),
sort_code: bacs.sort_code.clone(),
bank_account_holder_name: None,
})
}
pm_auth_types::PaymentMethodTypeDetails::Sepa(sepa) => {
domain::PaymentMethodData::BankDebit(domain::BankDebitData::SepaBankDebit {
iban: sepa.iban.clone(),
bank_account_holder_name: None,
})
}
};
Ok(Some((payment_method_data, enums::PaymentMethod::BankDebit)))
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 100,
"total_crates": null
} |
fn_clm_router_exchange_token_core_8118401249331794696 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/pm_auth
pub async fn exchange_token_core(
state: SessionState,
merchant_context: domain::MerchantContext,
payload: api_models::pm_auth::ExchangeTokenCreateRequest,
) -> RouterResponse<()> {
let db = &*state.store;
let config = get_selected_config_from_redis(db, &payload).await?;
let connector_name = config.connector_name.as_str();
let connector = PaymentAuthConnectorData::get_connector_by_name(connector_name)?;
#[cfg(feature = "v1")]
let merchant_connector_account = state
.store
.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
&(&state).into(),
merchant_context.get_merchant_account().get_id(),
&config.mca_id,
merchant_context.get_merchant_key_store(),
)
.await
.change_context(ApiErrorResponse::MerchantConnectorAccountNotFound {
id: merchant_context
.get_merchant_account()
.get_id()
.get_string_repr()
.to_owned(),
})?;
#[cfg(feature = "v2")]
let merchant_connector_account: domain::MerchantConnectorAccount = {
let _ = merchant_context.get_merchant_account();
let _ = connector;
let _ = merchant_context.get_merchant_key_store();
todo!()
};
let auth_type = helpers::get_connector_auth_type(merchant_connector_account.clone())?;
let access_token = get_access_token_from_exchange_api(
&connector,
connector_name,
&payload,
&auth_type,
&state,
)
.await?;
let bank_account_details_resp = get_bank_account_creds(
connector,
&merchant_context,
connector_name,
&access_token,
auth_type,
&state,
None,
)
.await?;
Box::pin(store_bank_details_in_payment_methods(
payload,
merchant_context,
state,
bank_account_details_resp,
(connector_name, access_token),
merchant_connector_account.get_id(),
))
.await?;
Ok(ApplicationResponse::StatusOk)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 57,
"total_crates": null
} |
fn_clm_router_get_selected_config_from_redis_8118401249331794696 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/pm_auth
async fn get_selected_config_from_redis(
db: &dyn StorageInterface,
payload: &api_models::pm_auth::ExchangeTokenCreateRequest,
) -> RouterResult<api_models::pm_auth::PaymentMethodAuthConnectorChoice> {
let redis_conn = db
.get_redis_conn()
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get redis connection")?;
let pm_auth_key = payload.payment_id.get_pm_auth_key();
redis_conn
.exists::<Vec<u8>>(&pm_auth_key.as_str().into())
.await
.change_context(ApiErrorResponse::InvalidRequestData {
message: "Incorrect payment_id provided in request".to_string(),
})
.attach_printable("Corresponding pm_auth_key does not exist in redis")?
.then_some(())
.ok_or(ApiErrorResponse::InvalidRequestData {
message: "Incorrect payment_id provided in request".to_string(),
})
.attach_printable("Corresponding pm_auth_key does not exist in redis")?;
let pm_auth_configs = redis_conn
.get_and_deserialize_key::<Vec<api_models::pm_auth::PaymentMethodAuthConnectorChoice>>(
&pm_auth_key.as_str().into(),
"Vec<PaymentMethodAuthConnectorChoice>",
)
.await
.change_context(ApiErrorResponse::GenericNotFoundError {
message: "payment method auth connector name not found".to_string(),
})
.attach_printable("Failed to get payment method auth choices from redis")?;
let selected_config = pm_auth_configs
.iter()
.find(|conf| {
conf.payment_method == payload.payment_method
&& conf.payment_method_type == payload.payment_method_type
})
.ok_or(ApiErrorResponse::GenericNotFoundError {
message: "payment method auth connector name not found".to_string(),
})?
.clone();
Ok(selected_config)
}
| {
"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_get_bank_account_creds_8118401249331794696 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/pm_auth
pub async fn get_bank_account_creds(
connector: PaymentAuthConnectorData,
merchant_context: &domain::MerchantContext,
connector_name: &str,
access_token: &Secret<String>,
auth_type: pm_auth_types::ConnectorAuthType,
state: &SessionState,
bank_account_id: Option<Secret<String>>,
) -> RouterResult<pm_auth_types::BankAccountCredentialsResponse> {
let connector_integration_bank_details: BoxedConnectorIntegration<
'_,
BankAccountCredentials,
pm_auth_types::BankAccountCredentialsRequest,
pm_auth_types::BankAccountCredentialsResponse,
> = connector.connector.get_connector_integration();
let router_data_bank_details = pm_auth_types::BankDetailsRouterData {
flow: std::marker::PhantomData,
merchant_id: Some(merchant_context.get_merchant_account().get_id().clone()),
connector: Some(connector_name.to_string()),
request: pm_auth_types::BankAccountCredentialsRequest {
access_token: access_token.clone(),
optional_ids: bank_account_id
.map(|id| pm_auth_types::BankAccountOptionalIDs { ids: vec![id] }),
},
response: Ok(pm_auth_types::BankAccountCredentialsResponse {
credentials: Vec::new(),
}),
connector_http_status_code: None,
connector_auth_type: auth_type,
};
let bank_details_resp = pm_auth_services::execute_connector_processing_step(
state,
connector_integration_bank_details,
&router_data_bank_details,
&connector.connector_name,
)
.await
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed while calling bank account details connector api")?;
let bank_account_details_resp =
bank_details_resp
.response
.map_err(|err| ApiErrorResponse::ExternalConnectorError {
code: err.code,
message: err.message,
connector: connector.connector_name.to_string(),
status_code: err.status_code,
reason: err.reason,
})?;
Ok(bank_account_details_resp)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 42,
"total_crates": null
} |
fn_clm_router_from_-8434373141473389824 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/tokenization
// Implementation of SavePaymentMethodData<Req> for From<&types::RouterData<F, Req, types::PaymentsResponseData>>
fn from(router_data: &types::RouterData<F, Req, types::PaymentsResponseData>) -> Self {
Self {
request: router_data.request.clone(),
response: router_data.response.clone(),
payment_method_token: router_data.payment_method_token.clone(),
payment_method: router_data.payment_method,
attempt_status: router_data.status,
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 2606,
"total_crates": null
} |
fn_clm_router_save_card_and_network_token_in_locker_-8434373141473389824 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/tokenization
pub async fn save_card_and_network_token_in_locker(
state: &SessionState,
customer_id: id_type::CustomerId,
payment_method_status: common_enums::PaymentMethodStatus,
payment_method_data: domain::PaymentMethodData,
vault_operation: Option<hyperswitch_domain_models::payments::VaultOperation>,
payment_method_info: Option<domain::PaymentMethod>,
merchant_context: &domain::MerchantContext,
payment_method_create_request: api::PaymentMethodCreate,
is_network_tokenization_enabled: bool,
business_profile: &domain::Profile,
) -> RouterResult<(
(
api_models::payment_methods::PaymentMethodResponse,
Option<payment_methods::transformers::DataDuplicationCheck>,
Option<String>,
),
Option<api_models::payment_methods::PaymentMethodResponse>,
)> {
let network_token_requestor_reference_id = payment_method_info
.and_then(|pm_info| pm_info.network_token_requestor_reference_id.clone());
match vault_operation {
Some(hyperswitch_domain_models::payments::VaultOperation::SaveCardData(card)) => {
let card_data = api::CardDetail::from(card.card_data.clone());
if let (Some(nt_ref_id), Some(tokenization_service)) = (
card.network_token_req_ref_id.clone(),
&state.conf.network_tokenization_service,
) {
let _ = record_operation_time(
async {
network_tokenization::delete_network_token_from_tokenization_service(
state,
nt_ref_id.clone(),
&customer_id,
tokenization_service.get_inner(),
)
.await
},
&metrics::DELETE_NETWORK_TOKEN_TIME,
&[],
)
.await;
}
let (res, dc) = Box::pin(save_in_locker(
state,
merchant_context,
payment_method_create_request.to_owned(),
Some(card_data),
business_profile,
))
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Add Card In Locker Failed")?;
Ok(((res, dc, None), None))
}
Some(hyperswitch_domain_models::payments::VaultOperation::SaveCardAndNetworkTokenData(
save_card_and_network_token_data,
)) => {
let card_data =
api::CardDetail::from(save_card_and_network_token_data.card_data.clone());
let network_token_data = api::CardDetail::from(
save_card_and_network_token_data
.network_token
.network_token_data
.clone(),
);
if payment_method_status == common_enums::PaymentMethodStatus::Active {
let (res, dc) = Box::pin(save_in_locker_internal(
state,
merchant_context,
payment_method_create_request.to_owned(),
Some(card_data),
))
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Add Card In Locker Failed")?;
let (network_token_resp, _dc, _) = Box::pin(save_network_token_in_locker(
state,
merchant_context,
&save_card_and_network_token_data.card_data,
Some(network_token_data),
payment_method_create_request.clone(),
))
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Add Network Token In Locker Failed")?;
Ok((
(res, dc, network_token_requestor_reference_id),
network_token_resp,
))
} else {
if let (Some(nt_ref_id), Some(tokenization_service)) = (
network_token_requestor_reference_id.clone(),
&state.conf.network_tokenization_service,
) {
let _ = record_operation_time(
async {
network_tokenization::delete_network_token_from_tokenization_service(
state,
nt_ref_id.clone(),
&customer_id,
tokenization_service.get_inner(),
)
.await
},
&metrics::DELETE_NETWORK_TOKEN_TIME,
&[],
)
.await;
}
let (res, dc) = Box::pin(save_in_locker_internal(
state,
merchant_context,
payment_method_create_request.to_owned(),
Some(card_data),
))
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Add Card In Locker Failed")?;
Ok(((res, dc, None), None))
}
}
_ => {
let card_data = payment_method_create_request.card.clone();
let (res, dc) = Box::pin(save_in_locker(
state,
merchant_context,
payment_method_create_request.to_owned(),
card_data,
business_profile,
))
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Add Card In Locker Failed")?;
if is_network_tokenization_enabled {
match &payment_method_data {
domain::PaymentMethodData::Card(card) => {
let (
network_token_resp,
_network_token_duplication_check, //the duplication check is discarded, since each card has only one token, handling card duplication check will be suffice
network_token_requestor_ref_id,
) = Box::pin(save_network_token_in_locker(
state,
merchant_context,
card,
None,
payment_method_create_request.clone(),
))
.await?;
Ok((
(res, dc, network_token_requestor_ref_id),
network_token_resp,
))
}
_ => Ok(((res, dc, None), None)), //network_token_resp is None in case of other payment methods
}
} else {
Ok(((res, dc, None), None))
}
}
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 104,
"total_crates": null
} |
fn_clm_router_save_in_locker_external_-8434373141473389824 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/tokenization
pub async fn save_in_locker_external(
state: &SessionState,
merchant_context: &domain::MerchantContext,
payment_method_request: api::PaymentMethodCreate,
card_detail: Option<api::CardDetail>,
external_vault_connector_details: &ExternalVaultConnectorDetails,
) -> RouterResult<(
api_models::payment_methods::PaymentMethodResponse,
Option<payment_methods::transformers::DataDuplicationCheck>,
)> {
let customer_id = payment_method_request
.customer_id
.clone()
.get_required_value("customer_id")?;
// For external vault, we need to convert the card data to PaymentMethodVaultingData
if let Some(card) = card_detail {
let payment_method_vaulting_data =
hyperswitch_domain_models::vault::PaymentMethodVaultingData::Card(card.clone());
let external_vault_mca_id = external_vault_connector_details.vault_connector_id.clone();
let key_manager_state = &state.into();
let merchant_connector_account_details = state
.store
.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
key_manager_state,
merchant_context.get_merchant_account().get_id(),
&external_vault_mca_id,
merchant_context.get_merchant_key_store(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: external_vault_mca_id.get_string_repr().to_string(),
})?;
// Call vault_payment_method_external_v1
let vault_response = vault_payment_method_external_v1(
state,
&payment_method_vaulting_data,
merchant_context.get_merchant_account(),
merchant_connector_account_details,
)
.await?;
let payment_method_id = vault_response.vault_id.to_string().to_owned();
let card_detail = CardDetailFromLocker::from(card);
let pm_resp = api::PaymentMethodResponse {
merchant_id: merchant_context.get_merchant_account().get_id().to_owned(),
customer_id: Some(customer_id),
payment_method_id,
payment_method: payment_method_request.payment_method,
payment_method_type: payment_method_request.payment_method_type,
card: Some(card_detail),
recurring_enabled: Some(false),
installment_payment_enabled: Some(false),
payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]),
metadata: None,
created: Some(common_utils::date_time::now()),
#[cfg(feature = "payouts")]
bank_transfer: None,
last_used_at: Some(common_utils::date_time::now()),
client_secret: None,
};
Ok((pm_resp, None))
} else {
//Similar implementation is done for save in locker internal
let pm_id = common_utils::generate_id(consts::ID_LENGTH, "pm");
let payment_method_response = api::PaymentMethodResponse {
merchant_id: merchant_context.get_merchant_account().get_id().to_owned(),
customer_id: Some(customer_id),
payment_method_id: pm_id,
payment_method: payment_method_request.payment_method,
payment_method_type: payment_method_request.payment_method_type,
#[cfg(feature = "payouts")]
bank_transfer: None,
card: None,
metadata: None,
created: Some(common_utils::date_time::now()),
recurring_enabled: Some(false),
installment_payment_enabled: Some(false),
payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), //[#219]
last_used_at: Some(common_utils::date_time::now()),
client_secret: None,
};
Ok((payment_method_response, None))
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 71,
"total_crates": null
} |
fn_clm_router_save_network_token_in_locker_-8434373141473389824 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/tokenization
pub async fn save_network_token_in_locker(
state: &SessionState,
merchant_context: &domain::MerchantContext,
card_data: &payment_method_data::Card,
network_token_data: Option<api::CardDetail>,
payment_method_request: api::PaymentMethodCreate,
) -> RouterResult<(
Option<api_models::payment_methods::PaymentMethodResponse>,
Option<payment_methods::transformers::DataDuplicationCheck>,
Option<String>,
)> {
let customer_id = payment_method_request
.customer_id
.clone()
.get_required_value("customer_id")?;
let network_tokenization_supported_card_networks = &state
.conf
.network_tokenization_supported_card_networks
.card_networks;
match network_token_data {
Some(nt_data) => {
let (res, dc) = Box::pin(
PmCards {
state,
merchant_context,
}
.add_card_to_locker(
payment_method_request,
&nt_data,
&customer_id,
None,
),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Add Network Token Failed")?;
Ok((Some(res), dc, None))
}
None => {
if card_data
.card_network
.as_ref()
.filter(|cn| network_tokenization_supported_card_networks.contains(cn))
.is_some()
{
let optional_card_cvc = Some(card_data.card_cvc.clone());
match network_tokenization::make_card_network_tokenization_request(
state,
&domain::CardDetail::from(card_data),
optional_card_cvc,
&customer_id,
)
.await
{
Ok((token_response, network_token_requestor_ref_id)) => {
// Only proceed if the tokenization was successful
let network_token_data = api::CardDetail {
card_number: token_response.token.clone(),
card_exp_month: token_response.token_expiry_month.clone(),
card_exp_year: token_response.token_expiry_year.clone(),
card_holder_name: None,
nick_name: None,
card_issuing_country: None,
card_network: Some(token_response.card_brand.clone()),
card_issuer: None,
card_type: None,
};
let (res, dc) = Box::pin(
PmCards {
state,
merchant_context,
}
.add_card_to_locker(
payment_method_request,
&network_token_data,
&customer_id,
None,
),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Add Network Token Failed")?;
Ok((Some(res), dc, network_token_requestor_ref_id))
}
Err(err) => {
logger::error!("Failed to tokenize card: {:?}", err);
Ok((None, None, None)) //None will be returned in case of error when calling network tokenization service
}
}
} else {
Ok((None, None, None)) //None will be returned in case of unsupported card network.
}
}
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 58,
"total_crates": null
} |
fn_clm_router_add_payment_method_token_-8434373141473389824 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/tokenization
pub async fn add_payment_method_token<F: Clone, T: types::Tokenizable + Clone>(
state: &SessionState,
connector: &api::ConnectorData,
tokenization_action: &payments::TokenizationAction,
router_data: &mut types::RouterData<F, T, types::PaymentsResponseData>,
pm_token_request_data: types::PaymentMethodTokenizationData,
should_continue_payment: bool,
) -> RouterResult<types::PaymentMethodTokenResult> {
if should_continue_payment {
match tokenization_action {
payments::TokenizationAction::TokenizeInConnector => {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::PaymentMethodToken,
types::PaymentMethodTokenizationData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
let pm_token_response_data: Result<
types::PaymentsResponseData,
types::ErrorResponse,
> = Err(types::ErrorResponse::default());
let pm_token_router_data =
helpers::router_data_type_conversion::<_, api::PaymentMethodToken, _, _, _, _>(
router_data.clone(),
pm_token_request_data,
pm_token_response_data,
);
router_data
.request
.set_session_token(pm_token_router_data.session_token.clone());
let mut resp = services::execute_connector_processing_step(
state,
connector_integration,
&pm_token_router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.to_payment_failed_response()?;
// checks for metadata in the ErrorResponse, if present bypasses it and constructs an Ok response
handle_tokenization_response(&mut resp);
metrics::CONNECTOR_PAYMENT_METHOD_TOKENIZATION.add(
1,
router_env::metric_attributes!(
("connector", connector.connector_name.to_string()),
("payment_method", router_data.payment_method.to_string()),
),
);
let payment_token_resp = resp.response.map(|res| {
if let types::PaymentsResponseData::TokenizationResponse { token } = res {
Some(token)
} else {
None
}
});
Ok(types::PaymentMethodTokenResult {
payment_method_token_result: payment_token_resp,
is_payment_method_tokenization_performed: true,
connector_response: resp.connector_response.clone(),
})
}
_ => Ok(types::PaymentMethodTokenResult {
payment_method_token_result: Ok(None),
is_payment_method_tokenization_performed: false,
connector_response: None,
}),
}
} else {
logger::debug!("Skipping connector tokenization based on should_continue_payment flag");
Ok(types::PaymentMethodTokenResult {
payment_method_token_result: Ok(None),
is_payment_method_tokenization_performed: false,
connector_response: None,
})
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 47,
"total_crates": null
} |
fn_clm_router_new_-6472491989664968317 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/payment_methods
// Inherent implementation for RequiredFieldsInput
fn new(
required_fields_config: settings::RequiredFields,
setup_future_usage: common_enums::FutureUsage,
) -> Self {
Self {
required_fields_config,
setup_future_usage,
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 14453,
"total_crates": null
} |
fn_clm_router_generate_response_-6472491989664968317 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/payment_methods
// Inherent implementation for RequiredFieldsAndSurchargeWithExtraInfoForEnabledPaymentMethodTypes
fn generate_response(
self,
customer_payment_methods: Option<
Vec<api_models::payment_methods::CustomerPaymentMethodResponseItem>,
>,
) -> api_models::payments::PaymentMethodListResponseForPayments {
let response_payment_methods = self
.0
.into_iter()
.map(|payment_methods_enabled| {
api_models::payments::ResponsePaymentMethodTypesForPayments {
payment_method_type: payment_methods_enabled.payment_method_type,
payment_method_subtype: payment_methods_enabled.payment_method_subtype,
payment_experience: payment_methods_enabled.payment_experience,
required_fields: payment_methods_enabled.required_fields,
surcharge_details: payment_methods_enabled.surcharge,
extra_information: payment_methods_enabled.pm_subtype_specific_data,
}
})
.collect();
api_models::payments::PaymentMethodListResponseForPayments {
payment_methods_enabled: response_payment_methods,
customer_payment_methods,
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 71,
"total_crates": null
} |
fn_clm_router_list_payment_methods_-6472491989664968317 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/payment_methods
pub async fn list_payment_methods(
state: routes::SessionState,
merchant_context: domain::MerchantContext,
profile: domain::Profile,
payment_id: id_type::GlobalPaymentId,
req: api_models::payments::ListMethodsForPaymentsRequest,
header_payload: &hyperswitch_domain_models::payments::HeaderPayload,
) -> errors::RouterResponse<api_models::payments::PaymentMethodListResponseForPayments> {
let db = &*state.store;
let key_manager_state = &(&state).into();
let payment_intent = db
.find_payment_intent_by_id(
key_manager_state,
&payment_id,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
validate_payment_status_for_payment_method_list(payment_intent.status)?;
let payment_connector_accounts = db
.list_enabled_connector_accounts_by_profile_id(
key_manager_state,
profile.get_id(),
merchant_context.get_merchant_key_store(),
common_enums::ConnectorType::PaymentProcessor,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("error when fetching merchant connector accounts")?;
let customer_payment_methods = match &payment_intent.customer_id {
Some(customer_id) => Some(
payment_methods::list_customer_payment_methods_core(
&state,
&merchant_context,
customer_id,
)
.await?,
),
None => None,
};
let response =
FlattenedPaymentMethodsEnabled(hyperswitch_domain_models::merchant_connector_account::FlattenedPaymentMethodsEnabled::from_payment_connectors_list(payment_connector_accounts))
.perform_filtering(
&state,
&merchant_context,
profile.get_id(),
&req,
&payment_intent,
).await?
.store_gift_card_mca_in_redis(&payment_id, db, &profile).await
.merge_and_transform()
.get_required_fields(RequiredFieldsInput::new(state.conf.required_fields.clone(), payment_intent.setup_future_usage))
.perform_surcharge_calculation()
.populate_pm_subtype_specific_data(&state.conf.bank_config)
.generate_response(customer_payment_methods);
Ok(hyperswitch_domain_models::api::ApplicationResponse::Json(
response,
))
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 66,
"total_crates": null
} |
fn_clm_router_get_required_fields_-6472491989664968317 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/payment_methods
// Implementation of None for MergedEnabledPaymentMethodTypes
fn get_required_fields(
self,
input: RequiredFieldsInput,
) -> RequiredFieldsForEnabledPaymentMethodTypes {
let required_fields_config = input.required_fields_config;
let is_cit_transaction = input.setup_future_usage == common_enums::FutureUsage::OffSession;
let required_fields_info = self
.0
.into_iter()
.map(|payment_methods_enabled| {
let required_fields =
required_fields_config.get_required_fields(&payment_methods_enabled);
let required_fields = required_fields
.map(|required_fields| {
let common_required_fields = required_fields
.common
.iter()
.flatten()
.map(ToOwned::to_owned);
// Collect mandate required fields because this is for zero auth mandates only
let mandate_required_fields = required_fields
.mandate
.iter()
.flatten()
.map(ToOwned::to_owned);
// Collect non-mandate required fields because this is for zero auth mandates only
let non_mandate_required_fields = required_fields
.non_mandate
.iter()
.flatten()
.map(ToOwned::to_owned);
// Combine mandate and non-mandate required fields based on setup_future_usage
if is_cit_transaction {
common_required_fields
.chain(non_mandate_required_fields)
.collect::<Vec<_>>()
} else {
common_required_fields
.chain(mandate_required_fields)
.collect::<Vec<_>>()
}
})
.unwrap_or_default();
RequiredFieldsForEnabledPaymentMethod {
required_fields,
payment_method_type: payment_methods_enabled.payment_method_type,
payment_method_subtype: payment_methods_enabled.payment_method_subtype,
payment_experience: payment_methods_enabled.payment_experience,
connectors: payment_methods_enabled.connectors,
}
})
.collect();
RequiredFieldsForEnabledPaymentMethodTypes(required_fields_info)
}
| {
"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_filter_payment_methods_-6472491989664968317 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/payment_methods
pub async fn filter_payment_methods(
payment_method_type_details: hyperswitch_domain_models::merchant_connector_account::PaymentMethodsEnabledForConnector,
req: &api_models::payments::ListMethodsForPaymentsRequest,
resp: &mut Vec<
hyperswitch_domain_models::merchant_connector_account::PaymentMethodsEnabledForConnector,
>,
payment_intent: Option<&storage::PaymentIntent>,
address: Option<&hyperswitch_domain_models::address::AddressDetails>,
configs: &settings::Settings<RawSecret>,
) -> errors::CustomResult<(), errors::ApiErrorResponse> {
let payment_method = payment_method_type_details.payment_method;
let mut payment_method_object = payment_method_type_details.payment_methods_enabled.clone();
// filter based on request parameters
let request_based_filter =
filter_recurring_based(&payment_method_object, req.recurring_enabled)
&& filter_amount_based(&payment_method_object, req.amount)
&& filter_card_network_based(
payment_method_object.card_networks.as_ref(),
req.card_networks.as_ref(),
payment_method_object.payment_method_subtype,
);
// filter based on payment intent
let intent_based_filter = if let Some(payment_intent) = payment_intent {
filter_country_based(address, &payment_method_object)
&& filter_currency_based(
payment_intent.amount_details.currency,
&payment_method_object,
)
&& filter_amount_based(
&payment_method_object,
Some(payment_intent.amount_details.calculate_net_amount()),
)
&& filter_zero_mandate_based(configs, payment_intent, &payment_method_type_details)
&& filter_allowed_payment_method_types_based(
payment_intent.allowed_payment_method_types.as_ref(),
payment_method_object.payment_method_subtype,
)
} else {
true
};
// filter based on payment method type configuration
let config_based_filter = filter_config_based(
configs,
&payment_method_type_details.connector.to_string(),
payment_method_object.payment_method_subtype,
payment_intent,
&mut payment_method_object.card_networks,
address.and_then(|inner| inner.country),
payment_intent.map(|value| value.amount_details.currency),
);
// if all filters pass, add the payment method type details to the response
if request_based_filter && intent_based_filter && config_based_filter {
resp.push(payment_method_type_details);
}
Ok(())
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 55,
"total_crates": null
} |
fn_clm_router_new_3021069567140654933 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/types
// Implementation of None for SurchargeMetadata
pub fn new(payment_attempt_id: String) -> Self {
Self {
surcharge_results: HashMap::new(),
payment_attempt_id,
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 14465,
"total_crates": null
} |
fn_clm_router_foreign_try_from_3021069567140654933 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/types
// Implementation of AuthenticationData for ForeignTryFrom<
&hyperswitch_domain_models::router_request_types::authentication::AuthenticationStore,
>
fn foreign_try_from(
authentication_store: &hyperswitch_domain_models::router_request_types::authentication::AuthenticationStore,
) -> Result<Self, Self::Error> {
let authentication = &authentication_store.authentication;
if authentication.authentication_status == common_enums::AuthenticationStatus::Success {
let threeds_server_transaction_id =
authentication.threeds_server_transaction_id.clone();
let message_version = authentication.message_version.clone();
let cavv = authentication_store
.cavv
.clone()
.get_required_value("cavv")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("cavv must not be null when authentication_status is success")?;
Ok(Self {
eci: authentication.eci.clone(),
created_at: authentication.created_at,
cavv,
threeds_server_transaction_id,
message_version,
ds_trans_id: authentication.ds_trans_id.clone(),
authentication_type: authentication.authentication_type,
challenge_code: authentication.challenge_code.clone(),
challenge_cancel: authentication.challenge_cancel.clone(),
challenge_code_reason: authentication.challenge_code_reason.clone(),
message_extension: authentication.message_extension.clone(),
acs_trans_id: authentication.acs_trans_id.clone(),
})
} else {
Err(errors::ApiErrorResponse::PaymentAuthenticationFailed { data: None }.into())
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 456,
"total_crates": null
} |
fn_clm_router_persist_individual_surcharge_details_in_redis_3021069567140654933 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/types
// Implementation of None for SurchargeMetadata
pub async fn persist_individual_surcharge_details_in_redis(
&self,
state: &SessionState,
business_profile: &Profile,
) -> RouterResult<()> {
if !self.is_empty_result() {
let redis_conn = state
.store
.get_redis_conn()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get redis connection")?;
let redis_key = Self::get_surcharge_metadata_redis_key(&self.payment_attempt_id);
let mut value_list = Vec::with_capacity(self.get_surcharge_results_size());
for (key, value) in self.get_individual_surcharge_key_value_pairs().into_iter() {
value_list.push((
key,
value
.encode_to_string_of_json()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to encode to string of json")?,
));
}
let intent_fulfillment_time = business_profile
.get_order_fulfillment_time()
.unwrap_or(router_consts::DEFAULT_FULFILLMENT_TIME);
redis_conn
.set_hash_fields(
&redis_key.as_str().into(),
value_list,
Some(intent_fulfillment_time),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to write to redis")?;
logger::debug!("Surcharge results stored in redis with key = {}", redis_key);
}
Ok(())
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 64,
"total_crates": null
} |
fn_clm_router_get_surcharge_details_3021069567140654933 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/types
// Implementation of None for SurchargeMetadata
pub fn get_surcharge_details(&self, surcharge_key: SurchargeKey) -> Option<&SurchargeDetails> {
self.surcharge_results.get(&surcharge_key)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 41,
"total_crates": null
} |
fn_clm_router_get_status_count_3021069567140654933 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/types
// Inherent implementation for MultipleCaptureData
pub fn get_status_count(&self) -> HashMap<storage_enums::CaptureStatus, i16> {
let mut hash_map: HashMap<storage_enums::CaptureStatus, i16> = HashMap::new();
hash_map.insert(storage_enums::CaptureStatus::Charged, 0);
hash_map.insert(storage_enums::CaptureStatus::Pending, 0);
hash_map.insert(storage_enums::CaptureStatus::Started, 0);
hash_map.insert(storage_enums::CaptureStatus::Failed, 0);
self.all_captures
.iter()
.fold(hash_map, |mut accumulator, capture| {
let current_capture_status = capture.1.status;
accumulator
.entry(current_capture_status)
.and_modify(|count| *count += 1);
accumulator
})
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 39,
"total_crates": null
} |
fn_clm_router_try_from_6001464818622983390 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/transformers
// Implementation of types::PaymentsPreProcessingData for TryFrom<PaymentAdditionalData<'_, F>>
fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> {
let payment_data = additional_data.payment_data;
let payment_method_data = payment_data.payment_method_data;
let router_base_url = &additional_data.router_base_url;
let attempt = &payment_data.payment_attempt;
let connector_name = &additional_data.connector_name;
let order_details = payment_data
.payment_intent
.order_details
.map(|order_details| {
order_details
.iter()
.map(|data| {
data.to_owned()
.parse_value("OrderDetailsWithAmount")
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "OrderDetailsWithAmount",
})
.attach_printable("Unable to parse OrderDetailsWithAmount")
})
.collect::<Result<Vec<_>, _>>()
})
.transpose()?;
let merchant_connector_account_id_or_connector_name = payment_data
.payment_attempt
.merchant_connector_id
.as_ref()
.map(|mca_id| mca_id.get_string_repr())
.unwrap_or(connector_name);
let webhook_url = Some(helpers::create_webhook_url(
router_base_url,
&attempt.merchant_id,
merchant_connector_account_id_or_connector_name,
));
let router_return_url = Some(helpers::create_redirect_url(
router_base_url,
attempt,
connector_name,
payment_data.creds_identifier.as_deref(),
));
let complete_authorize_url = Some(helpers::create_complete_authorize_url(
router_base_url,
attempt,
connector_name,
payment_data.creds_identifier.as_deref(),
));
let browser_info: Option<types::BrowserInformation> = payment_data
.payment_attempt
.browser_info
.clone()
.map(|b| b.parse_value("BrowserInformation"))
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "browser_info",
})?;
let amount = payment_data.payment_attempt.get_total_amount();
Ok(Self {
payment_method_data,
email: payment_data.email,
currency: Some(payment_data.currency),
amount: Some(amount.get_amount_as_i64()), // need to change this once we move to connector module
minor_amount: Some(amount),
payment_method_type: payment_data.payment_attempt.payment_method_type,
setup_mandate_details: payment_data.setup_mandate,
capture_method: payment_data.payment_attempt.capture_method,
order_details,
router_return_url,
webhook_url,
complete_authorize_url,
browser_info,
surcharge_details: payment_data.surcharge_details,
connector_transaction_id: payment_data
.payment_attempt
.get_connector_payment_id()
.map(ToString::to_string),
redirect_response: None,
mandate_id: payment_data.mandate_id,
related_transaction_id: None,
enrolled_for_3ds: true,
split_payments: payment_data.payment_intent.split_payments,
metadata: payment_data.payment_intent.metadata.map(Secret::new),
customer_acceptance: payment_data.customer_acceptance,
setup_future_usage: payment_data.payment_intent.setup_future_usage,
is_stored_credential: payment_data.payment_attempt.is_stored_credential,
})
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 2711,
"total_crates": null
} |
fn_clm_router_from_6001464818622983390 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/transformers
// Implementation of domain::NetworkTokenData for From<pm_types::TokenResponse>
fn from(token_response: pm_types::TokenResponse) -> Self {
Self {
token_number: token_response.authentication_details.token,
token_exp_month: token_response.token_details.exp_month,
token_exp_year: token_response.token_details.exp_year,
token_cryptogram: Some(token_response.authentication_details.cryptogram),
card_issuer: None,
card_network: Some(token_response.network),
card_type: None,
card_issuing_country: None,
bank_code: None,
nick_name: None,
eci: None,
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 2600,
"total_crates": null
} |
fn_clm_router_payments_to_payments_response_6001464818622983390 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/transformers
pub fn payments_to_payments_response<Op, F: Clone, D>(
payment_data: D,
captures: Option<Vec<storage::Capture>>,
customer: Option<domain::Customer>,
_auth_flow: services::AuthFlow,
base_url: &str,
operation: &Op,
connector_request_reference_id_config: &ConnectorRequestReferenceIdConfig,
connector_http_status_code: Option<u16>,
external_latency: Option<u128>,
_is_latency_header_enabled: Option<bool>,
) -> RouterResponse<api::PaymentsResponse>
where
Op: Debug,
D: OperationSessionGetters<F>,
{
use std::ops::Not;
use hyperswitch_interfaces::consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE};
let payment_attempt = payment_data.get_payment_attempt().clone();
let payment_intent = payment_data.get_payment_intent().clone();
let payment_link_data = payment_data.get_payment_link_data();
let currency = payment_attempt
.currency
.as_ref()
.get_required_value("currency")?;
let amount = currency
.to_currency_base_unit(
payment_attempt
.net_amount
.get_total_amount()
.get_amount_as_i64(),
)
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "amount",
})?;
let mandate_id = payment_attempt.mandate_id.clone();
let refunds_response = payment_data.get_refunds().is_empty().not().then(|| {
payment_data
.get_refunds()
.into_iter()
.map(ForeignInto::foreign_into)
.collect()
});
let disputes_response = payment_data.get_disputes().is_empty().not().then(|| {
payment_data
.get_disputes()
.into_iter()
.map(ForeignInto::foreign_into)
.collect()
});
let incremental_authorizations_response =
payment_data.get_authorizations().is_empty().not().then(|| {
payment_data
.get_authorizations()
.into_iter()
.map(ForeignInto::foreign_into)
.collect()
});
let external_authentication_details = payment_data
.get_authentication()
.map(ForeignInto::foreign_into);
let attempts_response = payment_data.get_attempts().map(|attempts| {
attempts
.into_iter()
.map(ForeignInto::foreign_into)
.collect()
});
let captures_response = captures.map(|captures| {
captures
.into_iter()
.map(ForeignInto::foreign_into)
.collect()
});
let merchant_id = payment_attempt.merchant_id.to_owned();
let payment_method_type = payment_attempt
.payment_method_type
.as_ref()
.map(ToString::to_string)
.unwrap_or("".to_owned());
let payment_method = payment_attempt
.payment_method
.as_ref()
.map(ToString::to_string)
.unwrap_or("".to_owned());
let additional_payment_method_data: Option<api_models::payments::AdditionalPaymentData> =
payment_attempt
.payment_method_data
.clone()
.and_then(|data| match data {
serde_json::Value::Null => None, // This is to handle the case when the payment_method_data is null
_ => Some(data.parse_value("AdditionalPaymentData")),
})
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to parse the AdditionalPaymentData from payment_attempt.payment_method_data")?;
let surcharge_details =
payment_attempt
.net_amount
.get_surcharge_amount()
.map(|surcharge_amount| RequestSurchargeDetails {
surcharge_amount,
tax_amount: payment_attempt.net_amount.get_tax_on_surcharge(),
});
let merchant_decision = payment_intent.merchant_decision.to_owned();
let frm_message = payment_data.get_frm_message().map(FrmMessage::foreign_from);
let payment_method_data =
additional_payment_method_data.map(api::PaymentMethodDataResponse::from);
let payment_method_data_response = (payment_method_data.is_some()
|| payment_data
.get_address()
.get_request_payment_method_billing()
.is_some())
.then_some(api_models::payments::PaymentMethodDataResponseWithBilling {
payment_method_data,
billing: payment_data
.get_address()
.get_request_payment_method_billing()
.cloned()
.map(From::from),
});
let mut headers = connector_http_status_code
.map(|status_code| {
vec![(
X_CONNECTOR_HTTP_STATUS_CODE.to_string(),
Maskable::new_normal(status_code.to_string()),
)]
})
.unwrap_or_default();
if let Some(payment_confirm_source) = payment_intent.payment_confirm_source {
headers.push((
X_PAYMENT_CONFIRM_SOURCE.to_string(),
Maskable::new_normal(payment_confirm_source.to_string()),
))
}
// For the case when we don't have Customer data directly stored in Payment intent
let customer_table_response: Option<CustomerDetailsResponse> =
customer.as_ref().map(ForeignInto::foreign_into);
// If we have customer data in Payment Intent and if the customer is not deleted, We are populating the Retrieve response from the
// same. If the customer is deleted then we use the customer table to populate customer details
let customer_details_response =
if let Some(customer_details_raw) = payment_intent.customer_details.clone() {
let customer_details_encrypted =
serde_json::from_value::<CustomerData>(customer_details_raw.into_inner().expose());
if let Ok(customer_details_encrypted_data) = customer_details_encrypted {
Some(CustomerDetailsResponse {
id: customer_table_response
.as_ref()
.and_then(|customer_data| customer_data.id.clone()),
name: customer_table_response
.as_ref()
.and_then(|customer_data| customer_data.name.clone())
.or(customer_details_encrypted_data
.name
.or(customer.as_ref().and_then(|customer| {
customer.name.as_ref().map(|name| name.clone().into_inner())
}))),
email: customer_table_response
.as_ref()
.and_then(|customer_data| customer_data.email.clone())
.or(customer_details_encrypted_data.email.or(customer
.as_ref()
.and_then(|customer| customer.email.clone().map(pii::Email::from)))),
phone: customer_table_response
.as_ref()
.and_then(|customer_data| customer_data.phone.clone())
.or(customer_details_encrypted_data
.phone
.or(customer.as_ref().and_then(|customer| {
customer
.phone
.as_ref()
.map(|phone| phone.clone().into_inner())
}))),
phone_country_code: customer_table_response
.as_ref()
.and_then(|customer_data| customer_data.phone_country_code.clone())
.or(customer_details_encrypted_data
.phone_country_code
.or(customer
.as_ref()
.and_then(|customer| customer.phone_country_code.clone()))),
})
} else {
customer_table_response
}
} else {
customer_table_response
};
headers.extend(
external_latency
.map(|latency| {
vec![(
X_HS_LATENCY.to_string(),
Maskable::new_normal(latency.to_string()),
)]
})
.unwrap_or_default(),
);
let connector_name = payment_attempt.connector.as_deref().unwrap_or_default();
let router_return_url = helpers::create_redirect_url(
&base_url.to_string(),
&payment_attempt,
connector_name,
payment_data.get_creds_identifier(),
);
let output = if payments::is_start_pay(&operation)
&& payment_attempt.authentication_data.is_some()
{
let redirection_data = payment_attempt
.authentication_data
.clone()
.get_required_value("redirection_data")?;
let form: RedirectForm = serde_json::from_value(redirection_data)
.map_err(|_| errors::ApiErrorResponse::InternalServerError)?;
services::ApplicationResponse::Form(Box::new(services::RedirectionFormData {
redirect_form: form,
payment_method_data: payment_data.get_payment_method_data().cloned(),
amount,
currency: currency.to_string(),
}))
} else {
let mut next_action_response = None;
// Early exit for terminal payment statuses - don't evaluate next_action at all
if payment_intent.status.is_in_terminal_state() {
next_action_response = None;
} else {
let bank_transfer_next_steps = bank_transfer_next_steps_check(payment_attempt.clone())?;
let next_action_voucher = voucher_next_steps_check(payment_attempt.clone())?;
let next_action_mobile_payment = mobile_payment_next_steps_check(&payment_attempt)?;
let next_action_containing_qr_code_url =
qr_code_next_steps_check(payment_attempt.clone())?;
let papal_sdk_next_action = paypal_sdk_next_steps_check(payment_attempt.clone())?;
let next_action_containing_fetch_qr_code_url =
fetch_qr_code_url_next_steps_check(payment_attempt.clone())?;
let next_action_containing_wait_screen =
wait_screen_next_steps_check(payment_attempt.clone())?;
let next_action_containing_sdk_upi_intent =
extract_sdk_uri_information(payment_attempt.clone())?;
let next_action_invoke_hidden_frame =
next_action_invoke_hidden_frame(&payment_attempt)?;
if payment_intent.status == enums::IntentStatus::RequiresCustomerAction
|| bank_transfer_next_steps.is_some()
|| next_action_voucher.is_some()
|| next_action_containing_qr_code_url.is_some()
|| next_action_containing_wait_screen.is_some()
|| next_action_containing_sdk_upi_intent.is_some()
|| papal_sdk_next_action.is_some()
|| next_action_containing_fetch_qr_code_url.is_some()
|| payment_data.get_authentication().is_some()
{
next_action_response = bank_transfer_next_steps
.map(|bank_transfer| {
api_models::payments::NextActionData::DisplayBankTransferInformation {
bank_transfer_steps_and_charges_details: bank_transfer,
}
})
.or(next_action_voucher.map(|voucher_data| {
api_models::payments::NextActionData::DisplayVoucherInformation {
voucher_details: voucher_data,
}
}))
.or(next_action_mobile_payment.map(|mobile_payment_data| {
api_models::payments::NextActionData::CollectOtp {
consent_data_required: mobile_payment_data.consent_data_required,
}
}))
.or(next_action_containing_qr_code_url.map(|qr_code_data| {
api_models::payments::NextActionData::foreign_from(qr_code_data)
}))
.or(next_action_containing_fetch_qr_code_url.map(|fetch_qr_code_data| {
api_models::payments::NextActionData::FetchQrCodeInformation {
qr_code_fetch_url: fetch_qr_code_data.qr_code_fetch_url
}
}))
.or(papal_sdk_next_action.map(|paypal_next_action_data| {
api_models::payments::NextActionData::InvokeSdkClient{
next_action_data: paypal_next_action_data
}
}))
.or(next_action_containing_sdk_upi_intent.map(|sdk_uri_data| {
api_models::payments::NextActionData::SdkUpiIntentInformation {
sdk_uri: sdk_uri_data.sdk_uri,
}
}))
.or(next_action_containing_wait_screen.map(|wait_screen_data| {
api_models::payments::NextActionData::WaitScreenInformation {
display_from_timestamp: wait_screen_data.display_from_timestamp,
display_to_timestamp: wait_screen_data.display_to_timestamp,
poll_config: wait_screen_data.poll_config,
}
}))
.or(payment_attempt.authentication_data.as_ref().map(|_| {
// Check if iframe redirection is enabled in the business profile
let redirect_url = helpers::create_startpay_url(
base_url,
&payment_attempt,
&payment_intent,
);
// Check if redirection inside popup is enabled in the payment intent
if payment_intent.is_iframe_redirection_enabled.unwrap_or(false) {
api_models::payments::NextActionData::RedirectInsidePopup {
popup_url: redirect_url,
redirect_response_url:router_return_url
}
} else {
api_models::payments::NextActionData::RedirectToUrl {
redirect_to_url: redirect_url,
}
}
}))
.or(match payment_data.get_authentication(){
Some(authentication_store) => {
let authentication = &authentication_store.authentication;
if payment_intent.status == common_enums::IntentStatus::RequiresCustomerAction && authentication_store.cavv.is_none() && authentication.is_separate_authn_required(){
// if preAuthn and separate authentication needed.
let poll_config = payment_data.get_poll_config().unwrap_or_default();
let request_poll_id = core_utils::get_external_authentication_request_poll_id(&payment_intent.payment_id);
let payment_connector_name = payment_attempt.connector
.as_ref()
.get_required_value("connector")?;
let is_jwt_flow = authentication.is_jwt_flow()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to determine if the authentication is JWT flow")?;
Some(api_models::payments::NextActionData::ThreeDsInvoke {
three_ds_data: api_models::payments::ThreeDsData {
three_ds_authentication_url: helpers::create_authentication_url(base_url, &payment_attempt),
three_ds_authorize_url: helpers::create_authorize_url(
base_url,
&payment_attempt,
payment_connector_name,
),
three_ds_method_details: authentication.three_ds_method_url.as_ref().zip(authentication.three_ds_method_data.as_ref()).map(|(three_ds_method_url,three_ds_method_data )|{
api_models::payments::ThreeDsMethodData::AcsThreeDsMethodData {
three_ds_method_data_submission: true,
three_ds_method_data: Some(three_ds_method_data.clone()),
three_ds_method_url: Some(three_ds_method_url.to_owned()),
three_ds_method_key: if is_jwt_flow {
Some(api_models::payments::ThreeDsMethodKey::JWT)
} else {
Some(api_models::payments::ThreeDsMethodKey::ThreeDsMethodData)
},
// In JWT flow, we need to wait for post message to get the result
consume_post_message_for_three_ds_method_completion: is_jwt_flow,
}
}).unwrap_or(api_models::payments::ThreeDsMethodData::AcsThreeDsMethodData {
three_ds_method_data_submission: false,
three_ds_method_data: None,
three_ds_method_url: None,
three_ds_method_key: None,
consume_post_message_for_three_ds_method_completion: false,
}),
poll_config: api_models::payments::PollConfigResponse {poll_id: request_poll_id, delay_in_secs: poll_config.delay_in_secs, frequency: poll_config.frequency},
message_version: authentication.message_version.as_ref()
.map(|version| version.to_string()),
directory_server_id: authentication.directory_server_id.clone(),
},
})
}else{
None
}
},
None => None
})
.or(match next_action_invoke_hidden_frame{
Some(threeds_invoke_data) => Some(construct_connector_invoke_hidden_frame(
threeds_invoke_data,
)?),
None => None
});
}
};
// next action check for third party sdk session (for ex: Apple pay through trustpay has third party sdk session response)
if third_party_sdk_session_next_action(&payment_attempt, operation) {
next_action_response = Some(
api_models::payments::NextActionData::ThirdPartySdkSessionToken {
session_token: payment_data.get_sessions_token().first().cloned(),
},
)
}
let routed_through = payment_attempt.connector.clone();
let connector_label = routed_through.as_ref().and_then(|connector_name| {
core_utils::get_connector_label(
payment_intent.business_country,
payment_intent.business_label.as_ref(),
payment_attempt.business_sub_label.as_ref(),
connector_name,
)
});
let mandate_data = payment_data.get_setup_mandate().map(|d| api::MandateData {
customer_acceptance: d.customer_acceptance.clone(),
mandate_type: d.mandate_type.clone().map(|d| match d {
hyperswitch_domain_models::mandates::MandateDataType::MultiUse(Some(i)) => {
api::MandateType::MultiUse(Some(api::MandateAmountData {
amount: i.amount,
currency: i.currency,
start_date: i.start_date,
end_date: i.end_date,
metadata: i.metadata,
}))
}
hyperswitch_domain_models::mandates::MandateDataType::SingleUse(i) => {
api::MandateType::SingleUse(api::payments::MandateAmountData {
amount: i.amount,
currency: i.currency,
start_date: i.start_date,
end_date: i.end_date,
metadata: i.metadata,
})
}
hyperswitch_domain_models::mandates::MandateDataType::MultiUse(None) => {
api::MandateType::MultiUse(None)
}
}),
update_mandate_id: d.update_mandate_id.clone(),
});
let order_tax_amount = payment_data
.get_payment_attempt()
.net_amount
.get_order_tax_amount()
.or_else(|| {
payment_data
.get_payment_intent()
.tax_details
.clone()
.and_then(|tax| {
tax.payment_method_type
.map(|a| a.order_tax_amount)
.or_else(|| tax.default.map(|a| a.order_tax_amount))
})
});
let connector_mandate_id = payment_data.get_mandate_id().and_then(|mandate| {
mandate
.mandate_reference_id
.as_ref()
.and_then(|mandate_ref| match mandate_ref {
api_models::payments::MandateReferenceId::ConnectorMandateId(
connector_mandate_reference_id,
) => connector_mandate_reference_id.get_connector_mandate_id(),
_ => None,
})
});
let connector_transaction_id = payment_attempt
.get_connector_payment_id()
.map(ToString::to_string);
let manual_retry_allowed = match payment_data.get_is_manual_retry_enabled() {
Some(true) => helpers::is_manual_retry_allowed(
&payment_intent.status,
&payment_attempt.status,
connector_request_reference_id_config,
&merchant_id,
),
Some(false) | None => None,
};
let payments_response = api::PaymentsResponse {
payment_id: payment_intent.payment_id,
merchant_id: payment_intent.merchant_id,
status: payment_intent.status,
amount: payment_attempt.net_amount.get_order_amount(),
net_amount: payment_attempt.get_total_amount(),
amount_capturable: payment_attempt.amount_capturable,
amount_received: payment_intent.amount_captured,
connector: routed_through,
client_secret: payment_intent.client_secret.map(Secret::new),
created: Some(payment_intent.created_at),
currency: currency.to_string(),
customer_id: customer.as_ref().map(|cus| cus.clone().customer_id),
customer: customer_details_response,
description: payment_intent.description,
refunds: refunds_response,
disputes: disputes_response,
attempts: attempts_response,
captures: captures_response,
mandate_id,
mandate_data,
setup_future_usage: payment_attempt.setup_future_usage_applied,
off_session: payment_intent.off_session,
capture_on: None,
capture_method: payment_attempt.capture_method,
payment_method: payment_attempt.payment_method,
payment_method_data: payment_method_data_response,
payment_token: payment_attempt.payment_token,
shipping: payment_data
.get_address()
.get_shipping()
.cloned()
.map(From::from),
billing: payment_data
.get_address()
.get_payment_billing()
.cloned()
.map(From::from),
order_details: payment_intent.order_details,
email: customer
.as_ref()
.and_then(|cus| cus.email.as_ref().map(|s| s.to_owned())),
name: customer
.as_ref()
.and_then(|cus| cus.name.as_ref().map(|s| s.to_owned())),
phone: customer
.as_ref()
.and_then(|cus| cus.phone.as_ref().map(|s| s.to_owned())),
return_url: payment_intent.return_url,
authentication_type: payment_attempt.authentication_type,
statement_descriptor_name: payment_intent.statement_descriptor_name,
statement_descriptor_suffix: payment_intent.statement_descriptor_suffix,
next_action: next_action_response,
cancellation_reason: payment_attempt.cancellation_reason,
error_code: payment_attempt
.error_code
.filter(|code| code != NO_ERROR_CODE),
error_message: payment_attempt
.error_reason
.or(payment_attempt.error_message)
.filter(|message| message != NO_ERROR_MESSAGE),
unified_code: payment_attempt.unified_code,
unified_message: payment_attempt.unified_message,
payment_experience: payment_attempt.payment_experience,
payment_method_type: payment_attempt.payment_method_type,
connector_label,
business_country: payment_intent.business_country,
business_label: payment_intent.business_label,
business_sub_label: payment_attempt.business_sub_label,
allowed_payment_method_types: payment_intent.allowed_payment_method_types,
ephemeral_key: payment_data
.get_ephemeral_key()
.map(ForeignFrom::foreign_from),
manual_retry_allowed,
connector_transaction_id,
frm_message,
metadata: payment_intent.metadata,
connector_metadata: payment_intent.connector_metadata,
feature_metadata: payment_intent.feature_metadata,
reference_id: payment_attempt.connector_response_reference_id,
payment_link: payment_link_data,
profile_id: payment_intent.profile_id,
surcharge_details,
attempt_count: payment_intent.attempt_count,
merchant_decision,
merchant_connector_id: payment_attempt.merchant_connector_id,
incremental_authorization_allowed: payment_intent.incremental_authorization_allowed,
authorization_count: payment_intent.authorization_count,
incremental_authorizations: incremental_authorizations_response,
external_authentication_details,
external_3ds_authentication_attempted: payment_attempt
.external_three_ds_authentication_attempted,
expires_on: payment_intent.session_expiry,
fingerprint: payment_intent.fingerprint_id,
browser_info: payment_attempt.browser_info,
payment_method_id: payment_attempt.payment_method_id,
network_transaction_id: payment_attempt.network_transaction_id,
payment_method_status: payment_data
.get_payment_method_info()
.map(|info| info.status),
updated: Some(payment_intent.modified_at),
split_payments: payment_attempt.charges,
frm_metadata: payment_intent.frm_metadata,
merchant_order_reference_id: payment_intent.merchant_order_reference_id,
order_tax_amount,
connector_mandate_id,
mit_category: payment_intent.mit_category,
shipping_cost: payment_intent.shipping_cost,
capture_before: payment_attempt.capture_before,
extended_authorization_applied: payment_attempt.extended_authorization_applied,
card_discovery: payment_attempt.card_discovery,
force_3ds_challenge: payment_intent.force_3ds_challenge,
force_3ds_challenge_trigger: payment_intent.force_3ds_challenge_trigger,
issuer_error_code: payment_attempt.issuer_error_code,
issuer_error_message: payment_attempt.issuer_error_message,
is_iframe_redirection_enabled: payment_intent.is_iframe_redirection_enabled,
whole_connector_response: payment_data.get_whole_connector_response(),
payment_channel: payment_intent.payment_channel,
enable_partial_authorization: payment_intent.enable_partial_authorization,
enable_overcapture: payment_intent.enable_overcapture,
is_overcapture_enabled: payment_attempt.is_overcapture_enabled,
network_details: payment_attempt
.network_details
.map(NetworkDetails::foreign_from),
is_stored_credential: payment_attempt.is_stored_credential,
request_extended_authorization: payment_attempt.request_extended_authorization,
};
services::ApplicationResponse::JsonWithHeaders((payments_response, headers))
};
metrics::PAYMENT_OPS_COUNT.add(
1,
router_env::metric_attributes!(
("operation", format!("{:?}", operation)),
("merchant", merchant_id.clone()),
("payment_method_type", payment_method_type),
("payment_method", payment_method),
),
);
Ok(output)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 617,
"total_crates": null
} |
fn_clm_router_foreign_try_from_6001464818622983390 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/transformers
// Implementation of storage::CaptureUpdate for ForeignTryFrom<types::CaptureSyncResponse>
fn foreign_try_from(
capture_sync_response: types::CaptureSyncResponse,
) -> Result<Self, Self::Error> {
match capture_sync_response {
types::CaptureSyncResponse::Success {
resource_id,
status,
connector_response_reference_id,
..
} => {
let (connector_capture_id, processor_capture_data) = match resource_id {
types::ResponseId::EncodedData(_) | types::ResponseId::NoResponseId => {
(None, None)
}
types::ResponseId::ConnectorTransactionId(id) => {
let (txn_id, txn_data) =
common_utils_type::ConnectorTransactionId::form_id_and_data(id);
(Some(txn_id), txn_data)
}
};
Ok(Self::ResponseUpdate {
status: enums::CaptureStatus::foreign_try_from(status)?,
connector_capture_id,
connector_response_reference_id,
processor_capture_data,
})
}
types::CaptureSyncResponse::Error {
code,
message,
reason,
status_code,
..
} => Ok(Self::ErrorUpdate {
status: match status_code {
500..=511 => enums::CaptureStatus::Pending,
_ => enums::CaptureStatus::Failed,
},
error_code: Some(code),
error_message: Some(message),
error_reason: reason,
}),
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 432,
"total_crates": null
} |
fn_clm_router_construct_payment_router_data_6001464818622983390 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/transformers
pub async fn construct_payment_router_data<'a, F, T>(
state: &'a SessionState,
payment_data: PaymentData<F>,
connector_id: &str,
merchant_context: &domain::MerchantContext,
customer: &'a 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::RouterData<F, T, types::PaymentsResponseData>>
where
T: TryFrom<PaymentAdditionalData<'a, F>>,
types::RouterData<F, T, types::PaymentsResponseData>: Feature<F, T>,
F: Clone,
error_stack::Report<errors::ApiErrorResponse>:
From<<T as TryFrom<PaymentAdditionalData<'a, F>>>::Error>,
{
fp_utils::when(merchant_connector_account.is_disabled(), || {
Err(errors::ApiErrorResponse::MerchantConnectorAccountDisabled)
})?;
let test_mode = merchant_connector_account.is_test_mode_on();
let auth_type: types::ConnectorAuthType = merchant_connector_account
.get_connector_account_details()
.parse_value("ConnectorAuthType")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while parsing value for ConnectorAuthType")?;
let payment_method = payment_data
.payment_attempt
.payment_method
.or(payment_method)
.get_required_value("payment_method")?;
let payment_method_type = payment_data
.payment_attempt
.payment_method_type
.or(payment_method_type);
let resource_id = match payment_data
.payment_attempt
.get_connector_payment_id()
.map(ToString::to_string)
{
Some(id) => types::ResponseId::ConnectorTransactionId(id),
None => types::ResponseId::NoResponseId,
};
// [#44]: why should response be filled during request
let response = Ok(types::PaymentsResponseData::TransactionResponse {
resource_id,
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
});
let additional_data = PaymentAdditionalData {
router_base_url: state.base_url.clone(),
connector_name: connector_id.to_string(),
payment_data: payment_data.clone(),
state,
customer_data: customer,
};
let customer_id = customer.to_owned().map(|customer| customer.customer_id);
let supported_connector = &state
.conf
.multiple_api_version_supported_connectors
.supported_connectors;
let connector_enum = api_models::enums::Connector::from_str(connector_id)
.change_context(errors::ConnectorError::InvalidConnectorName)
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "connector",
})
.attach_printable_lazy(|| format!("unable to parse connector name {connector_id:?}"))?;
let connector_api_version = if supported_connector.contains(&connector_enum) {
state
.store
.find_config_by_key(&format!("connector_api_version_{connector_id}"))
.await
.map(|value| value.config)
.ok()
} else {
None
};
let apple_pay_flow = payments::decide_apple_pay_flow(
state,
payment_data.payment_attempt.payment_method_type,
Some(merchant_connector_account),
);
let unified_address = if let Some(payment_method_info) =
payment_data.payment_method_info.clone()
{
let payment_method_billing = payment_method_info
.payment_method_billing_address
.map(|decrypted_data| decrypted_data.into_inner().expose())
.map(|decrypted_value| decrypted_value.parse_value("payment_method_billing_address"))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to parse payment_method_billing_address")?;
payment_data
.address
.clone()
.unify_with_payment_data_billing(payment_method_billing)
} else {
payment_data.address
};
let connector_mandate_request_reference_id = payment_data
.payment_attempt
.connector_mandate_detail
.as_ref()
.and_then(|detail| detail.get_connector_mandate_request_reference_id());
let order_details = payment_data
.payment_intent
.order_details
.as_ref()
.map(|order_details| {
order_details
.iter()
.map(|data| {
data.to_owned()
.parse_value("OrderDetailsWithAmount")
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "OrderDetailsWithAmount",
})
.attach_printable("Unable to parse OrderDetailsWithAmount")
})
.collect::<Result<Vec<_>, _>>()
})
.transpose()?;
let l2_l3_data =
(state.conf.l2_l3_data_config.enabled && payment_data.is_l2_l3_enabled).then(|| {
let shipping_address = unified_address.get_shipping();
let billing_address = unified_address.get_payment_billing();
let merchant_tax_registration_id = merchant_context
.get_merchant_account()
.get_merchant_tax_registration_id();
Box::new(types::L2L3Data {
order_date: payment_data.payment_intent.order_date,
tax_status: payment_data.payment_intent.tax_status,
customer_tax_registration_id: customer.as_ref().and_then(|c| {
c.tax_registration_id
.as_ref()
.map(|e| e.clone().into_inner())
}),
order_details: order_details.clone(),
discount_amount: payment_data.payment_intent.discount_amount,
shipping_cost: payment_data.payment_intent.shipping_cost,
shipping_amount_tax: payment_data.payment_intent.shipping_amount_tax,
duty_amount: payment_data.payment_intent.duty_amount,
order_tax_amount: payment_data
.payment_attempt
.net_amount
.get_order_tax_amount(),
merchant_order_reference_id: payment_data
.payment_intent
.merchant_order_reference_id
.clone(),
customer_id: payment_data.payment_intent.customer_id.clone(),
billing_address_city: billing_address
.as_ref()
.and_then(|addr| addr.address.as_ref())
.and_then(|details| details.city.clone()),
merchant_tax_registration_id,
customer_name: customer
.as_ref()
.and_then(|c| c.name.as_ref().map(|e| e.clone().into_inner())),
customer_email: payment_data.email,
customer_phone_number: customer
.as_ref()
.and_then(|c| c.phone.as_ref().map(|e| e.clone().into_inner())),
customer_phone_country_code: customer
.as_ref()
.and_then(|c| c.phone_country_code.clone()),
shipping_details: shipping_address
.and_then(|address| address.address.as_ref())
.cloned(),
})
});
crate::logger::debug!("unified address details {:?}", unified_address);
let router_data = types::RouterData {
flow: PhantomData,
merchant_id: merchant_context.get_merchant_account().get_id().clone(),
customer_id,
tenant_id: state.tenant.tenant_id.clone(),
connector: connector_id.to_owned(),
payment_id: payment_data
.payment_attempt
.payment_id
.get_string_repr()
.to_owned(),
attempt_id: payment_data.payment_attempt.attempt_id.clone(),
status: payment_data.payment_attempt.status,
payment_method,
payment_method_type,
connector_auth_type: auth_type,
description: payment_data.payment_intent.description.clone(),
address: unified_address,
auth_type: payment_data
.payment_attempt
.authentication_type
.unwrap_or_default(),
connector_meta_data: merchant_connector_account.get_metadata(),
connector_wallets_details: merchant_connector_account.get_connector_wallets_details(),
request: T::try_from(additional_data)?,
response,
amount_captured: payment_data
.payment_intent
.amount_captured
.map(|amt| amt.get_amount_as_i64()),
minor_amount_captured: payment_data.payment_intent.amount_captured,
access_token: None,
session_token: None,
reference_id: None,
payment_method_status: payment_data.payment_method_info.map(|info| info.status),
payment_method_token: payment_data
.pm_token
.map(|token| types::PaymentMethodToken::Token(Secret::new(token))),
connector_customer: payment_data.connector_customer_id,
recurring_mandate_payment_data: payment_data.recurring_mandate_payment_data,
connector_request_reference_id: core_utils::get_connector_request_reference_id(
&state.conf,
merchant_context.get_merchant_account().get_id(),
&payment_data.payment_intent,
&payment_data.payment_attempt,
connector_id,
)?,
preprocessing_id: payment_data.payment_attempt.preprocessing_step_id,
#[cfg(feature = "payouts")]
payout_method_data: None,
#[cfg(feature = "payouts")]
quote_id: None,
test_mode,
payment_method_balance: None,
connector_api_version,
connector_http_status_code: None,
external_latency: None,
apple_pay_flow,
frm_metadata: None,
refund_id: None,
dispute_id: None,
connector_response: None,
integrity_check: Ok(()),
additional_merchant_data: merchant_recipient_data.map(|data| {
api_models::admin::AdditionalMerchantData::foreign_from(
types::AdditionalMerchantData::OpenBankingRecipientData(data),
)
}),
header_payload,
connector_mandate_request_reference_id,
authentication_id: None,
psd2_sca_exemption_type: payment_data.payment_intent.psd2_sca_exemption_type,
raw_connector_response: None,
is_payment_id_from_merchant: payment_data.payment_intent.is_payment_id_from_merchant,
l2_l3_data,
minor_amount_capturable: None,
authorized_amount: None,
};
Ok(router_data)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 242,
"total_crates": null
} |
fn_clm_router_perform_decision_management_2645889128143593602 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/conditional_configs
pub fn perform_decision_management(
record: common_types::payments::DecisionManagerRecord,
payment_data: &core_routing::PaymentsDslInput<'_>,
) -> RouterResult<common_types::payments::ConditionalConfigs> {
let interpreter = backend::VirInterpreterBackend::with_program(record.program)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error initializing DSL interpreter backend")?;
let backend_input = make_dsl_input(payment_data)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error constructing DSL input")?;
execute_dsl_and_get_conditional_config(backend_input, &interpreter)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error executing DSL")
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 31,
"total_crates": null
} |
fn_clm_router_execute_dsl_and_get_conditional_config_2645889128143593602 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/conditional_configs
pub fn execute_dsl_and_get_conditional_config(
backend_input: dsl_inputs::BackendInput,
interpreter: &backend::VirInterpreterBackend<common_types::payments::ConditionalConfigs>,
) -> ConditionalConfigResult<common_types::payments::ConditionalConfigs> {
let routing_output = interpreter
.execute(backend_input)
.map(|out| out.connector_selection)
.change_context(ConfigError::DslExecutionError)?;
Ok(routing_output)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 22,
"total_crates": null
} |
fn_clm_router_populate_vault_session_details_-3529627794324716991 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/vault_session
pub async fn populate_vault_session_details<F, RouterDReq, ApiRequest, D>(
state: &SessionState,
req_state: ReqState,
customer: &Option<domain::Customer>,
merchant_context: &domain::MerchantContext,
operation: &BoxedOperation<'_, F, ApiRequest, D>,
profile: &domain::Profile,
payment_data: &mut D,
header_payload: HeaderPayload,
) -> RouterResult<()>
where
F: Send + Clone + Sync,
RouterDReq: Send + Sync,
// To create connector flow specific interface data
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
D: ConstructFlowSpecificData<F, RouterDReq, router_types::PaymentsResponseData>,
RouterData<F, RouterDReq, router_types::PaymentsResponseData>: Feature<F, RouterDReq> + Send,
// To construct connector flow specific api
dyn api::Connector:
services::api::ConnectorIntegration<F, RouterDReq, router_types::PaymentsResponseData>,
{
let is_external_vault_sdk_enabled = profile.is_vault_sdk_enabled();
if is_external_vault_sdk_enabled {
let external_vault_source = profile
.external_vault_connector_details
.as_ref()
.map(|details| &details.vault_connector_id);
let merchant_connector_account =
domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(Box::new(
helpers::get_merchant_connector_account_v2(
state,
merchant_context.get_merchant_key_store(),
external_vault_source,
)
.await?,
));
let updated_customer = call_create_connector_customer_if_required(
state,
customer,
merchant_context,
&merchant_connector_account,
payment_data,
)
.await?;
if let Some((customer, updated_customer)) = customer.clone().zip(updated_customer) {
let db = &*state.store;
let customer_id = customer.get_id().clone();
let customer_merchant_id = customer.merchant_id.clone();
let _updated_customer = db
.update_customer_by_global_id(
&state.into(),
&customer_id,
customer,
updated_customer,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update customer during Vault session")?;
};
let vault_session_details = generate_vault_session_details(
state,
merchant_context,
&merchant_connector_account,
payment_data.get_connector_customer_id(),
)
.await?;
payment_data.set_vault_session_details(vault_session_details);
}
Ok(())
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 57,
"total_crates": null
} |
fn_clm_router_call_create_connector_customer_if_required_-3529627794324716991 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/vault_session
pub async fn call_create_connector_customer_if_required<F, Req, D>(
state: &SessionState,
customer: &Option<domain::Customer>,
merchant_context: &domain::MerchantContext,
merchant_connector_account_type: &domain::MerchantConnectorAccountTypeDetails,
payment_data: &mut D,
) -> RouterResult<Option<storage::CustomerUpdate>>
where
F: Send + Clone + Sync,
Req: Send + Sync,
// To create connector flow specific interface data
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
D: ConstructFlowSpecificData<F, Req, router_types::PaymentsResponseData>,
RouterData<F, Req, router_types::PaymentsResponseData>: Feature<F, Req> + Send,
// To construct connector flow specific api
dyn api::Connector:
services::api::ConnectorIntegration<F, Req, router_types::PaymentsResponseData>,
{
let db_merchant_connector_account =
merchant_connector_account_type.get_inner_db_merchant_connector_account();
match db_merchant_connector_account {
Some(merchant_connector_account) => {
let connector_name = merchant_connector_account.get_connector_name_as_string();
let merchant_connector_id = merchant_connector_account.get_id();
let connector = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
&connector_name,
api::GetToken::Connector,
Some(merchant_connector_id.clone()),
)?;
let (should_call_connector, existing_connector_customer_id) =
customers::should_call_connector_create_customer(
&connector,
customer,
payment_data.get_payment_attempt(),
merchant_connector_account_type,
);
if should_call_connector {
// Create customer at connector and update the customer table to store this data
let router_data = payment_data
.construct_router_data(
state,
connector.connector.id(),
merchant_context,
customer,
merchant_connector_account_type,
None,
None,
)
.await?;
let connector_customer_id = router_data
.create_connector_customer(state, &connector)
.await?;
let customer_update = customers::update_connector_customer_in_customers(
merchant_connector_account_type,
customer.as_ref(),
connector_customer_id.clone(),
)
.await;
payment_data.set_connector_customer_id(connector_customer_id);
Ok(customer_update)
} else {
// Customer already created in previous calls use the same value, no need to update
payment_data.set_connector_customer_id(
existing_connector_customer_id.map(ToOwned::to_owned),
);
Ok(None)
}
}
None => {
router_env::logger::error!(
"Merchant connector account is missing, cannot create customer for vault session"
);
Err(errors::ApiErrorResponse::InternalServerError.into())
}
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 50,
"total_crates": null
} |
fn_clm_router_generate_vault_session_details_-3529627794324716991 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/vault_session
pub async fn generate_vault_session_details(
state: &SessionState,
merchant_context: &domain::MerchantContext,
merchant_connector_account_type: &domain::MerchantConnectorAccountTypeDetails,
connector_customer_id: Option<String>,
) -> RouterResult<Option<api::VaultSessionDetails>> {
let connector_name = merchant_connector_account_type
.get_connector_name()
.map(|name| name.to_string())
.ok_or(errors::ApiErrorResponse::InternalServerError)?; // should not panic since we should always have a connector name
let connector = api_enums::VaultConnectors::from_str(&connector_name)
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let connector_auth_type: router_types::ConnectorAuthType = merchant_connector_account_type
.get_connector_account_details()
.map_err(|err| {
err.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to parse connector auth type")
})?;
match (connector, connector_auth_type) {
// create session for vgs vault
(
api_enums::VaultConnectors::Vgs,
router_types::ConnectorAuthType::SignatureKey { api_secret, .. },
) => {
let sdk_env = match state.conf.env {
Env::Sandbox | Env::Development => "sandbox",
Env::Production => "live",
}
.to_string();
Ok(Some(api::VaultSessionDetails::Vgs(
api::VgsSessionDetails {
external_vault_id: api_secret,
sdk_env,
},
)))
}
// create session for hyperswitch vault
(
api_enums::VaultConnectors::HyperswitchVault,
router_types::ConnectorAuthType::SignatureKey {
key1, api_secret, ..
},
) => {
generate_hyperswitch_vault_session_details(
state,
merchant_context,
merchant_connector_account_type,
connector_customer_id,
connector_name,
key1,
api_secret,
)
.await
}
_ => {
router_env::logger::warn!(
"External vault session creation is not supported for connector: {}",
connector_name
);
Ok(None)
}
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 39,
"total_crates": null
} |
fn_clm_router_call_external_vault_create_-3529627794324716991 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/vault_session
async fn call_external_vault_create(
state: &SessionState,
merchant_context: &domain::MerchantContext,
connector_name: String,
merchant_connector_account_type: &domain::MerchantConnectorAccountTypeDetails,
connector_customer_id: Option<String>,
) -> RouterResult<VaultRouterData<ExternalVaultCreateFlow>>
where
dyn ConnectorTrait + Sync: services::api::ConnectorIntegration<
ExternalVaultCreateFlow,
router_types::VaultRequestData,
router_types::VaultResponseData,
>,
dyn ConnectorV2 + Sync: ConnectorIntegrationV2<
ExternalVaultCreateFlow,
VaultConnectorFlowData,
router_types::VaultRequestData,
router_types::VaultResponseData,
>,
{
let connector_data: api::ConnectorData = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
&connector_name,
api::GetToken::Connector,
merchant_connector_account_type.get_mca_id(),
)?;
let merchant_connector_account = match &merchant_connector_account_type {
domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(mca) => {
Ok(mca.as_ref())
}
domain::MerchantConnectorAccountTypeDetails::MerchantConnectorDetails(_) => {
Err(report!(errors::ApiErrorResponse::InternalServerError)
.attach_printable("MerchantConnectorDetails not supported for vault operations"))
}
}?;
let mut router_data = core_utils::construct_vault_router_data(
state,
merchant_context.get_merchant_account().get_id(),
merchant_connector_account,
None,
None,
connector_customer_id,
)
.await?;
let mut old_router_data = VaultConnectorFlowData::to_old_router_data(router_data)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Cannot construct router data for making the external vault create api call",
)?;
let connector_integration: services::BoxedVaultConnectorIntegrationInterface<
ExternalVaultCreateFlow,
router_types::VaultRequestData,
router_types::VaultResponseData,
> = connector_data.connector.get_connector_integration();
services::execute_connector_processing_step(
state,
connector_integration,
&old_router_data,
CallConnectorAction::Trigger,
None,
None,
)
.await
.to_vault_failed_response()
}
| {
"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_generate_hyperswitch_vault_session_details_-3529627794324716991 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/vault_session
async fn generate_hyperswitch_vault_session_details(
state: &SessionState,
merchant_context: &domain::MerchantContext,
merchant_connector_account_type: &domain::MerchantConnectorAccountTypeDetails,
connector_customer_id: Option<String>,
connector_name: String,
vault_publishable_key: masking::Secret<String>,
vault_profile_id: masking::Secret<String>,
) -> RouterResult<Option<api::VaultSessionDetails>> {
let connector_response = call_external_vault_create(
state,
merchant_context,
connector_name,
merchant_connector_account_type,
connector_customer_id,
)
.await?;
match connector_response.response {
Ok(router_types::VaultResponseData::ExternalVaultCreateResponse {
session_id,
client_secret,
}) => Ok(Some(api::VaultSessionDetails::HyperswitchVault(
api::HyperswitchVaultSessionDetails {
payment_method_session_id: session_id,
client_secret,
publishable_key: vault_publishable_key,
profile_id: vault_profile_id,
},
))),
Ok(_) => {
router_env::logger::warn!("Unexpected response from external vault create API");
Err(errors::ApiErrorResponse::InternalServerError.into())
}
Err(err) => {
router_env::logger::error!(error_response_from_external_vault_create=?err);
Err(errors::ApiErrorResponse::InternalServerError.into())
}
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 11,
"total_crates": null
} |
fn_clm_router_add_access_token_-8833259768231780590 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/access_token
pub async fn add_access_token<
F: Clone + 'static,
Req: Debug + Clone + 'static,
Res: Debug + Clone + 'static,
>(
state: &SessionState,
connector: &api_types::ConnectorData,
merchant_context: &domain::MerchantContext,
router_data: &types::RouterData<F, Req, Res>,
creds_identifier: Option<&str>,
) -> RouterResult<types::AddAccessTokenResult> {
if connector
.connector_name
.supports_access_token(router_data.payment_method)
{
let merchant_id = merchant_context.get_merchant_account().get_id();
let store = &*state.store;
// `merchant_connector_id` may not be present in the below cases
// - when straight through routing is used without passing the `merchant_connector_id`
// - when creds identifier is passed
//
// In these cases fallback to `connector_name`.
// We cannot use multiple merchant connector account in these cases
let merchant_connector_id_or_connector_name = connector
.merchant_connector_id
.clone()
.map(|mca_id| mca_id.get_string_repr().to_string())
.or(creds_identifier.map(|id| id.to_string()))
.unwrap_or(connector.connector_name.to_string());
let old_access_token = store
.get_access_token(merchant_id, &merchant_connector_id_or_connector_name)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("DB error when accessing the access token")?;
let res = match old_access_token {
Some(access_token) => {
router_env::logger::debug!(
"Access token found in redis for merchant_id: {:?}, payment_id: {:?}, connector: {} which has expiry of: {} seconds",
merchant_context.get_merchant_account().get_id(),
router_data.payment_id,
connector.connector_name,
access_token.expires
);
metrics::ACCESS_TOKEN_CACHE_HIT.add(
1,
router_env::metric_attributes!((
"connector",
connector.connector_name.to_string()
)),
);
Ok(Some(access_token))
}
None => {
metrics::ACCESS_TOKEN_CACHE_MISS.add(
1,
router_env::metric_attributes!((
"connector",
connector.connector_name.to_string()
)),
);
let authentication_token =
execute_authentication_token(state, connector, router_data).await?;
let cloned_router_data = router_data.clone();
let refresh_token_request_data = types::AccessTokenRequestData::try_from((
router_data.connector_auth_type.clone(),
authentication_token,
))
.attach_printable(
"Could not create access token request, invalid connector account credentials",
)?;
let refresh_token_response_data: Result<types::AccessToken, types::ErrorResponse> =
Err(types::ErrorResponse::default());
let refresh_token_router_data = payments::helpers::router_data_type_conversion::<
_,
api_types::AccessTokenAuth,
_,
_,
_,
_,
>(
cloned_router_data,
refresh_token_request_data,
refresh_token_response_data,
);
refresh_connector_auth(
state,
connector,
merchant_context,
&refresh_token_router_data,
)
.await?
.async_map(|access_token| async move {
let store = &*state.store;
// The expiry should be adjusted for network delays from the connector
// The access token might not have been expired when request is sent
// But once it reaches the connector, it might expire because of the network delay
// Subtract few seconds from the expiry in order to account for these network delays
// This will reduce the expiry time by `REDUCE_ACCESS_TOKEN_EXPIRY_TIME` seconds
let modified_access_token_with_expiry = types::AccessToken {
expires: access_token
.expires
.saturating_sub(consts::REDUCE_ACCESS_TOKEN_EXPIRY_TIME.into()),
..access_token
};
logger::debug!(
access_token_expiry_after_modification =
modified_access_token_with_expiry.expires
);
if let Err(access_token_set_error) = store
.set_access_token(
merchant_id,
&merchant_connector_id_or_connector_name,
modified_access_token_with_expiry.clone(),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("DB error when setting the access token")
{
// If we are not able to set the access token in redis, the error should just be logged and proceed with the payment
// Payments should not fail, once the access token is successfully created
// The next request will create new access token, if required
logger::error!(access_token_set_error=?access_token_set_error);
}
Some(modified_access_token_with_expiry)
})
.await
}
};
Ok(types::AddAccessTokenResult {
access_token_result: res,
connector_supports_access_token: true,
})
} else {
Ok(types::AddAccessTokenResult {
access_token_result: Err(types::ErrorResponse::default()),
connector_supports_access_token: false,
})
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 146,
"total_crates": null
} |
fn_clm_router_execute_authentication_token_-8833259768231780590 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/access_token
pub async fn execute_authentication_token<
F: Clone + 'static,
Req: Debug + Clone + 'static,
Res: Debug + Clone + 'static,
>(
state: &SessionState,
connector: &api_types::ConnectorData,
router_data: &types::RouterData<F, Req, Res>,
) -> RouterResult<Option<types::AccessTokenAuthenticationResponse>> {
let should_create_authentication_token = connector
.connector
.authentication_token_for_token_creation();
if !should_create_authentication_token {
return Ok(None);
}
let authentication_token_request_data = types::AccessTokenAuthenticationRequestData::try_from(
router_data.connector_auth_type.clone(),
)
.attach_printable(
"Could not create authentication token request, invalid connector account credentials",
)?;
let authentication_token_response_data: Result<
types::AccessTokenAuthenticationResponse,
types::ErrorResponse,
> = Err(types::ErrorResponse::default());
let auth_token_router_data = payments::helpers::router_data_type_conversion::<
_,
api_types::AccessTokenAuthentication,
_,
_,
_,
_,
>(
router_data.clone(),
authentication_token_request_data,
authentication_token_response_data,
);
let connector_integration: services::BoxedAuthenticationTokenConnectorIntegrationInterface<
api_types::AccessTokenAuthentication,
types::AccessTokenAuthenticationRequestData,
types::AccessTokenAuthenticationResponse,
> = connector.connector.get_connector_integration();
let auth_token_router_data_result = services::execute_connector_processing_step(
state,
connector_integration,
&auth_token_router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await;
let auth_token_result = match auth_token_router_data_result {
Ok(router_data) => router_data.response,
Err(connector_error) => {
// Handle timeout errors
if connector_error.current_context().is_connector_timeout() {
let error_response = types::ErrorResponse {
code: consts::REQUEST_TIMEOUT_ERROR_CODE.to_string(),
message: consts::REQUEST_TIMEOUT_ERROR_MESSAGE.to_string(),
reason: Some(consts::REQUEST_TIMEOUT_ERROR_MESSAGE.to_string()),
status_code: 504,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
};
Err(error_response)
} else {
return Err(connector_error
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Could not get authentication token"));
}
}
};
let authentication_token = auth_token_result
.map_err(|_error| errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get authentication token")?;
Ok(Some(authentication_token))
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 47,
"total_crates": null
} |
fn_clm_router_update_router_data_with_access_token_result_-8833259768231780590 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/access_token
/// After we get the access token, check if there was an error and if the flow should proceed further
/// Returns bool
/// true - Everything is well, continue with the flow
/// false - There was an error, cannot proceed further
pub fn update_router_data_with_access_token_result<F, Req, Res>(
add_access_token_result: &types::AddAccessTokenResult,
router_data: &mut types::RouterData<F, Req, Res>,
call_connector_action: &payments::CallConnectorAction,
) -> bool {
// Update router data with access token or error only if it will be calling connector
let should_update_router_data = matches!(
(
add_access_token_result.connector_supports_access_token,
call_connector_action
),
(true, payments::CallConnectorAction::Trigger)
);
if should_update_router_data {
match add_access_token_result.access_token_result.as_ref() {
Ok(access_token) => {
router_data.access_token.clone_from(access_token);
true
}
Err(connector_error) => {
router_data.response = Err(connector_error.clone());
false
}
}
} else {
true
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 40,
"total_crates": null
} |
fn_clm_router_refresh_connector_auth_-8833259768231780590 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/access_token
pub async fn refresh_connector_auth(
state: &SessionState,
connector: &api_types::ConnectorData,
_merchant_context: &domain::MerchantContext,
router_data: &types::RouterData<
api_types::AccessTokenAuth,
types::AccessTokenRequestData,
types::AccessToken,
>,
) -> RouterResult<Result<types::AccessToken, types::ErrorResponse>> {
let connector_integration: services::BoxedAccessTokenConnectorIntegrationInterface<
api_types::AccessTokenAuth,
types::AccessTokenRequestData,
types::AccessToken,
> = connector.connector.get_connector_integration();
let access_token_router_data_result = services::execute_connector_processing_step(
state,
connector_integration,
router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await;
let access_token_router_data = match access_token_router_data_result {
Ok(router_data) => Ok(router_data.response),
Err(connector_error) => {
// If we receive a timeout error from the connector, then
// the error has to be handled gracefully by updating the payment status to failed.
// further payment flow will not be continued
if connector_error.current_context().is_connector_timeout() {
let error_response = types::ErrorResponse {
code: consts::REQUEST_TIMEOUT_ERROR_CODE.to_string(),
message: consts::REQUEST_TIMEOUT_ERROR_MESSAGE.to_string(),
reason: Some(consts::REQUEST_TIMEOUT_ERROR_MESSAGE.to_string()),
status_code: 504,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
};
Ok(Err(error_response))
} else {
Err(connector_error
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Could not refresh access token"))
}
}
}?;
metrics::ACCESS_TOKEN_CREATION.add(
1,
router_env::metric_attributes!(("connector", connector.connector_name.to_string())),
);
Ok(access_token_router_data)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 36,
"total_crates": null
} |
fn_clm_router_new_-2203632526255929327 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/helpers
// Implementation of None for GooglePayTokenDecryptor
pub fn new(
root_keys: masking::Secret<String>,
recipient_id: masking::Secret<String>,
private_key: masking::Secret<String>,
) -> CustomResult<Self, errors::GooglePayDecryptionError> {
// base64 decode the private key
let decoded_key = BASE64_ENGINE
.decode(private_key.expose())
.change_context(errors::GooglePayDecryptionError::Base64DecodingFailed)?;
// base64 decode the root signing keys
let decoded_root_signing_keys = BASE64_ENGINE
.decode(root_keys.expose())
.change_context(errors::GooglePayDecryptionError::Base64DecodingFailed)?;
// create a private key from the decoded key
let private_key = PKey::private_key_from_pkcs8(&decoded_key)
.change_context(errors::GooglePayDecryptionError::KeyDeserializationFailed)
.attach_printable("cannot convert private key from decode_key")?;
// parse the root signing keys
let root_keys_vector: Vec<GooglePayRootSigningKey> = decoded_root_signing_keys
.parse_struct("GooglePayRootSigningKey")
.change_context(errors::GooglePayDecryptionError::DeserializationFailed)?;
// parse and filter the root signing keys by protocol version
let filtered_root_signing_keys = filter_root_signing_keys(root_keys_vector)?;
Ok(Self {
root_signing_keys: filtered_root_signing_keys,
recipient_id,
private_key,
})
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 14487,
"total_crates": null
} |
fn_clm_router_get_additional_payment_data_-2203632526255929327 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/helpers
pub async fn get_additional_payment_data(
pm_data: &domain::PaymentMethodData,
db: &dyn StorageInterface,
profile_id: &id_type::ProfileId,
) -> Result<
Option<api_models::payments::AdditionalPaymentData>,
error_stack::Report<errors::ApiErrorResponse>,
> {
match pm_data {
domain::PaymentMethodData::Card(card_data) => {
//todo!
let card_isin = Some(card_data.card_number.get_card_isin());
let enable_extended_bin =db
.find_config_by_key_unwrap_or(
format!("{}_enable_extended_card_bin", profile_id.get_string_repr()).as_str(),
Some("false".to_string()))
.await.map_err(|err| services::logger::error!(message="Failed to fetch the config", extended_card_bin_error=?err)).ok();
let card_extended_bin = match enable_extended_bin {
Some(config) if config.config == "true" => {
Some(card_data.card_number.get_extended_card_bin())
}
_ => None,
};
// Added an additional check for card_data.co_badged_card_data.is_some()
// because is_cobadged_card() only returns true if the card number matches a specific regex.
// However, this regex does not cover all possible co-badged networks.
// The co_badged_card_data field is populated based on a co-badged BIN lookup
// and helps identify co-badged cards that may not match the regex alone.
// Determine the card network based on cobadge detection and co-badged BIN data
let is_cobadged_based_on_regex = card_data
.card_number
.is_cobadged_card()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Card cobadge check failed due to an invalid card network regex",
)?;
let (card_network, signature_network, is_regulated) = card_data
.co_badged_card_data
.as_ref()
.map(|co_badged_data| {
logger::debug!("Co-badged card data found");
(
card_data.card_network.clone(),
co_badged_data
.co_badged_card_networks_info
.get_signature_network(),
Some(co_badged_data.is_regulated),
)
})
.or_else(|| {
is_cobadged_based_on_regex.then(|| {
logger::debug!("Card network is cobadged (regex-based detection)");
(card_data.card_network.clone(), None, None)
})
})
.unwrap_or_else(|| {
logger::debug!("Card network is not cobadged");
(None, None, None)
});
let last4 = Some(card_data.card_number.get_last4());
if card_data.card_issuer.is_some()
&& card_network.is_some()
&& card_data.card_type.is_some()
&& card_data.card_issuing_country.is_some()
&& card_data.bank_code.is_some()
{
Ok(Some(api_models::payments::AdditionalPaymentData::Card(
Box::new(api_models::payments::AdditionalCardInfo {
card_issuer: card_data.card_issuer.to_owned(),
card_network,
card_type: card_data.card_type.to_owned(),
card_issuing_country: card_data.card_issuing_country.to_owned(),
bank_code: card_data.bank_code.to_owned(),
card_exp_month: Some(card_data.card_exp_month.clone()),
card_exp_year: Some(card_data.card_exp_year.clone()),
card_holder_name: card_data.card_holder_name.clone(),
last4: last4.clone(),
card_isin: card_isin.clone(),
card_extended_bin: card_extended_bin.clone(),
// These are filled after calling the processor / connector
payment_checks: None,
authentication_data: None,
is_regulated,
signature_network: signature_network.clone(),
}),
)))
} else {
let card_info = card_isin
.clone()
.async_and_then(|card_isin| async move {
db.get_card_info(&card_isin)
.await
.map_err(|error| services::logger::warn!(card_info_error=?error))
.ok()
})
.await
.flatten()
.map(|card_info| {
api_models::payments::AdditionalPaymentData::Card(Box::new(
api_models::payments::AdditionalCardInfo {
card_issuer: card_info.card_issuer,
card_network: card_network.clone().or(card_info.card_network),
bank_code: card_info.bank_code,
card_type: card_info.card_type,
card_issuing_country: card_info.card_issuing_country,
last4: last4.clone(),
card_isin: card_isin.clone(),
card_extended_bin: card_extended_bin.clone(),
card_exp_month: Some(card_data.card_exp_month.clone()),
card_exp_year: Some(card_data.card_exp_year.clone()),
card_holder_name: card_data.card_holder_name.clone(),
// These are filled after calling the processor / connector
payment_checks: None,
authentication_data: None,
is_regulated,
signature_network: signature_network.clone(),
},
))
});
Ok(Some(card_info.unwrap_or_else(|| {
api_models::payments::AdditionalPaymentData::Card(Box::new(
api_models::payments::AdditionalCardInfo {
card_issuer: None,
card_network,
bank_code: None,
card_type: None,
card_issuing_country: None,
last4,
card_isin,
card_extended_bin,
card_exp_month: Some(card_data.card_exp_month.clone()),
card_exp_year: Some(card_data.card_exp_year.clone()),
card_holder_name: card_data.card_holder_name.clone(),
// These are filled after calling the processor / connector
payment_checks: None,
authentication_data: None,
is_regulated,
signature_network: signature_network.clone(),
},
))
})))
}
}
domain::PaymentMethodData::BankRedirect(bank_redirect_data) => match bank_redirect_data {
domain::BankRedirectData::Eps { bank_name, .. } => Ok(Some(
api_models::payments::AdditionalPaymentData::BankRedirect {
bank_name: bank_name.to_owned(),
details: None,
},
)),
domain::BankRedirectData::Eft { .. } => Ok(Some(
api_models::payments::AdditionalPaymentData::BankRedirect {
bank_name: None,
details: None,
},
)),
domain::BankRedirectData::OnlineBankingFpx { issuer } => Ok(Some(
api_models::payments::AdditionalPaymentData::BankRedirect {
bank_name: Some(issuer.to_owned()),
details: None,
},
)),
domain::BankRedirectData::Ideal { bank_name, .. } => Ok(Some(
api_models::payments::AdditionalPaymentData::BankRedirect {
bank_name: bank_name.to_owned(),
details: None,
},
)),
domain::BankRedirectData::BancontactCard {
card_number,
card_exp_month,
card_exp_year,
card_holder_name,
} => Ok(Some(
api_models::payments::AdditionalPaymentData::BankRedirect {
bank_name: None,
details: Some(
payment_additional_types::BankRedirectDetails::BancontactCard(Box::new(
payment_additional_types::BancontactBankRedirectAdditionalData {
last4: card_number.as_ref().map(|c| c.get_last4()),
card_exp_month: card_exp_month.clone(),
card_exp_year: card_exp_year.clone(),
card_holder_name: card_holder_name.clone(),
},
)),
),
},
)),
domain::BankRedirectData::Blik { blik_code } => Ok(Some(
api_models::payments::AdditionalPaymentData::BankRedirect {
bank_name: None,
details: blik_code.as_ref().map(|blik_code| {
payment_additional_types::BankRedirectDetails::Blik(Box::new(
payment_additional_types::BlikBankRedirectAdditionalData {
blik_code: Some(blik_code.to_owned()),
},
))
}),
},
)),
domain::BankRedirectData::Giropay {
bank_account_bic,
bank_account_iban,
country,
} => Ok(Some(
api_models::payments::AdditionalPaymentData::BankRedirect {
bank_name: None,
details: Some(payment_additional_types::BankRedirectDetails::Giropay(
Box::new(
payment_additional_types::GiropayBankRedirectAdditionalData {
bic: bank_account_bic
.as_ref()
.map(|bic| MaskedSortCode::from(bic.to_owned())),
iban: bank_account_iban
.as_ref()
.map(|iban| MaskedIban::from(iban.to_owned())),
country: *country,
},
),
)),
},
)),
_ => Ok(Some(
api_models::payments::AdditionalPaymentData::BankRedirect {
bank_name: None,
details: None,
},
)),
},
domain::PaymentMethodData::Wallet(wallet) => match wallet {
domain::WalletData::ApplePay(apple_pay_wallet_data) => {
Ok(Some(api_models::payments::AdditionalPaymentData::Wallet {
apple_pay: Some(api_models::payments::ApplepayPaymentMethod {
display_name: apple_pay_wallet_data.payment_method.display_name.clone(),
network: apple_pay_wallet_data.payment_method.network.clone(),
pm_type: apple_pay_wallet_data.payment_method.pm_type.clone(),
}),
google_pay: None,
samsung_pay: None,
}))
}
domain::WalletData::GooglePay(google_pay_pm_data) => {
Ok(Some(api_models::payments::AdditionalPaymentData::Wallet {
apple_pay: None,
google_pay: Some(payment_additional_types::WalletAdditionalDataForCard {
last4: google_pay_pm_data.info.card_details.clone(),
card_network: google_pay_pm_data.info.card_network.clone(),
card_type: Some(google_pay_pm_data.pm_type.clone()),
}),
samsung_pay: None,
}))
}
domain::WalletData::SamsungPay(samsung_pay_pm_data) => {
Ok(Some(api_models::payments::AdditionalPaymentData::Wallet {
apple_pay: None,
google_pay: None,
samsung_pay: Some(payment_additional_types::WalletAdditionalDataForCard {
last4: samsung_pay_pm_data
.payment_credential
.card_last_four_digits
.clone(),
card_network: samsung_pay_pm_data
.payment_credential
.card_brand
.to_string(),
card_type: None,
}),
}))
}
_ => Ok(Some(api_models::payments::AdditionalPaymentData::Wallet {
apple_pay: None,
google_pay: None,
samsung_pay: None,
})),
},
domain::PaymentMethodData::PayLater(_) => Ok(Some(
api_models::payments::AdditionalPaymentData::PayLater { klarna_sdk: None },
)),
domain::PaymentMethodData::BankTransfer(bank_transfer) => Ok(Some(
api_models::payments::AdditionalPaymentData::BankTransfer {
details: Some((*(bank_transfer.to_owned())).into()),
},
)),
domain::PaymentMethodData::Crypto(crypto) => {
Ok(Some(api_models::payments::AdditionalPaymentData::Crypto {
details: Some(crypto.to_owned().into()),
}))
}
domain::PaymentMethodData::BankDebit(bank_debit) => Ok(Some(
api_models::payments::AdditionalPaymentData::BankDebit {
details: Some(bank_debit.to_owned().into()),
},
)),
domain::PaymentMethodData::MandatePayment => Ok(Some(
api_models::payments::AdditionalPaymentData::MandatePayment {},
)),
domain::PaymentMethodData::Reward => {
Ok(Some(api_models::payments::AdditionalPaymentData::Reward {}))
}
domain::PaymentMethodData::RealTimePayment(realtime_payment) => Ok(Some(
api_models::payments::AdditionalPaymentData::RealTimePayment {
details: Some((*(realtime_payment.to_owned())).into()),
},
)),
domain::PaymentMethodData::Upi(upi) => {
Ok(Some(api_models::payments::AdditionalPaymentData::Upi {
details: Some(upi.to_owned().into()),
}))
}
domain::PaymentMethodData::CardRedirect(card_redirect) => Ok(Some(
api_models::payments::AdditionalPaymentData::CardRedirect {
details: Some(card_redirect.to_owned().into()),
},
)),
domain::PaymentMethodData::Voucher(voucher) => {
Ok(Some(api_models::payments::AdditionalPaymentData::Voucher {
details: Some(voucher.to_owned().into()),
}))
}
domain::PaymentMethodData::GiftCard(gift_card) => Ok(Some(
api_models::payments::AdditionalPaymentData::GiftCard {
details: Some((*(gift_card.to_owned())).into()),
},
)),
domain::PaymentMethodData::CardToken(card_token) => Ok(Some(
api_models::payments::AdditionalPaymentData::CardToken {
details: Some(card_token.to_owned().into()),
},
)),
domain::PaymentMethodData::OpenBanking(open_banking) => Ok(Some(
api_models::payments::AdditionalPaymentData::OpenBanking {
details: Some(open_banking.to_owned().into()),
},
)),
domain::PaymentMethodData::CardDetailsForNetworkTransactionId(card_data) => {
let card_isin = Some(card_data.card_number.get_card_isin());
let enable_extended_bin =db
.find_config_by_key_unwrap_or(
format!("{}_enable_extended_card_bin", profile_id.get_string_repr()).as_str(),
Some("false".to_string()))
.await.map_err(|err| services::logger::error!(message="Failed to fetch the config", extended_card_bin_error=?err)).ok();
let card_extended_bin = match enable_extended_bin {
Some(config) if config.config == "true" => {
Some(card_data.card_number.get_extended_card_bin())
}
_ => None,
};
let card_network = match card_data
.card_number
.is_cobadged_card()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Card cobadge check failed due to an invalid card network regex",
)? {
true => card_data.card_network.clone(),
false => None,
};
let last4 = Some(card_data.card_number.get_last4());
if card_data.card_issuer.is_some()
&& card_network.is_some()
&& card_data.card_type.is_some()
&& card_data.card_issuing_country.is_some()
&& card_data.bank_code.is_some()
{
Ok(Some(api_models::payments::AdditionalPaymentData::Card(
Box::new(api_models::payments::AdditionalCardInfo {
card_issuer: card_data.card_issuer.to_owned(),
card_network,
card_type: card_data.card_type.to_owned(),
card_issuing_country: card_data.card_issuing_country.to_owned(),
bank_code: card_data.bank_code.to_owned(),
card_exp_month: Some(card_data.card_exp_month.clone()),
card_exp_year: Some(card_data.card_exp_year.clone()),
card_holder_name: card_data.card_holder_name.clone(),
last4: last4.clone(),
card_isin: card_isin.clone(),
card_extended_bin: card_extended_bin.clone(),
// These are filled after calling the processor / connector
payment_checks: None,
authentication_data: None,
is_regulated: None,
signature_network: None,
}),
)))
} else {
let card_info = card_isin
.clone()
.async_and_then(|card_isin| async move {
db.get_card_info(&card_isin)
.await
.map_err(|error| services::logger::warn!(card_info_error=?error))
.ok()
})
.await
.flatten()
.map(|card_info| {
api_models::payments::AdditionalPaymentData::Card(Box::new(
api_models::payments::AdditionalCardInfo {
card_issuer: card_info.card_issuer,
card_network: card_network.clone().or(card_info.card_network),
bank_code: card_info.bank_code,
card_type: card_info.card_type,
card_issuing_country: card_info.card_issuing_country,
last4: last4.clone(),
card_isin: card_isin.clone(),
card_extended_bin: card_extended_bin.clone(),
card_exp_month: Some(card_data.card_exp_month.clone()),
card_exp_year: Some(card_data.card_exp_year.clone()),
card_holder_name: card_data.card_holder_name.clone(),
// These are filled after calling the processor / connector
payment_checks: None,
authentication_data: None,
is_regulated: None,
signature_network: None,
},
))
});
Ok(Some(card_info.unwrap_or_else(|| {
api_models::payments::AdditionalPaymentData::Card(Box::new(
api_models::payments::AdditionalCardInfo {
card_issuer: None,
card_network,
bank_code: None,
card_type: None,
card_issuing_country: None,
last4,
card_isin,
card_extended_bin,
card_exp_month: Some(card_data.card_exp_month.clone()),
card_exp_year: Some(card_data.card_exp_year.clone()),
card_holder_name: card_data.card_holder_name.clone(),
// These are filled after calling the processor / connector
payment_checks: None,
authentication_data: None,
is_regulated: None,
signature_network: None,
},
))
})))
}
}
domain::PaymentMethodData::MobilePayment(mobile_payment) => Ok(Some(
api_models::payments::AdditionalPaymentData::MobilePayment {
details: Some(mobile_payment.to_owned().into()),
},
)),
domain::PaymentMethodData::NetworkToken(_) => Ok(None),
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 362,
"total_crates": null
} |
fn_clm_router_create_customer_if_not_exist_-2203632526255929327 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/helpers
pub async fn create_customer_if_not_exist<'a, F: Clone, R, D>(
state: &SessionState,
operation: BoxedOperation<'a, F, R, D>,
payment_data: &mut PaymentData<F>,
req: Option<CustomerDetails>,
merchant_id: &id_type::MerchantId,
key_store: &domain::MerchantKeyStore,
storage_scheme: common_enums::enums::MerchantStorageScheme,
) -> CustomResult<(BoxedOperation<'a, F, R, D>, Option<domain::Customer>), errors::StorageError> {
let request_customer_details = req
.get_required_value("customer")
.change_context(errors::StorageError::ValueNotFound("customer".to_owned()))?;
let temp_customer_data = if request_customer_details.name.is_some()
|| request_customer_details.email.is_some()
|| request_customer_details.phone.is_some()
|| request_customer_details.phone_country_code.is_some()
|| request_customer_details.tax_registration_id.is_some()
{
Some(CustomerData {
name: request_customer_details.name.clone(),
email: request_customer_details.email.clone(),
phone: request_customer_details.phone.clone(),
phone_country_code: request_customer_details.phone_country_code.clone(),
tax_registration_id: request_customer_details.tax_registration_id.clone(),
})
} else {
None
};
// Updation of Customer Details for the cases where both customer_id and specific customer
// details are provided in Payment Update Request
let raw_customer_details = payment_data
.payment_intent
.customer_details
.clone()
.map(|customer_details_encrypted| {
customer_details_encrypted
.into_inner()
.expose()
.parse_value::<CustomerData>("CustomerData")
})
.transpose()
.change_context(errors::StorageError::DeserializationFailed)
.attach_printable("Failed to parse customer data from payment intent")?
.map(|parsed_customer_data| CustomerData {
name: request_customer_details
.name
.clone()
.or(parsed_customer_data.name.clone()),
email: request_customer_details
.email
.clone()
.or(parsed_customer_data.email.clone()),
phone: request_customer_details
.phone
.clone()
.or(parsed_customer_data.phone.clone()),
phone_country_code: request_customer_details
.phone_country_code
.clone()
.or(parsed_customer_data.phone_country_code.clone()),
tax_registration_id: request_customer_details
.tax_registration_id
.clone()
.or(parsed_customer_data.tax_registration_id.clone()),
})
.or(temp_customer_data);
let key_manager_state = state.into();
payment_data.payment_intent.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::StorageError::EncryptionError)
.attach_printable("Unable to encrypt customer details")?;
let customer_id = request_customer_details
.customer_id
.or(payment_data.payment_intent.customer_id.clone());
let db = &*state.store;
let key_manager_state = &state.into();
let optional_customer = match customer_id {
Some(customer_id) => {
let customer_data = db
.find_customer_optional_by_customer_id_merchant_id(
key_manager_state,
&customer_id,
merchant_id,
key_store,
storage_scheme,
)
.await?;
let key = key_store.key.get_inner().peek();
let encrypted_data = types::crypto_operation(
key_manager_state,
type_name!(domain::Customer),
types::CryptoOperation::BatchEncrypt(
domain::FromRequestEncryptableCustomer::to_encryptable(
domain::FromRequestEncryptableCustomer {
name: request_customer_details.name.clone(),
email: request_customer_details
.email
.as_ref()
.map(|e| e.clone().expose().switch_strategy()),
phone: request_customer_details.phone.clone(),
tax_registration_id: None,
},
),
),
Identifier::Merchant(key_store.merchant_id.clone()),
key,
)
.await
.and_then(|val| val.try_into_batchoperation())
.change_context(errors::StorageError::SerializationFailed)
.attach_printable("Failed while encrypting Customer while Update")?;
let encryptable_customer =
domain::FromRequestEncryptableCustomer::from_encryptable(encrypted_data)
.change_context(errors::StorageError::SerializationFailed)
.attach_printable("Failed while encrypting Customer while Update")?;
Some(match customer_data {
Some(c) => {
// Update the customer data if new data is passed in the request
if request_customer_details.email.is_some()
| request_customer_details.name.is_some()
| request_customer_details.phone.is_some()
| request_customer_details.phone_country_code.is_some()
| request_customer_details.tax_registration_id.is_some()
{
let customer_update = Update {
name: encryptable_customer.name,
email: encryptable_customer.email.map(|email| {
let encryptable: Encryptable<
masking::Secret<String, pii::EmailStrategy>,
> = Encryptable::new(
email.clone().into_inner().switch_strategy(),
email.into_encrypted(),
);
encryptable
}),
phone: Box::new(encryptable_customer.phone),
phone_country_code: request_customer_details.phone_country_code,
description: None,
connector_customer: Box::new(None),
metadata: Box::new(None),
address_id: None,
tax_registration_id: encryptable_customer.tax_registration_id,
};
db.update_customer_by_customer_id_merchant_id(
key_manager_state,
customer_id,
merchant_id.to_owned(),
c,
customer_update,
key_store,
storage_scheme,
)
.await
} else {
Ok(c)
}
}
None => {
let new_customer = domain::Customer {
customer_id,
merchant_id: merchant_id.to_owned(),
name: encryptable_customer.name,
email: encryptable_customer.email.map(|email| {
let encryptable: Encryptable<
masking::Secret<String, pii::EmailStrategy>,
> = Encryptable::new(
email.clone().into_inner().switch_strategy(),
email.into_encrypted(),
);
encryptable
}),
phone: encryptable_customer.phone,
phone_country_code: request_customer_details.phone_country_code.clone(),
description: None,
created_at: common_utils::date_time::now(),
metadata: None,
modified_at: common_utils::date_time::now(),
connector_customer: None,
address_id: None,
default_payment_method_id: None,
updated_by: None,
version: common_types::consts::API_VERSION,
tax_registration_id: encryptable_customer.tax_registration_id,
};
metrics::CUSTOMER_CREATED.add(1, &[]);
db.insert_customer(new_customer, key_manager_state, key_store, storage_scheme)
.await
}
})
}
None => match &payment_data.payment_intent.customer_id {
None => None,
Some(customer_id) => db
.find_customer_optional_by_customer_id_merchant_id(
key_manager_state,
customer_id,
merchant_id,
key_store,
storage_scheme,
)
.await?
.map(Ok),
},
};
Ok((
operation,
match optional_customer {
Some(customer) => {
let customer = customer?;
payment_data.payment_intent.customer_id = Some(customer.customer_id.clone());
payment_data.email = payment_data.email.clone().or_else(|| {
customer
.email
.clone()
.map(|encrypted_value| encrypted_value.into())
});
Some(customer)
}
None => None,
},
))
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 243,
"total_crates": null
} |
fn_clm_router_create_or_update_address_for_payment_by_request_-2203632526255929327 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/helpers
pub async fn create_or_update_address_for_payment_by_request(
session_state: &SessionState,
req_address: Option<&api::Address>,
address_id: Option<&str>,
merchant_id: &id_type::MerchantId,
customer_id: Option<&id_type::CustomerId>,
merchant_key_store: &domain::MerchantKeyStore,
payment_id: &id_type::PaymentId,
storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<Option<domain::Address>, errors::ApiErrorResponse> {
let key = merchant_key_store.key.get_inner().peek();
let db = &session_state.store;
let key_manager_state = &session_state.into();
Ok(match address_id {
Some(id) => match req_address {
Some(address) => {
let encrypted_data = types::crypto_operation(
&session_state.into(),
type_name!(domain::Address),
types::CryptoOperation::BatchEncrypt(
domain::FromRequestEncryptableAddress::to_encryptable(
domain::FromRequestEncryptableAddress {
line1: address.address.as_ref().and_then(|a| a.line1.clone()),
line2: address.address.as_ref().and_then(|a| a.line2.clone()),
line3: address.address.as_ref().and_then(|a| a.line3.clone()),
state: address.address.as_ref().and_then(|a| a.state.clone()),
first_name: address
.address
.as_ref()
.and_then(|a| a.first_name.clone()),
last_name: address
.address
.as_ref()
.and_then(|a| a.last_name.clone()),
zip: address.address.as_ref().and_then(|a| a.zip.clone()),
phone_number: address
.phone
.as_ref()
.and_then(|phone| phone.number.clone()),
email: address
.email
.as_ref()
.map(|a| a.clone().expose().switch_strategy()),
origin_zip: address
.address
.as_ref()
.and_then(|a| a.origin_zip.clone()),
},
),
),
Identifier::Merchant(merchant_key_store.merchant_id.clone()),
key,
)
.await
.and_then(|val| val.try_into_batchoperation())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while encrypting address")?;
let encryptable_address =
domain::FromRequestEncryptableAddress::from_encryptable(encrypted_data)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while encrypting address")?;
let address_update = storage::AddressUpdate::Update {
city: address
.address
.as_ref()
.and_then(|value| value.city.clone()),
country: address.address.as_ref().and_then(|value| value.country),
line1: encryptable_address.line1,
line2: encryptable_address.line2,
line3: encryptable_address.line3,
state: encryptable_address.state,
zip: encryptable_address.zip,
first_name: encryptable_address.first_name,
last_name: encryptable_address.last_name,
phone_number: encryptable_address.phone_number,
country_code: address
.phone
.as_ref()
.and_then(|value| value.country_code.clone()),
updated_by: storage_scheme.to_string(),
email: encryptable_address.email.map(|email| {
let encryptable: Encryptable<masking::Secret<String, pii::EmailStrategy>> =
Encryptable::new(
email.clone().into_inner().switch_strategy(),
email.into_encrypted(),
);
encryptable
}),
origin_zip: encryptable_address.origin_zip,
};
let address = db
.find_address_by_merchant_id_payment_id_address_id(
key_manager_state,
merchant_id,
payment_id,
id,
merchant_key_store,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error while fetching address")?;
Some(
db.update_address_for_payments(
key_manager_state,
address,
address_update,
payment_id.to_owned(),
merchant_key_store,
storage_scheme,
)
.await
.map(|payment_address| payment_address.address)
.to_not_found_response(errors::ApiErrorResponse::AddressNotFound)?,
)
}
None => Some(
db.find_address_by_merchant_id_payment_id_address_id(
key_manager_state,
merchant_id,
payment_id,
id,
merchant_key_store,
storage_scheme,
)
.await
.map(|payment_address| payment_address.address),
)
.transpose()
.to_not_found_response(errors::ApiErrorResponse::AddressNotFound)?,
},
None => match req_address {
Some(address) => {
let address =
get_domain_address(session_state, address, merchant_id, key, storage_scheme)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while encrypting address while insert")?;
let payment_address = domain::PaymentAddress {
address,
payment_id: payment_id.clone(),
customer_id: customer_id.cloned(),
};
Some(
db.insert_address_for_payments(
key_manager_state,
payment_id,
payment_address,
merchant_key_store,
storage_scheme,
)
.await
.map(|payment_address| payment_address.address)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while inserting new address")?,
)
}
None => None,
},
})
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 197,
"total_crates": null
} |
fn_clm_router_get_token_pm_type_mandate_details_-2203632526255929327 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/helpers
pub async fn get_token_pm_type_mandate_details(
state: &SessionState,
request: &api::PaymentsRequest,
mandate_type: Option<api::MandateTransactionType>,
merchant_context: &domain::MerchantContext,
payment_method_id: Option<String>,
payment_intent_customer_id: Option<&id_type::CustomerId>,
) -> RouterResult<MandateGenericData> {
let mandate_data = request.mandate_data.clone().map(MandateData::foreign_from);
let (
payment_token,
payment_method,
payment_method_type,
mandate_data,
recurring_payment_data,
mandate_connector_details,
payment_method_info,
) = match mandate_type {
Some(api::MandateTransactionType::NewMandateTransaction) => (
request.payment_token.to_owned(),
request.payment_method,
request.payment_method_type,
mandate_data.clone(),
None,
None,
None,
),
Some(api::MandateTransactionType::RecurringMandateTransaction) => {
match &request.recurring_details {
Some(recurring_details) => {
match recurring_details {
RecurringDetails::NetworkTransactionIdAndCardDetails(_) => {
(None, request.payment_method, None, None, None, None, None)
}
RecurringDetails::ProcessorPaymentToken(processor_payment_token) => {
if let Some(mca_id) = &processor_payment_token.merchant_connector_id {
let db = &*state.store;
let key_manager_state = &state.into();
#[cfg(feature = "v1")]
let connector_name = db
.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
key_manager_state,
merchant_context.get_merchant_account().get_id(),
mca_id,
merchant_context.get_merchant_key_store(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: mca_id.clone().get_string_repr().to_string(),
})?.connector_name;
#[cfg(feature = "v2")]
let connector_name = db
.find_merchant_connector_account_by_id(key_manager_state, mca_id, merchant_key_store)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: mca_id.clone().get_string_repr().to_string(),
})?.connector_name;
(
None,
request.payment_method,
None,
None,
None,
Some(payments::MandateConnectorDetails {
connector: connector_name,
merchant_connector_id: Some(mca_id.clone()),
}),
None,
)
} else {
(None, request.payment_method, None, None, None, None, None)
}
}
RecurringDetails::MandateId(mandate_id) => {
let mandate_generic_data = Box::pin(get_token_for_recurring_mandate(
state,
request,
merchant_context,
mandate_id.to_owned(),
))
.await?;
(
mandate_generic_data.token,
mandate_generic_data.payment_method,
mandate_generic_data
.payment_method_type
.or(request.payment_method_type),
None,
mandate_generic_data.recurring_mandate_payment_data,
mandate_generic_data.mandate_connector,
mandate_generic_data.payment_method_info,
)
}
RecurringDetails::PaymentMethodId(payment_method_id) => {
let payment_method_info = state
.store
.find_payment_method(
&(state.into()),
merchant_context.get_merchant_key_store(),
payment_method_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(
errors::ApiErrorResponse::PaymentMethodNotFound,
)?;
let customer_id = request
.get_customer_id()
.get_required_value("customer_id")?;
verify_mandate_details_for_recurring_payments(
&payment_method_info.merchant_id,
merchant_context.get_merchant_account().get_id(),
&payment_method_info.customer_id,
customer_id,
)?;
(
None,
payment_method_info.get_payment_method_type(),
payment_method_info.get_payment_method_subtype(),
None,
None,
None,
Some(payment_method_info),
)
}
}
}
None => {
if let Some(mandate_id) = request.mandate_id.clone() {
let mandate_generic_data = Box::pin(get_token_for_recurring_mandate(
state,
request,
merchant_context,
mandate_id,
))
.await?;
(
mandate_generic_data.token,
mandate_generic_data.payment_method,
mandate_generic_data
.payment_method_type
.or(request.payment_method_type),
None,
mandate_generic_data.recurring_mandate_payment_data,
mandate_generic_data.mandate_connector,
mandate_generic_data.payment_method_info,
)
} else if request
.payment_method_type
.map(|payment_method_type_value| {
payment_method_type_value
.should_check_for_customer_saved_payment_method_type()
})
.unwrap_or(false)
{
let payment_request_customer_id = request.get_customer_id();
if let Some(customer_id) =
payment_request_customer_id.or(payment_intent_customer_id)
{
let customer_saved_pm_option = match state
.store
.find_payment_method_by_customer_id_merchant_id_list(
&(state.into()),
merchant_context.get_merchant_key_store(),
customer_id,
merchant_context.get_merchant_account().get_id(),
None,
)
.await
{
Ok(customer_payment_methods) => Ok(customer_payment_methods
.iter()
.find(|payment_method| {
payment_method.get_payment_method_subtype()
== request.payment_method_type
})
.cloned()),
Err(error) => {
if error.current_context().is_db_not_found() {
Ok(None)
} else {
Err(error)
.change_context(
errors::ApiErrorResponse::InternalServerError,
)
.attach_printable(
"failed to find payment methods for a customer",
)
}
}
}?;
(
None,
request.payment_method,
request.payment_method_type,
None,
None,
None,
customer_saved_pm_option,
)
} else {
(
None,
request.payment_method,
request.payment_method_type,
None,
None,
None,
None,
)
}
} else {
let payment_method_info = payment_method_id
.async_map(|payment_method_id| async move {
state
.store
.find_payment_method(
&(state.into()),
merchant_context.get_merchant_key_store(),
&payment_method_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(
errors::ApiErrorResponse::PaymentMethodNotFound,
)
})
.await
.transpose()?;
(
request.payment_token.to_owned(),
request.payment_method,
request.payment_method_type,
None,
None,
None,
payment_method_info,
)
}
}
}
}
None => {
let payment_method_info = payment_method_id
.async_map(|payment_method_id| async move {
state
.store
.find_payment_method(
&(state.into()),
merchant_context.get_merchant_key_store(),
&payment_method_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)
})
.await
.transpose()?;
(
request.payment_token.to_owned(),
request.payment_method,
request.payment_method_type,
mandate_data,
None,
None,
payment_method_info,
)
}
};
Ok(MandateGenericData {
token: payment_token,
payment_method,
payment_method_type,
mandate_data,
recurring_mandate_payment_data: recurring_payment_data,
mandate_connector: mandate_connector_details,
payment_method_info,
})
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 168,
"total_crates": null
} |
fn_clm_router_payments_session_operation_core_6017468959956368064 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/session_operation
pub async fn payments_session_operation_core<F, Req, Op, FData, D>(
state: &SessionState,
req_state: ReqState,
merchant_context: domain::MerchantContext,
profile: domain::Profile,
operation: Op,
req: Req,
payment_id: id_type::GlobalPaymentId,
_call_connector_action: CallConnectorAction,
header_payload: HeaderPayload,
) -> RouterResult<(D, Req, Option<domain::Customer>, Option<u16>, Option<u128>)>
where
F: Send + Clone + Sync,
Req: Send + Sync,
Op: Operation<F, Req, Data = D> + Send + Sync,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
// To create connector flow specific interface data
D: ConstructFlowSpecificData<F, FData, router_types::PaymentsResponseData>,
RouterData<F, FData, router_types::PaymentsResponseData>: Feature<F, FData>,
// To construct connector flow specific api
dyn api::Connector:
services::api::ConnectorIntegration<F, FData, router_types::PaymentsResponseData>,
FData: Send + Sync + Clone,
{
let operation: BoxedOperation<'_, F, Req, D> = Box::new(operation);
let _validate_result = operation
.to_validate_request()?
.validate_request(&req, &merchant_context)?;
let operations::GetTrackerResponse { mut payment_data } = operation
.to_get_tracker()?
.get_trackers(
state,
&payment_id,
&req,
&merchant_context,
&profile,
&header_payload,
)
.await?;
let (_operation, customer) = operation
.to_domain()?
.get_customer_details(
state,
&mut payment_data,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)
.attach_printable("Failed while fetching/creating customer")?;
vault_session::populate_vault_session_details(
state,
req_state.clone(),
&customer,
&merchant_context,
&operation,
&profile,
&mut payment_data,
header_payload.clone(),
)
.await?;
let connector = operation
.to_domain()?
.perform_routing(
&merchant_context,
&profile,
&state.clone(),
&mut payment_data,
)
.await?;
let payment_data = match connector {
api::ConnectorCallType::PreDetermined(_connector) => {
todo!()
}
api::ConnectorCallType::Retryable(_connectors) => todo!(),
api::ConnectorCallType::Skip => todo!(),
api::ConnectorCallType::SessionMultiple(connectors) => {
operation
.to_update_tracker()?
.update_trackers(
state,
req_state,
payment_data.clone(),
customer.clone(),
merchant_context.get_merchant_account().storage_scheme,
None,
merchant_context.get_merchant_key_store(),
None,
header_payload.clone(),
)
.await?;
// todo: call surcharge manager for session token call.
Box::pin(call_multiple_connectors_service(
state,
&merchant_context,
connectors,
&operation,
payment_data,
&customer,
None,
&profile,
header_payload.clone(),
None,
))
.await?
}
};
Ok((payment_data, req, customer, None, None))
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 64,
"total_crates": null
} |
fn_clm_router_payments_session_core_6017468959956368064 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/session_operation
pub async fn payments_session_core<F, Res, Req, Op, FData, D>(
state: SessionState,
req_state: ReqState,
merchant_context: domain::MerchantContext,
profile: domain::Profile,
operation: Op,
req: Req,
payment_id: id_type::GlobalPaymentId,
call_connector_action: CallConnectorAction,
header_payload: HeaderPayload,
) -> RouterResponse<Res>
where
F: Send + Clone + Sync,
Req: Send + Sync,
FData: Send + Sync + Clone,
Op: Operation<F, Req, Data = D> + Send + Sync + Clone,
Req: Debug,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
Res: transformers::ToResponse<F, D, Op>,
// To create connector flow specific interface data
D: ConstructFlowSpecificData<F, FData, router_types::PaymentsResponseData>,
RouterData<F, FData, router_types::PaymentsResponseData>: Feature<F, FData>,
// To construct connector flow specific api
dyn api::Connector:
services::api::ConnectorIntegration<F, FData, router_types::PaymentsResponseData>,
{
let (payment_data, _req, customer, connector_http_status_code, external_latency) =
payments_session_operation_core::<_, _, _, _, _>(
&state,
req_state,
merchant_context.clone(),
profile,
operation.clone(),
req,
payment_id,
call_connector_action,
header_payload.clone(),
)
.await?;
Res::generate_response(
payment_data,
customer,
&state.base_url,
operation,
&state.conf.connector_request_reference_id_config,
connector_http_status_code,
external_latency,
header_payload.x_hs_latency,
&merchant_context,
)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 18,
"total_crates": null
} |
fn_clm_router_create_connector_customer_-4607615658226197830 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/customers
pub async fn create_connector_customer<F: Clone, T: Clone>(
state: &SessionState,
connector: &api::ConnectorData,
router_data: &types::RouterData<F, T, types::PaymentsResponseData>,
customer_request_data: types::ConnectorCustomerData,
) -> RouterResult<Option<String>> {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::CreateConnectorCustomer,
types::ConnectorCustomerData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
let customer_response_data: Result<types::PaymentsResponseData, types::ErrorResponse> =
Err(types::ErrorResponse::default());
let customer_router_data = payments::helpers::router_data_type_conversion::<
_,
api::CreateConnectorCustomer,
_,
_,
_,
_,
>(
router_data.clone(),
customer_request_data,
customer_response_data,
);
let resp = services::execute_connector_processing_step(
state,
connector_integration,
&customer_router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.to_payment_failed_response()?;
metrics::CONNECTOR_CUSTOMER_CREATE.add(
1,
router_env::metric_attributes!(("connector", connector.connector_name.to_string())),
);
let connector_customer_id = match resp.response {
Ok(response) => match response {
types::PaymentsResponseData::ConnectorCustomerResponse(customer_data) => {
Some(customer_data.connector_customer_id)
}
_ => None,
},
Err(err) => {
logger::error!(create_connector_customer_error=?err);
None
}
};
Ok(connector_customer_id)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 52,
"total_crates": null
} |
fn_clm_router_should_call_connector_create_customer_-4607615658226197830 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/customers
pub fn should_call_connector_create_customer<'a>(
connector: &api::ConnectorData,
customer: &'a Option<domain::Customer>,
payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt,
merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
) -> (bool, Option<&'a str>) {
// Check if create customer is required for the connector
match merchant_connector_account {
domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(_) => {
let connector_needs_customer = connector
.connector
.should_call_connector_customer(payment_attempt);
if connector_needs_customer {
let connector_customer_details = customer
.as_ref()
.and_then(|cust| cust.get_connector_customer_id(merchant_connector_account));
let should_call_connector = connector_customer_details.is_none();
(should_call_connector, connector_customer_details)
} else {
(false, None)
}
}
// TODO: Construct connector_customer for MerchantConnectorDetails if required by connector.
domain::MerchantConnectorAccountTypeDetails::MerchantConnectorDetails(_) => {
todo!("Handle connector_customer construction for MerchantConnectorDetails");
}
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 26,
"total_crates": null
} |
fn_clm_router_default_-350303204233383802 | 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
// Implementation of MerchantAccountRoutingAlgorithm for Default
fn default() -> Self {
Self::V1(routing_types::RoutingAlgorithmRef::default())
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 7707,
"total_crates": null
} |
fn_clm_router_perform_contract_based_routing_-350303204233383802 | 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
pub async fn perform_contract_based_routing<F, D>(
state: &SessionState,
routable_connectors: Vec<api_routing::RoutableConnectorChoice>,
profile_id: &common_utils::id_type::ProfileId,
merchant_id: &common_utils::id_type::MerchantId,
payment_id: &common_utils::id_type::PaymentId,
_dynamic_routing_config_params_interpolator: routing::helpers::DynamicRoutingConfigParamsInterpolator,
contract_based_algo_ref: api_routing::ContractRoutingAlgorithm,
payment_data: &mut D,
) -> RoutingResult<Vec<api_routing::RoutableConnectorChoice>>
where
F: Send + Clone,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
{
if contract_based_algo_ref.enabled_feature
== api_routing::DynamicRoutingFeatures::DynamicConnectorSelection
{
logger::debug!(
"performing contract_based_routing for profile {}",
profile_id.get_string_repr()
);
let client = &state
.grpc_client
.dynamic_routing
.as_ref()
.ok_or(errors::RoutingError::ContractRoutingClientInitializationError)
.attach_printable("dynamic routing gRPC client not found")?
.contract_based_client;
let contract_based_routing_configs = routing::helpers::fetch_dynamic_routing_configs::<
api_routing::ContractBasedRoutingConfig,
>(
state,
profile_id,
contract_based_algo_ref
.algorithm_id_with_timestamp
.algorithm_id
.ok_or(errors::RoutingError::GenericNotFoundError {
field: "contract_based_routing_algorithm_id".to_string(),
})
.attach_printable("contract_based_routing_algorithm_id not found in profile_id")?,
)
.await
.change_context(errors::RoutingError::ContractBasedRoutingConfigError)
.attach_printable("unable to fetch contract based dynamic routing configs")?;
let label_info = contract_based_routing_configs
.label_info
.clone()
.ok_or(errors::RoutingError::ContractBasedRoutingConfigError)
.attach_printable("Label information not found in contract routing configs")?;
let contract_based_connectors = routable_connectors
.clone()
.into_iter()
.filter(|conn| {
label_info
.iter()
.any(|info| Some(info.mca_id.clone()) == conn.merchant_connector_id.clone())
})
.collect::<Vec<_>>();
let mut other_connectors = routable_connectors
.into_iter()
.filter(|conn| {
label_info
.iter()
.all(|info| Some(info.mca_id.clone()) != conn.merchant_connector_id.clone())
})
.collect::<Vec<_>>();
let event_request = utils::CalContractScoreEventRequest {
id: profile_id.get_string_repr().to_string(),
params: "".to_string(),
labels: contract_based_connectors
.iter()
.map(|conn_choice| conn_choice.to_string())
.collect::<Vec<_>>(),
config: Some(contract_based_routing_configs.clone()),
};
let routing_events_wrapper = utils::RoutingEventsWrapper::new(
state.tenant.tenant_id.clone(),
state.request_id,
payment_id.get_string_repr().to_string(),
profile_id.to_owned(),
merchant_id.to_owned(),
"IntelligentRouter: PerformContractRouting".to_string(),
Some(event_request.clone()),
true,
false,
);
let closure = || async {
let contract_based_connectors_result = client
.calculate_contract_score(
profile_id.get_string_repr().into(),
contract_based_routing_configs.clone(),
"".to_string(),
contract_based_connectors,
state.get_grpc_headers(),
)
.await
.attach_printable(
"unable to calculate/fetch contract score from dynamic routing service",
);
let contract_based_connectors = match contract_based_connectors_result {
Ok(resp) => Some(utils::CalContractScoreEventResponse::from(&resp)),
Err(err) => match err.current_context() {
DynamicRoutingError::ContractNotFound => {
client
.update_contracts(
profile_id.get_string_repr().into(),
label_info,
"".to_string(),
vec![],
u64::default(),
state.get_grpc_headers(),
)
.await
.change_context(errors::RoutingError::ContractScoreUpdationError)
.attach_printable(
"unable to update contract based routing window in dynamic routing service",
)?;
return Err((errors::RoutingError::ContractScoreCalculationError {
err: err.to_string(),
})
.into());
}
_ => {
return Err((errors::RoutingError::ContractScoreCalculationError {
err: err.to_string(),
})
.into())
}
},
};
Ok(contract_based_connectors)
};
let events_response = routing_events_wrapper
.construct_event_builder(
"ContractScoreCalculator.FetchContractScore".to_string(),
RoutingEngine::IntelligentRouter,
ApiMethod::Grpc,
)?
.trigger_event(state, closure)
.await?;
let contract_based_connectors: utils::CalContractScoreEventResponse = events_response
.response
.ok_or(errors::RoutingError::ContractScoreCalculationError {
err: "CalContractScoreEventResponse not found".to_string(),
})?;
let mut routing_event = events_response
.event
.ok_or(errors::RoutingError::RoutingEventsError {
message:
"ContractRouting-Intelligent-Router: RoutingEvent not found in RoutingEventsResponse"
.to_string(),
status_code: 500,
})?;
payment_data.set_routing_approach_in_attempt(Some(
common_enums::RoutingApproach::ContractBasedRouting,
));
let mut connectors = Vec::with_capacity(contract_based_connectors.labels_with_score.len());
for label_with_score in contract_based_connectors.labels_with_score {
let (connector, merchant_connector_id) = label_with_score.label
.split_once(':')
.ok_or(errors::RoutingError::InvalidContractBasedConnectorLabel(label_with_score.label.to_string()))
.attach_printable(
"unable to split connector_name and mca_id from the label obtained by the dynamic routing service",
)?;
connectors.push(api_routing::RoutableConnectorChoice {
choice_kind: api_routing::RoutableChoiceKind::FullStruct,
connector: common_enums::RoutableConnectors::from_str(connector)
.change_context(errors::RoutingError::GenericConversionError {
from: "String".to_string(),
to: "RoutableConnectors".to_string(),
})
.attach_printable("unable to convert String to RoutableConnectors")?,
merchant_connector_id: Some(
common_utils::id_type::MerchantConnectorAccountId::wrap(
merchant_connector_id.to_string(),
)
.change_context(errors::RoutingError::GenericConversionError {
from: "String".to_string(),
to: "MerchantConnectorAccountId".to_string(),
})
.attach_printable("unable to convert MerchantConnectorAccountId from string")?,
),
});
}
connectors.append(&mut other_connectors);
logger::debug!(contract_based_routing_connectors=?connectors);
routing_event.set_status_code(200);
routing_event.set_routable_connectors(connectors.clone());
routing_event.set_routing_approach(api_routing::RoutingApproach::ContractBased.to_string());
state.event_handler().log_event(&routing_event);
Ok(connectors)
} else {
Ok(routable_connectors)
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 203,
"total_crates": null
} |
fn_clm_router_perform_elimination_routing_-350303204233383802 | 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
pub async fn perform_elimination_routing(
state: &SessionState,
routable_connectors: Vec<api_routing::RoutableConnectorChoice>,
profile_id: &common_utils::id_type::ProfileId,
merchant_id: &common_utils::id_type::MerchantId,
payment_id: &common_utils::id_type::PaymentId,
elimination_routing_configs_params_interpolator: routing::helpers::DynamicRoutingConfigParamsInterpolator,
elimination_algo_ref: api_routing::EliminationRoutingAlgorithm,
) -> RoutingResult<Vec<api_routing::RoutableConnectorChoice>> {
if elimination_algo_ref.enabled_feature
== api_routing::DynamicRoutingFeatures::DynamicConnectorSelection
{
logger::debug!(
"performing elimination_routing for profile {}",
profile_id.get_string_repr()
);
let client = &state
.grpc_client
.dynamic_routing
.as_ref()
.ok_or(errors::RoutingError::EliminationClientInitializationError)
.attach_printable("dynamic routing gRPC client not found")?
.elimination_based_client;
let elimination_routing_config = routing::helpers::fetch_dynamic_routing_configs::<
api_routing::EliminationRoutingConfig,
>(
state,
profile_id,
elimination_algo_ref
.algorithm_id_with_timestamp
.algorithm_id
.ok_or(errors::RoutingError::GenericNotFoundError {
field: "elimination_routing_algorithm_id".to_string(),
})
.attach_printable(
"elimination_routing_algorithm_id not found in business_profile",
)?,
)
.await
.change_context(errors::RoutingError::EliminationRoutingConfigError)
.attach_printable("unable to fetch elimination dynamic routing configs")?;
let elimination_routing_config_params = elimination_routing_configs_params_interpolator
.get_string_val(
elimination_routing_config
.params
.as_ref()
.ok_or(errors::RoutingError::EliminationBasedRoutingParamsNotFoundError)?,
);
let event_request = utils::EliminationRoutingEventRequest {
id: profile_id.get_string_repr().to_string(),
params: elimination_routing_config_params.clone(),
labels: routable_connectors
.iter()
.map(|conn_choice| conn_choice.to_string())
.collect::<Vec<_>>(),
config: elimination_routing_config
.elimination_analyser_config
.as_ref()
.map(utils::EliminationRoutingEventBucketConfig::from),
};
let routing_events_wrapper = utils::RoutingEventsWrapper::new(
state.tenant.tenant_id.clone(),
state.request_id,
payment_id.get_string_repr().to_string(),
profile_id.to_owned(),
merchant_id.to_owned(),
"IntelligentRouter: PerformEliminationRouting".to_string(),
Some(event_request.clone()),
true,
false,
);
let closure = || async {
let elimination_based_connectors_result = client
.perform_elimination_routing(
profile_id.get_string_repr().to_string(),
elimination_routing_config_params,
routable_connectors.clone(),
elimination_routing_config.elimination_analyser_config,
state.get_grpc_headers(),
)
.await
.change_context(errors::RoutingError::EliminationRoutingCalculationError)
.attach_printable(
"unable to analyze/fetch elimination routing from dynamic routing service",
);
match elimination_based_connectors_result {
Ok(elimination_response) => Ok(Some(utils::EliminationEventResponse::from(
&elimination_response,
))),
Err(e) => {
logger::error!(
"unable to analyze/fetch elimination routing from dynamic routing service: {:?}",
e.current_context()
);
Err(error_stack::report!(
errors::RoutingError::EliminationRoutingCalculationError
))
}
}
};
let events_response = routing_events_wrapper
.construct_event_builder(
"EliminationAnalyser.GetEliminationStatus".to_string(),
RoutingEngine::IntelligentRouter,
ApiMethod::Grpc,
)?
.trigger_event(state, closure)
.await?;
let elimination_based_connectors: utils::EliminationEventResponse = events_response
.response
.ok_or(errors::RoutingError::EliminationRoutingCalculationError)?;
let mut routing_event = events_response
.event
.ok_or(errors::RoutingError::RoutingEventsError {
message:
"Elimination-Intelligent-Router: RoutingEvent not found in RoutingEventsResponse"
.to_string(),
status_code: 500,
})?;
routing_event.set_routing_approach(utils::RoutingApproach::Elimination.to_string());
let mut connectors =
Vec::with_capacity(elimination_based_connectors.labels_with_status.len());
let mut eliminated_connectors =
Vec::with_capacity(elimination_based_connectors.labels_with_status.len());
let mut non_eliminated_connectors =
Vec::with_capacity(elimination_based_connectors.labels_with_status.len());
for labels_with_status in elimination_based_connectors.labels_with_status {
let (connector, merchant_connector_id) = labels_with_status.label
.split_once(':')
.ok_or(errors::RoutingError::InvalidEliminationBasedConnectorLabel(labels_with_status.label.to_string()))
.attach_printable(
"unable to split connector_name and mca_id from the label obtained by the elimination based dynamic routing service",
)?;
let routable_connector = api_routing::RoutableConnectorChoice {
choice_kind: api_routing::RoutableChoiceKind::FullStruct,
connector: common_enums::RoutableConnectors::from_str(connector)
.change_context(errors::RoutingError::GenericConversionError {
from: "String".to_string(),
to: "RoutableConnectors".to_string(),
})
.attach_printable("unable to convert String to RoutableConnectors")?,
merchant_connector_id: Some(
common_utils::id_type::MerchantConnectorAccountId::wrap(
merchant_connector_id.to_string(),
)
.change_context(errors::RoutingError::GenericConversionError {
from: "String".to_string(),
to: "MerchantConnectorAccountId".to_string(),
})
.attach_printable("unable to convert MerchantConnectorAccountId from string")?,
),
};
if labels_with_status
.elimination_information
.is_some_and(|elimination_info| {
elimination_info
.entity
.is_some_and(|entity_info| entity_info.is_eliminated)
})
{
eliminated_connectors.push(routable_connector);
} else {
non_eliminated_connectors.push(routable_connector);
}
connectors.extend(non_eliminated_connectors.clone());
connectors.extend(eliminated_connectors.clone());
}
logger::debug!(dynamic_eliminated_connectors=?eliminated_connectors);
logger::debug!(dynamic_elimination_based_routing_connectors=?connectors);
routing_event.set_status_code(200);
routing_event.set_routable_connectors(connectors.clone());
state.event_handler().log_event(&routing_event);
Ok(connectors)
} else {
Ok(routable_connectors)
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 172,
"total_crates": null
} |
fn_clm_router_perform_success_based_routing_-350303204233383802 | 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
pub async fn perform_success_based_routing<F, D>(
state: &SessionState,
routable_connectors: Vec<api_routing::RoutableConnectorChoice>,
profile_id: &common_utils::id_type::ProfileId,
merchant_id: &common_utils::id_type::MerchantId,
payment_id: &common_utils::id_type::PaymentId,
success_based_routing_config_params_interpolator: routing::helpers::DynamicRoutingConfigParamsInterpolator,
success_based_algo_ref: api_routing::SuccessBasedAlgorithm,
payment_data: &mut D,
) -> RoutingResult<Vec<api_routing::RoutableConnectorChoice>>
where
F: Send + Clone,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
{
if success_based_algo_ref.enabled_feature
== api_routing::DynamicRoutingFeatures::DynamicConnectorSelection
{
logger::debug!(
"performing success_based_routing for profile {}",
profile_id.get_string_repr()
);
let client = &state
.grpc_client
.dynamic_routing
.as_ref()
.ok_or(errors::RoutingError::SuccessRateClientInitializationError)
.attach_printable("dynamic routing gRPC client not found")?
.success_rate_client;
let success_based_routing_configs = routing::helpers::fetch_dynamic_routing_configs::<
api_routing::SuccessBasedRoutingConfig,
>(
state,
profile_id,
success_based_algo_ref
.algorithm_id_with_timestamp
.algorithm_id
.ok_or(errors::RoutingError::GenericNotFoundError {
field: "success_based_routing_algorithm_id".to_string(),
})
.attach_printable("success_based_routing_algorithm_id not found in profile_id")?,
)
.await
.change_context(errors::RoutingError::SuccessBasedRoutingConfigError)
.attach_printable("unable to fetch success_rate based dynamic routing configs")?;
let success_based_routing_config_params = success_based_routing_config_params_interpolator
.get_string_val(
success_based_routing_configs
.params
.as_ref()
.ok_or(errors::RoutingError::SuccessBasedRoutingParamsNotFoundError)?,
);
let event_request = utils::CalSuccessRateEventRequest {
id: profile_id.get_string_repr().to_string(),
params: success_based_routing_config_params.clone(),
labels: routable_connectors
.iter()
.map(|conn_choice| conn_choice.to_string())
.collect::<Vec<_>>(),
config: success_based_routing_configs
.config
.as_ref()
.map(utils::CalSuccessRateConfigEventRequest::from),
};
let routing_events_wrapper = utils::RoutingEventsWrapper::new(
state.tenant.tenant_id.clone(),
state.request_id,
payment_id.get_string_repr().to_string(),
profile_id.to_owned(),
merchant_id.to_owned(),
"IntelligentRouter: CalculateSuccessRate".to_string(),
Some(event_request.clone()),
true,
false,
);
let closure = || async {
let success_based_connectors_result = client
.calculate_success_rate(
profile_id.get_string_repr().into(),
success_based_routing_configs,
success_based_routing_config_params,
routable_connectors,
state.get_grpc_headers(),
)
.await
.change_context(errors::RoutingError::SuccessRateCalculationError)
.attach_printable(
"unable to calculate/fetch success rate from dynamic routing service",
);
match success_based_connectors_result {
Ok(success_response) => {
let updated_resp = utils::CalSuccessRateEventResponse::try_from(
&success_response,
)
.change_context(errors::RoutingError::RoutingEventsError { message: "unable to convert SuccessBasedConnectors to CalSuccessRateEventResponse".to_string(), status_code: 500 })
.attach_printable(
"unable to convert SuccessBasedConnectors to CalSuccessRateEventResponse",
)?;
Ok(Some(updated_resp))
}
Err(e) => {
logger::error!(
"unable to calculate/fetch success rate from dynamic routing service: {:?}",
e.current_context()
);
Err(error_stack::report!(
errors::RoutingError::SuccessRateCalculationError
))
}
}
};
let events_response = routing_events_wrapper
.construct_event_builder(
"SuccessRateCalculator.FetchSuccessRate".to_string(),
RoutingEngine::IntelligentRouter,
ApiMethod::Grpc,
)?
.trigger_event(state, closure)
.await?;
let success_based_connectors: utils::CalSuccessRateEventResponse = events_response
.response
.ok_or(errors::RoutingError::SuccessRateCalculationError)?;
// Need to log error case
let mut routing_event =
events_response
.event
.ok_or(errors::RoutingError::RoutingEventsError {
message:
"SR-Intelligent-Router: RoutingEvent not found in RoutingEventsResponse"
.to_string(),
status_code: 500,
})?;
routing_event.set_routing_approach(success_based_connectors.routing_approach.to_string());
payment_data.set_routing_approach_in_attempt(Some(common_enums::RoutingApproach::from(
success_based_connectors.routing_approach,
)));
let mut connectors = Vec::with_capacity(success_based_connectors.labels_with_score.len());
for label_with_score in success_based_connectors.labels_with_score {
let (connector, merchant_connector_id) = label_with_score.label
.split_once(':')
.ok_or(errors::RoutingError::InvalidSuccessBasedConnectorLabel(label_with_score.label.to_string()))
.attach_printable(
"unable to split connector_name and mca_id from the label obtained by the dynamic routing service",
)?;
connectors.push(api_routing::RoutableConnectorChoice {
choice_kind: api_routing::RoutableChoiceKind::FullStruct,
connector: common_enums::RoutableConnectors::from_str(connector)
.change_context(errors::RoutingError::GenericConversionError {
from: "String".to_string(),
to: "RoutableConnectors".to_string(),
})
.attach_printable("unable to convert String to RoutableConnectors")?,
merchant_connector_id: Some(
common_utils::id_type::MerchantConnectorAccountId::wrap(
merchant_connector_id.to_string(),
)
.change_context(errors::RoutingError::GenericConversionError {
from: "String".to_string(),
to: "MerchantConnectorAccountId".to_string(),
})
.attach_printable("unable to convert MerchantConnectorAccountId from string")?,
),
});
}
logger::debug!(success_based_routing_connectors=?connectors);
routing_event.set_status_code(200);
routing_event.set_routable_connectors(connectors.clone());
state.event_handler().log_event(&routing_event);
Ok(connectors)
} else {
Ok(routable_connectors)
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 155,
"total_crates": null
} |
fn_clm_router_perform_dynamic_routing_with_intelligent_router_-350303204233383802 | 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
pub async fn perform_dynamic_routing_with_intelligent_router<F, D>(
state: &SessionState,
routable_connectors: Vec<api_routing::RoutableConnectorChoice>,
profile: &domain::Profile,
dynamic_routing_config_params_interpolator: routing::helpers::DynamicRoutingConfigParamsInterpolator,
payment_data: &mut D,
) -> RoutingResult<Vec<api_routing::RoutableConnectorChoice>>
where
F: Send + Clone,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
{
let dynamic_routing_algo_ref: api_routing::DynamicRoutingAlgorithmRef = profile
.dynamic_routing_algorithm
.clone()
.map(|val| val.parse_value("DynamicRoutingAlgorithmRef"))
.transpose()
.change_context(errors::RoutingError::DeserializationError {
from: "JSON".to_string(),
to: "DynamicRoutingAlgorithmRef".to_string(),
})
.attach_printable("unable to deserialize DynamicRoutingAlgorithmRef from JSON")?
.ok_or(errors::RoutingError::GenericNotFoundError {
field: "dynamic_routing_algorithm".to_string(),
})?;
logger::debug!(
"performing dynamic_routing for profile {}",
profile.get_id().get_string_repr()
);
let payment_attempt = payment_data.get_payment_attempt().clone();
let mut connector_list = match dynamic_routing_algo_ref
.success_based_algorithm
.as_ref()
.async_map(|algorithm| {
perform_success_based_routing(
state,
routable_connectors.clone(),
profile.get_id(),
&payment_attempt.merchant_id,
&payment_attempt.payment_id,
dynamic_routing_config_params_interpolator.clone(),
algorithm.clone(),
payment_data,
)
})
.await
.transpose()
.inspect_err(|e| logger::error!(dynamic_routing_error=?e))
.ok()
.flatten()
{
Some(success_based_list) => success_based_list,
None => {
// Only run contract based if success based returns None
dynamic_routing_algo_ref
.contract_based_routing
.as_ref()
.async_map(|algorithm| {
perform_contract_based_routing(
state,
routable_connectors.clone(),
profile.get_id(),
&payment_attempt.merchant_id,
&payment_attempt.payment_id,
dynamic_routing_config_params_interpolator.clone(),
algorithm.clone(),
payment_data,
)
})
.await
.transpose()
.inspect_err(|e| logger::error!(dynamic_routing_error=?e))
.ok()
.flatten()
.unwrap_or(routable_connectors.clone())
}
};
connector_list = dynamic_routing_algo_ref
.elimination_routing_algorithm
.as_ref()
.async_map(|algorithm| {
perform_elimination_routing(
state,
connector_list.clone(),
profile.get_id(),
&payment_attempt.merchant_id,
&payment_attempt.payment_id,
dynamic_routing_config_params_interpolator.clone(),
algorithm.clone(),
)
})
.await
.transpose()
.inspect_err(|e| logger::error!(dynamic_routing_error=?e))
.ok()
.flatten()
.unwrap_or(connector_list);
Ok(connector_list)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 106,
"total_crates": null
} |
fn_clm_router_preprocessing_steps_2525949574710016118 | 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
async fn preprocessing_steps<'a>(
self,
_state: &SessionState,
_connector: &api::ConnectorData,
) -> RouterResult<Self>
where
F: Clone,
Self: Sized,
dyn api::Connector: services::ConnectorIntegration<F, T, types::PaymentsResponseData>,
{
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": 39,
"total_crates": null
} |
fn_clm_router_create_connector_customer_2525949574710016118 | 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
async fn create_connector_customer<'a>(
&self,
_state: &SessionState,
_connector: &api::ConnectorData,
) -> RouterResult<Option<String>>
where
F: Clone,
Self: Sized,
dyn api::Connector: services::ConnectorIntegration<F, T, types::PaymentsResponseData>,
{
Ok(None)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 30,
"total_crates": null
} |
fn_clm_router_call_capture_request_2525949574710016118 | 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
/// Executes a capture request by building a connector-specific request and deciding
/// the appropriate flow to send it to the payment connector.
pub async fn call_capture_request(
mut capture_router_data: types::RouterData<
api::Capture,
PaymentsCaptureData,
types::PaymentsResponseData,
>,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
business_profile: &domain::Profile,
header_payload: domain_payments::HeaderPayload,
) -> RouterResult<types::RouterData<api::Capture, PaymentsCaptureData, types::PaymentsResponseData>>
{
// Build capture-specific connector request
let (connector_request, _should_continue_further) = capture_router_data
.build_flow_specific_connector_request(state, connector, call_connector_action.clone())
.await?;
// Execute capture flow
capture_router_data
.decide_flows(
state,
connector,
call_connector_action,
connector_request,
business_profile,
header_payload.clone(),
None,
)
.await
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 24,
"total_crates": null
} |
fn_clm_router_should_initiate_capture_flow_2525949574710016118 | 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
/// Determines whether a capture API call should be made for a payment attempt
/// This function evaluates whether an authorized payment should proceed with a capture API call
/// based on various payment parameters. It's primarily used in two-step (auth + capture) payment flows for CaptureMethod SequentialAutomatic
///
pub fn should_initiate_capture_flow(
connector_name: &router_types::Connector,
customer_acceptance: Option<CustomerAcceptance>,
capture_method: Option<api_enums::CaptureMethod>,
setup_future_usage: Option<api_enums::FutureUsage>,
status: common_enums::AttemptStatus,
) -> bool {
match status {
common_enums::AttemptStatus::Authorized => {
if let Some(api_enums::CaptureMethod::SequentialAutomatic) = capture_method {
match connector_name {
router_types::Connector::Paybox => {
// Check CIT conditions for Paybox
setup_future_usage == Some(api_enums::FutureUsage::OffSession)
&& customer_acceptance.is_some()
}
_ => false,
}
} else {
false
}
}
_ => false,
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 18,
"total_crates": null
} |
fn_clm_router_add_payment_method_token_2525949574710016118 | 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
async fn add_payment_method_token<'a>(
&mut self,
_state: &SessionState,
_connector: &api::ConnectorData,
_tokenization_action: &payments::TokenizationAction,
_should_continue_payment: bool,
) -> RouterResult<types::PaymentMethodTokenResult>
where
F: Clone,
Self: Sized,
dyn api::Connector: services::ConnectorIntegration<F, T, types::PaymentsResponseData>,
{
Ok(types::PaymentMethodTokenResult {
payment_method_token_result: Ok(None),
is_payment_method_tokenization_performed: false,
connector_response: None,
})
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 15,
"total_crates": null
} |
fn_clm_router_to_domain_4619263918661394846 | 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
fn to_domain(&self) -> RouterResult<&dyn Domain<F, T, Self::Data>> {
Err(report!(errors::ApiErrorResponse::InternalServerError))
.attach_printable_lazy(|| format!("domain interface not found for {self:?}"))
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 86,
"total_crates": null
} |
fn_clm_router_update_payment_method_4619263918661394846 | 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
async fn update_payment_method<'a>(
&'a self,
state: &SessionState,
merchant_context: &domain::MerchantContext,
payment_data: &mut D,
) {
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 78,
"total_crates": null
} |
fn_clm_router_to_update_tracker_4619263918661394846 | 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
fn to_update_tracker(
&self,
) -> RouterResult<&(dyn UpdateTracker<F, Self::Data, T> + Send + Sync)> {
Err(report!(errors::ApiErrorResponse::InternalServerError))
.attach_printable_lazy(|| format!("update tracker interface not found for {self:?}"))
}
| {
"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_to_get_tracker_4619263918661394846 | 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
fn to_get_tracker(&self) -> RouterResult<&(dyn GetTracker<F, Self::Data, T> + Send + Sync)> {
Err(report!(errors::ApiErrorResponse::InternalServerError))
.attach_printable_lazy(|| format!("get tracker interface not found for {self:?}"))
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 38,
"total_crates": null
} |
fn_clm_router_to_validate_request_4619263918661394846 | 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
fn to_validate_request(
&self,
) -> RouterResult<&(dyn ValidateRequest<F, T, Self::Data> + Send + Sync)> {
Err(report!(errors::ApiErrorResponse::InternalServerError))
.attach_printable_lazy(|| format!("validate request interface not found for {self:?}"))
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 26,
"total_crates": null
} |
fn_clm_router_modify_trackers_-5292370442346665372 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/retry
pub async fn modify_trackers<F, FData, D>(
state: &routes::SessionState,
connector: String,
payment_data: &mut D,
key_store: &domain::MerchantKeyStore,
storage_scheme: storage_enums::MerchantStorageScheme,
router_data: types::RouterData<F, FData, types::PaymentsResponseData>,
is_step_up: bool,
) -> RouterResult<()>
where
F: Clone + Send,
FData: Send + types::Capturable,
D: payments::OperationSessionGetters<F> + payments::OperationSessionSetters<F> + Send + Sync,
{
let new_attempt_count = payment_data.get_payment_intent().attempt_count + 1;
let new_payment_attempt = make_new_payment_attempt(
connector,
payment_data.get_payment_attempt().clone(),
new_attempt_count,
is_step_up,
payment_data.get_payment_intent().setup_future_usage,
);
let db = &*state.store;
let key_manager_state = &state.into();
let additional_payment_method_data =
payments::helpers::update_additional_payment_data_with_connector_response_pm_data(
payment_data
.get_payment_attempt()
.payment_method_data
.clone(),
router_data
.connector_response
.clone()
.and_then(|connector_response| connector_response.additional_payment_method_data),
)?;
let debit_routing_savings = payment_data.get_payment_method_data().and_then(|data| {
payments::helpers::get_debit_routing_savings_amount(
data,
payment_data.get_payment_attempt(),
)
});
match router_data.response {
Ok(types::PaymentsResponseData::TransactionResponse {
resource_id,
connector_metadata,
redirection_data,
charges,
..
}) => {
let encoded_data = payment_data.get_payment_attempt().encoded_data.clone();
let authentication_data = (*redirection_data)
.as_ref()
.map(Encode::encode_to_value)
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Could not parse the connector response")?;
let payment_attempt_update = storage::PaymentAttemptUpdate::ResponseUpdate {
status: router_data.status,
connector: None,
connector_transaction_id: match resource_id {
types::ResponseId::NoResponseId => None,
types::ResponseId::ConnectorTransactionId(id)
| types::ResponseId::EncodedData(id) => Some(id),
},
connector_response_reference_id: payment_data
.get_payment_attempt()
.connector_response_reference_id
.clone(),
authentication_type: None,
payment_method_id: payment_data.get_payment_attempt().payment_method_id.clone(),
mandate_id: payment_data
.get_mandate_id()
.and_then(|mandate| mandate.mandate_id.clone()),
connector_metadata,
payment_token: None,
error_code: None,
error_message: None,
error_reason: None,
amount_capturable: if router_data.status.is_terminal_status() {
Some(MinorUnit::new(0))
} else {
None
},
updated_by: storage_scheme.to_string(),
authentication_data,
encoded_data,
unified_code: None,
unified_message: None,
capture_before: None,
extended_authorization_applied: None,
payment_method_data: additional_payment_method_data,
connector_mandate_detail: None,
charges,
setup_future_usage_applied: None,
debit_routing_savings,
network_transaction_id: payment_data
.get_payment_attempt()
.network_transaction_id
.clone(),
is_overcapture_enabled: None,
authorized_amount: router_data.authorized_amount,
};
#[cfg(feature = "v1")]
db.update_payment_attempt_with_attempt_id(
payment_data.get_payment_attempt().clone(),
payment_attempt_update,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
#[cfg(feature = "v2")]
db.update_payment_attempt_with_attempt_id(
key_manager_state,
key_store,
payment_data.get_payment_attempt().clone(),
payment_attempt_update,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
}
Ok(_) => {
logger::error!("unexpected response: this response was not expected in Retry flow");
return Ok(());
}
Err(ref error_response) => {
let option_gsm = get_gsm(state, &router_data).await?;
let auth_update = if Some(router_data.auth_type)
!= payment_data.get_payment_attempt().authentication_type
{
Some(router_data.auth_type)
} else {
None
};
let payment_attempt_update = storage::PaymentAttemptUpdate::ErrorUpdate {
connector: None,
error_code: Some(Some(error_response.code.clone())),
error_message: Some(Some(error_response.message.clone())),
status: storage_enums::AttemptStatus::Failure,
error_reason: Some(error_response.reason.clone()),
amount_capturable: Some(MinorUnit::new(0)),
updated_by: storage_scheme.to_string(),
unified_code: option_gsm.clone().map(|gsm| gsm.unified_code),
unified_message: option_gsm.map(|gsm| gsm.unified_message),
connector_transaction_id: error_response.connector_transaction_id.clone(),
payment_method_data: additional_payment_method_data,
authentication_type: auth_update,
issuer_error_code: error_response.network_decline_code.clone(),
issuer_error_message: error_response.network_error_message.clone(),
network_details: Some(ForeignFrom::foreign_from(error_response)),
};
#[cfg(feature = "v1")]
db.update_payment_attempt_with_attempt_id(
payment_data.get_payment_attempt().clone(),
payment_attempt_update,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
#[cfg(feature = "v2")]
db.update_payment_attempt_with_attempt_id(
key_manager_state,
key_store,
payment_data.get_payment_attempt().clone(),
payment_attempt_update,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
}
}
#[cfg(feature = "v1")]
let payment_attempt = db
.insert_payment_attempt(new_payment_attempt, storage_scheme)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error inserting payment attempt")?;
#[cfg(feature = "v2")]
let payment_attempt = db
.insert_payment_attempt(
key_manager_state,
key_store,
new_payment_attempt,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error inserting payment attempt")?;
// update payment_attempt, connector_response and payment_intent in payment_data
payment_data.set_payment_attempt(payment_attempt);
let payment_intent = db
.update_payment_intent(
key_manager_state,
payment_data.get_payment_intent().clone(),
storage::PaymentIntentUpdate::PaymentAttemptAndAttemptCountUpdate {
active_attempt_id: payment_data.get_payment_attempt().get_id().to_owned(),
attempt_count: new_attempt_count,
updated_by: storage_scheme.to_string(),
},
key_store,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
payment_data.set_payment_intent(payment_intent);
Ok(())
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 176,
"total_crates": null
} |
fn_clm_router_do_gsm_actions_-5292370442346665372 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/retry
pub async fn do_gsm_actions<'a, F, ApiRequest, FData, D>(
state: &app::SessionState,
req_state: ReqState,
payment_data: &mut D,
mut connector_routing_data: IntoIter<api::ConnectorRoutingData>,
original_connector_data: &api::ConnectorData,
mut router_data: types::RouterData<F, FData, types::PaymentsResponseData>,
merchant_context: &domain::MerchantContext,
operation: &operations::BoxedOperation<'_, F, ApiRequest, D>,
customer: &Option<domain::Customer>,
validate_result: &operations::ValidateResult,
schedule_time: Option<time::PrimitiveDateTime>,
frm_suggestion: Option<storage_enums::FrmSuggestion>,
business_profile: &domain::Profile,
) -> RouterResult<types::RouterData<F, FData, types::PaymentsResponseData>>
where
F: Clone + Send + Sync + 'static,
FData: Send + Sync + types::Capturable + Clone + 'static + serde::Serialize,
payments::PaymentResponse: operations::Operation<F, FData>,
D: payments::OperationSessionGetters<F>
+ payments::OperationSessionSetters<F>
+ Send
+ Sync
+ Clone,
D: ConstructFlowSpecificData<F, FData, types::PaymentsResponseData>,
types::RouterData<F, FData, types::PaymentsResponseData>: Feature<F, FData>,
dyn api::Connector: services::api::ConnectorIntegration<F, FData, types::PaymentsResponseData>,
{
let mut retries = None;
metrics::AUTO_RETRY_ELIGIBLE_REQUEST_COUNT.add(1, &[]);
let mut initial_gsm = get_gsm(state, &router_data).await?;
let step_up_possible = initial_gsm
.as_ref()
.and_then(|data| data.feature_data.get_retry_feature_data())
.map(|data| data.is_step_up_possible())
.unwrap_or(false);
#[cfg(feature = "v1")]
let is_no_three_ds_payment = matches!(
payment_data.get_payment_attempt().authentication_type,
Some(storage_enums::AuthenticationType::NoThreeDs)
);
#[cfg(feature = "v2")]
let is_no_three_ds_payment = matches!(
payment_data.get_payment_attempt().authentication_type,
storage_enums::AuthenticationType::NoThreeDs
);
let should_step_up = if step_up_possible && is_no_three_ds_payment {
is_step_up_enabled_for_merchant_connector(
state,
merchant_context.get_merchant_account().get_id(),
original_connector_data.connector_name,
)
.await
} else {
false
};
if should_step_up {
router_data = do_retry(
&state.clone(),
req_state.clone(),
original_connector_data,
operation,
customer,
merchant_context,
payment_data,
router_data,
validate_result,
schedule_time,
true,
frm_suggestion,
business_profile,
false, //should_retry_with_pan is not applicable for step-up
None,
)
.await?;
}
// Step up is not applicable so proceed with auto retries flow
else {
loop {
// Use initial_gsm for first time alone
let gsm = match initial_gsm.as_ref() {
Some(gsm) => Some(gsm.clone()),
None => get_gsm(state, &router_data).await?,
};
match get_gsm_decision(gsm) {
storage_enums::GsmDecision::Retry => {
retries = get_retries(
state,
retries,
merchant_context.get_merchant_account().get_id(),
business_profile,
)
.await;
if retries.is_none() || retries == Some(0) {
metrics::AUTO_RETRY_EXHAUSTED_COUNT.add(1, &[]);
logger::info!("retries exhausted for auto_retry payment");
break;
}
if connector_routing_data.len() == 0 {
logger::info!("connectors exhausted for auto_retry payment");
metrics::AUTO_RETRY_EXHAUSTED_COUNT.add(1, &[]);
break;
}
let is_network_token = payment_data
.get_payment_method_data()
.map(|pmd| pmd.is_network_token_payment_method_data())
.unwrap_or(false);
let clear_pan_possible = initial_gsm
.and_then(|data| data.feature_data.get_retry_feature_data())
.map(|data| data.is_clear_pan_possible())
.unwrap_or(false);
let should_retry_with_pan = is_network_token
&& clear_pan_possible
&& business_profile.is_clear_pan_retries_enabled;
// Currently we are taking off_session as a source of truth to identify MIT payments.
let is_mit_payment = payment_data
.get_payment_intent()
.off_session
.unwrap_or(false);
let (connector, routing_decision) = if is_mit_payment {
let connector_routing_data =
super::get_connector_data(&mut connector_routing_data)?;
let payment_method_info = payment_data
.get_payment_method_info()
.get_required_value("payment_method_info")?
.clone();
let mandate_reference_id = payments::get_mandate_reference_id(
connector_routing_data.action_type.clone(),
connector_routing_data.clone(),
payment_data,
&payment_method_info,
)?;
payment_data.set_mandate_id(api_models::payments::MandateIds {
mandate_id: None,
mandate_reference_id, //mandate_ref_id
});
(connector_routing_data.connector_data, None)
} else if should_retry_with_pan {
// If should_retry_with_pan is true, it indicates that we are retrying with PAN using the same connector.
(original_connector_data.clone(), None)
} else {
let connector_routing_data =
super::get_connector_data(&mut connector_routing_data)?;
let routing_decision = connector_routing_data.network.map(|card_network| {
routing_helpers::RoutingDecisionData::get_debit_routing_decision_data(
card_network,
None,
)
});
(connector_routing_data.connector_data, routing_decision)
};
router_data = do_retry(
&state.clone(),
req_state.clone(),
&connector,
operation,
customer,
merchant_context,
payment_data,
router_data,
validate_result,
schedule_time,
//this is an auto retry payment, but not step-up
false,
frm_suggestion,
business_profile,
should_retry_with_pan,
routing_decision,
)
.await?;
retries = retries.map(|i| i - 1);
}
storage_enums::GsmDecision::DoDefault => break,
}
initial_gsm = None;
}
}
Ok(router_data)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 117,
"total_crates": null
} |
fn_clm_router_get_gsm_-5292370442346665372 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/retry
pub async fn get_gsm<F, FData>(
state: &app::SessionState,
router_data: &types::RouterData<F, FData, types::PaymentsResponseData>,
) -> RouterResult<Option<hyperswitch_domain_models::gsm::GatewayStatusMap>> {
let error_response = router_data.response.as_ref().err();
let error_code = error_response.map(|err| err.code.to_owned());
let error_message = error_response.map(|err| err.message.to_owned());
let connector_name = router_data.connector.to_string();
let flow = get_flow_name::<F>()?;
Ok(
payments::helpers::get_gsm_record(state, error_code, error_message, connector_name, flow)
.await,
)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 47,
"total_crates": null
} |
fn_clm_router_do_retry_-5292370442346665372 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/retry
pub async fn do_retry<'a, F, ApiRequest, FData, D>(
state: &'a routes::SessionState,
req_state: ReqState,
connector: &'a api::ConnectorData,
operation: &'a operations::BoxedOperation<'a, F, ApiRequest, D>,
customer: &'a Option<domain::Customer>,
merchant_context: &domain::MerchantContext,
payment_data: &'a mut D,
router_data: types::RouterData<F, FData, types::PaymentsResponseData>,
validate_result: &operations::ValidateResult,
schedule_time: Option<time::PrimitiveDateTime>,
is_step_up: bool,
frm_suggestion: Option<storage_enums::FrmSuggestion>,
business_profile: &domain::Profile,
should_retry_with_pan: bool,
routing_decision: Option<routing_helpers::RoutingDecisionData>,
) -> RouterResult<types::RouterData<F, FData, types::PaymentsResponseData>>
where
F: Clone + Send + Sync + 'static,
FData: Send + Sync + types::Capturable + Clone + 'static + serde::Serialize,
payments::PaymentResponse: operations::Operation<F, FData>,
D: payments::OperationSessionGetters<F>
+ payments::OperationSessionSetters<F>
+ Send
+ Sync
+ Clone,
D: ConstructFlowSpecificData<F, FData, types::PaymentsResponseData>,
types::RouterData<F, FData, types::PaymentsResponseData>: Feature<F, FData>,
dyn api::Connector: services::api::ConnectorIntegration<F, FData, types::PaymentsResponseData>,
{
metrics::AUTO_RETRY_PAYMENT_COUNT.add(1, &[]);
modify_trackers(
state,
connector.connector_name.to_string(),
payment_data,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
router_data,
is_step_up,
)
.await?;
let (merchant_connector_account, router_data, tokenization_action) =
payments::call_connector_service_prerequisites(
state,
merchant_context,
connector.clone(),
operation,
payment_data,
customer,
validate_result,
business_profile,
should_retry_with_pan,
routing_decision,
)
.await?;
let (router_data, _mca) = payments::decide_unified_connector_service_call(
state,
req_state,
merchant_context,
connector.clone(),
operation,
payment_data,
customer,
payments::CallConnectorAction::Trigger,
validate_result,
schedule_time,
hyperswitch_domain_models::payments::HeaderPayload::default(),
frm_suggestion,
business_profile,
true,
None,
merchant_connector_account,
router_data,
tokenization_action,
)
.await?;
Ok(router_data)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 42,
"total_crates": null
} |
fn_clm_router_is_step_up_enabled_for_merchant_connector_-5292370442346665372 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payments/retry
pub async fn is_step_up_enabled_for_merchant_connector(
state: &app::SessionState,
merchant_id: &common_utils::id_type::MerchantId,
connector_name: types::Connector,
) -> bool {
let key = merchant_id.get_step_up_enabled_key();
let db = &*state.store;
db.find_config_by_key_unwrap_or(key.as_str(), Some("[]".to_string()))
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.and_then(|step_up_config| {
serde_json::from_str::<Vec<types::Connector>>(&step_up_config.config)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Step-up config parsing failed")
})
.map_err(|err| {
logger::error!(step_up_config_error=?err);
})
.ok()
.map(|connectors_enabled| connectors_enabled.contains(&connector_name))
.unwrap_or(false)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 39,
"total_crates": null
} |
fn_clm_router_get_tracker_for_sync_419988890593240561 | 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_status
async fn get_tracker_for_sync<
'a,
F: Send + Clone,
Op: Operation<F, api::PaymentsRetrieveRequest, Data = PaymentData<F>> + 'a + Send + Sync,
>(
payment_id: &api::PaymentIdType,
merchant_context: &domain::MerchantContext,
state: &SessionState,
request: &api::PaymentsRetrieveRequest,
operation: Op,
storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsRetrieveRequest, PaymentData<F>>>
{
let (payment_intent, mut payment_attempt, currency, amount);
(payment_intent, payment_attempt) = get_payment_intent_payment_attempt(
state,
payment_id,
merchant_context.get_merchant_account().get_id(),
merchant_context.get_merchant_key_store(),
storage_scheme,
)
.await?;
helpers::authenticate_client_secret(request.client_secret.as_ref(), &payment_intent)?;
let payment_id = payment_attempt.payment_id.clone();
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.clone(),
merchant_context.get_merchant_account().get_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.clone(),
merchant_context.get_merchant_account().get_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.clone(),
merchant_context.get_merchant_account().get_id(),
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
payment_attempt.encoded_data.clone_from(&request.param);
let db = &*state.store;
let key_manager_state = &state.into();
let attempts = match request.expand_attempts {
Some(true) => {
Some(db
.find_attempts_by_merchant_id_payment_id(merchant_context.get_merchant_account().get_id(), &payment_id, storage_scheme)
.await
.change_context(errors::ApiErrorResponse::PaymentNotFound)
.attach_printable_lazy(|| {
format!("Error while retrieving attempt list for, merchant_id: {:?}, payment_id: {payment_id:?}",merchant_context.get_merchant_account().get_id())
})?)
},
_ => None,
};
let multiple_capture_data = if payment_attempt.multiple_capture_count > Some(0) {
let 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
.change_context(errors::ApiErrorResponse::PaymentNotFound)
.attach_printable_lazy(|| {
format!("Error while retrieving capture list for, merchant_id: {:?}, payment_id: {payment_id:?}", merchant_context.get_merchant_account().get_id())
})?;
Some(payment_types::MultipleCaptureData::new_for_sync(
captures,
request.expand_captures,
)?)
} else {
None
};
let refunds = db
.find_refund_by_payment_id_merchant_id(
&payment_id,
merchant_context.get_merchant_account().get_id(),
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::PaymentNotFound)
.attach_printable_lazy(|| {
format!(
"Failed while getting refund list for, payment_id: {:?}, merchant_id: {:?}",
&payment_id,
merchant_context.get_merchant_account().get_id()
)
})?;
let authorizations = db
.find_all_authorizations_by_merchant_id_payment_id(
merchant_context.get_merchant_account().get_id(),
&payment_id,
)
.await
.change_context(errors::ApiErrorResponse::PaymentNotFound)
.attach_printable_lazy(|| {
format!(
"Failed while getting authorizations list for, payment_id: {:?}, merchant_id: {:?}",
&payment_id,
merchant_context.get_merchant_account().get_id()
)
})?;
let disputes = db
.find_disputes_by_merchant_id_payment_id(merchant_context.get_merchant_account().get_id(), &payment_id)
.await
.change_context(errors::ApiErrorResponse::PaymentNotFound)
.attach_printable_lazy(|| {
format!("Error while retrieving dispute list for, merchant_id: {:?}, payment_id: {payment_id:?}", merchant_context.get_merchant_account().get_id())
})?;
let frm_response = if cfg!(feature = "frm") {
db.find_fraud_check_by_payment_id(payment_id.to_owned(), merchant_context.get_merchant_account().get_id().clone())
.await
.change_context(errors::ApiErrorResponse::PaymentNotFound)
.attach_printable_lazy(|| {
format!("Error while retrieving frm_response, merchant_id: {:?}, payment_id: {payment_id:?}", merchant_context.get_merchant_account().get_id())
})
.ok()
} else {
None
};
let contains_encoded_data = payment_attempt.encoded_data.is_some();
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_method_info =
if let Some(ref payment_method_id) = payment_attempt.payment_method_id.clone() {
match db
.find_payment_method(
&(state.into()),
merchant_context.get_merchant_key_store(),
payment_method_id,
storage_scheme,
)
.await
{
Ok(payment_method) => Some(payment_method),
Err(error) => {
if error.current_context().is_db_not_found() {
logger::info!("Payment Method not found in db {:?}", error);
None
} else {
Err(error)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error retrieving payment method from db")?
}
}
}
} else {
None
};
let merchant_id = payment_intent.merchant_id.clone();
let authentication_store = if let Some(ref authentication_id) =
payment_attempt.authentication_id
{
let authentication = db
.find_authentication_by_merchant_id_authentication_id(&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()
)
})?;
Some(
hyperswitch_domain_models::router_request_types::authentication::AuthenticationStore {
authentication,
cavv: None, // marking this as None since we don't need authentication value in payment status flow
},
)
} else {
None
};
let payment_link_data = payment_intent
.payment_link_id
.as_ref()
.async_map(|id| crate::core::payments::get_payment_link_response_from_id(state, id))
.await
.transpose()?;
let payment_data = PaymentData {
flow: PhantomData,
payment_intent,
currency,
amount,
email: None,
mandate_id: payment_attempt
.mandate_id
.clone()
.map(|id| api_models::payments::MandateIds {
mandate_id: Some(id),
mandate_reference_id: None,
}),
mandate_connector: None,
setup_mandate: None,
customer_acceptance: None,
token: None,
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,
),
token_data: None,
confirm: Some(request.force_sync),
payment_method_data: None,
payment_method_token: None,
payment_method_info,
force_sync: Some(
request.force_sync
&& (helpers::check_force_psync_precondition(payment_attempt.status)
|| contains_encoded_data),
),
all_keys_required: request.all_keys_required,
payment_attempt,
refunds,
disputes,
attempts,
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,
payment_link_data,
surcharge_details: None,
frm_message: frm_response,
incremental_authorization_details: None,
authorizations,
authentication: authentication_store,
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: 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(operation),
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": 225,
"total_crates": null
} |
fn_clm_router_to_domain_419988890593240561 | 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_status
// Implementation of None for Operation<F, api::PaymentsRequest>
fn to_domain(&self) -> RouterResult<&dyn Domain<F, api::PaymentsRequest, PaymentData<F>>> {
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_419988890593240561 | 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_status
// Implementation of PaymentStatus for UpdateTracker<F, PaymentData<F>, api::PaymentsRetrieveRequest>
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<(
PaymentStatusOperation<'b, F, api::PaymentsRetrieveRequest>,
PaymentData<F>,
)>
where
F: 'b + Send,
{
req_state
.event_context
.event(AuditEvent::new(AuditEventType::PaymentStatus))
.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": 71,
"total_crates": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.