text
stringlengths 81
477k
| file_path
stringlengths 22
92
| module
stringlengths 13
87
| token_count
int64 24
94.8k
| has_source_code
bool 1
class |
|---|---|---|---|---|
// File: crates/router/src/core/payments/operations/payments_extend_authorization.rs
// Module: router::src::core::payments::operations::payments_extend_authorization
use std::marker::PhantomData;
use api_models::enums::FrmSuggestion;
use async_trait::async_trait;
use error_stack::ResultExt;
use router_derive;
use router_env::{instrument, tracing};
use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest};
use crate::{
core::{
errors::{self, RouterResult, StorageErrorExt},
payments::{self, helpers, operations, PaymentData},
},
routes::{app::ReqState, SessionState},
services,
types::{
self as core_types,
api::{self, PaymentIdTypeExt},
domain,
storage::{self, enums},
},
utils::OptionExt,
};
#[derive(Debug, Clone, Copy, router_derive::PaymentOperation)]
#[operation(operations = "all", flow = "extend_authorization")]
pub struct PaymentExtendAuthorization;
type PaymentExtendAuthorizationOperation<'b, F> =
BoxedOperation<'b, F, api::PaymentsExtendAuthorizationRequest, PaymentData<F>>;
#[async_trait]
impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsExtendAuthorizationRequest>
for PaymentExtendAuthorization
{
#[instrument(skip_all)]
async fn get_trackers<'a>(
&'a self,
state: &'a SessionState,
payment_id: &api::PaymentIdType,
_request: &api::PaymentsExtendAuthorizationRequest,
merchant_context: &domain::MerchantContext,
_auth_flow: services::AuthFlow,
_header_payload: &hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<
operations::GetTrackerResponse<
'a,
F,
api::PaymentsExtendAuthorizationRequest,
PaymentData<F>,
>,
> {
let db = &*state.store;
let key_manager_state = &state.into();
let merchant_id = merchant_context.get_merchant_account().get_id();
let storage_scheme = merchant_context.get_merchant_account().storage_scheme;
let payment_id = payment_id
.get_payment_intent_id()
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
let payment_intent = db
.find_payment_intent_by_payment_id_merchant_id(
key_manager_state,
&payment_id,
merchant_id,
merchant_context.get_merchant_key_store(),
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
helpers::validate_payment_status_against_allowed_statuses(
payment_intent.status,
&[
enums::IntentStatus::RequiresCapture,
enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture,
],
"extend authorization",
)?;
let payment_attempt = db
.find_payment_attempt_by_payment_id_merchant_id_attempt_id(
&payment_intent.payment_id,
merchant_id,
payment_intent.active_attempt.get_id().as_str(),
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
if !payment_attempt
.request_extended_authorization
.is_some_and(|request_extended_authorization| request_extended_authorization.is_true())
{
Err(errors::ApiErrorResponse::PreconditionFailed {
message:
"You cannot extend the authorization for this payment because authorization extension is not enabled.".to_owned(),
})?
}
let shipping_address = helpers::get_address_by_id(
state,
payment_intent.shipping_address_id.clone(),
merchant_context.get_merchant_key_store(),
&payment_intent.payment_id,
merchant_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let billing_address = helpers::get_address_by_id(
state,
payment_intent.billing_address_id.clone(),
merchant_context.get_merchant_key_store(),
&payment_intent.payment_id,
merchant_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let payment_method_billing = helpers::get_address_by_id(
state,
payment_attempt.payment_method_billing_address_id.clone(),
merchant_context.get_merchant_key_store(),
&payment_intent.payment_id,
merchant_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let currency = payment_attempt.currency.get_required_value("currency")?;
let amount = payment_attempt.get_total_amount().into();
let profile_id = payment_intent
.profile_id
.as_ref()
.get_required_value("profile_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("'profile_id' not set in payment intent")?;
let business_profile = db
.find_business_profile_by_profile_id(
key_manager_state,
merchant_context.get_merchant_key_store(),
profile_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
let payment_data = PaymentData {
flow: PhantomData,
payment_intent,
payment_attempt,
currency,
amount,
email: None,
mandate_id: None,
mandate_connector: None,
setup_mandate: None,
customer_acceptance: None,
token: None,
token_data: None,
address: core_types::PaymentAddress::new(
shipping_address.as_ref().map(From::from),
billing_address.as_ref().map(From::from),
payment_method_billing.as_ref().map(From::from),
business_profile.use_billing_as_payment_method_billing,
),
confirm: None,
payment_method_data: None,
payment_method_token: None,
payment_method_info: None,
force_sync: None,
all_keys_required: None,
refunds: vec![],
disputes: vec![],
attempts: None,
sessions_token: vec![],
card_cvc: None,
creds_identifier: None,
pm_token: None,
connector_customer_id: None,
recurring_mandate_payment_data: None,
ephemeral_key: None,
multiple_capture_data: None,
redirect_response: None,
surcharge_details: None,
frm_message: None,
payment_link_data: None,
incremental_authorization_details: None,
authorizations: vec![],
authentication: None,
recurring_details: None,
poll_config: None,
tax_data: None,
session_id: None,
service_details: None,
card_testing_guard_data: None,
vault_operation: None,
threeds_method_comp_ind: None,
whole_connector_response: None,
is_manual_retry_enabled: None,
is_l2_l3_enabled: false,
};
let get_trackers_response = operations::GetTrackerResponse {
operation: Box::new(self),
customer_details: None,
payment_data,
business_profile,
mandate_type: None,
};
Ok(get_trackers_response)
}
}
#[async_trait]
impl<F: Clone + Send + Sync> Domain<F, api::PaymentsExtendAuthorizationRequest, PaymentData<F>>
for PaymentExtendAuthorization
{
#[instrument(skip_all)]
async fn get_or_create_customer_details<'a>(
&'a self,
_state: &SessionState,
_payment_data: &mut PaymentData<F>,
_request: Option<payments::CustomerDetails>,
_merchant_key_store: &domain::MerchantKeyStore,
_storage_scheme: enums::MerchantStorageScheme,
) -> errors::CustomResult<
(
PaymentExtendAuthorizationOperation<'a, F>,
Option<domain::Customer>,
),
errors::StorageError,
> {
Ok((Box::new(self), None))
}
#[instrument(skip_all)]
async fn make_pm_data<'a>(
&'a self,
_state: &'a SessionState,
_payment_data: &mut PaymentData<F>,
_storage_scheme: enums::MerchantStorageScheme,
_merchant_key_store: &domain::MerchantKeyStore,
_customer: &Option<domain::Customer>,
_business_profile: &domain::Profile,
_should_retry_with_pan: bool,
) -> RouterResult<(
PaymentExtendAuthorizationOperation<'a, F>,
Option<domain::PaymentMethodData>,
Option<String>,
)> {
Ok((Box::new(self), None, None))
}
async fn get_connector<'a>(
&'a self,
_merchant_context: &domain::MerchantContext,
state: &SessionState,
_request: &api::PaymentsExtendAuthorizationRequest,
_payment_intent: &storage::PaymentIntent,
) -> errors::CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> {
helpers::get_connector_default(state, None).await
}
#[instrument(skip_all)]
async fn guard_payment_against_blocklist<'a>(
&'a self,
_state: &SessionState,
_merchant_context: &domain::MerchantContext,
_payment_data: &mut PaymentData<F>,
) -> errors::CustomResult<bool, errors::ApiErrorResponse> {
Ok(false)
}
}
#[async_trait]
impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsExtendAuthorizationRequest>
for PaymentExtendAuthorization
{
#[instrument(skip_all)]
async fn update_trackers<'b>(
&'b self,
_state: &'b SessionState,
_req_state: ReqState,
payment_data: PaymentData<F>,
_customer: Option<domain::Customer>,
_storage_scheme: enums::MerchantStorageScheme,
_updated_customer: Option<storage::CustomerUpdate>,
_key_store: &domain::MerchantKeyStore,
_frm_suggestion: Option<FrmSuggestion>,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<(PaymentExtendAuthorizationOperation<'b, F>, PaymentData<F>)>
where
F: 'b + Send,
{
Ok((Box::new(self), payment_data))
}
}
impl<F: Send + Clone + Sync>
ValidateRequest<F, api::PaymentsExtendAuthorizationRequest, PaymentData<F>>
for PaymentExtendAuthorization
{
#[instrument(skip_all)]
fn validate_request<'a, 'b>(
&'b self,
request: &api::PaymentsExtendAuthorizationRequest,
merchant_context: &'a domain::MerchantContext,
) -> RouterResult<(
PaymentExtendAuthorizationOperation<'b, F>,
operations::ValidateResult,
)> {
Ok((
Box::new(self),
operations::ValidateResult {
merchant_id: merchant_context.get_merchant_account().get_id().to_owned(),
payment_id: api::PaymentIdType::PaymentIntentId(request.payment_id.to_owned()),
storage_scheme: merchant_context.get_merchant_account().storage_scheme,
requeue: false,
},
))
}
}
|
crates/router/src/core/payments/operations/payments_extend_authorization.rs
|
router::src::core::payments::operations::payments_extend_authorization
| 2,349
| true
|
// File: crates/router/src/core/payments/operations/payment_update.rs
// Module: router::src::core::payments::operations::payment_update
use std::marker::PhantomData;
use api_models::{
enums::FrmSuggestion, mandates::RecurringDetails, payments::RequestSurchargeDetails,
};
use async_trait::async_trait;
use common_utils::{
ext_traits::{AsyncExt, Encode, ValueExt},
pii::Email,
types::keymanager::KeyManagerState,
};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::payments::payment_intent::{
CustomerData, PaymentIntentUpdateFields,
};
use router_derive::PaymentOperation;
use router_env::{instrument, tracing};
use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest};
use crate::{
core::{
errors::{self, CustomResult, RouterResult, StorageErrorExt},
mandate::helpers as m_helpers,
payment_methods::cards::create_encrypted_data,
payments::{self, helpers, operations, CustomerDetails, PaymentAddress, PaymentData},
utils as core_utils,
},
events::audit_events::{AuditEvent, AuditEventType},
routes::{app::ReqState, SessionState},
services,
types::{
self,
api::{self, ConnectorCallType, PaymentIdTypeExt},
domain,
storage::{self, enums as storage_enums, payment_attempt::PaymentAttemptExt},
transformers::ForeignTryFrom,
},
utils::OptionExt,
};
#[derive(Debug, Clone, Copy, PaymentOperation)]
#[operation(operations = "all", flow = "authorize")]
pub struct PaymentUpdate;
type PaymentUpdateOperation<'a, F> = BoxedOperation<'a, F, api::PaymentsRequest, PaymentData<F>>;
#[async_trait]
impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for PaymentUpdate {
#[instrument(skip_all)]
async fn get_trackers<'a>(
&'a self,
state: &'a SessionState,
payment_id: &api::PaymentIdType,
request: &api::PaymentsRequest,
merchant_context: &domain::MerchantContext,
auth_flow: services::AuthFlow,
_header_payload: &hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsRequest, PaymentData<F>>>
{
let (mut payment_intent, mut payment_attempt, currency): (_, _, storage_enums::Currency);
let payment_id = payment_id
.get_payment_intent_id()
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
let merchant_id = merchant_context.get_merchant_account().get_id();
let storage_scheme = merchant_context.get_merchant_account().storage_scheme;
let db = &*state.store;
let key_manager_state = &state.into();
helpers::allow_payment_update_enabled_for_client_auth(merchant_id, state, auth_flow)
.await?;
payment_intent = db
.find_payment_intent_by_payment_id_merchant_id(
key_manager_state,
&payment_id,
merchant_id,
merchant_context.get_merchant_key_store(),
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
// TODO (#7195): Add platform merchant account validation once publishable key auth is solved
if let Some(order_details) = &request.order_details {
helpers::validate_order_details_amount(
order_details.to_owned(),
payment_intent.amount,
false,
)?;
}
payment_intent.setup_future_usage = request
.setup_future_usage
.or(payment_intent.setup_future_usage);
helpers::validate_customer_access(&payment_intent, auth_flow, request)?;
helpers::validate_card_data(
request
.payment_method_data
.as_ref()
.and_then(|pmd| pmd.payment_method_data.clone()),
)?;
helpers::validate_payment_status_against_allowed_statuses(
payment_intent.status,
&[
storage_enums::IntentStatus::RequiresPaymentMethod,
storage_enums::IntentStatus::RequiresConfirmation,
],
"update",
)?;
helpers::authenticate_client_secret(request.client_secret.as_ref(), &payment_intent)?;
payment_intent.order_details = request
.get_order_details_as_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to convert order details to value")?
.or(payment_intent.order_details);
payment_attempt = db
.find_payment_attempt_by_payment_id_merchant_id_attempt_id(
&payment_intent.payment_id,
merchant_id,
payment_intent.active_attempt.get_id().as_str(),
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
let customer_acceptance = request.customer_acceptance.clone();
let recurring_details = request.recurring_details.clone();
let mandate_type = m_helpers::get_mandate_type(
request.mandate_data.clone(),
request.off_session,
payment_intent.setup_future_usage,
request.customer_acceptance.clone(),
request.payment_token.clone(),
payment_attempt.payment_method.or(request.payment_method),
)
.change_context(errors::ApiErrorResponse::MandateValidationFailed {
reason: "Expected one out of recurring_details and mandate_data but got both".into(),
})?;
let m_helpers::MandateGenericData {
token,
payment_method,
payment_method_type,
mandate_data,
recurring_mandate_payment_data,
mandate_connector,
payment_method_info,
} = Box::pin(helpers::get_token_pm_type_mandate_details(
state,
request,
mandate_type.to_owned(),
merchant_context,
None,
payment_intent.customer_id.as_ref(),
))
.await?;
helpers::validate_amount_to_capture_and_capture_method(Some(&payment_attempt), request)?;
helpers::validate_request_amount_and_amount_to_capture(
request.amount,
request.amount_to_capture,
request
.surcharge_details
.or(payment_attempt.get_surcharge_details()),
)
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "amount_to_capture".to_string(),
expected_format: "amount_to_capture lesser than or equal to amount".to_string(),
})?;
currency = request
.currency
.or(payment_attempt.currency)
.get_required_value("currency")?;
payment_attempt.payment_method = payment_method.or(payment_attempt.payment_method);
payment_attempt.payment_method_type =
payment_method_type.or(payment_attempt.payment_method_type);
let customer_details = helpers::get_customer_details_from_request(request);
let amount = request
.amount
.unwrap_or_else(|| payment_attempt.net_amount.get_order_amount().into());
if request.confirm.unwrap_or(false) {
helpers::validate_customer_id_mandatory_cases(
request.setup_future_usage.is_some(),
payment_intent
.customer_id
.as_ref()
.or(customer_details.customer_id.as_ref()),
)?;
}
let shipping_address = helpers::create_or_update_address_for_payment_by_request(
state,
request.shipping.as_ref(),
payment_intent.shipping_address_id.as_deref(),
merchant_id,
payment_intent
.customer_id
.as_ref()
.or(customer_details.customer_id.as_ref()),
merchant_context.get_merchant_key_store(),
&payment_intent.payment_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let billing_address = helpers::create_or_update_address_for_payment_by_request(
state,
request.billing.as_ref(),
payment_intent.billing_address_id.as_deref(),
merchant_id,
payment_intent
.customer_id
.as_ref()
.or(customer_details.customer_id.as_ref()),
merchant_context.get_merchant_key_store(),
&payment_intent.payment_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let payment_method_billing = helpers::create_or_update_address_for_payment_by_request(
state,
request
.payment_method_data
.as_ref()
.and_then(|pmd| pmd.billing.as_ref()),
payment_attempt.payment_method_billing_address_id.as_deref(),
merchant_id,
payment_intent
.customer_id
.as_ref()
.or(customer_details.customer_id.as_ref()),
merchant_context.get_merchant_key_store(),
&payment_intent.payment_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
payment_intent.shipping_address_id = shipping_address.clone().map(|x| x.address_id);
payment_intent.billing_address_id = billing_address.clone().map(|x| x.address_id);
payment_attempt.payment_method_billing_address_id = payment_method_billing
.as_ref()
.map(|payment_method_billing| payment_method_billing.address_id.clone());
payment_intent.allowed_payment_method_types = request
.get_allowed_payment_method_types_as_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error converting allowed_payment_types to Value")?
.or(payment_intent.allowed_payment_method_types);
payment_intent.connector_metadata = request
.get_connector_metadata_as_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error converting connector_metadata to Value")?
.or(payment_intent.connector_metadata);
payment_intent.feature_metadata = request
.get_feature_metadata_as_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error converting feature_metadata to Value")?
.or(payment_intent.feature_metadata);
payment_intent.metadata = request.metadata.clone().or(payment_intent.metadata);
payment_intent.frm_metadata = request.frm_metadata.clone().or(payment_intent.frm_metadata);
payment_intent.psd2_sca_exemption_type = request
.psd2_sca_exemption_type
.or(payment_intent.psd2_sca_exemption_type);
Self::populate_payment_intent_with_request(&mut payment_intent, request);
let token = token.or_else(|| payment_attempt.payment_token.clone());
if request.confirm.unwrap_or(false) {
helpers::validate_pm_or_token_given(
&request.payment_method,
&request
.payment_method_data
.as_ref()
.and_then(|pmd| pmd.payment_method_data.clone()),
&request.payment_method_type,
&mandate_type,
&token,
&request.ctp_service_details,
)?;
}
let token_data = if let Some(token) = token.clone() {
Some(helpers::retrieve_payment_token_data(state, token, payment_method).await?)
} else {
None
};
let mandate_id = request
.mandate_id
.as_ref()
.or_else(|| {
request.recurring_details
.as_ref()
.and_then(|recurring_details| match recurring_details {
RecurringDetails::MandateId(id) => Some(id),
_ => None,
})
})
.async_and_then(|mandate_id| async {
let mandate = db
.find_mandate_by_merchant_id_mandate_id(merchant_id, mandate_id, merchant_context.get_merchant_account().storage_scheme)
.await
.change_context(errors::ApiErrorResponse::MandateNotFound);
Some(mandate.and_then(|mandate_obj| {
match (
mandate_obj.network_transaction_id,
mandate_obj.connector_mandate_ids,
) {
(Some(network_tx_id), _) => Ok(api_models::payments::MandateIds {
mandate_id: Some(mandate_obj.mandate_id),
mandate_reference_id: Some(
api_models::payments::MandateReferenceId::NetworkMandateId(
network_tx_id,
),
),
}),
(_, Some(connector_mandate_id)) => connector_mandate_id
.parse_value("ConnectorMandateId")
.change_context(errors::ApiErrorResponse::MandateNotFound)
.map(|connector_id: api_models::payments::ConnectorMandateReferenceId| {
api_models::payments::MandateIds {
mandate_id: Some(mandate_obj.mandate_id),
mandate_reference_id: Some(api_models::payments::MandateReferenceId::ConnectorMandateId(
api_models::payments::ConnectorMandateReferenceId::new(
connector_id.get_connector_mandate_id(), // connector_mandate_id
connector_id.get_payment_method_id(), // payment_method_id
None, // update_history
connector_id.get_mandate_metadata(), // mandate_metadata
connector_id.get_connector_mandate_request_reference_id() // connector_mandate_request_reference_id
)
))
}
}),
(_, _) => Ok(api_models::payments::MandateIds {
mandate_id: Some(mandate_obj.mandate_id),
mandate_reference_id: None,
}),
}
}))
})
.await
.transpose()?;
let (next_operation, amount): (PaymentUpdateOperation<'a, F>, _) =
if request.confirm.unwrap_or(false) {
let amount = {
let amount = request
.amount
.map(Into::into)
.unwrap_or(payment_attempt.net_amount.get_order_amount());
payment_attempt.net_amount.set_order_amount(amount);
payment_intent.amount = amount;
let surcharge_amount = request
.surcharge_details
.as_ref()
.map(RequestSurchargeDetails::get_total_surcharge_amount)
.or(payment_attempt.get_total_surcharge_amount());
amount + surcharge_amount.unwrap_or_default()
};
(Box::new(operations::PaymentConfirm), amount.into())
} else {
(Box::new(self), amount)
};
payment_intent.status = if request
.payment_method_data
.as_ref()
.is_some_and(|payment_method_data| payment_method_data.payment_method_data.is_some())
{
if request.confirm.unwrap_or(false) {
payment_intent.status
} else {
storage_enums::IntentStatus::RequiresConfirmation
}
} else {
storage_enums::IntentStatus::RequiresPaymentMethod
};
payment_intent.request_external_three_ds_authentication = request
.request_external_three_ds_authentication
.or(payment_intent.request_external_three_ds_authentication);
payment_intent.merchant_order_reference_id = request
.merchant_order_reference_id
.clone()
.or(payment_intent.merchant_order_reference_id);
Self::populate_payment_attempt_with_request(&mut payment_attempt, request);
let creds_identifier = request
.merchant_connector_details
.as_ref()
.map(|mcd| mcd.creds_identifier.to_owned());
request
.merchant_connector_details
.to_owned()
.async_map(|mcd| async {
helpers::insert_merchant_connector_creds_to_config(
db,
merchant_context.get_merchant_account().get_id(),
mcd,
)
.await
})
.await
.transpose()?;
// The operation merges mandate data from both request and payment_attempt
let setup_mandate = mandate_data;
let mandate_details_present =
payment_attempt.mandate_details.is_some() || request.mandate_data.is_some();
helpers::validate_mandate_data_and_future_usage(
payment_intent.setup_future_usage,
mandate_details_present,
)?;
let profile_id = payment_intent
.profile_id
.as_ref()
.get_required_value("profile_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("'profile_id' not set in payment intent")?;
let business_profile = db
.find_business_profile_by_profile_id(
key_manager_state,
merchant_context.get_merchant_key_store(),
profile_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
let surcharge_details = request.surcharge_details.map(|request_surcharge_details| {
payments::types::SurchargeDetails::from((&request_surcharge_details, &payment_attempt))
});
payment_intent.force_3ds_challenge = request
.force_3ds_challenge
.or(payment_intent.force_3ds_challenge);
payment_intent.payment_channel = request
.payment_channel
.clone()
.or(payment_intent.payment_channel);
payment_intent.enable_partial_authorization = request
.enable_partial_authorization
.or(payment_intent.enable_partial_authorization);
helpers::validate_overcapture_request(
&request.enable_overcapture,
&payment_attempt.capture_method,
)?;
payment_intent.enable_overcapture = request.enable_overcapture;
let payment_data = PaymentData {
flow: PhantomData,
payment_intent,
payment_attempt,
currency,
amount,
email: request.email.clone(),
mandate_id,
mandate_connector,
token,
token_data,
setup_mandate,
customer_acceptance,
address: PaymentAddress::new(
shipping_address.as_ref().map(From::from),
billing_address.as_ref().map(From::from),
payment_method_billing.as_ref().map(From::from),
business_profile.use_billing_as_payment_method_billing,
),
confirm: request.confirm,
payment_method_data: request
.payment_method_data
.as_ref()
.and_then(|pmd| pmd.payment_method_data.clone().map(Into::into)),
payment_method_token: None,
payment_method_info,
force_sync: None,
all_keys_required: None,
refunds: vec![],
disputes: vec![],
attempts: None,
sessions_token: vec![],
card_cvc: request.card_cvc.clone(),
creds_identifier,
pm_token: None,
connector_customer_id: None,
recurring_mandate_payment_data,
ephemeral_key: None,
multiple_capture_data: None,
redirect_response: None,
surcharge_details,
frm_message: None,
payment_link_data: None,
incremental_authorization_details: None,
authorizations: vec![],
authentication: None,
recurring_details,
poll_config: None,
tax_data: None,
session_id: None,
service_details: None,
card_testing_guard_data: None,
vault_operation: None,
threeds_method_comp_ind: None,
whole_connector_response: None,
is_manual_retry_enabled: None,
is_l2_l3_enabled: business_profile.is_l2_l3_enabled,
};
let get_trackers_response = operations::GetTrackerResponse {
operation: next_operation,
customer_details: Some(customer_details),
payment_data,
business_profile,
mandate_type,
};
Ok(get_trackers_response)
}
}
#[async_trait]
impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for PaymentUpdate {
#[instrument(skip_all)]
async fn get_or_create_customer_details<'a>(
&'a self,
state: &SessionState,
payment_data: &mut PaymentData<F>,
request: Option<CustomerDetails>,
key_store: &domain::MerchantKeyStore,
storage_scheme: common_enums::enums::MerchantStorageScheme,
) -> CustomResult<(PaymentUpdateOperation<'a, F>, Option<domain::Customer>), errors::StorageError>
{
helpers::create_customer_if_not_exist(
state,
Box::new(self),
payment_data,
request,
&key_store.merchant_id,
key_store,
storage_scheme,
)
.await
}
async fn payments_dynamic_tax_calculation<'a>(
&'a self,
state: &SessionState,
payment_data: &mut PaymentData<F>,
_connector_call_type: &ConnectorCallType,
business_profile: &domain::Profile,
merchant_context: &domain::MerchantContext,
) -> CustomResult<(), errors::ApiErrorResponse> {
let is_tax_connector_enabled = business_profile.get_is_tax_connector_enabled();
let skip_external_tax_calculation = payment_data
.payment_intent
.skip_external_tax_calculation
.unwrap_or(false);
if is_tax_connector_enabled && !skip_external_tax_calculation {
let db = state.store.as_ref();
let key_manager_state: &KeyManagerState = &state.into();
let merchant_connector_id = business_profile
.tax_connector_id
.as_ref()
.get_required_value("business_profile.tax_connector_id")?;
#[cfg(feature = "v1")]
let mca = db
.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
key_manager_state,
&business_profile.merchant_id,
merchant_connector_id,
merchant_context.get_merchant_key_store(),
)
.await
.to_not_found_response(
errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: merchant_connector_id.get_string_repr().to_string(),
},
)?;
#[cfg(feature = "v2")]
let mca = db
.find_merchant_connector_account_by_id(
key_manager_state,
merchant_connector_id,
key_store,
)
.await
.to_not_found_response(
errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: merchant_connector_id.get_string_repr().to_string(),
},
)?;
let connector_data =
api::TaxCalculateConnectorData::get_connector_by_name(&mca.connector_name)?;
let router_data = core_utils::construct_payments_dynamic_tax_calculation_router_data(
state,
merchant_context,
payment_data,
&mca,
)
.await?;
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::CalculateTax,
types::PaymentsTaxCalculationData,
types::TaxCalculationResponseData,
> = connector_data.connector.get_connector_integration();
let response = services::execute_connector_processing_step(
state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Tax connector Response Failed")?;
let tax_response = response.response.map_err(|err| {
errors::ApiErrorResponse::ExternalConnectorError {
code: err.code,
message: err.message,
connector: connector_data.connector_name.clone().to_string(),
status_code: err.status_code,
reason: err.reason,
}
})?;
payment_data.payment_intent.tax_details = Some(diesel_models::TaxDetails {
default: Some(diesel_models::DefaultTax {
order_tax_amount: tax_response.order_tax_amount,
}),
payment_method_type: None,
});
Ok(())
} else {
Ok(())
}
}
#[instrument(skip_all)]
async fn make_pm_data<'a>(
&'a self,
state: &'a SessionState,
payment_data: &mut PaymentData<F>,
storage_scheme: storage_enums::MerchantStorageScheme,
merchant_key_store: &domain::MerchantKeyStore,
customer: &Option<domain::Customer>,
business_profile: &domain::Profile,
should_retry_with_pan: bool,
) -> RouterResult<(
PaymentUpdateOperation<'a, F>,
Option<domain::PaymentMethodData>,
Option<String>,
)> {
Box::pin(helpers::make_pm_data(
Box::new(self),
state,
payment_data,
merchant_key_store,
customer,
storage_scheme,
business_profile,
should_retry_with_pan,
))
.await
}
#[instrument(skip_all)]
async fn add_task_to_process_tracker<'a>(
&'a self,
_state: &'a SessionState,
_payment_attempt: &storage::PaymentAttempt,
_requeue: bool,
_schedule_time: Option<time::PrimitiveDateTime>,
) -> CustomResult<(), errors::ApiErrorResponse> {
Ok(())
}
async fn get_connector<'a>(
&'a self,
_merchant_context: &domain::MerchantContext,
state: &SessionState,
request: &api::PaymentsRequest,
_payment_intent: &storage::PaymentIntent,
) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> {
helpers::get_connector_default(state, request.routing.clone()).await
}
#[instrument(skip_all)]
async fn guard_payment_against_blocklist<'a>(
&'a self,
_state: &SessionState,
_merchant_context: &domain::MerchantContext,
_payment_data: &mut PaymentData<F>,
) -> CustomResult<bool, errors::ApiErrorResponse> {
Ok(false)
}
}
#[async_trait]
impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for PaymentUpdate {
#[cfg(feature = "v2")]
#[instrument(skip_all)]
async fn update_trackers<'b>(
&'b self,
_state: &'b SessionState,
req_state: ReqState,
mut _payment_data: PaymentData<F>,
_customer: Option<domain::Customer>,
_storage_scheme: storage_enums::MerchantStorageScheme,
_updated_customer: Option<storage::CustomerUpdate>,
_key_store: &domain::MerchantKeyStore,
_frm_suggestion: Option<FrmSuggestion>,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<(PaymentUpdateOperation<'b, F>, PaymentData<F>)>
where
F: 'b + Send,
{
todo!()
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn update_trackers<'b>(
&'b self,
state: &'b SessionState,
req_state: ReqState,
mut payment_data: PaymentData<F>,
customer: Option<domain::Customer>,
storage_scheme: storage_enums::MerchantStorageScheme,
_updated_customer: Option<storage::CustomerUpdate>,
key_store: &domain::MerchantKeyStore,
_frm_suggestion: Option<FrmSuggestion>,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<(PaymentUpdateOperation<'b, F>, PaymentData<F>)>
where
F: 'b + Send,
{
let is_payment_method_unavailable =
payment_data.payment_attempt.payment_method_id.is_none()
&& payment_data.payment_intent.status
== storage_enums::IntentStatus::RequiresPaymentMethod;
let payment_method = payment_data.payment_attempt.payment_method;
let get_attempt_status = || {
if is_payment_method_unavailable {
storage_enums::AttemptStatus::PaymentMethodAwaited
} else {
storage_enums::AttemptStatus::ConfirmationAwaited
}
};
let profile_id = payment_data
.payment_intent
.profile_id
.as_ref()
.get_required_value("profile_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("'profile_id' not set in payment intent")?;
let additional_pm_data = payment_data
.payment_method_data
.as_ref()
.async_map(|payment_method_data| async {
helpers::get_additional_payment_data(payment_method_data, &*state.store, profile_id)
.await
})
.await
.transpose()?
.flatten();
let encoded_pm_data = additional_pm_data
.as_ref()
.map(Encode::encode_to_value)
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to encode additional pm data")?;
let business_sub_label = payment_data.payment_attempt.business_sub_label.clone();
let payment_method_type = payment_data.payment_attempt.payment_method_type;
let payment_experience = payment_data.payment_attempt.payment_experience;
let amount_to_capture = payment_data.payment_attempt.amount_to_capture;
let capture_method = payment_data.payment_attempt.capture_method;
let payment_method_billing_address_id = payment_data
.payment_attempt
.payment_method_billing_address_id
.clone();
let surcharge_amount = payment_data
.surcharge_details
.as_ref()
.map(|surcharge_details| surcharge_details.surcharge_amount);
let tax_amount = payment_data
.surcharge_details
.as_ref()
.map(|surcharge_details| surcharge_details.tax_on_surcharge_amount);
let network_transaction_id = payment_data.payment_attempt.network_transaction_id.clone();
payment_data.payment_attempt = state
.store
.update_payment_attempt_with_attempt_id(
payment_data.payment_attempt,
storage::PaymentAttemptUpdate::Update {
currency: payment_data.currency,
status: get_attempt_status(),
authentication_type: None,
payment_method,
payment_token: payment_data.token.clone(),
payment_method_data: encoded_pm_data,
payment_experience,
payment_method_type,
business_sub_label,
amount_to_capture,
capture_method,
fingerprint_id: None,
payment_method_billing_address_id,
updated_by: storage_scheme.to_string(),
network_transaction_id,
net_amount:
hyperswitch_domain_models::payments::payment_attempt::NetAmount::new(
payment_data.amount.into(),
None,
None,
surcharge_amount,
tax_amount,
),
},
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
let customer_id = customer.clone().map(|c| c.customer_id);
let intent_status = {
let current_intent_status = payment_data.payment_intent.status;
if is_payment_method_unavailable {
storage_enums::IntentStatus::RequiresPaymentMethod
} else if !payment_data.confirm.unwrap_or(true)
|| current_intent_status == storage_enums::IntentStatus::RequiresCustomerAction
{
storage_enums::IntentStatus::RequiresConfirmation
} else {
payment_data.payment_intent.status
}
};
let (shipping_address, billing_address) = (
payment_data.payment_intent.shipping_address_id.clone(),
payment_data.payment_intent.billing_address_id.clone(),
);
let customer_details = payment_data.payment_intent.customer_details.clone();
let return_url = payment_data.payment_intent.return_url.clone();
let setup_future_usage = payment_data.payment_intent.setup_future_usage;
let business_label = payment_data.payment_intent.business_label.clone();
let business_country = payment_data.payment_intent.business_country;
let description = payment_data.payment_intent.description.clone();
let statement_descriptor_name = payment_data
.payment_intent
.statement_descriptor_name
.clone();
let statement_descriptor_suffix = payment_data
.payment_intent
.statement_descriptor_suffix
.clone();
let key_manager_state = state.into();
let billing_details = payment_data
.address
.get_payment_billing()
.async_map(|billing_details| {
create_encrypted_data(&key_manager_state, key_store, billing_details)
})
.await
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt billing details")?;
let shipping_details = payment_data
.address
.get_shipping()
.async_map(|shipping_details| {
create_encrypted_data(&key_manager_state, key_store, shipping_details)
})
.await
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt shipping details")?;
let order_details = payment_data.payment_intent.order_details.clone();
let metadata = payment_data.payment_intent.metadata.clone();
let frm_metadata = payment_data.payment_intent.frm_metadata.clone();
let session_expiry = payment_data.payment_intent.session_expiry;
let merchant_order_reference_id = payment_data
.payment_intent
.merchant_order_reference_id
.clone();
payment_data.payment_intent = state
.store
.update_payment_intent(
&state.into(),
payment_data.payment_intent.clone(),
storage::PaymentIntentUpdate::Update(Box::new(PaymentIntentUpdateFields {
amount: payment_data.amount.into(),
currency: payment_data.currency,
setup_future_usage,
status: intent_status,
customer_id: customer_id.clone(),
shipping_address_id: shipping_address,
billing_address_id: billing_address,
return_url,
business_country,
business_label,
description,
statement_descriptor_name,
statement_descriptor_suffix,
order_details,
metadata,
payment_confirm_source: None,
updated_by: storage_scheme.to_string(),
fingerprint_id: None,
session_expiry,
request_external_three_ds_authentication: payment_data
.payment_intent
.request_external_three_ds_authentication,
frm_metadata,
customer_details,
merchant_order_reference_id,
billing_details,
shipping_details,
is_payment_processor_token_flow: None,
tax_details: None,
force_3ds_challenge: payment_data.payment_intent.force_3ds_challenge,
is_iframe_redirection_enabled: payment_data
.payment_intent
.is_iframe_redirection_enabled,
is_confirm_operation: false, // this is not a confirm operation
payment_channel: payment_data.payment_intent.payment_channel,
feature_metadata: payment_data
.payment_intent
.feature_metadata
.clone()
.map(masking::Secret::new),
tax_status: payment_data.payment_intent.tax_status,
discount_amount: payment_data.payment_intent.discount_amount,
order_date: payment_data.payment_intent.order_date,
shipping_amount_tax: payment_data.payment_intent.shipping_amount_tax,
duty_amount: payment_data.payment_intent.duty_amount,
enable_partial_authorization: payment_data
.payment_intent
.enable_partial_authorization,
enable_overcapture: payment_data.payment_intent.enable_overcapture,
})),
key_store,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
let amount = payment_data.amount;
req_state
.event_context
.event(AuditEvent::new(AuditEventType::PaymentUpdate { amount }))
.with(payment_data.to_event())
.emit();
Ok((
payments::is_confirm(self, payment_data.confirm),
payment_data,
))
}
}
impl ForeignTryFrom<domain::Customer> for CustomerData {
type Error = errors::ApiErrorResponse;
fn foreign_try_from(value: domain::Customer) -> Result<Self, Self::Error> {
Ok(Self {
name: value.name.map(|name| name.into_inner()),
email: value.email.map(Email::from),
phone: value.phone.map(|ph| ph.into_inner()),
phone_country_code: value.phone_country_code,
tax_registration_id: value
.tax_registration_id
.map(|tax_registration_id| tax_registration_id.into_inner()),
})
}
}
impl<F: Send + Clone + Sync> ValidateRequest<F, api::PaymentsRequest, PaymentData<F>>
for PaymentUpdate
{
#[instrument(skip_all)]
fn validate_request<'a, 'b>(
&'b self,
request: &api::PaymentsRequest,
merchant_context: &'a domain::MerchantContext,
) -> RouterResult<(PaymentUpdateOperation<'b, F>, operations::ValidateResult)> {
helpers::validate_customer_information(request)?;
if let Some(amount) = request.amount {
helpers::validate_max_amount(amount)?;
}
if let Some(session_expiry) = &request.session_expiry {
helpers::validate_session_expiry(session_expiry.to_owned())?;
}
let payment_id = request
.payment_id
.clone()
.ok_or(report!(errors::ApiErrorResponse::PaymentNotFound))?;
let request_merchant_id = request.merchant_id.as_ref();
helpers::validate_merchant_id(
merchant_context.get_merchant_account().get_id(),
request_merchant_id,
)
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "merchant_id".to_string(),
expected_format: "merchant_id from merchant account".to_string(),
})?;
helpers::validate_request_amount_and_amount_to_capture(
request.amount,
request.amount_to_capture,
request.surcharge_details,
)
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "amount_to_capture".to_string(),
expected_format: "amount_to_capture lesser than or equal to amount".to_string(),
})?;
helpers::validate_payment_method_fields_present(request)?;
let _mandate_type = helpers::validate_mandate(request, false)?;
helpers::validate_recurring_details_and_token(
&request.recurring_details,
&request.payment_token,
&request.mandate_id,
)?;
let _request_straight_through: Option<api::routing::StraightThroughAlgorithm> = request
.routing
.clone()
.map(|val| val.parse_value("RoutingAlgorithm"))
.transpose()
.change_context(errors::ApiErrorResponse::InvalidRequestData {
message: "Invalid straight through routing rules format".to_string(),
})
.attach_printable("Invalid straight through routing rules format")?;
Ok((
Box::new(self),
operations::ValidateResult {
merchant_id: merchant_context.get_merchant_account().get_id().to_owned(),
payment_id,
storage_scheme: merchant_context.get_merchant_account().storage_scheme,
requeue: matches!(
request.retry_action,
Some(api_models::enums::RetryAction::Requeue)
),
},
))
}
}
impl PaymentUpdate {
fn populate_payment_attempt_with_request(
payment_attempt: &mut storage::PaymentAttempt,
request: &api::PaymentsRequest,
) {
request
.business_sub_label
.clone()
.map(|bsl| payment_attempt.business_sub_label.replace(bsl));
request
.payment_method_type
.map(|pmt| payment_attempt.payment_method_type.replace(pmt));
request
.payment_experience
.map(|experience| payment_attempt.payment_experience.replace(experience));
payment_attempt.amount_to_capture = request
.amount_to_capture
.or(payment_attempt.amount_to_capture);
request
.capture_method
.map(|i| payment_attempt.capture_method.replace(i));
}
fn populate_payment_intent_with_request(
payment_intent: &mut storage::PaymentIntent,
request: &api::PaymentsRequest,
) {
request
.return_url
.clone()
.map(|i| payment_intent.return_url.replace(i.to_string()));
payment_intent.business_country = request.business_country;
payment_intent
.business_label
.clone_from(&request.business_label);
request
.description
.clone()
.map(|i| payment_intent.description.replace(i));
request
.statement_descriptor_name
.clone()
.map(|i| payment_intent.statement_descriptor_name.replace(i));
request
.statement_descriptor_suffix
.clone()
.map(|i| payment_intent.statement_descriptor_suffix.replace(i));
request
.client_secret
.clone()
.map(|i| payment_intent.client_secret.replace(i));
}
}
|
crates/router/src/core/payments/operations/payment_update.rs
|
router::src::core::payments::operations::payment_update
| 8,352
| true
|
// File: crates/router/src/core/payments/routing/transformers.rs
// Module: router::src::core::payments::routing::transformers
use std::collections::HashMap;
use api_models::{self, routing as routing_types};
use common_types::payments as common_payments_types;
use diesel_models::enums as storage_enums;
use euclid::{enums as dsl_enums, frontend::ast as dsl_ast};
use kgraph_utils::types;
use crate::{
configs::settings,
types::transformers::{ForeignFrom, ForeignInto},
};
impl ForeignFrom<routing_types::RoutableConnectorChoice> for dsl_ast::ConnectorChoice {
fn foreign_from(from: routing_types::RoutableConnectorChoice) -> Self {
Self {
connector: from.connector,
}
}
}
impl ForeignFrom<storage_enums::CaptureMethod> for Option<dsl_enums::CaptureMethod> {
fn foreign_from(value: storage_enums::CaptureMethod) -> Self {
match value {
storage_enums::CaptureMethod::Automatic => Some(dsl_enums::CaptureMethod::Automatic),
storage_enums::CaptureMethod::SequentialAutomatic => {
Some(dsl_enums::CaptureMethod::SequentialAutomatic)
}
storage_enums::CaptureMethod::Manual => Some(dsl_enums::CaptureMethod::Manual),
_ => None,
}
}
}
impl ForeignFrom<common_payments_types::AcceptanceType> for dsl_enums::MandateAcceptanceType {
fn foreign_from(from: common_payments_types::AcceptanceType) -> Self {
match from {
common_payments_types::AcceptanceType::Online => Self::Online,
common_payments_types::AcceptanceType::Offline => Self::Offline,
}
}
}
impl ForeignFrom<api_models::payments::MandateType> for dsl_enums::MandateType {
fn foreign_from(from: api_models::payments::MandateType) -> Self {
match from {
api_models::payments::MandateType::MultiUse(_) => Self::MultiUse,
api_models::payments::MandateType::SingleUse(_) => Self::SingleUse,
}
}
}
impl ForeignFrom<storage_enums::MandateDataType> for dsl_enums::MandateType {
fn foreign_from(from: storage_enums::MandateDataType) -> Self {
match from {
storage_enums::MandateDataType::MultiUse(_) => Self::MultiUse,
storage_enums::MandateDataType::SingleUse(_) => Self::SingleUse,
}
}
}
impl ForeignFrom<settings::PaymentMethodFilterKey> for types::PaymentMethodFilterKey {
fn foreign_from(from: settings::PaymentMethodFilterKey) -> Self {
match from {
settings::PaymentMethodFilterKey::PaymentMethodType(pmt) => {
Self::PaymentMethodType(pmt)
}
settings::PaymentMethodFilterKey::CardNetwork(cn) => Self::CardNetwork(cn),
}
}
}
impl ForeignFrom<settings::CurrencyCountryFlowFilter> for types::CurrencyCountryFlowFilter {
fn foreign_from(from: settings::CurrencyCountryFlowFilter) -> Self {
Self {
currency: from.currency,
country: from.country,
not_available_flows: from.not_available_flows.map(ForeignInto::foreign_into),
}
}
}
impl ForeignFrom<settings::NotAvailableFlows> for types::NotAvailableFlows {
fn foreign_from(from: settings::NotAvailableFlows) -> Self {
Self {
capture_method: from.capture_method,
}
}
}
impl ForeignFrom<settings::PaymentMethodFilters> for types::PaymentMethodFilters {
fn foreign_from(from: settings::PaymentMethodFilters) -> Self {
let iter_map = from
.0
.into_iter()
.map(|(key, val)| (key.foreign_into(), val.foreign_into()))
.collect::<HashMap<_, _>>();
Self(iter_map)
}
}
|
crates/router/src/core/payments/routing/transformers.rs
|
router::src::core::payments::routing::transformers
| 855
| true
|
// File: crates/router/src/core/payments/routing/utils.rs
// Module: router::src::core::payments::routing::utils
use std::{
collections::{HashMap, HashSet},
str::FromStr,
};
use api_models::{
open_router as or_types,
routing::{
self as api_routing, ComparisonType, ConnectorSelection, ConnectorVolumeSplit,
DeRoutableConnectorChoice, MetadataValue, NumberComparison, RoutableConnectorChoice,
RoutingEvaluateRequest, RoutingEvaluateResponse, ValueType,
},
};
use async_trait::async_trait;
use common_enums::{RoutableConnectors, TransactionType};
use common_utils::{
ext_traits::{BytesExt, StringExt},
id_type,
};
use diesel_models::{enums, routing_algorithm};
use error_stack::ResultExt;
use euclid::{
backend::BackendInput,
frontend::{
ast::{self},
dir::{self, transformers::IntoDirValue},
},
};
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
use external_services::grpc_client::dynamic_routing as ir_client;
use hyperswitch_domain_models::business_profile;
use hyperswitch_interfaces::events::routing_api_logs as routing_events;
use router_env::tracing_actix_web::RequestId;
use serde::{Deserialize, Serialize};
use super::RoutingResult;
use crate::{
core::errors,
db::domain,
routes::{app::SessionStateInfo, SessionState},
services::{self, logger},
types::transformers::ForeignInto,
};
// New Trait for handling Euclid API calls
#[async_trait]
pub trait DecisionEngineApiHandler {
async fn send_decision_engine_request<Req, Res>(
state: &SessionState,
http_method: services::Method,
path: &str,
request_body: Option<Req>, // Option to handle GET/DELETE requests without body
timeout: Option<u64>,
events_wrapper: Option<RoutingEventsWrapper<Req>>,
) -> RoutingResult<RoutingEventsResponse<Res>>
where
Req: Serialize + Send + Sync + 'static + Clone,
Res: Serialize + serde::de::DeserializeOwned + Send + 'static + std::fmt::Debug + Clone;
}
// Struct to implement the DecisionEngineApiHandler trait
pub struct EuclidApiClient;
pub struct ConfigApiClient;
pub struct SRApiClient;
pub async fn build_and_send_decision_engine_http_request<Req, Res, ErrRes>(
state: &SessionState,
http_method: services::Method,
path: &str,
request_body: Option<Req>,
_timeout: Option<u64>,
context_message: &str,
events_wrapper: Option<RoutingEventsWrapper<Req>>,
) -> RoutingResult<RoutingEventsResponse<Res>>
where
Req: Serialize + Send + Sync + 'static + Clone,
Res: Serialize + serde::de::DeserializeOwned + std::fmt::Debug + Clone + 'static,
ErrRes: serde::de::DeserializeOwned + std::fmt::Debug + Clone + DecisionEngineErrorsInterface,
{
let decision_engine_base_url = &state.conf.open_router.url;
let url = format!("{decision_engine_base_url}/{path}");
logger::debug!(decision_engine_api_call_url = %url, decision_engine_request_path = %path, http_method = ?http_method, "decision_engine: Initiating decision_engine API call ({})", context_message);
let mut request_builder = services::RequestBuilder::new()
.method(http_method)
.url(&url);
if let Some(body_content) = request_body {
let body = common_utils::request::RequestContent::Json(Box::new(body_content));
request_builder = request_builder.set_body(body);
}
let http_request = request_builder.build();
logger::info!(?http_request, decision_engine_request_path = %path, "decision_engine: Constructed Decision Engine API request details ({})", context_message);
let should_parse_response = events_wrapper
.as_ref()
.map(|wrapper| wrapper.parse_response)
.unwrap_or(true);
let closure = || async {
let response =
services::call_connector_api(state, http_request, "Decision Engine API call")
.await
.change_context(errors::RoutingError::OpenRouterCallFailed)?;
match response {
Ok(resp) => {
logger::debug!(
"decision_engine: Received response from Decision Engine API ({:?})",
String::from_utf8_lossy(&resp.response) // For logging
);
let resp = should_parse_response
.then(|| {
if std::any::TypeId::of::<Res>() == std::any::TypeId::of::<String>()
&& resp.response.is_empty()
{
return serde_json::from_str::<Res>("\"\"").change_context(
errors::RoutingError::OpenRouterError(
"Failed to parse empty response as String".into(),
),
);
}
let response_type: Res = resp
.response
.parse_struct(std::any::type_name::<Res>())
.change_context(errors::RoutingError::OpenRouterError(
"Failed to parse the response from open_router".into(),
))?;
Ok::<_, error_stack::Report<errors::RoutingError>>(response_type)
})
.transpose()?;
logger::debug!("decision_engine_success_response: {:?}", resp);
Ok(resp)
}
Err(err) => {
logger::debug!(
"decision_engine: Received response from Decision Engine API ({:?})",
String::from_utf8_lossy(&err.response) // For logging
);
let err_resp: ErrRes = err
.response
.parse_struct(std::any::type_name::<ErrRes>())
.change_context(errors::RoutingError::OpenRouterError(
"Failed to parse the response from open_router".into(),
))?;
logger::error!(
decision_engine_error_code = %err_resp.get_error_code(),
decision_engine_error_message = %err_resp.get_error_message(),
decision_engine_raw_response = ?err_resp.get_error_data(),
);
Err(error_stack::report!(
errors::RoutingError::RoutingEventsError {
message: err_resp.get_error_message(),
status_code: err.status_code,
}
))
}
}
};
let events_response = if let Some(wrapper) = events_wrapper {
wrapper
.construct_event_builder(
url,
routing_events::RoutingEngine::DecisionEngine,
routing_events::ApiMethod::Rest(http_method),
)?
.trigger_event(state, closure)
.await?
} else {
let resp = closure()
.await
.change_context(errors::RoutingError::OpenRouterCallFailed)?;
RoutingEventsResponse::new(None, resp)
};
Ok(events_response)
}
#[async_trait]
impl DecisionEngineApiHandler for EuclidApiClient {
async fn send_decision_engine_request<Req, Res>(
state: &SessionState,
http_method: services::Method,
path: &str,
request_body: Option<Req>, // Option to handle GET/DELETE requests without body
timeout: Option<u64>,
events_wrapper: Option<RoutingEventsWrapper<Req>>,
) -> RoutingResult<RoutingEventsResponse<Res>>
where
Req: Serialize + Send + Sync + 'static + Clone,
Res: Serialize + serde::de::DeserializeOwned + Send + 'static + std::fmt::Debug + Clone,
{
let event_response = build_and_send_decision_engine_http_request::<_, _, DeErrorResponse>(
state,
http_method,
path,
request_body,
timeout,
"parsing response",
events_wrapper,
)
.await?;
let parsed_response =
event_response
.response
.as_ref()
.ok_or(errors::RoutingError::OpenRouterError(
"Response from decision engine API is empty".to_string(),
))?;
logger::debug!(parsed_response = ?parsed_response, response_type = %std::any::type_name::<Res>(), euclid_request_path = %path, "decision_engine_euclid: Successfully parsed response from Euclid API");
Ok(event_response)
}
}
#[async_trait]
impl DecisionEngineApiHandler for ConfigApiClient {
async fn send_decision_engine_request<Req, Res>(
state: &SessionState,
http_method: services::Method,
path: &str,
request_body: Option<Req>,
timeout: Option<u64>,
events_wrapper: Option<RoutingEventsWrapper<Req>>,
) -> RoutingResult<RoutingEventsResponse<Res>>
where
Req: Serialize + Send + Sync + 'static + Clone,
Res: Serialize + serde::de::DeserializeOwned + Send + 'static + std::fmt::Debug + Clone,
{
let events_response = build_and_send_decision_engine_http_request::<_, _, DeErrorResponse>(
state,
http_method,
path,
request_body,
timeout,
"parsing response",
events_wrapper,
)
.await?;
let parsed_response =
events_response
.response
.as_ref()
.ok_or(errors::RoutingError::OpenRouterError(
"Response from decision engine API is empty".to_string(),
))?;
logger::debug!(parsed_response = ?parsed_response, response_type = %std::any::type_name::<Res>(), decision_engine_request_path = %path, "decision_engine_config: Successfully parsed response from Decision Engine config API");
Ok(events_response)
}
}
#[async_trait]
impl DecisionEngineApiHandler for SRApiClient {
async fn send_decision_engine_request<Req, Res>(
state: &SessionState,
http_method: services::Method,
path: &str,
request_body: Option<Req>,
timeout: Option<u64>,
events_wrapper: Option<RoutingEventsWrapper<Req>>,
) -> RoutingResult<RoutingEventsResponse<Res>>
where
Req: Serialize + Send + Sync + 'static + Clone,
Res: Serialize + serde::de::DeserializeOwned + Send + 'static + std::fmt::Debug + Clone,
{
let events_response =
build_and_send_decision_engine_http_request::<_, _, or_types::ErrorResponse>(
state,
http_method,
path,
request_body,
timeout,
"parsing response",
events_wrapper,
)
.await?;
let parsed_response =
events_response
.response
.as_ref()
.ok_or(errors::RoutingError::OpenRouterError(
"Response from decision engine API is empty".to_string(),
))?;
logger::debug!(parsed_response = ?parsed_response, response_type = %std::any::type_name::<Res>(), decision_engine_request_path = %path, "decision_engine_config: Successfully parsed response from Decision Engine config API");
Ok(events_response)
}
}
const EUCLID_API_TIMEOUT: u64 = 5;
pub async fn perform_decision_euclid_routing(
state: &SessionState,
input: BackendInput,
created_by: String,
events_wrapper: RoutingEventsWrapper<RoutingEvaluateRequest>,
fallback_output: Vec<RoutableConnectorChoice>,
) -> RoutingResult<RoutingEvaluateResponse> {
logger::debug!("decision_engine_euclid: evaluate api call for euclid routing evaluation");
let mut events_wrapper = events_wrapper;
let fallback_output = fallback_output
.into_iter()
.map(|c| DeRoutableConnectorChoice {
gateway_name: c.connector,
gateway_id: c.merchant_connector_id,
})
.collect::<Vec<_>>();
let routing_request =
convert_backend_input_to_routing_eval(created_by, input, fallback_output)?;
events_wrapper.set_request_body(routing_request.clone());
let event_response = EuclidApiClient::send_decision_engine_request(
state,
services::Method::Post,
"routing/evaluate",
Some(routing_request),
Some(EUCLID_API_TIMEOUT),
Some(events_wrapper),
)
.await?;
let euclid_response: RoutingEvaluateResponse =
event_response
.response
.ok_or(errors::RoutingError::OpenRouterError(
"Response from decision engine API is empty".to_string(),
))?;
let mut routing_event =
event_response
.event
.ok_or(errors::RoutingError::RoutingEventsError {
message: "Routing event not found in EventsResponse".to_string(),
status_code: 500,
})?;
routing_event.set_routing_approach(RoutingApproach::StaticRouting.to_string());
routing_event.set_routable_connectors(euclid_response.evaluated_output.clone());
state.event_handler.log_event(&routing_event);
logger::debug!(decision_engine_euclid_response=?euclid_response,"decision_engine_euclid");
logger::debug!(decision_engine_euclid_selected_connector=?euclid_response.evaluated_output,"decision_engine_euclid");
Ok(euclid_response)
}
/// This function transforms the decision_engine response in a way that's usable for further flows:
/// It places evaluated_output connectors first, followed by remaining output connectors (no duplicates).
pub fn transform_de_output_for_router(
de_output: Vec<ConnectorInfo>,
de_evaluated_output: Vec<RoutableConnectorChoice>,
) -> RoutingResult<Vec<RoutableConnectorChoice>> {
let mut seen = HashSet::new();
// evaluated connectors on top, to ensure the fallback is based on other connectors.
let mut ordered = Vec::with_capacity(de_output.len() + de_evaluated_output.len());
for eval_conn in de_evaluated_output {
if seen.insert(eval_conn.connector) {
ordered.push(eval_conn);
}
}
// Add remaining connectors from de_output (only if not already seen), for fallback
for conn in de_output {
let key = RoutableConnectors::from_str(&conn.gateway_name).map_err(|_| {
errors::RoutingError::GenericConversionError {
from: "String".to_string(),
to: "RoutableConnectors".to_string(),
}
})?;
if seen.insert(key) {
let de_choice = DeRoutableConnectorChoice::try_from(conn)?;
ordered.push(RoutableConnectorChoice::from(de_choice));
}
}
Ok(ordered)
}
pub async fn decision_engine_routing(
state: &SessionState,
backend_input: BackendInput,
business_profile: &domain::Profile,
payment_id: String,
merchant_fallback_config: Vec<RoutableConnectorChoice>,
) -> RoutingResult<Vec<RoutableConnectorChoice>> {
let routing_events_wrapper = RoutingEventsWrapper::new(
state.tenant.tenant_id.clone(),
state.request_id,
payment_id,
business_profile.get_id().to_owned(),
business_profile.merchant_id.to_owned(),
"DecisionEngine: Euclid Static Routing".to_string(),
None,
true,
false,
);
let de_euclid_evaluate_response = perform_decision_euclid_routing(
state,
backend_input.clone(),
business_profile.get_id().get_string_repr().to_string(),
routing_events_wrapper,
merchant_fallback_config,
)
.await;
let Ok(de_euclid_response) = de_euclid_evaluate_response else {
logger::error!("decision_engine_euclid_evaluation_error: error in evaluation of rule");
return Ok(Vec::default());
};
let de_output_connector = extract_de_output_connectors(de_euclid_response.output)
.map_err(|e| {
logger::error!(error=?e, "decision_engine_euclid_evaluation_error: Failed to extract connector from Output");
e
})?;
transform_de_output_for_router(
de_output_connector.clone(),
de_euclid_response.evaluated_output.clone(),
)
.map_err(|e| {
logger::error!(error=?e, "decision_engine_euclid_evaluation_error: failed to transform connector from de-output");
e
})
}
/// Custom deserializer for output from decision_engine, this is required as untagged enum is
/// stored but the enum requires tagged deserialization, hence deserializing it into specific
/// variants
pub fn extract_de_output_connectors(
output_value: serde_json::Value,
) -> RoutingResult<Vec<ConnectorInfo>> {
const SINGLE: &str = "straight_through";
const PRIORITY: &str = "priority";
const VOLUME_SPLIT: &str = "volume_split";
const VOLUME_SPLIT_PRIORITY: &str = "volume_split_priority";
let obj = output_value.as_object().ok_or_else(|| {
logger::error!("decision_engine_euclid_error: output is not a JSON object");
errors::RoutingError::OpenRouterError("Expected output to be a JSON object".into())
})?;
let type_str = obj.get("type").and_then(|v| v.as_str()).ok_or_else(|| {
logger::error!("decision_engine_euclid_error: missing or invalid 'type' in output");
errors::RoutingError::OpenRouterError("Missing or invalid 'type' field in output".into())
})?;
match type_str {
SINGLE => {
let connector_value = obj.get("connector").ok_or_else(|| {
logger::error!(
"decision_engine_euclid_error: missing 'connector' field for type=single"
);
errors::RoutingError::OpenRouterError(
"Missing 'connector' field for single output".into(),
)
})?;
let connector: ConnectorInfo = serde_json::from_value(connector_value.clone())
.map_err(|e| {
logger::error!(
?e,
"decision_engine_euclid_error: Failed to parse single connector"
);
errors::RoutingError::OpenRouterError(
"Failed to deserialize single connector".into(),
)
})?;
Ok(vec![connector])
}
PRIORITY => {
let connectors_value = obj.get("connectors").ok_or_else(|| {
logger::error!(
"decision_engine_euclid_error: missing 'connectors' field for type=priority"
);
errors::RoutingError::OpenRouterError(
"Missing 'connectors' field for priority output".into(),
)
})?;
let connectors: Vec<ConnectorInfo> = serde_json::from_value(connectors_value.clone())
.map_err(|e| {
logger::error!(
?e,
"decision_engine_euclid_error: Failed to parse connectors for priority"
);
errors::RoutingError::OpenRouterError(
"Failed to deserialize priority connectors".into(),
)
})?;
Ok(connectors)
}
VOLUME_SPLIT => {
let splits_value = obj.get("splits").ok_or_else(|| {
logger::error!(
"decision_engine_euclid_error: missing 'splits' field for type=volume_split"
);
errors::RoutingError::OpenRouterError(
"Missing 'splits' field for volume_split output".into(),
)
})?;
// Transform each {connector, split} into {output, split}
let fixed_splits: Vec<_> = splits_value
.as_array()
.ok_or_else(|| {
logger::error!("decision_engine_euclid_error: 'splits' is not an array");
errors::RoutingError::OpenRouterError("'splits' field must be an array".into())
})?
.iter()
.map(|entry| {
let mut entry_map = entry.as_object().cloned().ok_or_else(|| {
logger::error!(
"decision_engine_euclid_error: invalid split entry in volume_split"
);
errors::RoutingError::OpenRouterError(
"Invalid entry in splits array".into(),
)
})?;
if let Some(connector) = entry_map.remove("connector") {
entry_map.insert("output".to_string(), connector);
}
Ok::<_, error_stack::Report<errors::RoutingError>>(serde_json::Value::Object(
entry_map,
))
})
.collect::<Result<Vec<_>, _>>()?;
let splits: Vec<VolumeSplit<ConnectorInfo>> =
serde_json::from_value(serde_json::Value::Array(fixed_splits)).map_err(|e| {
logger::error!(
?e,
"decision_engine_euclid_error: Failed to parse volume_split"
);
errors::RoutingError::OpenRouterError(
"Failed to deserialize volume_split connectors".into(),
)
})?;
Ok(splits.into_iter().map(|s| s.output).collect())
}
VOLUME_SPLIT_PRIORITY => {
let splits_value = obj.get("splits").ok_or_else(|| {
logger::error!("decision_engine_euclid_error: missing 'splits' field for type=volume_split_priority");
errors::RoutingError::OpenRouterError("Missing 'splits' field for volume_split_priority output".into())
})?;
// Transform each {connector: [...], split} into {output: [...], split}
let fixed_splits: Vec<_> = splits_value
.as_array()
.ok_or_else(|| {
logger::error!("decision_engine_euclid_error: 'splits' is not an array");
errors::RoutingError::OpenRouterError("'splits' field must be an array".into())
})?
.iter()
.map(|entry| {
let mut entry_map = entry.as_object().cloned().ok_or_else(|| {
logger::error!("decision_engine_euclid_error: invalid split entry in volume_split_priority");
errors::RoutingError::OpenRouterError("Invalid entry in splits array".into())
})?;
if let Some(connector) = entry_map.remove("connector") {
entry_map.insert("output".to_string(), connector);
}
Ok::<_, error_stack::Report<errors::RoutingError>>(serde_json::Value::Object(entry_map))
})
.collect::<Result<Vec<_>, _>>()?;
let splits: Vec<VolumeSplit<Vec<ConnectorInfo>>> =
serde_json::from_value(serde_json::Value::Array(fixed_splits)).map_err(|e| {
logger::error!(
?e,
"decision_engine_euclid_error: Failed to parse volume_split_priority"
);
errors::RoutingError::OpenRouterError(
"Failed to deserialize volume_split_priority connectors".into(),
)
})?;
Ok(splits.into_iter().flat_map(|s| s.output).collect())
}
other => {
logger::error!(type_str=%other, "decision_engine_euclid_error: unknown output type");
Err(
errors::RoutingError::OpenRouterError(format!("Unknown output type: {other}"))
.into(),
)
}
}
}
pub async fn create_de_euclid_routing_algo(
state: &SessionState,
routing_request: &RoutingRule,
) -> RoutingResult<String> {
logger::debug!("decision_engine_euclid: create api call for euclid routing rule creation");
logger::debug!(decision_engine_euclid_request=?routing_request,"decision_engine_euclid");
let events_response = EuclidApiClient::send_decision_engine_request(
state,
services::Method::Post,
"routing/create",
Some(routing_request.clone()),
Some(EUCLID_API_TIMEOUT),
None,
)
.await?;
let euclid_response: RoutingDictionaryRecord =
events_response
.response
.ok_or(errors::RoutingError::OpenRouterError(
"Response from decision engine API is empty".to_string(),
))?;
logger::debug!(decision_engine_euclid_parsed_response=?euclid_response,"decision_engine_euclid");
Ok(euclid_response.rule_id)
}
pub async fn link_de_euclid_routing_algorithm(
state: &SessionState,
routing_request: ActivateRoutingConfigRequest,
) -> RoutingResult<()> {
logger::debug!("decision_engine_euclid: link api call for euclid routing algorithm");
EuclidApiClient::send_decision_engine_request::<_, String>(
state,
services::Method::Post,
"routing/activate",
Some(routing_request.clone()),
Some(EUCLID_API_TIMEOUT),
None,
)
.await?;
logger::debug!(decision_engine_euclid_activated=?routing_request, "decision_engine_euclid: link_de_euclid_routing_algorithm completed");
Ok(())
}
pub async fn list_de_euclid_routing_algorithms(
state: &SessionState,
routing_list_request: ListRountingAlgorithmsRequest,
) -> RoutingResult<Vec<api_routing::RoutingDictionaryRecord>> {
logger::debug!("decision_engine_euclid: list api call for euclid routing algorithms");
let created_by = routing_list_request.created_by;
let events_response = EuclidApiClient::send_decision_engine_request(
state,
services::Method::Post,
format!("routing/list/{created_by}").as_str(),
None::<()>,
Some(EUCLID_API_TIMEOUT),
None,
)
.await?;
let euclid_response: Vec<RoutingAlgorithmRecord> =
events_response
.response
.ok_or(errors::RoutingError::OpenRouterError(
"Response from decision engine API is empty".to_string(),
))?;
Ok(euclid_response
.into_iter()
.map(routing_algorithm::RoutingProfileMetadata::from)
.map(ForeignInto::foreign_into)
.collect::<Vec<_>>())
}
pub async fn list_de_euclid_active_routing_algorithm(
state: &SessionState,
created_by: String,
) -> RoutingResult<Vec<api_routing::RoutingDictionaryRecord>> {
logger::debug!("decision_engine_euclid: list api call for euclid active routing algorithm");
let response: Vec<RoutingAlgorithmRecord> = EuclidApiClient::send_decision_engine_request(
state,
services::Method::Post,
format!("routing/list/active/{created_by}").as_str(),
None::<()>,
Some(EUCLID_API_TIMEOUT),
None,
)
.await?
.response
.ok_or(errors::RoutingError::OpenRouterError(
"Response from decision engine API is empty".to_string(),
))?;
Ok(response
.into_iter()
.map(|record| routing_algorithm::RoutingProfileMetadata::from(record).foreign_into())
.collect())
}
pub fn compare_and_log_result<T: RoutingEq<T> + Serialize>(
de_result: Vec<T>,
result: Vec<T>,
flow: String,
) {
let is_equal = de_result
.iter()
.zip(result.iter())
.all(|(a, b)| T::is_equal(a, b));
let is_equal_in_length = de_result.len() == result.len();
router_env::logger::debug!(routing_flow=?flow, is_equal=?is_equal, is_equal_length=?is_equal_in_length, de_response=?to_json_string(&de_result), hs_response=?to_json_string(&result), "decision_engine_euclid");
}
pub trait RoutingEq<T> {
fn is_equal(a: &T, b: &T) -> bool;
}
impl RoutingEq<Self> for api_routing::RoutingDictionaryRecord {
fn is_equal(a: &Self, b: &Self) -> bool {
a.id == b.id
&& a.name == b.name
&& a.profile_id == b.profile_id
&& a.description == b.description
&& a.kind == b.kind
&& a.algorithm_for == b.algorithm_for
}
}
impl RoutingEq<Self> for String {
fn is_equal(a: &Self, b: &Self) -> bool {
a.to_lowercase() == b.to_lowercase()
}
}
impl RoutingEq<Self> for RoutableConnectorChoice {
fn is_equal(a: &Self, b: &Self) -> bool {
a.connector.eq(&b.connector)
&& a.choice_kind.eq(&b.choice_kind)
&& a.merchant_connector_id.eq(&b.merchant_connector_id)
}
}
pub fn to_json_string<T: Serialize>(value: &T) -> String {
serde_json::to_string(value)
.map_err(|_| errors::RoutingError::GenericConversionError {
from: "T".to_string(),
to: "JsonValue".to_string(),
})
.unwrap_or_default()
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct ActivateRoutingConfigRequest {
pub created_by: String,
pub routing_algorithm_id: String,
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct ListRountingAlgorithmsRequest {
pub created_by: String,
}
// Maps Hyperswitch `BackendInput` to a `RoutingEvaluateRequest` compatible with Decision Engine
pub fn convert_backend_input_to_routing_eval(
created_by: String,
input: BackendInput,
fallback_output: Vec<DeRoutableConnectorChoice>,
) -> RoutingResult<RoutingEvaluateRequest> {
let mut params: HashMap<String, Option<ValueType>> = HashMap::new();
// Payment
params.insert(
"amount".to_string(),
Some(ValueType::Number(
input
.payment
.amount
.get_amount_as_i64()
.try_into()
.unwrap_or_default(),
)),
);
params.insert(
"currency".to_string(),
Some(ValueType::EnumVariant(input.payment.currency.to_string())),
);
if let Some(auth_type) = input.payment.authentication_type {
params.insert(
"authentication_type".to_string(),
Some(ValueType::EnumVariant(auth_type.to_string())),
);
}
if let Some(bin) = input.payment.card_bin {
params.insert("card_bin".to_string(), Some(ValueType::StrValue(bin)));
}
if let Some(capture_method) = input.payment.capture_method {
params.insert(
"capture_method".to_string(),
Some(ValueType::EnumVariant(capture_method.to_string())),
);
}
if let Some(country) = input.payment.business_country {
params.insert(
"business_country".to_string(),
Some(ValueType::EnumVariant(country.to_string())),
);
}
if let Some(country) = input.payment.billing_country {
params.insert(
"billing_country".to_string(),
Some(ValueType::EnumVariant(country.to_string())),
);
}
if let Some(label) = input.payment.business_label {
params.insert(
"business_label".to_string(),
Some(ValueType::StrValue(label)),
);
}
if let Some(sfu) = input.payment.setup_future_usage {
params.insert(
"setup_future_usage".to_string(),
Some(ValueType::EnumVariant(sfu.to_string())),
);
}
// PaymentMethod
if let Some(pm) = input.payment_method.payment_method {
params.insert(
"payment_method".to_string(),
Some(ValueType::EnumVariant(pm.to_string())),
);
if let Some(pmt) = input.payment_method.payment_method_type {
match (pmt, pm).into_dir_value() {
Ok(dv) => insert_dirvalue_param(&mut params, dv),
Err(e) => logger::debug!(
?e,
?pmt,
?pm,
"decision_engine_euclid: into_dir_value failed; skipping subset param"
),
}
}
}
if let Some(pmt) = input.payment_method.payment_method_type {
params.insert(
"payment_method_type".to_string(),
Some(ValueType::EnumVariant(pmt.to_string())),
);
}
if let Some(network) = input.payment_method.card_network {
params.insert(
"card_network".to_string(),
Some(ValueType::EnumVariant(network.to_string())),
);
}
// Mandate
if let Some(pt) = input.mandate.payment_type {
params.insert(
"payment_type".to_string(),
Some(ValueType::EnumVariant(pt.to_string())),
);
}
if let Some(mt) = input.mandate.mandate_type {
params.insert(
"mandate_type".to_string(),
Some(ValueType::EnumVariant(mt.to_string())),
);
}
if let Some(mat) = input.mandate.mandate_acceptance_type {
params.insert(
"mandate_acceptance_type".to_string(),
Some(ValueType::EnumVariant(mat.to_string())),
);
}
// Metadata
if let Some(meta) = input.metadata {
for (k, v) in meta.into_iter() {
params.insert(
k.clone(),
Some(ValueType::MetadataVariant(MetadataValue {
key: k,
value: v,
})),
);
}
}
Ok(RoutingEvaluateRequest {
created_by,
parameters: params,
fallback_output,
})
}
// All the independent variants of payment method types, configured via dashboard
fn insert_dirvalue_param(params: &mut HashMap<String, Option<ValueType>>, dv: dir::DirValue) {
match dv {
dir::DirValue::RewardType(v) => {
params.insert(
"reward".to_string(),
Some(ValueType::EnumVariant(v.to_string())),
);
}
dir::DirValue::CardType(v) => {
params.insert(
"card".to_string(),
Some(ValueType::EnumVariant(v.to_string())),
);
}
dir::DirValue::PayLaterType(v) => {
params.insert(
"pay_later".to_string(),
Some(ValueType::EnumVariant(v.to_string())),
);
}
dir::DirValue::WalletType(v) => {
params.insert(
"wallet".to_string(),
Some(ValueType::EnumVariant(v.to_string())),
);
}
dir::DirValue::VoucherType(v) => {
params.insert(
"voucher".to_string(),
Some(ValueType::EnumVariant(v.to_string())),
);
}
dir::DirValue::BankRedirectType(v) => {
params.insert(
"bank_redirect".to_string(),
Some(ValueType::EnumVariant(v.to_string())),
);
}
dir::DirValue::BankDebitType(v) => {
params.insert(
"bank_debit".to_string(),
Some(ValueType::EnumVariant(v.to_string())),
);
}
dir::DirValue::BankTransferType(v) => {
params.insert(
"bank_transfer".to_string(),
Some(ValueType::EnumVariant(v.to_string())),
);
}
dir::DirValue::RealTimePaymentType(v) => {
params.insert(
"real_time_payment".to_string(),
Some(ValueType::EnumVariant(v.to_string())),
);
}
dir::DirValue::UpiType(v) => {
params.insert(
"upi".to_string(),
Some(ValueType::EnumVariant(v.to_string())),
);
}
dir::DirValue::GiftCardType(v) => {
params.insert(
"gift_card".to_string(),
Some(ValueType::EnumVariant(v.to_string())),
);
}
dir::DirValue::CardRedirectType(v) => {
params.insert(
"card_redirect".to_string(),
Some(ValueType::EnumVariant(v.to_string())),
);
}
dir::DirValue::OpenBankingType(v) => {
params.insert(
"open_banking".to_string(),
Some(ValueType::EnumVariant(v.to_string())),
);
}
dir::DirValue::MobilePaymentType(v) => {
params.insert(
"mobile_payment".to_string(),
Some(ValueType::EnumVariant(v.to_string())),
);
}
dir::DirValue::CryptoType(v) => {
params.insert(
"crypto".to_string(),
Some(ValueType::EnumVariant(v.to_string())),
);
}
other => {
// all other values can be ignored for now as they don't converge with
// payment method type
logger::warn!(
?other,
"decision_engine_euclid: unmapped dir::DirValue; add a mapping here"
);
}
}
}
#[derive(Debug, Clone, serde::Deserialize)]
struct DeErrorResponse {
code: String,
message: String,
data: Option<serde_json::Value>,
}
impl DecisionEngineErrorsInterface for DeErrorResponse {
fn get_error_message(&self) -> String {
self.message.clone()
}
fn get_error_code(&self) -> String {
self.code.clone()
}
fn get_error_data(&self) -> Option<String> {
self.data.as_ref().map(|data| data.to_string())
}
}
impl DecisionEngineErrorsInterface for or_types::ErrorResponse {
fn get_error_message(&self) -> String {
self.error_message.clone()
}
fn get_error_code(&self) -> String {
self.error_code.clone()
}
fn get_error_data(&self) -> Option<String> {
Some(format!(
"decision_engine Error: {}",
self.error_message.clone()
))
}
}
pub type Metadata = HashMap<String, serde_json::Value>;
/// Represents a single comparison condition.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct Comparison {
/// The left hand side which will always be a domain input identifier like "payment.method.cardtype"
pub lhs: String,
/// The comparison operator
pub comparison: ComparisonType,
/// The value to compare against
pub value: ValueType,
/// Additional metadata that the Static Analyzer and Backend does not touch.
/// This can be used to store useful information for the frontend and is required for communication
/// between the static analyzer and the frontend.
// #[schema(value_type=HashMap<String, serde_json::Value>)]
pub metadata: Metadata,
}
/// Represents all the conditions of an IF statement
/// eg:
///
/// ```text
/// payment.method = card & payment.method.cardtype = debit & payment.method.network = diners
/// ```
pub type IfCondition = Vec<Comparison>;
/// Represents an IF statement with conditions and optional nested IF statements
///
/// ```text
/// payment.method = card {
/// payment.method.cardtype = (credit, debit) {
/// payment.method.network = (amex, rupay, diners)
/// }
/// }
/// ```
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct IfStatement {
// #[schema(value_type=Vec<Comparison>)]
pub condition: IfCondition,
pub nested: Option<Vec<IfStatement>>,
}
/// Represents a rule
///
/// ```text
/// rule_name: [stripe, adyen, checkout]
/// {
/// payment.method = card {
/// payment.method.cardtype = (credit, debit) {
/// payment.method.network = (amex, rupay, diners)
/// }
///
/// payment.method.cardtype = credit
/// }
/// }
/// ```
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
// #[aliases(RuleConnectorSelection = Rule<ConnectorSelection>)]
pub struct Rule {
pub name: String,
#[serde(alias = "routingType")]
pub routing_type: RoutingType,
#[serde(alias = "routingOutput")]
pub output: Output,
pub statements: Vec<IfStatement>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RoutingType {
Priority,
VolumeSplit,
VolumeSplitPriority,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct VolumeSplit<T> {
pub split: u8,
pub output: T,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct ConnectorInfo {
pub gateway_name: String,
pub gateway_id: Option<String>,
}
impl TryFrom<ConnectorInfo> for DeRoutableConnectorChoice {
type Error = error_stack::Report<errors::RoutingError>;
fn try_from(c: ConnectorInfo) -> Result<Self, Self::Error> {
let gateway_id = c
.gateway_id
.map(|mca| {
id_type::MerchantConnectorAccountId::wrap(mca)
.change_context(errors::RoutingError::GenericConversionError {
from: "String".to_string(),
to: "MerchantConnectorAccountId".to_string(),
})
.attach_printable("unable to convert MerchantConnectorAccountId from string")
})
.transpose()?;
let gateway_name = RoutableConnectors::from_str(&c.gateway_name)
.map_err(|_| errors::RoutingError::GenericConversionError {
from: "String".to_string(),
to: "RoutableConnectors".to_string(),
})
.attach_printable("unable to convert connector name to RoutableConnectors")?;
Ok(Self {
gateway_name,
gateway_id,
})
}
}
impl ConnectorInfo {
pub fn new(gateway_name: String, gateway_id: Option<String>) -> Self {
Self {
gateway_name,
gateway_id,
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Output {
Single(ConnectorInfo),
Priority(Vec<ConnectorInfo>),
VolumeSplit(Vec<VolumeSplit<ConnectorInfo>>),
VolumeSplitPriority(Vec<VolumeSplit<Vec<ConnectorInfo>>>),
}
pub type Globals = HashMap<String, HashSet<ValueType>>;
/// The program, having a default connector selection and
/// a bunch of rules. Also can hold arbitrary metadata.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
// #[aliases(ProgramConnectorSelection = Program<ConnectorSelection>)]
pub struct Program {
pub globals: Globals,
pub default_selection: Output,
// #[schema(value_type=RuleConnectorSelection)]
pub rules: Vec<Rule>,
// #[schema(value_type=HashMap<String, serde_json::Value>)]
pub metadata: Option<Metadata>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct RoutingRule {
pub rule_id: Option<String>,
pub name: String,
pub description: Option<String>,
pub metadata: Option<RoutingMetadata>,
pub created_by: String,
#[serde(default)]
pub algorithm_for: AlgorithmType,
pub algorithm: StaticRoutingAlgorithm,
}
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize, strum::Display)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum AlgorithmType {
#[default]
Payment,
Payout,
ThreeDsAuthentication,
}
impl From<TransactionType> for AlgorithmType {
fn from(transaction_type: TransactionType) -> Self {
match transaction_type {
TransactionType::Payment => Self::Payment,
TransactionType::Payout => Self::Payout,
TransactionType::ThreeDsAuthentication => Self::ThreeDsAuthentication,
}
}
}
impl From<RoutableConnectorChoice> for ConnectorInfo {
fn from(c: RoutableConnectorChoice) -> Self {
Self {
gateway_name: c.connector.to_string(),
gateway_id: c
.merchant_connector_id
.map(|mca_id| mca_id.get_string_repr().to_string()),
}
}
}
impl From<Box<RoutableConnectorChoice>> for ConnectorInfo {
fn from(c: Box<RoutableConnectorChoice>) -> Self {
Self {
gateway_name: c.connector.to_string(),
gateway_id: c
.merchant_connector_id
.map(|mca_id| mca_id.get_string_repr().to_string()),
}
}
}
impl From<ConnectorVolumeSplit> for VolumeSplit<ConnectorInfo> {
fn from(v: ConnectorVolumeSplit) -> Self {
Self {
split: v.split,
output: ConnectorInfo {
gateway_name: v.connector.connector.to_string(),
gateway_id: v
.connector
.merchant_connector_id
.map(|mca_id| mca_id.get_string_repr().to_string()),
},
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", content = "data", rename_all = "snake_case")]
pub enum StaticRoutingAlgorithm {
Single(Box<ConnectorInfo>),
Priority(Vec<ConnectorInfo>),
VolumeSplit(Vec<VolumeSplit<ConnectorInfo>>),
Advanced(Program),
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct RoutingMetadata {
pub kind: enums::RoutingAlgorithmKind,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct RoutingDictionaryRecord {
pub rule_id: String,
pub name: String,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct RoutingAlgorithmRecord {
pub id: id_type::RoutingId,
pub name: String,
pub description: Option<String>,
pub created_by: id_type::ProfileId,
pub algorithm_data: StaticRoutingAlgorithm,
pub algorithm_for: TransactionType,
pub metadata: Option<RoutingMetadata>,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
}
impl From<RoutingAlgorithmRecord> for routing_algorithm::RoutingProfileMetadata {
fn from(record: RoutingAlgorithmRecord) -> Self {
let kind = match record.algorithm_data {
StaticRoutingAlgorithm::Single(_) => enums::RoutingAlgorithmKind::Single,
StaticRoutingAlgorithm::Priority(_) => enums::RoutingAlgorithmKind::Priority,
StaticRoutingAlgorithm::VolumeSplit(_) => enums::RoutingAlgorithmKind::VolumeSplit,
StaticRoutingAlgorithm::Advanced(_) => enums::RoutingAlgorithmKind::Advanced,
};
Self {
profile_id: record.created_by,
algorithm_id: record.id,
name: record.name,
description: record.description,
kind,
created_at: record.created_at,
modified_at: record.modified_at,
algorithm_for: record.algorithm_for,
}
}
}
impl TryFrom<ast::Program<ConnectorSelection>> for Program {
type Error = error_stack::Report<errors::RoutingError>;
fn try_from(p: ast::Program<ConnectorSelection>) -> Result<Self, Self::Error> {
let rules = p
.rules
.into_iter()
.map(convert_rule)
.collect::<Result<Vec<_>, _>>()?;
Ok(Self {
globals: HashMap::new(),
default_selection: convert_output(p.default_selection),
rules,
metadata: Some(p.metadata),
})
}
}
impl TryFrom<ast::Program<ConnectorSelection>> for StaticRoutingAlgorithm {
type Error = error_stack::Report<errors::RoutingError>;
fn try_from(p: ast::Program<ConnectorSelection>) -> Result<Self, Self::Error> {
let internal_program: Program = p.try_into()?;
Ok(Self::Advanced(internal_program))
}
}
fn convert_rule(rule: ast::Rule<ConnectorSelection>) -> RoutingResult<Rule> {
let routing_type = match &rule.connector_selection {
ConnectorSelection::Priority(_) => RoutingType::Priority,
ConnectorSelection::VolumeSplit(_) => RoutingType::VolumeSplit,
};
Ok(Rule {
name: rule.name,
routing_type,
output: convert_output(rule.connector_selection),
statements: rule
.statements
.into_iter()
.map(convert_if_stmt)
.collect::<RoutingResult<Vec<IfStatement>>>()?,
})
}
fn convert_if_stmt(stmt: ast::IfStatement) -> RoutingResult<IfStatement> {
Ok(IfStatement {
condition: stmt
.condition
.into_iter()
.map(convert_comparison)
.collect::<RoutingResult<Vec<Comparison>>>()?,
nested: stmt
.nested
.map(|v| {
v.into_iter()
.map(convert_if_stmt)
.collect::<RoutingResult<Vec<IfStatement>>>()
})
.transpose()?,
})
}
fn convert_comparison(c: ast::Comparison) -> RoutingResult<Comparison> {
Ok(Comparison {
lhs: c.lhs,
comparison: convert_comparison_type(c.comparison),
value: convert_value(c.value)?,
metadata: c.metadata,
})
}
fn convert_comparison_type(ct: ast::ComparisonType) -> ComparisonType {
match ct {
ast::ComparisonType::Equal => ComparisonType::Equal,
ast::ComparisonType::NotEqual => ComparisonType::NotEqual,
ast::ComparisonType::LessThan => ComparisonType::LessThan,
ast::ComparisonType::LessThanEqual => ComparisonType::LessThanEqual,
ast::ComparisonType::GreaterThan => ComparisonType::GreaterThan,
ast::ComparisonType::GreaterThanEqual => ComparisonType::GreaterThanEqual,
}
}
fn convert_value(v: ast::ValueType) -> RoutingResult<ValueType> {
use ast::ValueType::*;
match v {
Number(n) => Ok(ValueType::Number(
n.get_amount_as_i64().try_into().unwrap_or_default(),
)),
EnumVariant(e) => Ok(ValueType::EnumVariant(e)),
MetadataVariant(m) => Ok(ValueType::MetadataVariant(MetadataValue {
key: m.key,
value: m.value,
})),
StrValue(s) => Ok(ValueType::StrValue(s)),
NumberArray(arr) => Ok(ValueType::NumberArray(
arr.into_iter()
.map(|n| n.get_amount_as_i64().try_into().unwrap_or_default())
.collect(),
)),
EnumVariantArray(arr) => Ok(ValueType::EnumVariantArray(arr)),
NumberComparisonArray(arr) => Ok(ValueType::NumberComparisonArray(
arr.into_iter()
.map(|nc| NumberComparison {
comparison_type: convert_comparison_type(nc.comparison_type),
number: nc.number.get_amount_as_i64().try_into().unwrap_or_default(),
})
.collect(),
)),
}
}
fn convert_output(sel: ConnectorSelection) -> Output {
match sel {
ConnectorSelection::Priority(choices) => {
Output::Priority(choices.into_iter().map(stringify_choice).collect())
}
ConnectorSelection::VolumeSplit(vs) => Output::VolumeSplit(
vs.into_iter()
.map(|v| VolumeSplit {
split: v.split,
output: stringify_choice(v.connector),
})
.collect(),
),
}
}
fn stringify_choice(c: RoutableConnectorChoice) -> ConnectorInfo {
ConnectorInfo::new(
c.connector.to_string(),
c.merchant_connector_id
.map(|mca_id| mca_id.get_string_repr().to_string()),
)
}
pub async fn select_routing_result<T>(
state: &SessionState,
business_profile: &business_profile::Profile,
hyperswitch_result: T,
de_result: T,
) -> T {
let routing_result_source: Option<api_routing::RoutingResultSource> = state
.store
.find_config_by_key(&format!(
"routing_result_source_{0}",
business_profile.get_id().get_string_repr()
))
.await
.map(|c| c.config.parse_enum("RoutingResultSource").ok())
.unwrap_or(None); //Ignore errors so that we can use the hyperswitch result as a fallback
if let Some(api_routing::RoutingResultSource::DecisionEngine) = routing_result_source {
logger::debug!(business_profile_id=?business_profile.get_id(), "Using Decision Engine routing result");
de_result
} else {
logger::debug!(business_profile_id=?business_profile.get_id(), "Using Hyperswitch routing result");
hyperswitch_result
}
}
pub trait DecisionEngineErrorsInterface {
fn get_error_message(&self) -> String;
fn get_error_code(&self) -> String;
fn get_error_data(&self) -> Option<String>;
}
#[derive(Debug)]
pub struct RoutingEventsWrapper<Req>
where
Req: Serialize + Clone,
{
pub tenant_id: id_type::TenantId,
pub request_id: Option<RequestId>,
pub payment_id: String,
pub profile_id: id_type::ProfileId,
pub merchant_id: id_type::MerchantId,
pub flow: String,
pub request: Option<Req>,
pub parse_response: bool,
pub log_event: bool,
pub routing_event: Option<routing_events::RoutingEvent>,
}
#[derive(Debug)]
pub enum EventResponseType<Res>
where
Res: Serialize + serde::de::DeserializeOwned + Clone,
{
Structured(Res),
String(String),
}
#[derive(Debug, Serialize)]
pub struct RoutingEventsResponse<Res>
where
Res: Serialize + serde::de::DeserializeOwned + Clone,
{
pub event: Option<routing_events::RoutingEvent>,
pub response: Option<Res>,
}
impl<Res> RoutingEventsResponse<Res>
where
Res: Serialize + serde::de::DeserializeOwned + Clone,
{
pub fn new(event: Option<routing_events::RoutingEvent>, response: Option<Res>) -> Self {
Self { event, response }
}
pub fn set_response(&mut self, response: Res) {
self.response = Some(response);
}
pub fn set_event(&mut self, event: routing_events::RoutingEvent) {
self.event = Some(event);
}
}
impl<Req> RoutingEventsWrapper<Req>
where
Req: Serialize + Clone,
{
#[allow(clippy::too_many_arguments)]
pub fn new(
tenant_id: id_type::TenantId,
request_id: Option<RequestId>,
payment_id: String,
profile_id: id_type::ProfileId,
merchant_id: id_type::MerchantId,
flow: String,
request: Option<Req>,
parse_response: bool,
log_event: bool,
) -> Self {
Self {
tenant_id,
request_id,
payment_id,
profile_id,
merchant_id,
flow,
request,
parse_response,
log_event,
routing_event: None,
}
}
pub fn construct_event_builder(
self,
url: String,
routing_engine: routing_events::RoutingEngine,
method: routing_events::ApiMethod,
) -> RoutingResult<Self> {
let mut wrapper = self;
let request = wrapper
.request
.clone()
.ok_or(errors::RoutingError::RoutingEventsError {
message: "Request body is missing".to_string(),
status_code: 400,
})?;
let serialized_request = serde_json::to_value(&request)
.change_context(errors::RoutingError::RoutingEventsError {
message: "Failed to serialize RoutingRequest".to_string(),
status_code: 500,
})
.attach_printable("Failed to serialize request body")?;
let routing_event = routing_events::RoutingEvent::new(
wrapper.tenant_id.clone(),
"".to_string(),
&wrapper.flow,
serialized_request,
url,
method,
wrapper.payment_id.clone(),
wrapper.profile_id.clone(),
wrapper.merchant_id.clone(),
wrapper.request_id,
routing_engine,
);
wrapper.set_routing_event(routing_event);
Ok(wrapper)
}
pub async fn trigger_event<Res, F, Fut>(
self,
state: &SessionState,
func: F,
) -> RoutingResult<RoutingEventsResponse<Res>>
where
F: FnOnce() -> Fut + Send,
Res: Serialize + serde::de::DeserializeOwned + Clone,
Fut: futures::Future<Output = RoutingResult<Option<Res>>> + Send,
{
let mut routing_event =
self.routing_event
.ok_or(errors::RoutingError::RoutingEventsError {
message: "Routing event is missing".to_string(),
status_code: 500,
})?;
let mut response = RoutingEventsResponse::new(None, None);
let resp = func().await;
match resp {
Ok(ok_resp) => {
if let Some(resp) = ok_resp {
routing_event.set_response_body(&resp);
// routing_event
// .set_routable_connectors(ok_resp.get_routable_connectors().unwrap_or_default());
// routing_event.set_payment_connector(ok_resp.get_payment_connector());
routing_event.set_status_code(200);
response.set_response(resp.clone());
self.log_event
.then(|| state.event_handler().log_event(&routing_event));
}
}
Err(err) => {
// Need to figure out a generic way to log errors
routing_event
.set_error(serde_json::json!({"error": err.current_context().to_string()}));
match err.current_context() {
errors::RoutingError::RoutingEventsError { status_code, .. } => {
routing_event.set_status_code(*status_code);
}
_ => {
routing_event.set_status_code(500);
}
}
state.event_handler().log_event(&routing_event)
}
}
response.set_event(routing_event);
Ok(response)
}
pub fn set_log_event(&mut self, log_event: bool) {
self.log_event = log_event;
}
pub fn set_request_body(&mut self, request: Req) {
self.request = Some(request);
}
pub fn set_routing_event(&mut self, routing_event: routing_events::RoutingEvent) {
self.routing_event = Some(routing_event);
}
}
pub trait RoutingEventsInterface {
fn get_routable_connectors(&self) -> Option<Vec<RoutableConnectorChoice>>;
fn get_payment_connector(&self) -> Option<RoutableConnectorChoice>;
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct CalSuccessRateConfigEventRequest {
pub min_aggregates_size: Option<u32>,
pub default_success_rate: Option<f64>,
pub specificity_level: api_routing::SuccessRateSpecificityLevel,
pub exploration_percent: Option<f64>,
}
impl From<&api_routing::SuccessBasedRoutingConfigBody> for CalSuccessRateConfigEventRequest {
fn from(value: &api_routing::SuccessBasedRoutingConfigBody) -> Self {
Self {
min_aggregates_size: value.min_aggregates_size,
default_success_rate: value.default_success_rate,
specificity_level: value.specificity_level,
exploration_percent: value.exploration_percent,
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct CalSuccessRateEventRequest {
pub id: String,
pub params: String,
pub labels: Vec<String>,
pub config: Option<CalSuccessRateConfigEventRequest>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct EliminationRoutingEventBucketConfig {
pub bucket_size: Option<u64>,
pub bucket_leak_interval_in_secs: Option<u64>,
}
impl From<&api_routing::EliminationAnalyserConfig> for EliminationRoutingEventBucketConfig {
fn from(value: &api_routing::EliminationAnalyserConfig) -> Self {
Self {
bucket_size: value.bucket_size,
bucket_leak_interval_in_secs: value.bucket_leak_interval_in_secs,
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct EliminationRoutingEventRequest {
pub id: String,
pub params: String,
pub labels: Vec<String>,
pub config: Option<EliminationRoutingEventBucketConfig>,
}
/// API-1 types
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct CalContractScoreEventRequest {
pub id: String,
pub params: String,
pub labels: Vec<String>,
pub config: Option<api_routing::ContractBasedRoutingConfig>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct LabelWithScoreEventResponse {
pub score: f64,
pub label: String,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct CalSuccessRateEventResponse {
pub labels_with_score: Vec<LabelWithScoreEventResponse>,
pub routing_approach: RoutingApproach,
}
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
impl TryFrom<&ir_client::success_rate_client::CalSuccessRateResponse>
for CalSuccessRateEventResponse
{
type Error = errors::RoutingError;
fn try_from(
value: &ir_client::success_rate_client::CalSuccessRateResponse,
) -> Result<Self, Self::Error> {
Ok(Self {
labels_with_score: value
.labels_with_score
.iter()
.map(|l| LabelWithScoreEventResponse {
score: l.score,
label: l.label.clone(),
})
.collect(),
routing_approach: match value.routing_approach {
0 => RoutingApproach::Exploration,
1 => RoutingApproach::Exploitation,
_ => {
return Err(errors::RoutingError::GenericNotFoundError {
field: "unknown routing approach from dynamic routing service".to_string(),
})
}
},
})
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RoutingApproach {
Exploitation,
Exploration,
Elimination,
ContractBased,
StaticRouting,
Default,
}
impl RoutingApproach {
pub fn from_decision_engine_approach(approach: &str) -> Self {
match approach {
"SR_SELECTION_V3_ROUTING" => Self::Exploitation,
"SR_V3_HEDGING" => Self::Exploration,
_ => Self::Default,
}
}
}
impl From<RoutingApproach> for common_enums::RoutingApproach {
fn from(approach: RoutingApproach) -> Self {
match approach {
RoutingApproach::Exploitation => Self::SuccessRateExploitation,
RoutingApproach::Exploration => Self::SuccessRateExploration,
RoutingApproach::ContractBased => Self::ContractBasedRouting,
RoutingApproach::StaticRouting => Self::RuleBasedRouting,
_ => Self::DefaultFallback,
}
}
}
impl std::fmt::Display for RoutingApproach {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Exploitation => write!(f, "Exploitation"),
Self::Exploration => write!(f, "Exploration"),
Self::Elimination => write!(f, "Elimination"),
Self::ContractBased => write!(f, "ContractBased"),
Self::StaticRouting => write!(f, "StaticRouting"),
Self::Default => write!(f, "Default"),
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct BucketInformationEventResponse {
pub is_eliminated: bool,
pub bucket_name: Vec<String>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct EliminationInformationEventResponse {
pub entity: Option<BucketInformationEventResponse>,
pub global: Option<BucketInformationEventResponse>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct LabelWithStatusEliminationEventResponse {
pub label: String,
pub elimination_information: Option<EliminationInformationEventResponse>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct EliminationEventResponse {
pub labels_with_status: Vec<LabelWithStatusEliminationEventResponse>,
}
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
impl From<&ir_client::elimination_based_client::EliminationResponse> for EliminationEventResponse {
fn from(value: &ir_client::elimination_based_client::EliminationResponse) -> Self {
Self {
labels_with_status: value
.labels_with_status
.iter()
.map(
|label_with_status| LabelWithStatusEliminationEventResponse {
label: label_with_status.label.clone(),
elimination_information: label_with_status
.elimination_information
.as_ref()
.map(|info| EliminationInformationEventResponse {
entity: info.entity.as_ref().map(|entity_info| {
BucketInformationEventResponse {
is_eliminated: entity_info.is_eliminated,
bucket_name: entity_info.bucket_name.clone(),
}
}),
global: info.global.as_ref().map(|global_info| {
BucketInformationEventResponse {
is_eliminated: global_info.is_eliminated,
bucket_name: global_info.bucket_name.clone(),
}
}),
}),
},
)
.collect(),
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct ScoreDataEventResponse {
pub score: f64,
pub label: String,
pub current_count: u64,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct CalContractScoreEventResponse {
pub labels_with_score: Vec<ScoreDataEventResponse>,
}
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
impl From<&ir_client::contract_routing_client::CalContractScoreResponse>
for CalContractScoreEventResponse
{
fn from(value: &ir_client::contract_routing_client::CalContractScoreResponse) -> Self {
Self {
labels_with_score: value
.labels_with_score
.iter()
.map(|label_with_score| ScoreDataEventResponse {
score: label_with_score.score,
label: label_with_score.label.clone(),
current_count: label_with_score.current_count,
})
.collect(),
}
}
}
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct CalGlobalSuccessRateConfigEventRequest {
pub entity_min_aggregates_size: u32,
pub entity_default_success_rate: f64,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct CalGlobalSuccessRateEventRequest {
pub entity_id: String,
pub entity_params: String,
pub entity_labels: Vec<String>,
pub global_labels: Vec<String>,
pub config: Option<CalGlobalSuccessRateConfigEventRequest>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct UpdateSuccessRateWindowConfig {
pub max_aggregates_size: Option<u32>,
pub current_block_threshold: Option<api_routing::CurrentBlockThreshold>,
}
impl From<&api_routing::SuccessBasedRoutingConfigBody> for UpdateSuccessRateWindowConfig {
fn from(value: &api_routing::SuccessBasedRoutingConfigBody) -> Self {
Self {
max_aggregates_size: value.max_aggregates_size,
current_block_threshold: value.current_block_threshold.clone(),
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct UpdateLabelWithStatusEventRequest {
pub label: String,
pub status: bool,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct UpdateSuccessRateWindowEventRequest {
pub id: String,
pub params: String,
pub labels_with_status: Vec<UpdateLabelWithStatusEventRequest>,
pub config: Option<UpdateSuccessRateWindowConfig>,
pub global_labels_with_status: Vec<UpdateLabelWithStatusEventRequest>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct UpdateSuccessRateWindowEventResponse {
pub status: UpdationStatusEventResponse,
}
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
impl TryFrom<&ir_client::success_rate_client::UpdateSuccessRateWindowResponse>
for UpdateSuccessRateWindowEventResponse
{
type Error = errors::RoutingError;
fn try_from(
value: &ir_client::success_rate_client::UpdateSuccessRateWindowResponse,
) -> Result<Self, Self::Error> {
Ok(Self {
status: match value.status {
0 => UpdationStatusEventResponse::WindowUpdationSucceeded,
1 => UpdationStatusEventResponse::WindowUpdationFailed,
_ => {
return Err(errors::RoutingError::GenericNotFoundError {
field: "unknown updation status from dynamic routing service".to_string(),
})
}
},
})
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum UpdationStatusEventResponse {
WindowUpdationSucceeded,
WindowUpdationFailed,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct LabelWithBucketNameEventRequest {
pub label: String,
pub bucket_name: String,
}
impl From<&api_routing::RoutableConnectorChoiceWithBucketName> for LabelWithBucketNameEventRequest {
fn from(value: &api_routing::RoutableConnectorChoiceWithBucketName) -> Self {
Self {
label: value.routable_connector_choice.to_string(),
bucket_name: value.bucket_name.clone(),
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct UpdateEliminationBucketEventRequest {
pub id: String,
pub params: String,
pub labels_with_bucket_name: Vec<LabelWithBucketNameEventRequest>,
pub config: Option<EliminationRoutingEventBucketConfig>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct UpdateEliminationBucketEventResponse {
pub status: EliminationUpdationStatusEventResponse,
}
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
impl TryFrom<&ir_client::elimination_based_client::UpdateEliminationBucketResponse>
for UpdateEliminationBucketEventResponse
{
type Error = errors::RoutingError;
fn try_from(
value: &ir_client::elimination_based_client::UpdateEliminationBucketResponse,
) -> Result<Self, Self::Error> {
Ok(Self {
status: match value.status {
0 => EliminationUpdationStatusEventResponse::BucketUpdationSucceeded,
1 => EliminationUpdationStatusEventResponse::BucketUpdationFailed,
_ => {
return Err(errors::RoutingError::GenericNotFoundError {
field: "unknown updation status from dynamic routing service".to_string(),
})
}
},
})
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum EliminationUpdationStatusEventResponse {
BucketUpdationSucceeded,
BucketUpdationFailed,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct ContractLabelInformationEventRequest {
pub label: String,
pub target_count: u64,
pub target_time: u64,
pub current_count: u64,
}
impl From<&api_routing::LabelInformation> for ContractLabelInformationEventRequest {
fn from(value: &api_routing::LabelInformation) -> Self {
Self {
label: value.label.clone(),
target_count: value.target_count,
target_time: value.target_time,
current_count: 1,
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct UpdateContractRequestEventRequest {
pub id: String,
pub params: String,
pub labels_information: Vec<ContractLabelInformationEventRequest>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct UpdateContractEventResponse {
pub status: ContractUpdationStatusEventResponse,
}
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
impl TryFrom<&ir_client::contract_routing_client::UpdateContractResponse>
for UpdateContractEventResponse
{
type Error = errors::RoutingError;
fn try_from(
value: &ir_client::contract_routing_client::UpdateContractResponse,
) -> Result<Self, Self::Error> {
Ok(Self {
status: match value.status {
0 => ContractUpdationStatusEventResponse::ContractUpdationSucceeded,
1 => ContractUpdationStatusEventResponse::ContractUpdationFailed,
_ => {
return Err(errors::RoutingError::GenericNotFoundError {
field: "unknown updation status from dynamic routing service".to_string(),
})
}
},
})
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ContractUpdationStatusEventResponse {
ContractUpdationSucceeded,
ContractUpdationFailed,
}
|
crates/router/src/core/payments/routing/utils.rs
|
router::src::core::payments::routing::utils
| 15,638
| true
|
// File: crates/router/src/core/payments/flows/complete_authorize_flow.rs
// Module: router::src::core::payments::flows::complete_authorize_flow
use async_trait::async_trait;
use masking::ExposeInterface;
use super::{ConstructFlowSpecificData, Feature};
use crate::{
core::{
errors::{ApiErrorResponse, ConnectorErrorExt, RouterResult},
payments::{self, access_token, helpers, transformers, PaymentData},
},
routes::{metrics, SessionState},
services,
types::{self, api, domain, transformers::ForeignTryFrom},
};
#[async_trait]
impl
ConstructFlowSpecificData<
api::CompleteAuthorize,
types::CompleteAuthorizeData,
types::PaymentsResponseData,
> for PaymentData<api::CompleteAuthorize>
{
#[cfg(feature = "v1")]
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
merchant_context: &domain::MerchantContext,
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
_payment_method: Option<common_enums::PaymentMethod>,
_payment_method_type: Option<common_enums::PaymentMethodType>,
) -> RouterResult<
types::RouterData<
api::CompleteAuthorize,
types::CompleteAuthorizeData,
types::PaymentsResponseData,
>,
> {
Box::pin(transformers::construct_payment_router_data::<
api::CompleteAuthorize,
types::CompleteAuthorizeData,
>(
state,
self.clone(),
connector_id,
merchant_context,
customer,
merchant_connector_account,
merchant_recipient_data,
header_payload,
None,
None,
))
.await
}
#[cfg(feature = "v2")]
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
merchant_context: &domain::MerchantContext,
customer: &Option<domain::Customer>,
merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
) -> RouterResult<
types::RouterData<
api::CompleteAuthorize,
types::CompleteAuthorizeData,
types::PaymentsResponseData,
>,
> {
todo!()
}
}
#[async_trait]
impl Feature<api::CompleteAuthorize, types::CompleteAuthorizeData>
for types::RouterData<
api::CompleteAuthorize,
types::CompleteAuthorizeData,
types::PaymentsResponseData,
>
{
async fn decide_flows<'a>(
mut self,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
connector_request: Option<services::Request>,
business_profile: &domain::Profile,
header_payload: hyperswitch_domain_models::payments::HeaderPayload,
_return_raw_connector_response: Option<bool>,
) -> RouterResult<Self> {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::CompleteAuthorize,
types::CompleteAuthorizeData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
let mut complete_authorize_router_data = services::execute_connector_processing_step(
state,
connector_integration,
&self,
call_connector_action.clone(),
connector_request,
None,
)
.await
.to_payment_failed_response()?;
match complete_authorize_router_data.response.clone() {
Err(_) => Ok(complete_authorize_router_data),
Ok(complete_authorize_response) => {
// Check if the Capture API should be called based on the connector and other parameters
if super::should_initiate_capture_flow(
&connector.connector_name,
self.request.customer_acceptance,
self.request.capture_method,
self.request.setup_future_usage,
complete_authorize_router_data.status,
) {
complete_authorize_router_data = Box::pin(process_capture_flow(
complete_authorize_router_data,
complete_authorize_response,
state,
connector,
call_connector_action.clone(),
business_profile,
header_payload,
))
.await?;
}
Ok(complete_authorize_router_data)
}
}
}
async fn add_access_token<'a>(
&self,
state: &SessionState,
connector: &api::ConnectorData,
merchant_context: &domain::MerchantContext,
creds_identifier: Option<&str>,
) -> RouterResult<types::AddAccessTokenResult> {
Box::pin(access_token::add_access_token(
state,
connector,
merchant_context,
self,
creds_identifier,
))
.await
}
async fn add_payment_method_token<'a>(
&mut self,
state: &SessionState,
connector: &api::ConnectorData,
_tokenization_action: &payments::TokenizationAction,
should_continue_payment: bool,
) -> RouterResult<types::PaymentMethodTokenResult> {
// TODO: remove this and handle it in core
if matches!(connector.connector_name, types::Connector::Payme) {
let request = self.request.clone();
payments::tokenization::add_payment_method_token(
state,
connector,
&payments::TokenizationAction::TokenizeInConnector,
self,
types::PaymentMethodTokenizationData::try_from(request)?,
should_continue_payment,
)
.await
} else {
Ok(types::PaymentMethodTokenResult {
payment_method_token_result: Ok(None),
is_payment_method_tokenization_performed: false,
connector_response: None,
})
}
}
async fn build_flow_specific_connector_request(
&mut self,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
) -> RouterResult<(Option<services::Request>, bool)> {
let request = match call_connector_action {
payments::CallConnectorAction::Trigger => {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::CompleteAuthorize,
types::CompleteAuthorizeData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
connector_integration
.build_request(self, &state.conf.connectors)
.to_payment_failed_response()?
}
_ => None,
};
Ok((request, true))
}
async fn preprocessing_steps<'a>(
self,
state: &SessionState,
connector: &api::ConnectorData,
) -> RouterResult<Self> {
complete_authorize_preprocessing_steps(state, &self, true, connector).await
}
}
pub async fn complete_authorize_preprocessing_steps<F: Clone>(
state: &SessionState,
router_data: &types::RouterData<F, types::CompleteAuthorizeData, types::PaymentsResponseData>,
confirm: bool,
connector: &api::ConnectorData,
) -> RouterResult<types::RouterData<F, types::CompleteAuthorizeData, types::PaymentsResponseData>> {
if confirm {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::PreProcessing,
types::PaymentsPreProcessingData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
let preprocessing_request_data =
types::PaymentsPreProcessingData::try_from(router_data.request.to_owned())?;
let preprocessing_response_data: Result<types::PaymentsResponseData, types::ErrorResponse> =
Err(types::ErrorResponse::default());
let preprocessing_router_data =
helpers::router_data_type_conversion::<_, api::PreProcessing, _, _, _, _>(
router_data.clone(),
preprocessing_request_data,
preprocessing_response_data,
);
let resp = services::execute_connector_processing_step(
state,
connector_integration,
&preprocessing_router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.to_payment_failed_response()?;
metrics::PREPROCESSING_STEPS_COUNT.add(
1,
router_env::metric_attributes!(
("connector", connector.connector_name.to_string()),
("payment_method", router_data.payment_method.to_string()),
),
);
let mut router_data_request = router_data.request.to_owned();
if let Ok(types::PaymentsResponseData::TransactionResponse {
connector_metadata, ..
}) = &resp.response
{
connector_metadata.clone_into(&mut router_data_request.connector_meta);
};
let authorize_router_data = helpers::router_data_type_conversion::<_, F, _, _, _, _>(
resp.clone(),
router_data_request,
resp.response,
);
Ok(authorize_router_data)
} else {
Ok(router_data.clone())
}
}
impl<F>
ForeignTryFrom<types::RouterData<F, types::CompleteAuthorizeData, types::PaymentsResponseData>>
for types::PaymentsCaptureData
{
type Error = error_stack::Report<ApiErrorResponse>;
fn foreign_try_from(
item: types::RouterData<F, types::CompleteAuthorizeData, types::PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let response = item
.response
.map_err(|err| ApiErrorResponse::ExternalConnectorError {
code: err.code,
message: err.message,
connector: item.connector.clone().to_string(),
status_code: err.status_code,
reason: err.reason,
})?;
Ok(Self {
amount_to_capture: item.request.amount,
currency: item.request.currency,
connector_transaction_id: types::PaymentsResponseData::get_connector_transaction_id(
&response,
)?,
payment_amount: item.request.amount,
multiple_capture_data: None,
connector_meta: types::PaymentsResponseData::get_connector_metadata(&response)
.map(|secret| secret.expose()),
browser_info: None,
metadata: None,
capture_method: item.request.capture_method,
minor_payment_amount: item.request.minor_amount,
minor_amount_to_capture: item.request.minor_amount,
integrity_object: None,
split_payments: None,
webhook_url: None,
})
}
}
async fn process_capture_flow(
mut router_data: types::RouterData<
api::CompleteAuthorize,
types::CompleteAuthorizeData,
types::PaymentsResponseData,
>,
complete_authorize_response: types::PaymentsResponseData,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
business_profile: &domain::Profile,
header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<
types::RouterData<
api::CompleteAuthorize,
types::CompleteAuthorizeData,
types::PaymentsResponseData,
>,
> {
// Convert RouterData into Capture RouterData
let capture_router_data = helpers::router_data_type_conversion(
router_data.clone(),
types::PaymentsCaptureData::foreign_try_from(router_data.clone())?,
Err(types::ErrorResponse::default()),
);
// Call capture request
let post_capture_router_data = super::call_capture_request(
capture_router_data,
state,
connector,
call_connector_action,
business_profile,
header_payload,
)
.await;
// Process capture response
let (updated_status, updated_response) =
super::handle_post_capture_response(complete_authorize_response, post_capture_router_data)?;
router_data.status = updated_status;
router_data.response = Ok(updated_response);
Ok(router_data)
}
|
crates/router/src/core/payments/flows/complete_authorize_flow.rs
|
router::src::core::payments::flows::complete_authorize_flow
| 2,503
| true
|
// File: crates/router/src/core/payments/flows/cancel_post_capture_flow.rs
// Module: router::src::core::payments::flows::cancel_post_capture_flow
use async_trait::async_trait;
use super::{ConstructFlowSpecificData, Feature};
use crate::{
core::{
errors::{ConnectorErrorExt, RouterResult},
payments::{self, access_token, helpers, transformers, PaymentData},
},
routes::{metrics, SessionState},
services,
types::{self, api, domain},
};
#[async_trait]
impl
ConstructFlowSpecificData<
api::PostCaptureVoid,
types::PaymentsCancelPostCaptureData,
types::PaymentsResponseData,
> for PaymentData<api::PostCaptureVoid>
{
#[cfg(feature = "v2")]
async fn construct_router_data<'a>(
&self,
_state: &SessionState,
_connector_id: &str,
_merchant_context: &domain::MerchantContext,
_customer: &Option<domain::Customer>,
_merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
_merchant_recipient_data: Option<types::MerchantRecipientData>,
_header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
) -> RouterResult<types::PaymentsCancelPostCaptureRouterData> {
todo!()
}
#[cfg(feature = "v1")]
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
merchant_context: &domain::MerchantContext,
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
_payment_method: Option<common_enums::PaymentMethod>,
_payment_method_type: Option<common_enums::PaymentMethodType>,
) -> RouterResult<types::PaymentsCancelPostCaptureRouterData> {
Box::pin(transformers::construct_payment_router_data::<
api::PostCaptureVoid,
types::PaymentsCancelPostCaptureData,
>(
state,
self.clone(),
connector_id,
merchant_context,
customer,
merchant_connector_account,
merchant_recipient_data,
header_payload,
None,
None,
))
.await
}
}
#[async_trait]
impl Feature<api::PostCaptureVoid, types::PaymentsCancelPostCaptureData>
for types::RouterData<
api::PostCaptureVoid,
types::PaymentsCancelPostCaptureData,
types::PaymentsResponseData,
>
{
async fn decide_flows<'a>(
self,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
connector_request: Option<services::Request>,
_business_profile: &domain::Profile,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
_return_raw_connector_response: Option<bool>,
) -> RouterResult<Self> {
metrics::PAYMENT_CANCEL_COUNT.add(
1,
router_env::metric_attributes!(("connector", connector.connector_name.to_string())),
);
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::PostCaptureVoid,
types::PaymentsCancelPostCaptureData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
let resp = services::execute_connector_processing_step(
state,
connector_integration,
&self,
call_connector_action,
connector_request,
None,
)
.await
.to_payment_failed_response()?;
Ok(resp)
}
async fn add_access_token<'a>(
&self,
state: &SessionState,
connector: &api::ConnectorData,
merchant_context: &domain::MerchantContext,
creds_identifier: Option<&str>,
) -> RouterResult<types::AddAccessTokenResult> {
Box::pin(access_token::add_access_token(
state,
connector,
merchant_context,
self,
creds_identifier,
))
.await
}
async fn build_flow_specific_connector_request(
&mut self,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
) -> RouterResult<(Option<services::Request>, bool)> {
let request = match call_connector_action {
payments::CallConnectorAction::Trigger => {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::PostCaptureVoid,
types::PaymentsCancelPostCaptureData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
connector_integration
.build_request(self, &state.conf.connectors)
.to_payment_failed_response()?
}
_ => None,
};
Ok((request, true))
}
}
|
crates/router/src/core/payments/flows/cancel_post_capture_flow.rs
|
router::src::core::payments::flows::cancel_post_capture_flow
| 1,048
| true
|
// File: crates/router/src/core/payments/flows/setup_mandate_flow.rs
// Module: router::src::core::payments::flows::setup_mandate_flow
use std::str::FromStr;
use async_trait::async_trait;
use common_enums::{self, enums};
use common_types::payments as common_payments_types;
use common_utils::{id_type, ucs_types};
use error_stack::ResultExt;
use external_services::grpc_client;
use hyperswitch_domain_models::payments as domain_payments;
use router_env::logger;
use unified_connector_service_client::payments as payments_grpc;
use super::{ConstructFlowSpecificData, Feature};
use crate::{
core::{
errors::{ApiErrorResponse, ConnectorErrorExt, RouterResult},
mandate,
payments::{
self, access_token, customers, helpers, tokenization, transformers, PaymentData,
},
unified_connector_service::{
build_unified_connector_service_auth_metadata,
handle_unified_connector_service_response_for_payment_register, ucs_logging_wrapper,
},
},
routes::SessionState,
services,
types::{
self, api, domain,
transformers::{ForeignFrom, ForeignTryFrom},
},
};
#[cfg(feature = "v1")]
#[async_trait]
impl
ConstructFlowSpecificData<
api::SetupMandate,
types::SetupMandateRequestData,
types::PaymentsResponseData,
> for PaymentData<api::SetupMandate>
{
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
merchant_context: &domain::MerchantContext,
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<domain_payments::HeaderPayload>,
_payment_method: Option<common_enums::PaymentMethod>,
_payment_method_type: Option<common_enums::PaymentMethodType>,
) -> RouterResult<types::SetupMandateRouterData> {
Box::pin(transformers::construct_payment_router_data::<
api::SetupMandate,
types::SetupMandateRequestData,
>(
state,
self.clone(),
connector_id,
merchant_context,
customer,
merchant_connector_account,
merchant_recipient_data,
header_payload,
None,
None,
))
.await
}
}
#[cfg(feature = "v2")]
#[async_trait]
impl
ConstructFlowSpecificData<
api::SetupMandate,
types::SetupMandateRequestData,
types::PaymentsResponseData,
> for hyperswitch_domain_models::payments::PaymentConfirmData<api::SetupMandate>
{
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
merchant_context: &domain::MerchantContext,
customer: &Option<domain::Customer>,
merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<domain_payments::HeaderPayload>,
) -> RouterResult<types::SetupMandateRouterData> {
Box::pin(
transformers::construct_payment_router_data_for_setup_mandate(
state,
self.clone(),
connector_id,
merchant_context,
customer,
merchant_connector_account,
merchant_recipient_data,
header_payload,
),
)
.await
}
}
#[async_trait]
impl Feature<api::SetupMandate, types::SetupMandateRequestData> for types::SetupMandateRouterData {
async fn decide_flows<'a>(
mut self,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
connector_request: Option<services::Request>,
_business_profile: &domain::Profile,
_header_payload: domain_payments::HeaderPayload,
_return_raw_connector_response: Option<bool>,
) -> RouterResult<Self> {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::SetupMandate,
types::SetupMandateRequestData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
// Change the authentication_type to ThreeDs, for google_pay wallet if card_holder_authenticated or account_verified in assurance_details is false
if let hyperswitch_domain_models::payment_method_data::PaymentMethodData::Wallet(
hyperswitch_domain_models::payment_method_data::WalletData::GooglePay(google_pay_data),
) = &self.request.payment_method_data
{
if let Some(assurance_details) = google_pay_data.info.assurance_details.as_ref() {
// Step up the transaction to 3DS when either assurance_details.card_holder_authenticated or assurance_details.account_verified is false
if !assurance_details.card_holder_authenticated
|| !assurance_details.account_verified
{
logger::info!("Googlepay transaction stepped up to 3DS");
self.auth_type = diesel_models::enums::AuthenticationType::ThreeDs;
}
}
}
let resp = services::execute_connector_processing_step(
state,
connector_integration,
&self,
call_connector_action.clone(),
connector_request,
None,
)
.await
.to_setup_mandate_failed_response()?;
Ok(resp)
}
async fn add_access_token<'a>(
&self,
state: &SessionState,
connector: &api::ConnectorData,
merchant_context: &domain::MerchantContext,
creds_identifier: Option<&str>,
) -> RouterResult<types::AddAccessTokenResult> {
Box::pin(access_token::add_access_token(
state,
connector,
merchant_context,
self,
creds_identifier,
))
.await
}
async fn add_session_token<'a>(
self,
state: &SessionState,
connector: &api::ConnectorData,
) -> RouterResult<Self>
where
Self: Sized,
{
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::AuthorizeSessionToken,
types::AuthorizeSessionTokenData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
let authorize_data = &types::PaymentsAuthorizeSessionTokenRouterData::foreign_from((
&self,
types::AuthorizeSessionTokenData::foreign_from(&self),
));
let resp = services::execute_connector_processing_step(
state,
connector_integration,
authorize_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.to_payment_failed_response()?;
let mut router_data = self;
router_data.session_token = resp.session_token;
Ok(router_data)
}
async fn add_payment_method_token<'a>(
&mut self,
state: &SessionState,
connector: &api::ConnectorData,
tokenization_action: &payments::TokenizationAction,
should_continue_payment: bool,
) -> RouterResult<types::PaymentMethodTokenResult> {
let request = self.request.clone();
tokenization::add_payment_method_token(
state,
connector,
tokenization_action,
self,
types::PaymentMethodTokenizationData::try_from(request)?,
should_continue_payment,
)
.await
}
async fn create_connector_customer<'a>(
&self,
state: &SessionState,
connector: &api::ConnectorData,
) -> RouterResult<Option<String>> {
customers::create_connector_customer(
state,
connector,
self,
types::ConnectorCustomerData::try_from(self.request.to_owned())?,
)
.await
}
async fn build_flow_specific_connector_request(
&mut self,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
) -> RouterResult<(Option<services::Request>, bool)> {
match call_connector_action {
payments::CallConnectorAction::Trigger => {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::SetupMandate,
types::SetupMandateRequestData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
Ok((
connector_integration
.build_request(self, &state.conf.connectors)
.to_payment_failed_response()?,
true,
))
}
_ => Ok((None, true)),
}
}
async fn preprocessing_steps<'a>(
self,
state: &SessionState,
connector: &api::ConnectorData,
) -> RouterResult<Self> {
setup_mandate_preprocessing_steps(state, &self, true, connector).await
}
async fn call_unified_connector_service<'a>(
&mut self,
state: &SessionState,
header_payload: &domain_payments::HeaderPayload,
lineage_ids: grpc_client::LineageIds,
#[cfg(feature = "v1")] merchant_connector_account: helpers::MerchantConnectorAccountType,
#[cfg(feature = "v2")]
merchant_connector_account: domain::MerchantConnectorAccountTypeDetails,
merchant_context: &domain::MerchantContext,
unified_connector_service_execution_mode: enums::ExecutionMode,
) -> RouterResult<()> {
let client = state
.grpc_client
.unified_connector_service_client
.clone()
.ok_or(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to fetch Unified Connector Service client")?;
let payment_register_request =
payments_grpc::PaymentServiceRegisterRequest::foreign_try_from(&*self)
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to construct Payment Setup Mandate Request")?;
let connector_auth_metadata = build_unified_connector_service_auth_metadata(
merchant_connector_account,
merchant_context,
)
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to construct request metadata")?;
let merchant_reference_id = header_payload
.x_reference_id
.clone()
.map(|id| id_type::PaymentReferenceId::from_str(id.as_str()))
.transpose()
.inspect_err(|err| logger::warn!(error=?err, "Invalid Merchant ReferenceId found"))
.ok()
.flatten()
.map(ucs_types::UcsReferenceId::Payment);
let header_payload = state
.get_grpc_headers_ucs(unified_connector_service_execution_mode)
.external_vault_proxy_metadata(None)
.merchant_reference_id(merchant_reference_id)
.lineage_ids(lineage_ids);
let updated_router_data = Box::pin(ucs_logging_wrapper(
self.clone(),
state,
payment_register_request,
header_payload,
|mut router_data, payment_register_request, grpc_headers| async move {
let response = client
.payment_setup_mandate(
payment_register_request,
connector_auth_metadata,
grpc_headers,
)
.await
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to Setup Mandate payment")?;
let payment_register_response = response.into_inner();
let (router_data_response, status_code) =
handle_unified_connector_service_response_for_payment_register(
payment_register_response.clone(),
)
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to deserialize UCS response")?;
let router_data_response = router_data_response.map(|(response, status)| {
router_data.status = status;
response
});
router_data.response = router_data_response;
router_data.connector_http_status_code = Some(status_code);
Ok((router_data, payment_register_response))
},
))
.await?;
// Copy back the updated data
*self = updated_router_data;
Ok(())
}
}
impl mandate::MandateBehaviour for types::SetupMandateRequestData {
fn get_amount(&self) -> i64 {
0
}
fn get_setup_future_usage(&self) -> Option<diesel_models::enums::FutureUsage> {
self.setup_future_usage
}
fn get_mandate_id(&self) -> Option<&api_models::payments::MandateIds> {
self.mandate_id.as_ref()
}
fn set_mandate_id(&mut self, new_mandate_id: Option<api_models::payments::MandateIds>) {
self.mandate_id = new_mandate_id;
}
fn get_payment_method_data(&self) -> domain::payments::PaymentMethodData {
self.payment_method_data.clone()
}
fn get_setup_mandate_details(
&self,
) -> Option<&hyperswitch_domain_models::mandates::MandateData> {
self.setup_mandate_details.as_ref()
}
fn get_customer_acceptance(&self) -> Option<common_payments_types::CustomerAcceptance> {
self.customer_acceptance.clone()
}
}
pub async fn setup_mandate_preprocessing_steps<F: Clone>(
state: &SessionState,
router_data: &types::RouterData<F, types::SetupMandateRequestData, types::PaymentsResponseData>,
confirm: bool,
connector: &api::ConnectorData,
) -> RouterResult<types::RouterData<F, types::SetupMandateRequestData, types::PaymentsResponseData>>
{
if confirm {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::PreProcessing,
types::PaymentsPreProcessingData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
let preprocessing_request_data =
types::PaymentsPreProcessingData::try_from(router_data.request.clone())?;
let preprocessing_response_data: Result<types::PaymentsResponseData, types::ErrorResponse> =
Err(types::ErrorResponse::default());
let preprocessing_router_data =
helpers::router_data_type_conversion::<_, api::PreProcessing, _, _, _, _>(
router_data.clone(),
preprocessing_request_data,
preprocessing_response_data,
);
let resp = services::execute_connector_processing_step(
state,
connector_integration,
&preprocessing_router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.to_payment_failed_response()?;
let mut setup_mandate_router_data = helpers::router_data_type_conversion::<_, F, _, _, _, _>(
resp.clone(),
router_data.request.to_owned(),
resp.response.clone(),
);
if connector.connector_name == api_models::enums::Connector::Nuvei {
let (enrolled_for_3ds, related_transaction_id) =
match &setup_mandate_router_data.response {
Ok(types::PaymentsResponseData::ThreeDSEnrollmentResponse {
enrolled_v2,
related_transaction_id,
}) => (*enrolled_v2, related_transaction_id.clone()),
_ => (false, None),
};
setup_mandate_router_data.request.enrolled_for_3ds = enrolled_for_3ds;
setup_mandate_router_data.request.related_transaction_id = related_transaction_id;
}
Ok(setup_mandate_router_data)
} else {
Ok(router_data.clone())
}
}
|
crates/router/src/core/payments/flows/setup_mandate_flow.rs
|
router::src::core::payments::flows::setup_mandate_flow
| 3,254
| true
|
// File: crates/router/src/core/payments/flows/approve_flow.rs
// Module: router::src::core::payments::flows::approve_flow
use async_trait::async_trait;
use super::{ConstructFlowSpecificData, Feature};
use crate::{
core::{
errors::{ApiErrorResponse, NotImplementedMessage, RouterResult},
payments::{self, access_token, helpers, transformers, PaymentData},
},
routes::SessionState,
services,
types::{self, api, domain},
};
#[async_trait]
impl
ConstructFlowSpecificData<api::Approve, types::PaymentsApproveData, types::PaymentsResponseData>
for PaymentData<api::Approve>
{
#[cfg(feature = "v2")]
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
merchant_context: &domain::MerchantContext,
customer: &Option<domain::Customer>,
merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
) -> RouterResult<types::PaymentsApproveRouterData> {
todo!()
}
#[cfg(feature = "v1")]
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
merchant_context: &domain::MerchantContext,
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
_payment_method: Option<common_enums::PaymentMethod>,
_payment_method_type: Option<common_enums::PaymentMethodType>,
) -> RouterResult<types::PaymentsApproveRouterData> {
Box::pin(transformers::construct_payment_router_data::<
api::Approve,
types::PaymentsApproveData,
>(
state,
self.clone(),
connector_id,
merchant_context,
customer,
merchant_connector_account,
merchant_recipient_data,
header_payload,
None,
None,
))
.await
}
}
#[async_trait]
impl Feature<api::Approve, types::PaymentsApproveData>
for types::RouterData<api::Approve, types::PaymentsApproveData, types::PaymentsResponseData>
{
async fn decide_flows<'a>(
self,
_state: &SessionState,
_connector: &api::ConnectorData,
_call_connector_action: payments::CallConnectorAction,
_connector_request: Option<services::Request>,
_business_profile: &domain::Profile,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
_return_raw_connector_response: Option<bool>,
) -> RouterResult<Self> {
Err(ApiErrorResponse::NotImplemented {
message: NotImplementedMessage::Reason("Flow not supported".to_string()),
}
.into())
}
async fn add_access_token<'a>(
&self,
state: &SessionState,
connector: &api::ConnectorData,
merchant_context: &domain::MerchantContext,
creds_identifier: Option<&str>,
) -> RouterResult<types::AddAccessTokenResult> {
Box::pin(access_token::add_access_token(
state,
connector,
merchant_context,
self,
creds_identifier,
))
.await
}
async fn build_flow_specific_connector_request(
&mut self,
_state: &SessionState,
_connector: &api::ConnectorData,
_call_connector_action: payments::CallConnectorAction,
) -> RouterResult<(Option<services::Request>, bool)> {
Err(ApiErrorResponse::NotImplemented {
message: NotImplementedMessage::Reason("Flow not supported".to_string()),
}
.into())
}
}
|
crates/router/src/core/payments/flows/approve_flow.rs
|
router::src::core::payments::flows::approve_flow
| 848
| true
|
// File: crates/router/src/core/payments/flows/update_metadata_flow.rs
// Module: router::src::core::payments::flows::update_metadata_flow
use async_trait::async_trait;
use super::ConstructFlowSpecificData;
use crate::{
core::{
errors::{ConnectorErrorExt, RouterResult},
payments::{self, access_token, helpers, transformers, Feature, PaymentData},
},
routes::SessionState,
services,
types::{self, api, domain},
};
#[async_trait]
impl
ConstructFlowSpecificData<
api::UpdateMetadata,
types::PaymentsUpdateMetadataData,
types::PaymentsResponseData,
> for PaymentData<api::UpdateMetadata>
{
#[cfg(feature = "v1")]
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
merchant_context: &domain::MerchantContext,
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
_payment_method: Option<common_enums::PaymentMethod>,
_payment_method_type: Option<common_enums::PaymentMethodType>,
) -> RouterResult<types::PaymentsUpdateMetadataRouterData> {
Box::pin(
transformers::construct_payment_router_data_for_update_metadata(
state,
self.clone(),
connector_id,
merchant_context,
customer,
merchant_connector_account,
merchant_recipient_data,
header_payload,
),
)
.await
}
#[cfg(feature = "v2")]
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
merchant_context: &domain::MerchantContext,
customer: &Option<domain::Customer>,
merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
) -> RouterResult<types::PaymentsUpdateMetadataRouterData> {
todo!()
}
}
#[async_trait]
impl Feature<api::UpdateMetadata, types::PaymentsUpdateMetadataData>
for types::RouterData<
api::UpdateMetadata,
types::PaymentsUpdateMetadataData,
types::PaymentsResponseData,
>
{
async fn decide_flows<'a>(
self,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
connector_request: Option<services::Request>,
_business_profile: &domain::Profile,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
return_raw_connector_response: Option<bool>,
) -> RouterResult<Self> {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::UpdateMetadata,
types::PaymentsUpdateMetadataData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
let resp = services::execute_connector_processing_step(
state,
connector_integration,
&self,
call_connector_action,
connector_request,
return_raw_connector_response,
)
.await
.to_payment_failed_response()?;
Ok(resp)
}
async fn add_access_token<'a>(
&self,
state: &SessionState,
connector: &api::ConnectorData,
merchant_context: &domain::MerchantContext,
creds_identifier: Option<&str>,
) -> RouterResult<types::AddAccessTokenResult> {
Box::pin(access_token::add_access_token(
state,
connector,
merchant_context,
self,
creds_identifier,
))
.await
}
async fn build_flow_specific_connector_request(
&mut self,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
) -> RouterResult<(Option<services::Request>, bool)> {
let request = match call_connector_action {
payments::CallConnectorAction::Trigger => {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::UpdateMetadata,
types::PaymentsUpdateMetadataData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
connector_integration
.build_request(self, &state.conf.connectors)
.to_payment_failed_response()?
}
_ => None,
};
Ok((request, true))
}
}
|
crates/router/src/core/payments/flows/update_metadata_flow.rs
|
router::src::core::payments::flows::update_metadata_flow
| 973
| true
|
// File: crates/router/src/core/payments/flows/external_proxy_flow.rs
// Module: router::src::core::payments::flows::external_proxy_flow
use std::str::FromStr;
use async_trait::async_trait;
use common_enums as enums;
use common_utils::{id_type, ucs_types, ucs_types::UcsReferenceId};
use error_stack::ResultExt;
use external_services::grpc_client;
#[cfg(feature = "v2")]
use hyperswitch_domain_models::payments::PaymentConfirmData;
use hyperswitch_domain_models::{
errors::api_error_response::ApiErrorResponse, payments as domain_payments,
};
use masking::ExposeInterface;
use unified_connector_service_client::payments as payments_grpc;
use super::{ConstructFlowSpecificData, Feature};
use crate::{
core::{
errors::{ConnectorErrorExt, RouterResult},
mandate,
payments::{
self, access_token, customers, helpers, tokenization, transformers, PaymentData,
},
unified_connector_service::{self, ucs_logging_wrapper},
},
logger,
routes::{metrics, SessionState},
services::{self, api::ConnectorValidation},
types::{
self, api, domain,
transformers::{ForeignFrom, ForeignTryFrom},
},
utils::OptionExt,
};
#[cfg(feature = "v2")]
#[async_trait]
impl
ConstructFlowSpecificData<
api::ExternalVaultProxy,
types::ExternalVaultProxyPaymentsData,
types::PaymentsResponseData,
> for PaymentConfirmData<api::ExternalVaultProxy>
{
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
merchant_context: &domain::MerchantContext,
customer: &Option<domain::Customer>,
merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<domain_payments::HeaderPayload>,
) -> RouterResult<
types::RouterData<
api::ExternalVaultProxy,
types::ExternalVaultProxyPaymentsData,
types::PaymentsResponseData,
>,
> {
Box::pin(
transformers::construct_external_vault_proxy_payment_router_data(
state,
self.clone(),
connector_id,
merchant_context,
customer,
merchant_connector_account,
merchant_recipient_data,
header_payload,
),
)
.await
}
}
#[async_trait]
impl Feature<api::ExternalVaultProxy, types::ExternalVaultProxyPaymentsData>
for types::ExternalVaultProxyPaymentsRouterData
{
async fn decide_flows<'a>(
mut self,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
connector_request: Option<services::Request>,
business_profile: &domain::Profile,
header_payload: domain_payments::HeaderPayload,
return_raw_connector_response: Option<bool>,
) -> RouterResult<Self> {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::ExternalVaultProxy,
types::ExternalVaultProxyPaymentsData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
logger::debug!(auth_type=?self.auth_type);
let mut auth_router_data = services::execute_connector_processing_step(
state,
connector_integration,
&self,
call_connector_action.clone(),
connector_request,
return_raw_connector_response,
)
.await
.to_payment_failed_response()?;
// External vault proxy doesn't use integrity checks
auth_router_data.integrity_check = Ok(());
metrics::PAYMENT_COUNT.add(1, &[]);
Ok(auth_router_data)
}
async fn add_access_token<'a>(
&self,
state: &SessionState,
connector: &api::ConnectorData,
merchant_context: &domain::MerchantContext,
creds_identifier: Option<&str>,
) -> RouterResult<types::AddAccessTokenResult> {
access_token::add_access_token(state, connector, merchant_context, self, creds_identifier)
.await
}
async fn add_session_token<'a>(
self,
state: &SessionState,
connector: &api::ConnectorData,
) -> RouterResult<Self>
where
Self: Sized,
{
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::AuthorizeSessionToken,
types::AuthorizeSessionTokenData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
let authorize_data = &types::PaymentsAuthorizeSessionTokenRouterData::foreign_from((
&self,
types::AuthorizeSessionTokenData::foreign_from(&self),
));
let resp = services::execute_connector_processing_step(
state,
connector_integration,
authorize_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.to_payment_failed_response()?;
let mut router_data = self;
router_data.session_token = resp.session_token;
Ok(router_data)
}
async fn add_payment_method_token<'a>(
&mut self,
state: &SessionState,
connector: &api::ConnectorData,
tokenization_action: &payments::TokenizationAction,
should_continue_payment: bool,
) -> RouterResult<types::PaymentMethodTokenResult> {
let request = self.request.clone();
tokenization::add_payment_method_token(
state,
connector,
tokenization_action,
self,
types::PaymentMethodTokenizationData::try_from(request)?,
should_continue_payment,
)
.await
}
async fn preprocessing_steps<'a>(
self,
state: &SessionState,
connector: &api::ConnectorData,
) -> RouterResult<Self> {
todo!()
}
async fn postprocessing_steps<'a>(
self,
state: &SessionState,
connector: &api::ConnectorData,
) -> RouterResult<Self> {
todo!()
}
async fn create_connector_customer<'a>(
&self,
state: &SessionState,
connector: &api::ConnectorData,
) -> RouterResult<Option<String>> {
customers::create_connector_customer(
state,
connector,
self,
types::ConnectorCustomerData::try_from(self)?,
)
.await
}
async fn build_flow_specific_connector_request(
&mut self,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
) -> RouterResult<(Option<services::Request>, bool)> {
match call_connector_action {
payments::CallConnectorAction::Trigger => {
connector
.connector
.validate_connector_against_payment_request(
self.request.capture_method,
self.payment_method,
self.request.payment_method_type,
)
.to_payment_failed_response()?;
// Check if the connector supports mandate payment
// if the payment_method_type does not support mandate for the given connector, downgrade the setup future usage to on session
if self.request.setup_future_usage
== Some(diesel_models::enums::FutureUsage::OffSession)
&& !self
.request
.payment_method_type
.and_then(|payment_method_type| {
state
.conf
.mandates
.supported_payment_methods
.0
.get(&enums::PaymentMethod::from(payment_method_type))
.and_then(|supported_pm_for_mandates| {
supported_pm_for_mandates.0.get(&payment_method_type).map(
|supported_connector_for_mandates| {
supported_connector_for_mandates
.connector_list
.contains(&connector.connector_name)
},
)
})
})
.unwrap_or(false)
{
// downgrade the setup future usage to on session
self.request.setup_future_usage =
Some(diesel_models::enums::FutureUsage::OnSession);
};
// External vault proxy doesn't use regular payment method validation
// Skip mandate payment validation for external vault proxy
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::ExternalVaultProxy,
types::ExternalVaultProxyPaymentsData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
metrics::EXECUTE_PRETASK_COUNT.add(
1,
router_env::metric_attributes!(
("connector", connector.connector_name.to_string()),
("flow", format!("{:?}", api::ExternalVaultProxy)),
),
);
logger::debug!(completed_pre_tasks=?true);
// External vault proxy always proceeds
Ok((
connector_integration
.build_request(self, &state.conf.connectors)
.to_payment_failed_response()?,
true,
))
}
_ => Ok((None, true)),
}
}
async fn create_order_at_connector(
&mut self,
state: &SessionState,
connector: &api::ConnectorData,
should_continue_payment: bool,
) -> RouterResult<Option<types::CreateOrderResult>> {
if connector
.connector_name
.requires_order_creation_before_payment(self.payment_method)
&& should_continue_payment
{
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::CreateOrder,
types::CreateOrderRequestData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
let request_data = types::CreateOrderRequestData::try_from(self.request.clone())?;
let response_data: Result<types::PaymentsResponseData, types::ErrorResponse> =
Err(types::ErrorResponse::default());
let createorder_router_data =
helpers::router_data_type_conversion::<_, api::CreateOrder, _, _, _, _>(
self.clone(),
request_data,
response_data,
);
let resp = services::execute_connector_processing_step(
state,
connector_integration,
&createorder_router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.to_payment_failed_response()?;
let create_order_resp = match resp.response {
Ok(res) => {
if let types::PaymentsResponseData::PaymentsCreateOrderResponse { order_id } =
res
{
Ok(order_id)
} else {
Err(error_stack::report!(ApiErrorResponse::InternalServerError)
.attach_printable(format!(
"Unexpected response format from connector: {res:?}",
)))?
}
}
Err(error) => Err(error),
};
Ok(Some(types::CreateOrderResult {
create_order_result: create_order_resp,
}))
} else {
// If the connector does not require order creation, return None
Ok(None)
}
}
fn update_router_data_with_create_order_response(
&mut self,
create_order_result: types::CreateOrderResult,
) {
match create_order_result.create_order_result {
Ok(order_id) => {
self.request.order_id = Some(order_id.clone()); // ? why this is assigned here and ucs also wants this to populate data
self.response =
Ok(types::PaymentsResponseData::PaymentsCreateOrderResponse { order_id });
}
Err(err) => {
self.response = Err(err.clone());
}
}
}
#[cfg(feature = "v2")]
async fn call_unified_connector_service_with_external_vault_proxy<'a>(
&mut self,
state: &SessionState,
header_payload: &domain_payments::HeaderPayload,
lineage_ids: grpc_client::LineageIds,
merchant_connector_account: domain::MerchantConnectorAccountTypeDetails,
external_vault_merchant_connector_account: domain::MerchantConnectorAccountTypeDetails,
merchant_context: &domain::MerchantContext,
unified_connector_service_execution_mode: enums::ExecutionMode,
) -> RouterResult<()> {
let client = state
.grpc_client
.unified_connector_service_client
.clone()
.ok_or(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to fetch Unified Connector Service client")?;
let payment_authorize_request =
payments_grpc::PaymentServiceAuthorizeRequest::foreign_try_from(&*self)
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to construct Payment Authorize Request")?;
let connector_auth_metadata =
unified_connector_service::build_unified_connector_service_auth_metadata(
merchant_connector_account,
merchant_context,
)
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to construct request metadata")?;
let external_vault_proxy_metadata =
unified_connector_service::build_unified_connector_service_external_vault_proxy_metadata(
external_vault_merchant_connector_account
)
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to construct external vault proxy metadata")?;
let merchant_order_reference_id = header_payload
.x_reference_id
.clone()
.map(|id| id_type::PaymentReferenceId::from_str(id.as_str()))
.transpose()
.inspect_err(|err| logger::warn!(error=?err, "Invalid Merchant ReferenceId found"))
.ok()
.flatten()
.map(ucs_types::UcsReferenceId::Payment);
let headers_builder = state
.get_grpc_headers_ucs(unified_connector_service_execution_mode)
.external_vault_proxy_metadata(Some(external_vault_proxy_metadata))
.merchant_reference_id(merchant_order_reference_id)
.lineage_ids(lineage_ids);
let updated_router_data = Box::pin(ucs_logging_wrapper(
self.clone(),
state,
payment_authorize_request.clone(),
headers_builder,
|mut router_data, payment_authorize_request, grpc_headers| async move {
let response = client
.payment_authorize(
payment_authorize_request,
connector_auth_metadata,
grpc_headers,
)
.await
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to authorize payment")?;
let payment_authorize_response = response.into_inner();
let (router_data_response, status_code) =
unified_connector_service::handle_unified_connector_service_response_for_payment_authorize(
payment_authorize_response.clone(),
)
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to deserialize UCS response")?;
let router_data_response = router_data_response.map(|(response, status)|{
router_data.status = status;
response
});
router_data.response = router_data_response;
router_data.raw_connector_response = payment_authorize_response
.raw_connector_response
.clone()
.map(masking::Secret::new);
router_data.connector_http_status_code = Some(status_code);
Ok((router_data, payment_authorize_response))
}
)).await?;
// Copy back the updated data
*self = updated_router_data;
Ok(())
}
}
|
crates/router/src/core/payments/flows/external_proxy_flow.rs
|
router::src::core::payments::flows::external_proxy_flow
| 3,164
| true
|
// File: crates/router/src/core/payments/flows/incremental_authorization_flow.rs
// Module: router::src::core::payments::flows::incremental_authorization_flow
use async_trait::async_trait;
use super::ConstructFlowSpecificData;
use crate::{
core::{
errors::{ConnectorErrorExt, RouterResult},
payments::{self, access_token, helpers, transformers, Feature, PaymentData},
},
routes::SessionState,
services,
types::{self, api, domain},
};
#[async_trait]
impl
ConstructFlowSpecificData<
api::IncrementalAuthorization,
types::PaymentsIncrementalAuthorizationData,
types::PaymentsResponseData,
> for PaymentData<api::IncrementalAuthorization>
{
#[cfg(feature = "v1")]
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
merchant_context: &domain::MerchantContext,
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
_payment_method: Option<common_enums::PaymentMethod>,
_payment_method_type: Option<common_enums::PaymentMethodType>,
) -> RouterResult<types::PaymentsIncrementalAuthorizationRouterData> {
Box::pin(transformers::construct_payment_router_data::<
api::IncrementalAuthorization,
types::PaymentsIncrementalAuthorizationData,
>(
state,
self.clone(),
connector_id,
merchant_context,
customer,
merchant_connector_account,
merchant_recipient_data,
header_payload,
None,
None,
))
.await
}
#[cfg(feature = "v2")]
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
merchant_context: &domain::MerchantContext,
customer: &Option<domain::Customer>,
merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
) -> RouterResult<types::PaymentsIncrementalAuthorizationRouterData> {
todo!()
}
}
#[async_trait]
impl Feature<api::IncrementalAuthorization, types::PaymentsIncrementalAuthorizationData>
for types::RouterData<
api::IncrementalAuthorization,
types::PaymentsIncrementalAuthorizationData,
types::PaymentsResponseData,
>
{
async fn decide_flows<'a>(
self,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
connector_request: Option<services::Request>,
_business_profile: &domain::Profile,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
_return_raw_connector_response: Option<bool>,
) -> RouterResult<Self> {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::IncrementalAuthorization,
types::PaymentsIncrementalAuthorizationData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
let resp = services::execute_connector_processing_step(
state,
connector_integration,
&self,
call_connector_action,
connector_request,
None,
)
.await
.to_payment_failed_response()?;
Ok(resp)
}
async fn add_access_token<'a>(
&self,
state: &SessionState,
connector: &api::ConnectorData,
merchant_context: &domain::MerchantContext,
creds_identifier: Option<&str>,
) -> RouterResult<types::AddAccessTokenResult> {
Box::pin(access_token::add_access_token(
state,
connector,
merchant_context,
self,
creds_identifier,
))
.await
}
async fn build_flow_specific_connector_request(
&mut self,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
) -> RouterResult<(Option<services::Request>, bool)> {
let request = match call_connector_action {
payments::CallConnectorAction::Trigger => {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::IncrementalAuthorization,
types::PaymentsIncrementalAuthorizationData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
connector_integration
.build_request(self, &state.conf.connectors)
.to_payment_failed_response()?
}
_ => None,
};
Ok((request, true))
}
}
|
crates/router/src/core/payments/flows/incremental_authorization_flow.rs
|
router::src::core::payments::flows::incremental_authorization_flow
| 1,010
| true
|
// File: crates/router/src/core/payments/flows/extend_authorization_flow.rs
// Module: router::src::core::payments::flows::extend_authorization_flow
use async_trait::async_trait;
use super::{ConstructFlowSpecificData, Feature};
use crate::{
core::{
errors::{ConnectorErrorExt, RouterResult},
payments::{self, access_token, helpers, transformers, PaymentData},
},
routes::{metrics, SessionState},
services,
types::{self, api, domain},
};
#[async_trait]
impl
ConstructFlowSpecificData<
api::ExtendAuthorization,
types::PaymentsExtendAuthorizationData,
types::PaymentsResponseData,
> for PaymentData<api::ExtendAuthorization>
{
#[cfg(feature = "v2")]
async fn construct_router_data<'a>(
&self,
_state: &SessionState,
_connector_id: &str,
_merchant_context: &domain::MerchantContext,
_customer: &Option<domain::Customer>,
_merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
_merchant_recipient_data: Option<types::MerchantRecipientData>,
_header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
) -> RouterResult<types::PaymentsExtendAuthorizationRouterData> {
todo!()
}
#[cfg(feature = "v1")]
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
merchant_context: &domain::MerchantContext,
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
_payment_method: Option<common_enums::PaymentMethod>,
_payment_method_type: Option<common_enums::PaymentMethodType>,
) -> RouterResult<types::PaymentsExtendAuthorizationRouterData> {
Box::pin(transformers::construct_payment_router_data::<
api::ExtendAuthorization,
types::PaymentsExtendAuthorizationData,
>(
state,
self.clone(),
connector_id,
merchant_context,
customer,
merchant_connector_account,
merchant_recipient_data,
header_payload,
None,
None,
))
.await
}
}
#[async_trait]
impl Feature<api::ExtendAuthorization, types::PaymentsExtendAuthorizationData>
for types::RouterData<
api::ExtendAuthorization,
types::PaymentsExtendAuthorizationData,
types::PaymentsResponseData,
>
{
async fn decide_flows<'a>(
self,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
connector_request: Option<services::Request>,
_business_profile: &domain::Profile,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
_return_raw_connector_response: Option<bool>,
) -> RouterResult<Self> {
metrics::PAYMENT_EXTEND_AUTHORIZATION_COUNT.add(
1,
router_env::metric_attributes!(("connector", connector.connector_name.to_string())),
);
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::ExtendAuthorization,
types::PaymentsExtendAuthorizationData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
let resp = services::execute_connector_processing_step(
state,
connector_integration,
&self,
call_connector_action,
connector_request,
None,
)
.await
.to_payment_failed_response()?;
Ok(resp)
}
async fn add_access_token<'a>(
&self,
state: &SessionState,
connector: &api::ConnectorData,
merchant_context: &domain::MerchantContext,
creds_identifier: Option<&str>,
) -> RouterResult<types::AddAccessTokenResult> {
Box::pin(access_token::add_access_token(
state,
connector,
merchant_context,
self,
creds_identifier,
))
.await
}
async fn build_flow_specific_connector_request(
&mut self,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
) -> RouterResult<(Option<services::Request>, bool)> {
let request = match call_connector_action {
payments::CallConnectorAction::Trigger => {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::ExtendAuthorization,
types::PaymentsExtendAuthorizationData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
connector_integration
.build_request(self, &state.conf.connectors)
.to_payment_failed_response()?
}
_ => None,
};
Ok((request, true))
}
}
|
crates/router/src/core/payments/flows/extend_authorization_flow.rs
|
router::src::core::payments::flows::extend_authorization_flow
| 1,036
| true
|
// File: crates/router/src/core/payments/flows/session_flow.rs
// Module: router::src::core::payments::flows::session_flow
use api_models::{admin as admin_types, payments as payment_types};
use async_trait::async_trait;
use common_utils::{
ext_traits::ByteSliceExt,
request::RequestContent,
types::{AmountConvertor, StringMajorUnitForConnector},
};
use error_stack::{Report, ResultExt};
#[cfg(feature = "v2")]
use hyperswitch_domain_models::payments::PaymentIntentData;
use masking::{ExposeInterface, ExposeOptionInterface};
use super::{ConstructFlowSpecificData, Feature};
use crate::{
consts::PROTOCOL,
core::{
errors::{self, ConnectorErrorExt, RouterResult},
payments::{self, access_token, customers, helpers, transformers, PaymentData},
},
headers, logger,
routes::{self, app::settings, metrics},
services,
types::{
self,
api::{self, enums},
domain,
},
utils::OptionExt,
};
#[cfg(feature = "v2")]
#[async_trait]
impl
ConstructFlowSpecificData<api::Session, types::PaymentsSessionData, types::PaymentsResponseData>
for PaymentIntentData<api::Session>
{
async fn construct_router_data<'a>(
&self,
state: &routes::SessionState,
connector_id: &str,
merchant_context: &domain::MerchantContext,
customer: &Option<domain::Customer>,
merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
) -> RouterResult<types::PaymentsSessionRouterData> {
Box::pin(transformers::construct_payment_router_data_for_sdk_session(
state,
self.clone(),
connector_id,
merchant_context,
customer,
merchant_connector_account,
merchant_recipient_data,
header_payload,
))
.await
}
}
#[cfg(feature = "v1")]
#[async_trait]
impl
ConstructFlowSpecificData<api::Session, types::PaymentsSessionData, types::PaymentsResponseData>
for PaymentData<api::Session>
{
async fn construct_router_data<'a>(
&self,
state: &routes::SessionState,
connector_id: &str,
merchant_context: &domain::MerchantContext,
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
payment_method: Option<common_enums::PaymentMethod>,
payment_method_type: Option<common_enums::PaymentMethodType>,
) -> RouterResult<types::PaymentsSessionRouterData> {
Box::pin(transformers::construct_payment_router_data::<
api::Session,
types::PaymentsSessionData,
>(
state,
self.clone(),
connector_id,
merchant_context,
customer,
merchant_connector_account,
merchant_recipient_data,
header_payload,
payment_method,
payment_method_type,
))
.await
}
}
#[async_trait]
impl Feature<api::Session, types::PaymentsSessionData> for types::PaymentsSessionRouterData {
async fn decide_flows<'a>(
self,
state: &routes::SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
_connector_request: Option<services::Request>,
business_profile: &domain::Profile,
header_payload: hyperswitch_domain_models::payments::HeaderPayload,
_return_raw_connector_response: Option<bool>,
) -> RouterResult<Self> {
metrics::SESSION_TOKEN_CREATED.add(
1,
router_env::metric_attributes!(("connector", connector.connector_name.to_string())),
);
self.decide_flow(
state,
connector,
Some(true),
call_connector_action,
business_profile,
header_payload,
)
.await
}
async fn add_access_token<'a>(
&self,
state: &routes::SessionState,
connector: &api::ConnectorData,
merchant_context: &domain::MerchantContext,
creds_identifier: Option<&str>,
) -> RouterResult<types::AddAccessTokenResult> {
Box::pin(access_token::add_access_token(
state,
connector,
merchant_context,
self,
creds_identifier,
))
.await
}
async fn create_connector_customer<'a>(
&self,
state: &routes::SessionState,
connector: &api::ConnectorData,
) -> RouterResult<Option<String>> {
customers::create_connector_customer(
state,
connector,
self,
types::ConnectorCustomerData::try_from(self)?,
)
.await
}
}
/// This function checks if for a given connector, payment_method and payment_method_type,
/// the list of required_field_type is present in dynamic fields
#[cfg(feature = "v1")]
fn is_dynamic_fields_required(
required_fields: &settings::RequiredFields,
payment_method: enums::PaymentMethod,
payment_method_type: enums::PaymentMethodType,
connector: types::Connector,
required_field_type: Vec<enums::FieldType>,
) -> bool {
required_fields
.0
.get(&payment_method)
.and_then(|pm_type| pm_type.0.get(&payment_method_type))
.and_then(|required_fields_for_connector| {
required_fields_for_connector.fields.get(&connector)
})
.map(|required_fields_final| {
required_fields_final
.non_mandate
.iter()
.any(|(_, val)| required_field_type.contains(&val.field_type))
|| required_fields_final
.mandate
.iter()
.any(|(_, val)| required_field_type.contains(&val.field_type))
|| required_fields_final
.common
.iter()
.any(|(_, val)| required_field_type.contains(&val.field_type))
})
.unwrap_or(false)
}
/// This function checks if for a given connector, payment_method and payment_method_type,
/// the list of required_field_type is present in dynamic fields
#[cfg(feature = "v2")]
fn is_dynamic_fields_required(
required_fields: &settings::RequiredFields,
payment_method: enums::PaymentMethod,
payment_method_type: enums::PaymentMethodType,
connector: types::Connector,
required_field_type: Vec<enums::FieldType>,
) -> bool {
required_fields
.0
.get(&payment_method)
.and_then(|pm_type| pm_type.0.get(&payment_method_type))
.and_then(|required_fields_for_connector| {
required_fields_for_connector.fields.get(&connector)
})
.map(|required_fields_final| {
required_fields_final
.non_mandate
.iter()
.flatten()
.any(|field_info| required_field_type.contains(&field_info.field_type))
|| required_fields_final
.mandate
.iter()
.flatten()
.any(|field_info| required_field_type.contains(&field_info.field_type))
|| required_fields_final
.common
.iter()
.flatten()
.any(|field_info| required_field_type.contains(&field_info.field_type))
})
.unwrap_or(false)
}
fn build_apple_pay_session_request(
state: &routes::SessionState,
request: payment_types::ApplepaySessionRequest,
apple_pay_merchant_cert: masking::Secret<String>,
apple_pay_merchant_cert_key: masking::Secret<String>,
) -> RouterResult<services::Request> {
let mut url = state.conf.connectors.applepay.base_url.to_owned();
url.push_str("paymentservices/paymentSession");
let session_request = services::RequestBuilder::new()
.method(services::Method::Post)
.url(url.as_str())
.attach_default_headers()
.headers(vec![(
headers::CONTENT_TYPE.to_string(),
"application/json".to_string().into(),
)])
.set_body(RequestContent::Json(Box::new(request)))
.add_certificate(Some(apple_pay_merchant_cert))
.add_certificate_key(Some(apple_pay_merchant_cert_key))
.build();
Ok(session_request)
}
async fn create_applepay_session_token(
state: &routes::SessionState,
router_data: &types::PaymentsSessionRouterData,
connector: &api::ConnectorData,
business_profile: &domain::Profile,
header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<types::PaymentsSessionRouterData> {
let delayed_response = is_session_response_delayed(state, connector);
if delayed_response {
let delayed_response_apple_pay_session =
Some(payment_types::ApplePaySessionResponse::NoSessionResponse(
api_models::payments::NullObject,
));
create_apple_pay_session_response(
router_data,
delayed_response_apple_pay_session,
None, // Apple pay payment request will be none for delayed session response
connector.connector_name.to_string(),
delayed_response,
payment_types::NextActionCall::Confirm,
header_payload,
)
} else {
// Get the apple pay metadata
let apple_pay_metadata =
helpers::get_applepay_metadata(router_data.connector_meta_data.clone())
.attach_printable(
"Failed to to fetch apple pay certificates during session call",
)?;
// Get payment request data , apple pay session request and merchant keys
let (
payment_request_data,
apple_pay_session_request_optional,
apple_pay_merchant_cert,
apple_pay_merchant_cert_key,
apple_pay_merchant_identifier,
merchant_business_country,
merchant_configured_domain_optional,
) = match apple_pay_metadata {
payment_types::ApplepaySessionTokenMetadata::ApplePayCombined(
apple_pay_combined_metadata,
) => match apple_pay_combined_metadata {
payment_types::ApplePayCombinedMetadata::Simplified {
payment_request_data,
session_token_data,
} => {
logger::info!("Apple pay simplified flow");
let merchant_identifier = state
.conf
.applepay_merchant_configs
.get_inner()
.common_merchant_identifier
.clone()
.expose();
let merchant_business_country = session_token_data.merchant_business_country;
let apple_pay_session_request = get_session_request_for_simplified_apple_pay(
merchant_identifier.clone(),
session_token_data.clone(),
);
let apple_pay_merchant_cert = state
.conf
.applepay_decrypt_keys
.get_inner()
.apple_pay_merchant_cert
.clone();
let apple_pay_merchant_cert_key = state
.conf
.applepay_decrypt_keys
.get_inner()
.apple_pay_merchant_cert_key
.clone();
(
payment_request_data,
Ok(apple_pay_session_request),
apple_pay_merchant_cert,
apple_pay_merchant_cert_key,
merchant_identifier,
merchant_business_country,
Some(session_token_data.initiative_context),
)
}
payment_types::ApplePayCombinedMetadata::Manual {
payment_request_data,
session_token_data,
} => {
logger::info!("Apple pay manual flow");
let apple_pay_session_request = get_session_request_for_manual_apple_pay(
session_token_data.clone(),
header_payload.x_merchant_domain.clone(),
);
let merchant_business_country = session_token_data.merchant_business_country;
(
payment_request_data,
apple_pay_session_request,
session_token_data.certificate.clone(),
session_token_data.certificate_keys,
session_token_data.merchant_identifier,
merchant_business_country,
session_token_data.initiative_context,
)
}
},
payment_types::ApplepaySessionTokenMetadata::ApplePay(apple_pay_metadata) => {
logger::info!("Apple pay manual flow");
let apple_pay_session_request = get_session_request_for_manual_apple_pay(
apple_pay_metadata.session_token_data.clone(),
header_payload.x_merchant_domain.clone(),
);
let merchant_business_country = apple_pay_metadata
.session_token_data
.merchant_business_country;
(
apple_pay_metadata.payment_request_data,
apple_pay_session_request,
apple_pay_metadata.session_token_data.certificate.clone(),
apple_pay_metadata
.session_token_data
.certificate_keys
.clone(),
apple_pay_metadata.session_token_data.merchant_identifier,
merchant_business_country,
apple_pay_metadata.session_token_data.initiative_context,
)
}
};
// Get amount info for apple pay
let amount_info = get_apple_pay_amount_info(
payment_request_data.label.as_str(),
router_data.request.to_owned(),
)?;
let required_billing_contact_fields = if business_profile
.always_collect_billing_details_from_wallet_connector
.unwrap_or(false)
{
Some(payment_types::ApplePayBillingContactFields(vec![
payment_types::ApplePayAddressParameters::PostalAddress,
]))
} else if business_profile
.collect_billing_details_from_wallet_connector
.unwrap_or(false)
{
let billing_variants = enums::FieldType::get_billing_variants();
is_dynamic_fields_required(
&state.conf.required_fields,
enums::PaymentMethod::Wallet,
enums::PaymentMethodType::ApplePay,
connector.connector_name,
billing_variants,
)
.then_some(payment_types::ApplePayBillingContactFields(vec![
payment_types::ApplePayAddressParameters::PostalAddress,
]))
} else {
None
};
let required_shipping_contact_fields = if business_profile
.always_collect_shipping_details_from_wallet_connector
.unwrap_or(false)
{
Some(payment_types::ApplePayShippingContactFields(vec![
payment_types::ApplePayAddressParameters::PostalAddress,
payment_types::ApplePayAddressParameters::Phone,
payment_types::ApplePayAddressParameters::Email,
]))
} else if business_profile
.collect_shipping_details_from_wallet_connector
.unwrap_or(false)
{
let shipping_variants = enums::FieldType::get_shipping_variants();
is_dynamic_fields_required(
&state.conf.required_fields,
enums::PaymentMethod::Wallet,
enums::PaymentMethodType::ApplePay,
connector.connector_name,
shipping_variants,
)
.then_some(payment_types::ApplePayShippingContactFields(vec![
payment_types::ApplePayAddressParameters::PostalAddress,
payment_types::ApplePayAddressParameters::Phone,
payment_types::ApplePayAddressParameters::Email,
]))
} else {
None
};
// If collect_shipping_details_from_wallet_connector is false, we check if
// collect_billing_details_from_wallet_connector is true. If it is, then we pass the Email and Phone in
// ApplePayShippingContactFields as it is a required parameter and ApplePayBillingContactFields
// does not contain Email and Phone.
let required_shipping_contact_fields_updated = if required_billing_contact_fields.is_some()
&& required_shipping_contact_fields.is_none()
{
Some(payment_types::ApplePayShippingContactFields(vec![
payment_types::ApplePayAddressParameters::Phone,
payment_types::ApplePayAddressParameters::Email,
]))
} else {
required_shipping_contact_fields
};
// Get apple pay payment request
let applepay_payment_request = get_apple_pay_payment_request(
amount_info,
payment_request_data,
router_data.request.to_owned(),
apple_pay_merchant_identifier.as_str(),
merchant_business_country,
required_billing_contact_fields,
required_shipping_contact_fields_updated,
)?;
let apple_pay_session_response = match (
header_payload.browser_name.clone(),
header_payload.x_client_platform.clone(),
) {
(Some(common_enums::BrowserName::Safari), Some(common_enums::ClientPlatform::Web))
| (None, None) => {
let apple_pay_session_request = apple_pay_session_request_optional
.attach_printable("Failed to obtain apple pay session request")?;
let applepay_session_request = build_apple_pay_session_request(
state,
apple_pay_session_request.clone(),
apple_pay_merchant_cert.clone(),
apple_pay_merchant_cert_key.clone(),
)?;
let response = services::call_connector_api(
state,
applepay_session_request,
"create_apple_pay_session_token",
)
.await;
let updated_response = match (
response.as_ref().ok(),
header_payload.x_merchant_domain.clone(),
) {
(Some(Err(error)), Some(_)) => {
logger::error!(
"Retry apple pay session call with the merchant configured domain {error:?}"
);
let merchant_configured_domain = merchant_configured_domain_optional
.get_required_value("apple pay domain")
.attach_printable("Failed to get domain for apple pay session call")?;
let apple_pay_retry_session_request =
payment_types::ApplepaySessionRequest {
initiative_context: merchant_configured_domain,
..apple_pay_session_request
};
let applepay_retry_session_request = build_apple_pay_session_request(
state,
apple_pay_retry_session_request,
apple_pay_merchant_cert,
apple_pay_merchant_cert_key,
)?;
services::call_connector_api(
state,
applepay_retry_session_request,
"create_apple_pay_session_token",
)
.await
}
_ => response,
};
// logging the error if present in session call response
log_session_response_if_error(&updated_response);
updated_response
.ok()
.and_then(|apple_pay_res| {
apple_pay_res
.map(|res| {
let response: Result<
payment_types::NoThirdPartySdkSessionResponse,
Report<common_utils::errors::ParsingError>,
> = res.response.parse_struct("NoThirdPartySdkSessionResponse");
// logging the parsing failed error
if let Err(error) = response.as_ref() {
logger::error!(?error);
};
response.ok()
})
.ok()
})
.flatten()
}
_ => {
logger::debug!("Skipping apple pay session call based on the browser name");
None
}
};
let session_response =
apple_pay_session_response.map(payment_types::ApplePaySessionResponse::NoThirdPartySdk);
create_apple_pay_session_response(
router_data,
session_response,
Some(applepay_payment_request),
connector.connector_name.to_string(),
delayed_response,
payment_types::NextActionCall::Confirm,
header_payload,
)
}
}
fn create_paze_session_token(
router_data: &types::PaymentsSessionRouterData,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<types::PaymentsSessionRouterData> {
let paze_wallet_details = router_data
.connector_wallets_details
.clone()
.parse_value::<payment_types::PazeSessionTokenData>("PazeSessionTokenData")
.change_context(errors::ConnectorError::NoConnectorWalletDetails)
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "connector_wallets_details".to_string(),
expected_format: "paze_metadata_format".to_string(),
})?;
let required_amount_type = StringMajorUnitForConnector;
let transaction_currency_code = router_data.request.currency;
let transaction_amount = required_amount_type
.convert(router_data.request.minor_amount, transaction_currency_code)
.change_context(errors::ApiErrorResponse::PreconditionFailed {
message: "Failed to convert amount to string major unit for paze".to_string(),
})?;
Ok(types::PaymentsSessionRouterData {
response: Ok(types::PaymentsResponseData::SessionResponse {
session_token: payment_types::SessionToken::Paze(Box::new(
payment_types::PazeSessionTokenResponse {
client_id: paze_wallet_details.data.client_id,
client_name: paze_wallet_details.data.client_name,
client_profile_id: paze_wallet_details.data.client_profile_id,
transaction_currency_code,
transaction_amount,
email_address: router_data.request.email.clone(),
},
)),
}),
..router_data.clone()
})
}
fn create_samsung_pay_session_token(
state: &routes::SessionState,
router_data: &types::PaymentsSessionRouterData,
header_payload: hyperswitch_domain_models::payments::HeaderPayload,
connector: &api::ConnectorData,
business_profile: &domain::Profile,
) -> RouterResult<types::PaymentsSessionRouterData> {
let samsung_pay_session_token_data = router_data
.connector_wallets_details
.clone()
.parse_value::<payment_types::SamsungPaySessionTokenData>("SamsungPaySessionTokenData")
.change_context(errors::ConnectorError::NoConnectorWalletDetails)
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "connector_wallets_details".to_string(),
expected_format: "samsung_pay_metadata_format".to_string(),
})?;
let required_amount_type = StringMajorUnitForConnector;
let samsung_pay_amount = required_amount_type
.convert(
router_data.request.minor_amount,
router_data.request.currency,
)
.change_context(errors::ApiErrorResponse::PreconditionFailed {
message: "Failed to convert amount to string major unit for Samsung Pay".to_string(),
})?;
let merchant_domain = match header_payload.x_client_platform {
Some(common_enums::ClientPlatform::Web) => Some(
header_payload
.x_merchant_domain
.get_required_value("samsung pay domain")
.attach_printable("Failed to get domain for samsung pay session call")?,
),
_ => None,
};
let samsung_pay_wallet_details = match samsung_pay_session_token_data.data {
payment_types::SamsungPayCombinedMetadata::MerchantCredentials(
samsung_pay_merchant_credentials,
) => samsung_pay_merchant_credentials,
payment_types::SamsungPayCombinedMetadata::ApplicationCredentials(
_samsung_pay_application_credentials,
) => Err(errors::ApiErrorResponse::NotSupported {
message: "Samsung Pay decryption flow with application credentials is not implemented"
.to_owned(),
})?,
};
let formatted_payment_id = router_data.payment_id.replace("_", "-");
let billing_address_required = is_billing_address_required_to_be_collected_from_wallet(
state,
connector,
business_profile,
enums::PaymentMethodType::SamsungPay,
);
let shipping_address_required = is_shipping_address_required_to_be_collected_form_wallet(
state,
connector,
business_profile,
enums::PaymentMethodType::SamsungPay,
);
Ok(types::PaymentsSessionRouterData {
response: Ok(types::PaymentsResponseData::SessionResponse {
session_token: payment_types::SessionToken::SamsungPay(Box::new(
payment_types::SamsungPaySessionTokenResponse {
version: "2".to_string(),
service_id: samsung_pay_wallet_details.service_id,
order_number: formatted_payment_id,
merchant_payment_information:
payment_types::SamsungPayMerchantPaymentInformation {
name: samsung_pay_wallet_details.merchant_display_name,
url: merchant_domain,
country_code: samsung_pay_wallet_details.merchant_business_country,
},
amount: payment_types::SamsungPayAmountDetails {
amount_format: payment_types::SamsungPayAmountFormat::FormatTotalPriceOnly,
currency_code: router_data.request.currency,
total_amount: samsung_pay_amount,
},
protocol: payment_types::SamsungPayProtocolType::Protocol3ds,
allowed_brands: samsung_pay_wallet_details.allowed_brands,
billing_address_required,
shipping_address_required,
},
)),
}),
..router_data.clone()
})
}
/// Function to determine whether the billing address is required to be collected from the wallet,
/// based on business profile settings, the payment method type, and the connector's required fields
/// for the specific payment method.
///
/// If `always_collect_billing_details_from_wallet_connector` is enabled, it indicates that the
/// billing address is always required to be collected from the wallet.
///
/// If only `collect_billing_details_from_wallet_connector` is enabled, the billing address will be
/// collected only if the connector required fields for the specific payment method type contain
/// the billing fields.
fn is_billing_address_required_to_be_collected_from_wallet(
state: &routes::SessionState,
connector: &api::ConnectorData,
business_profile: &domain::Profile,
payment_method_type: enums::PaymentMethodType,
) -> bool {
let always_collect_billing_details_from_wallet_connector = business_profile
.always_collect_billing_details_from_wallet_connector
.unwrap_or(false);
if always_collect_billing_details_from_wallet_connector {
always_collect_billing_details_from_wallet_connector
} else if business_profile
.collect_billing_details_from_wallet_connector
.unwrap_or(false)
{
let billing_variants = enums::FieldType::get_billing_variants();
is_dynamic_fields_required(
&state.conf.required_fields,
enums::PaymentMethod::Wallet,
payment_method_type,
connector.connector_name,
billing_variants,
)
} else {
false
}
}
/// Function to determine whether the shipping address is required to be collected from the wallet,
/// based on business profile settings, the payment method type, and the connector required fields
/// for the specific payment method type.
///
/// If `always_collect_shipping_details_from_wallet_connector` is enabled, it indicates that the
/// shipping address is always required to be collected from the wallet.
///
/// If only `collect_shipping_details_from_wallet_connector` is enabled, the shipping address will be
/// collected only if the connector required fields for the specific payment method type contain
/// the shipping fields.
fn is_shipping_address_required_to_be_collected_form_wallet(
state: &routes::SessionState,
connector: &api::ConnectorData,
business_profile: &domain::Profile,
payment_method_type: enums::PaymentMethodType,
) -> bool {
let always_collect_shipping_details_from_wallet_connector = business_profile
.always_collect_shipping_details_from_wallet_connector
.unwrap_or(false);
if always_collect_shipping_details_from_wallet_connector {
always_collect_shipping_details_from_wallet_connector
} else if business_profile
.collect_shipping_details_from_wallet_connector
.unwrap_or(false)
{
let shipping_variants = enums::FieldType::get_shipping_variants();
is_dynamic_fields_required(
&state.conf.required_fields,
enums::PaymentMethod::Wallet,
payment_method_type,
connector.connector_name,
shipping_variants,
)
} else {
false
}
}
fn get_session_request_for_simplified_apple_pay(
apple_pay_merchant_identifier: String,
session_token_data: payment_types::SessionTokenForSimplifiedApplePay,
) -> payment_types::ApplepaySessionRequest {
payment_types::ApplepaySessionRequest {
merchant_identifier: apple_pay_merchant_identifier,
display_name: "Apple pay".to_string(),
initiative: "web".to_string(),
initiative_context: session_token_data.initiative_context,
}
}
fn get_session_request_for_manual_apple_pay(
session_token_data: payment_types::SessionTokenInfo,
merchant_domain: Option<String>,
) -> RouterResult<payment_types::ApplepaySessionRequest> {
let initiative_context = merchant_domain
.or_else(|| session_token_data.initiative_context.clone())
.get_required_value("apple pay domain")
.attach_printable("Failed to get domain for apple pay session call")?;
Ok(payment_types::ApplepaySessionRequest {
merchant_identifier: session_token_data.merchant_identifier.clone(),
display_name: session_token_data.display_name.clone(),
initiative: session_token_data.initiative.to_string(),
initiative_context,
})
}
fn get_apple_pay_amount_info(
label: &str,
session_data: types::PaymentsSessionData,
) -> RouterResult<payment_types::AmountInfo> {
let required_amount_type = StringMajorUnitForConnector;
let apple_pay_amount = required_amount_type
.convert(session_data.minor_amount, session_data.currency)
.change_context(errors::ApiErrorResponse::PreconditionFailed {
message: "Failed to convert amount to string major unit for applePay".to_string(),
})?;
let amount_info = payment_types::AmountInfo {
label: label.to_string(),
total_type: Some("final".to_string()),
amount: apple_pay_amount,
};
Ok(amount_info)
}
fn get_apple_pay_payment_request(
amount_info: payment_types::AmountInfo,
payment_request_data: payment_types::PaymentRequestMetadata,
session_data: types::PaymentsSessionData,
merchant_identifier: &str,
merchant_business_country: Option<api_models::enums::CountryAlpha2>,
required_billing_contact_fields: Option<payment_types::ApplePayBillingContactFields>,
required_shipping_contact_fields: Option<payment_types::ApplePayShippingContactFields>,
) -> RouterResult<payment_types::ApplePayPaymentRequest> {
let applepay_payment_request = payment_types::ApplePayPaymentRequest {
country_code: merchant_business_country.or(session_data.country).ok_or(
errors::ApiErrorResponse::MissingRequiredField {
field_name: "country_code",
},
)?,
currency_code: session_data.currency,
total: amount_info,
merchant_capabilities: Some(payment_request_data.merchant_capabilities),
supported_networks: Some(payment_request_data.supported_networks),
merchant_identifier: Some(merchant_identifier.to_string()),
required_billing_contact_fields,
required_shipping_contact_fields,
recurring_payment_request: session_data.apple_pay_recurring_details,
};
Ok(applepay_payment_request)
}
fn create_apple_pay_session_response(
router_data: &types::PaymentsSessionRouterData,
session_response: Option<payment_types::ApplePaySessionResponse>,
apple_pay_payment_request: Option<payment_types::ApplePayPaymentRequest>,
connector_name: String,
delayed_response: bool,
next_action: payment_types::NextActionCall,
header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<types::PaymentsSessionRouterData> {
match session_response {
Some(response) => Ok(types::PaymentsSessionRouterData {
response: Ok(types::PaymentsResponseData::SessionResponse {
session_token: payment_types::SessionToken::ApplePay(Box::new(
payment_types::ApplepaySessionTokenResponse {
session_token_data: Some(response),
payment_request_data: apple_pay_payment_request,
connector: connector_name,
delayed_session_token: delayed_response,
sdk_next_action: { payment_types::SdkNextAction { next_action } },
connector_reference_id: None,
connector_sdk_public_key: None,
connector_merchant_id: None,
},
)),
}),
..router_data.clone()
}),
None => {
match (
header_payload.browser_name,
header_payload.x_client_platform,
) {
(
Some(common_enums::BrowserName::Safari),
Some(common_enums::ClientPlatform::Web),
)
| (None, None) => Ok(types::PaymentsSessionRouterData {
response: Ok(types::PaymentsResponseData::SessionResponse {
session_token: payment_types::SessionToken::NoSessionTokenReceived,
}),
..router_data.clone()
}),
_ => Ok(types::PaymentsSessionRouterData {
response: Ok(types::PaymentsResponseData::SessionResponse {
session_token: payment_types::SessionToken::ApplePay(Box::new(
payment_types::ApplepaySessionTokenResponse {
session_token_data: None,
payment_request_data: apple_pay_payment_request,
connector: connector_name,
delayed_session_token: delayed_response,
sdk_next_action: { payment_types::SdkNextAction { next_action } },
connector_reference_id: None,
connector_sdk_public_key: None,
connector_merchant_id: None,
},
)),
}),
..router_data.clone()
}),
}
}
}
}
fn create_gpay_session_token(
state: &routes::SessionState,
router_data: &types::PaymentsSessionRouterData,
connector: &api::ConnectorData,
business_profile: &domain::Profile,
) -> RouterResult<types::PaymentsSessionRouterData> {
// connector_wallet_details is being parse into admin types to check specifically if google_pay field is present
// this is being done because apple_pay details from metadata is also being filled into connector_wallets_details
let google_pay_wallets_details = router_data
.connector_wallets_details
.clone()
.parse_value::<admin_types::ConnectorWalletDetails>("ConnectorWalletDetails")
.change_context(errors::ConnectorError::NoConnectorWalletDetails)
.attach_printable(format!(
"cannot parse connector_wallets_details from the given value {:?}",
router_data.connector_wallets_details
))
.map_err(|err| {
logger::debug!(
"Failed to parse connector_wallets_details for google_pay flow: {:?}",
err
);
})
.ok()
.and_then(|connector_wallets_details| connector_wallets_details.google_pay);
let connector_metadata = router_data.connector_meta_data.clone();
let delayed_response = is_session_response_delayed(state, connector);
if delayed_response {
Ok(types::PaymentsSessionRouterData {
response: Ok(types::PaymentsResponseData::SessionResponse {
session_token: payment_types::SessionToken::GooglePay(Box::new(
payment_types::GpaySessionTokenResponse::ThirdPartyResponse(
payment_types::GooglePayThirdPartySdk {
delayed_session_token: true,
connector: connector.connector_name.to_string(),
sdk_next_action: payment_types::SdkNextAction {
next_action: payment_types::NextActionCall::Confirm,
},
},
),
)),
}),
..router_data.clone()
})
} else {
let is_billing_details_required = is_billing_address_required_to_be_collected_from_wallet(
state,
connector,
business_profile,
enums::PaymentMethodType::GooglePay,
);
let required_amount_type = StringMajorUnitForConnector;
let google_pay_amount = required_amount_type
.convert(
router_data.request.minor_amount,
router_data.request.currency,
)
.change_context(errors::ApiErrorResponse::PreconditionFailed {
message: "Failed to convert amount to string major unit for googlePay".to_string(),
})?;
let session_data = router_data.request.clone();
let transaction_info = payment_types::GpayTransactionInfo {
country_code: session_data.country.unwrap_or_default(),
currency_code: router_data.request.currency,
total_price_status: "Final".to_string(),
total_price: google_pay_amount,
};
let required_shipping_contact_fields =
is_shipping_address_required_to_be_collected_form_wallet(
state,
connector,
business_profile,
enums::PaymentMethodType::GooglePay,
);
if google_pay_wallets_details.is_some() {
let gpay_data = router_data
.connector_wallets_details
.clone()
.parse_value::<payment_types::GooglePayWalletDetails>("GooglePayWalletDetails")
.change_context(errors::ConnectorError::NoConnectorWalletDetails)
.attach_printable(format!(
"cannot parse gpay connector_wallets_details from the given value {:?}",
router_data.connector_wallets_details
))
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "connector_wallets_details".to_string(),
expected_format: "gpay_connector_wallets_details_format".to_string(),
})?;
let payment_types::GooglePayProviderDetails::GooglePayMerchantDetails(gpay_info) =
gpay_data.google_pay.provider_details.clone();
let gpay_allowed_payment_methods = get_allowed_payment_methods_from_cards(
gpay_data,
&gpay_info.merchant_info.tokenization_specification,
is_billing_details_required,
)?;
Ok(types::PaymentsSessionRouterData {
response: Ok(types::PaymentsResponseData::SessionResponse {
session_token: payment_types::SessionToken::GooglePay(Box::new(
payment_types::GpaySessionTokenResponse::GooglePaySession(
payment_types::GooglePaySessionResponse {
merchant_info: payment_types::GpayMerchantInfo {
merchant_name: gpay_info.merchant_info.merchant_name,
merchant_id: gpay_info.merchant_info.merchant_id,
},
allowed_payment_methods: vec![gpay_allowed_payment_methods],
transaction_info,
connector: connector.connector_name.to_string(),
sdk_next_action: payment_types::SdkNextAction {
next_action: payment_types::NextActionCall::Confirm,
},
delayed_session_token: false,
secrets: None,
shipping_address_required: required_shipping_contact_fields,
// We pass Email as a required field irrespective of
// collect_billing_details_from_wallet_connector or
// collect_shipping_details_from_wallet_connector as it is common to both.
email_required: required_shipping_contact_fields
|| is_billing_details_required,
shipping_address_parameters:
api_models::payments::GpayShippingAddressParameters {
phone_number_required: required_shipping_contact_fields,
},
},
),
)),
}),
..router_data.clone()
})
} else {
let billing_address_parameters = is_billing_details_required.then_some(
payment_types::GpayBillingAddressParameters {
phone_number_required: is_billing_details_required,
format: payment_types::GpayBillingAddressFormat::FULL,
},
);
let gpay_data = connector_metadata
.clone()
.parse_value::<payment_types::GpaySessionTokenData>("GpaySessionTokenData")
.change_context(errors::ConnectorError::NoConnectorMetaData)
.attach_printable(format!(
"cannot parse gpay metadata from the given value {connector_metadata:?}"
))
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "connector_metadata".to_string(),
expected_format: "gpay_metadata_format".to_string(),
})?;
let gpay_allowed_payment_methods = gpay_data
.data
.allowed_payment_methods
.into_iter()
.map(
|allowed_payment_methods| payment_types::GpayAllowedPaymentMethods {
parameters: payment_types::GpayAllowedMethodsParameters {
billing_address_required: Some(is_billing_details_required),
billing_address_parameters: billing_address_parameters.clone(),
..allowed_payment_methods.parameters
},
..allowed_payment_methods
},
)
.collect();
Ok(types::PaymentsSessionRouterData {
response: Ok(types::PaymentsResponseData::SessionResponse {
session_token: payment_types::SessionToken::GooglePay(Box::new(
payment_types::GpaySessionTokenResponse::GooglePaySession(
payment_types::GooglePaySessionResponse {
merchant_info: gpay_data.data.merchant_info,
allowed_payment_methods: gpay_allowed_payment_methods,
transaction_info,
connector: connector.connector_name.to_string(),
sdk_next_action: payment_types::SdkNextAction {
next_action: payment_types::NextActionCall::Confirm,
},
delayed_session_token: false,
secrets: None,
shipping_address_required: required_shipping_contact_fields,
// We pass Email as a required field irrespective of
// collect_billing_details_from_wallet_connector or
// collect_shipping_details_from_wallet_connector as it is common to both.
email_required: required_shipping_contact_fields
|| is_billing_details_required,
shipping_address_parameters:
api_models::payments::GpayShippingAddressParameters {
phone_number_required: required_shipping_contact_fields,
},
},
),
)),
}),
..router_data.clone()
})
}
}
}
/// Card Type for Google Pay Allowerd Payment Methods
pub(crate) const CARD: &str = "CARD";
fn get_allowed_payment_methods_from_cards(
gpay_info: payment_types::GooglePayWalletDetails,
gpay_token_specific_data: &payment_types::GooglePayTokenizationSpecification,
is_billing_details_required: bool,
) -> RouterResult<payment_types::GpayAllowedPaymentMethods> {
let billing_address_parameters =
is_billing_details_required.then_some(payment_types::GpayBillingAddressParameters {
phone_number_required: is_billing_details_required,
format: payment_types::GpayBillingAddressFormat::FULL,
});
let protocol_version: Option<String> = gpay_token_specific_data
.parameters
.public_key
.as_ref()
.map(|_| PROTOCOL.to_string());
Ok(payment_types::GpayAllowedPaymentMethods {
parameters: payment_types::GpayAllowedMethodsParameters {
billing_address_required: Some(is_billing_details_required),
billing_address_parameters: billing_address_parameters.clone(),
..gpay_info.google_pay.cards
},
payment_method_type: CARD.to_string(),
tokenization_specification: payment_types::GpayTokenizationSpecification {
token_specification_type: gpay_token_specific_data.tokenization_type.to_string(),
parameters: payment_types::GpayTokenParameters {
protocol_version,
public_key: gpay_token_specific_data.parameters.public_key.clone(),
gateway: gpay_token_specific_data.parameters.gateway.clone(),
gateway_merchant_id: gpay_token_specific_data
.parameters
.gateway_merchant_id
.clone()
.expose_option(),
stripe_publishable_key: gpay_token_specific_data
.parameters
.stripe_publishable_key
.clone()
.expose_option(),
stripe_version: gpay_token_specific_data
.parameters
.stripe_version
.clone()
.expose_option(),
},
},
})
}
fn is_session_response_delayed(
state: &routes::SessionState,
connector: &api::ConnectorData,
) -> bool {
let connectors_with_delayed_response = &state
.conf
.delayed_session_response
.connectors_with_delayed_session_response;
connectors_with_delayed_response.contains(&connector.connector_name)
}
fn log_session_response_if_error(
response: &Result<Result<types::Response, types::Response>, Report<errors::ApiClientError>>,
) {
if let Err(error) = response.as_ref() {
logger::error!(?error);
};
response
.as_ref()
.ok()
.map(|res| res.as_ref().map_err(|error| logger::error!(?error)));
}
#[async_trait]
pub trait RouterDataSession
where
Self: Sized,
{
async fn decide_flow<'a, 'b>(
&'b self,
state: &'a routes::SessionState,
connector: &api::ConnectorData,
_confirm: Option<bool>,
call_connector_action: payments::CallConnectorAction,
business_profile: &domain::Profile,
header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<Self>;
}
fn create_paypal_sdk_session_token(
_state: &routes::SessionState,
router_data: &types::PaymentsSessionRouterData,
connector: &api::ConnectorData,
_business_profile: &domain::Profile,
) -> RouterResult<types::PaymentsSessionRouterData> {
let connector_metadata = router_data.connector_meta_data.clone();
let paypal_sdk_data = connector_metadata
.clone()
.parse_value::<payment_types::PaypalSdkSessionTokenData>("PaypalSdkSessionTokenData")
.change_context(errors::ConnectorError::NoConnectorMetaData)
.attach_printable(format!(
"cannot parse paypal_sdk metadata from the given value {connector_metadata:?}"
))
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "connector_metadata".to_string(),
expected_format: "paypal_sdk_metadata_format".to_string(),
})?;
Ok(types::PaymentsSessionRouterData {
response: Ok(types::PaymentsResponseData::SessionResponse {
session_token: payment_types::SessionToken::Paypal(Box::new(
payment_types::PaypalSessionTokenResponse {
connector: connector.connector_name.to_string(),
session_token: paypal_sdk_data.data.client_id,
sdk_next_action: payment_types::SdkNextAction {
next_action: payment_types::NextActionCall::PostSessionTokens,
},
client_token: None,
transaction_info: None,
},
)),
}),
..router_data.clone()
})
}
async fn create_amazon_pay_session_token(
router_data: &types::PaymentsSessionRouterData,
state: &routes::SessionState,
) -> RouterResult<types::PaymentsSessionRouterData> {
let amazon_pay_session_token_data = router_data
.connector_wallets_details
.clone()
.parse_value::<payment_types::AmazonPaySessionTokenData>("AmazonPaySessionTokenData")
.change_context(errors::ApiErrorResponse::MissingRequiredField {
field_name: "merchant_id or store_id",
})?;
let amazon_pay_metadata = amazon_pay_session_token_data.data;
let merchant_id = amazon_pay_metadata.merchant_id;
let store_id = amazon_pay_metadata.store_id;
let amazonpay_supported_currencies =
payments::cards::list_countries_currencies_for_connector_payment_method_util(
state.conf.pm_filters.clone(),
enums::Connector::Amazonpay,
enums::PaymentMethodType::AmazonPay,
)
.await
.currencies;
// currently supports only the US region hence USD is the only supported currency
payment_types::AmazonPayDeliveryOptions::validate_currency(
router_data.request.currency,
amazonpay_supported_currencies.clone(),
)
.change_context(errors::ApiErrorResponse::CurrencyNotSupported {
message: "USD is the only supported currency.".to_string(),
})?;
let ledger_currency = router_data.request.currency;
// currently supports only the 'automatic' capture_method
let payment_intent = payment_types::AmazonPayPaymentIntent::AuthorizeWithCapture;
let required_amount_type = StringMajorUnitForConnector;
let total_tax_amount = required_amount_type
.convert(
router_data.request.order_tax_amount.unwrap_or_default(),
router_data.request.currency,
)
.change_context(errors::ApiErrorResponse::AmountConversionFailed {
amount_type: "StringMajorUnit",
})?;
let total_base_amount = required_amount_type
.convert(
router_data.request.minor_amount,
router_data.request.currency,
)
.change_context(errors::ApiErrorResponse::AmountConversionFailed {
amount_type: "StringMajorUnit",
})?;
let delivery_options_request = router_data
.request
.metadata
.clone()
.and_then(|metadata| {
metadata
.expose()
.get("delivery_options")
.and_then(|value| value.as_array().cloned())
})
.ok_or(errors::ApiErrorResponse::MissingRequiredField {
field_name: "metadata.delivery_options",
})?;
let mut delivery_options =
payment_types::AmazonPayDeliveryOptions::parse_delivery_options_request(
&delivery_options_request,
)
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "delivery_options".to_string(),
expected_format: r#""delivery_options": [{"id": String, "price": {"amount": Number, "currency_code": String}, "shipping_method":{"shipping_method_name": String, "shipping_method_code": String}, "is_default": Boolean}]"#.to_string(),
})?;
let default_amount = payment_types::AmazonPayDeliveryOptions::get_default_delivery_amount(
delivery_options.clone(),
)
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "is_default",
})?;
for option in &delivery_options {
payment_types::AmazonPayDeliveryOptions::validate_currency(
option.price.currency_code,
amazonpay_supported_currencies.clone(),
)
.change_context(errors::ApiErrorResponse::CurrencyNotSupported {
message: "USD is the only supported currency.".to_string(),
})?;
}
payment_types::AmazonPayDeliveryOptions::insert_display_amount(
&mut delivery_options,
router_data.request.currency,
)
.change_context(errors::ApiErrorResponse::AmountConversionFailed {
amount_type: "StringMajorUnit",
})?;
let total_shipping_amount = match router_data.request.shipping_cost {
Some(shipping_cost) => {
if shipping_cost == default_amount {
required_amount_type
.convert(shipping_cost, router_data.request.currency)
.change_context(errors::ApiErrorResponse::AmountConversionFailed {
amount_type: "StringMajorUnit",
})?
} else {
return Err(errors::ApiErrorResponse::InvalidDataValue {
field_name: "shipping_cost",
})
.attach_printable(format!(
"Provided shipping_cost ({shipping_cost}) does not match the default delivery amount ({default_amount})"
));
}
}
None => {
return Err(errors::ApiErrorResponse::MissingRequiredField {
field_name: "shipping_cost",
}
.into());
}
};
Ok(types::PaymentsSessionRouterData {
response: Ok(types::PaymentsResponseData::SessionResponse {
session_token: payment_types::SessionToken::AmazonPay(Box::new(
payment_types::AmazonPaySessionTokenResponse {
merchant_id,
ledger_currency,
store_id,
payment_intent,
total_shipping_amount,
total_tax_amount,
total_base_amount,
delivery_options,
},
)),
}),
..router_data.clone()
})
}
#[async_trait]
impl RouterDataSession for types::PaymentsSessionRouterData {
async fn decide_flow<'a, 'b>(
&'b self,
state: &'a routes::SessionState,
connector: &api::ConnectorData,
_confirm: Option<bool>,
call_connector_action: payments::CallConnectorAction,
business_profile: &domain::Profile,
header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<Self> {
match connector.get_token {
api::GetToken::GpayMetadata => {
create_gpay_session_token(state, self, connector, business_profile)
}
api::GetToken::SamsungPayMetadata => create_samsung_pay_session_token(
state,
self,
header_payload,
connector,
business_profile,
),
api::GetToken::ApplePayMetadata => {
create_applepay_session_token(
state,
self,
connector,
business_profile,
header_payload,
)
.await
}
api::GetToken::PaypalSdkMetadata => {
create_paypal_sdk_session_token(state, self, connector, business_profile)
}
api::GetToken::PazeMetadata => create_paze_session_token(self, header_payload),
api::GetToken::Connector => {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::Session,
types::PaymentsSessionData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
let resp = services::execute_connector_processing_step(
state,
connector_integration,
self,
call_connector_action,
None,
None,
)
.await
.to_payment_failed_response()?;
Ok(resp)
}
api::GetToken::AmazonPayMetadata => create_amazon_pay_session_token(self, state).await,
}
}
}
|
crates/router/src/core/payments/flows/session_flow.rs
|
router::src::core::payments::flows::session_flow
| 10,891
| true
|
// File: crates/router/src/core/payments/flows/cancel_flow.rs
// Module: router::src::core::payments::flows::cancel_flow
use async_trait::async_trait;
use super::{ConstructFlowSpecificData, Feature};
use crate::{
core::{
errors::{ConnectorErrorExt, RouterResult},
payments::{self, access_token, helpers, transformers, PaymentData},
},
routes::{metrics, SessionState},
services,
types::{self, api, domain},
};
#[cfg(feature = "v1")]
#[async_trait]
impl ConstructFlowSpecificData<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>
for PaymentData<api::Void>
{
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
merchant_context: &domain::MerchantContext,
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
_payment_method: Option<common_enums::PaymentMethod>,
_payment_method_type: Option<common_enums::PaymentMethodType>,
) -> RouterResult<types::PaymentsCancelRouterData> {
Box::pin(transformers::construct_payment_router_data::<
api::Void,
types::PaymentsCancelData,
>(
state,
self.clone(),
connector_id,
merchant_context,
customer,
merchant_connector_account,
merchant_recipient_data,
header_payload,
None,
None,
))
.await
}
}
#[cfg(feature = "v2")]
#[async_trait]
impl ConstructFlowSpecificData<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>
for hyperswitch_domain_models::payments::PaymentCancelData<api::Void>
{
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
merchant_context: &domain::MerchantContext,
customer: &Option<domain::Customer>,
merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
) -> RouterResult<types::PaymentsCancelRouterData> {
Box::pin(transformers::construct_router_data_for_cancel(
state,
self.clone(),
connector_id,
merchant_context,
customer,
merchant_connector_account,
merchant_recipient_data,
header_payload,
))
.await
}
}
#[async_trait]
impl Feature<api::Void, types::PaymentsCancelData>
for types::RouterData<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>
{
async fn decide_flows<'a>(
self,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
connector_request: Option<services::Request>,
_business_profile: &domain::Profile,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
_return_raw_connector_response: Option<bool>,
) -> RouterResult<Self> {
metrics::PAYMENT_CANCEL_COUNT.add(
1,
router_env::metric_attributes!(("connector", connector.connector_name.to_string())),
);
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::Void,
types::PaymentsCancelData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
let resp = services::execute_connector_processing_step(
state,
connector_integration,
&self,
call_connector_action,
connector_request,
None,
)
.await
.to_payment_failed_response()?;
Ok(resp)
}
async fn add_access_token<'a>(
&self,
state: &SessionState,
connector: &api::ConnectorData,
merchant_context: &domain::MerchantContext,
creds_identifier: Option<&str>,
) -> RouterResult<types::AddAccessTokenResult> {
Box::pin(access_token::add_access_token(
state,
connector,
merchant_context,
self,
creds_identifier,
))
.await
}
async fn build_flow_specific_connector_request(
&mut self,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
) -> RouterResult<(Option<services::Request>, bool)> {
let request = match call_connector_action {
payments::CallConnectorAction::Trigger => {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::Void,
types::PaymentsCancelData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
connector_integration
.build_request(self, &state.conf.connectors)
.to_payment_failed_response()?
}
_ => None,
};
Ok((request, true))
}
}
|
crates/router/src/core/payments/flows/cancel_flow.rs
|
router::src::core::payments::flows::cancel_flow
| 1,087
| true
|
// File: crates/router/src/core/payments/flows/psync_flow.rs
// Module: router::src::core::payments::flows::psync_flow
use std::{collections::HashMap, str::FromStr};
use async_trait::async_trait;
use common_enums::{self, enums};
use common_utils::{id_type, ucs_types};
use error_stack::ResultExt;
use external_services::grpc_client;
use hyperswitch_domain_models::payments as domain_payments;
use hyperswitch_interfaces::unified_connector_service::handle_unified_connector_service_response_for_payment_get;
use masking::Secret;
use unified_connector_service_client::payments as payments_grpc;
use super::{ConstructFlowSpecificData, Feature};
use crate::{
connector::utils::RouterData,
core::{
errors::{ApiErrorResponse, ConnectorErrorExt, RouterResult},
payments::{self, access_token, helpers, transformers, PaymentData},
unified_connector_service::{
build_unified_connector_service_auth_metadata, ucs_logging_wrapper,
},
},
routes::SessionState,
services::{self, api::ConnectorValidation, logger},
types::{self, api, domain, transformers::ForeignTryFrom},
};
#[cfg(feature = "v1")]
#[async_trait]
impl ConstructFlowSpecificData<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>
for PaymentData<api::PSync>
{
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
merchant_context: &domain::MerchantContext,
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<domain_payments::HeaderPayload>,
_payment_method: Option<common_enums::PaymentMethod>,
_payment_method_type: Option<common_enums::PaymentMethodType>,
) -> RouterResult<
types::RouterData<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>,
> {
Box::pin(transformers::construct_payment_router_data::<
api::PSync,
types::PaymentsSyncData,
>(
state,
self.clone(),
connector_id,
merchant_context,
customer,
merchant_connector_account,
merchant_recipient_data,
header_payload,
None,
None,
))
.await
}
}
#[cfg(feature = "v2")]
#[async_trait]
impl ConstructFlowSpecificData<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>
for hyperswitch_domain_models::payments::PaymentStatusData<api::PSync>
{
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
merchant_context: &domain::MerchantContext,
customer: &Option<domain::Customer>,
merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<domain_payments::HeaderPayload>,
) -> RouterResult<
types::RouterData<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>,
> {
Box::pin(transformers::construct_router_data_for_psync(
state,
self.clone(),
connector_id,
merchant_context,
customer,
merchant_connector_account,
merchant_recipient_data,
header_payload,
))
.await
}
}
#[async_trait]
impl Feature<api::PSync, types::PaymentsSyncData>
for types::RouterData<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>
{
async fn decide_flows<'a>(
mut self,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
connector_request: Option<services::Request>,
_business_profile: &domain::Profile,
_header_payload: domain_payments::HeaderPayload,
return_raw_connector_response: Option<bool>,
) -> RouterResult<Self> {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::PSync,
types::PaymentsSyncData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
let capture_sync_method_result = connector_integration
.get_multiple_capture_sync_method()
.to_payment_failed_response();
match (self.request.sync_type.clone(), capture_sync_method_result) {
(
types::SyncRequestType::MultipleCaptureSync(pending_connector_capture_id_list),
Ok(services::CaptureSyncMethod::Individual),
) => {
let mut new_router_data = self
.execute_connector_processing_step_for_each_capture(
state,
pending_connector_capture_id_list,
call_connector_action,
connector_integration,
return_raw_connector_response,
)
.await?;
// Initiating Integrity checks
let integrity_result = helpers::check_integrity_based_on_flow(
&new_router_data.request,
&new_router_data.response,
);
new_router_data.integrity_check = integrity_result;
Ok(new_router_data)
}
(types::SyncRequestType::MultipleCaptureSync(_), Err(err)) => Err(err),
_ => {
// for bulk sync of captures, above logic needs to be handled at connector end
let mut new_router_data = services::execute_connector_processing_step(
state,
connector_integration,
&self,
call_connector_action,
connector_request,
return_raw_connector_response,
)
.await
.to_payment_failed_response()?;
// Initiating Integrity checks
let integrity_result = helpers::check_integrity_based_on_flow(
&new_router_data.request,
&new_router_data.response,
);
new_router_data.integrity_check = integrity_result;
Ok(new_router_data)
}
}
}
async fn add_access_token<'a>(
&self,
state: &SessionState,
connector: &api::ConnectorData,
merchant_context: &domain::MerchantContext,
creds_identifier: Option<&str>,
) -> RouterResult<types::AddAccessTokenResult> {
Box::pin(access_token::add_access_token(
state,
connector,
merchant_context,
self,
creds_identifier,
))
.await
}
async fn build_flow_specific_connector_request(
&mut self,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
) -> RouterResult<(Option<services::Request>, bool)> {
let request = match call_connector_action {
payments::CallConnectorAction::Trigger => {
//validate_psync_reference_id if call_connector_action is trigger
if connector
.connector
.validate_psync_reference_id(
&self.request,
self.is_three_ds(),
self.status,
self.connector_meta_data.clone(),
)
.is_err()
{
logger::warn!(
"validate_psync_reference_id failed, hence skipping call to connector"
);
return Ok((None, false));
}
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::PSync,
types::PaymentsSyncData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
connector_integration
.build_request(self, &state.conf.connectors)
.to_payment_failed_response()?
}
_ => None,
};
Ok((request, true))
}
async fn call_unified_connector_service<'a>(
&mut self,
state: &SessionState,
header_payload: &domain_payments::HeaderPayload,
lineage_ids: grpc_client::LineageIds,
#[cfg(feature = "v1")] merchant_connector_account: helpers::MerchantConnectorAccountType,
#[cfg(feature = "v2")]
merchant_connector_account: domain::MerchantConnectorAccountTypeDetails,
merchant_context: &domain::MerchantContext,
unified_connector_service_execution_mode: enums::ExecutionMode,
) -> RouterResult<()> {
let connector_name = self.connector.clone();
let connector_enum = common_enums::connector_enums::Connector::from_str(&connector_name)
.change_context(ApiErrorResponse::IncorrectConnectorNameGiven)?;
let is_ucs_psync_disabled = state
.conf
.grpc_client
.unified_connector_service
.as_ref()
.is_some_and(|config| {
config
.ucs_psync_disabled_connectors
.contains(&connector_enum)
});
if is_ucs_psync_disabled {
logger::info!(
"UCS PSync call disabled for connector: {}, skipping UCS call",
connector_name
);
return Ok(());
}
let client = state
.grpc_client
.unified_connector_service_client
.clone()
.ok_or(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to fetch Unified Connector Service client")?;
let payment_get_request = payments_grpc::PaymentServiceGetRequest::foreign_try_from(&*self)
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to construct Payment Get Request")?;
let connector_auth_metadata = build_unified_connector_service_auth_metadata(
merchant_connector_account,
merchant_context,
)
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to construct request metadata")?;
let merchant_reference_id = header_payload
.x_reference_id
.clone()
.map(|id| id_type::PaymentReferenceId::from_str(id.as_str()))
.transpose()
.inspect_err(|err| logger::warn!(error=?err, "Invalid Merchant ReferenceId found"))
.ok()
.flatten()
.map(ucs_types::UcsReferenceId::Payment);
let header_payload = state
.get_grpc_headers_ucs(unified_connector_service_execution_mode)
.external_vault_proxy_metadata(None)
.merchant_reference_id(merchant_reference_id)
.lineage_ids(lineage_ids);
let updated_router_data = Box::pin(ucs_logging_wrapper(
self.clone(),
state,
payment_get_request,
header_payload,
|mut router_data, payment_get_request, grpc_headers| async move {
let response = client
.payment_get(payment_get_request, connector_auth_metadata, grpc_headers)
.await
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get payment")?;
let payment_get_response = response.into_inner();
let (router_data_response, status_code) =
handle_unified_connector_service_response_for_payment_get(
payment_get_response.clone(),
)
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to deserialize UCS response")?;
let router_data_response = router_data_response.map(|(response, status)| {
router_data.status = status;
response
});
router_data.response = router_data_response;
router_data.raw_connector_response = payment_get_response
.raw_connector_response
.clone()
.map(Secret::new);
router_data.connector_http_status_code = Some(status_code);
Ok((router_data, payment_get_response))
},
))
.await?;
// Copy back the updated data
*self = updated_router_data;
Ok(())
}
}
#[async_trait]
pub trait RouterDataPSync
where
Self: Sized,
{
async fn execute_connector_processing_step_for_each_capture(
&self,
_state: &SessionState,
_pending_connector_capture_id_list: Vec<String>,
_call_connector_action: payments::CallConnectorAction,
_connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::PSync,
types::PaymentsSyncData,
types::PaymentsResponseData,
>,
_return_raw_connector_response: Option<bool>,
) -> RouterResult<Self>;
}
#[async_trait]
impl RouterDataPSync
for types::RouterData<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>
{
async fn execute_connector_processing_step_for_each_capture(
&self,
state: &SessionState,
pending_connector_capture_id_list: Vec<String>,
call_connector_action: payments::CallConnectorAction,
connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::PSync,
types::PaymentsSyncData,
types::PaymentsResponseData,
>,
return_raw_connector_response: Option<bool>,
) -> RouterResult<Self> {
let mut capture_sync_response_map = HashMap::new();
if let payments::CallConnectorAction::HandleResponse(_) = call_connector_action {
// webhook consume flow, only call connector once. Since there will only be a single event in every webhook
let resp = services::execute_connector_processing_step(
state,
connector_integration,
self,
call_connector_action.clone(),
None,
return_raw_connector_response,
)
.await
.to_payment_failed_response()?;
Ok(resp)
} else {
// in trigger, call connector for every capture_id
for connector_capture_id in pending_connector_capture_id_list {
// TEMPORARY FIX: remove the clone on router data after removing this function as an impl on trait RouterDataPSync
// TRACKING ISSUE: https://github.com/juspay/hyperswitch/issues/4644
let mut cloned_router_data = self.clone();
cloned_router_data.request.connector_transaction_id =
types::ResponseId::ConnectorTransactionId(connector_capture_id.clone());
let resp = services::execute_connector_processing_step(
state,
connector_integration.clone_box(),
&cloned_router_data,
call_connector_action.clone(),
None,
return_raw_connector_response,
)
.await
.to_payment_failed_response()?;
match resp.response {
Err(err) => {
capture_sync_response_map.insert(connector_capture_id, types::CaptureSyncResponse::Error {
code: err.code,
message: err.message,
reason: err.reason,
status_code: err.status_code,
amount: None,
});
},
Ok(types::PaymentsResponseData::MultipleCaptureResponse { capture_sync_response_list })=> {
capture_sync_response_map.extend(capture_sync_response_list.into_iter());
}
_ => Err(ApiErrorResponse::PreconditionFailed { message: "Response type must be PaymentsResponseData::MultipleCaptureResponse for payment sync".into() })?,
};
}
let mut cloned_router_data = self.clone();
cloned_router_data.response =
Ok(types::PaymentsResponseData::MultipleCaptureResponse {
capture_sync_response_list: capture_sync_response_map,
});
Ok(cloned_router_data)
}
}
}
|
crates/router/src/core/payments/flows/psync_flow.rs
|
router::src::core::payments::flows::psync_flow
| 3,128
| true
|
// File: crates/router/src/core/payments/flows/reject_flow.rs
// Module: router::src::core::payments::flows::reject_flow
use async_trait::async_trait;
use super::{ConstructFlowSpecificData, Feature};
use crate::{
core::{
errors::{ApiErrorResponse, NotImplementedMessage, RouterResult},
payments::{self, access_token, helpers, transformers, PaymentData},
},
routes::SessionState,
services,
types::{self, api, domain},
};
#[async_trait]
impl ConstructFlowSpecificData<api::Reject, types::PaymentsRejectData, types::PaymentsResponseData>
for PaymentData<api::Reject>
{
#[cfg(feature = "v1")]
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
merchant_context: &domain::MerchantContext,
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
_payment_method: Option<common_enums::PaymentMethod>,
_payment_method_type: Option<common_enums::PaymentMethodType>,
) -> RouterResult<types::PaymentsRejectRouterData> {
Box::pin(transformers::construct_payment_router_data::<
api::Reject,
types::PaymentsRejectData,
>(
state,
self.clone(),
connector_id,
merchant_context,
customer,
merchant_connector_account,
merchant_recipient_data,
header_payload,
None,
None,
))
.await
}
#[cfg(feature = "v2")]
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
merchant_context: &domain::MerchantContext,
customer: &Option<domain::Customer>,
merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
) -> RouterResult<types::PaymentsRejectRouterData> {
todo!()
}
}
#[async_trait]
impl Feature<api::Reject, types::PaymentsRejectData>
for types::RouterData<api::Reject, types::PaymentsRejectData, types::PaymentsResponseData>
{
async fn decide_flows<'a>(
self,
_state: &SessionState,
_connector: &api::ConnectorData,
_call_connector_action: payments::CallConnectorAction,
_connector_request: Option<services::Request>,
_business_profile: &domain::Profile,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
_return_raw_connector_response: Option<bool>,
) -> RouterResult<Self> {
Err(ApiErrorResponse::NotImplemented {
message: NotImplementedMessage::Reason("Flow not supported".to_string()),
}
.into())
}
async fn add_access_token<'a>(
&self,
state: &SessionState,
connector: &api::ConnectorData,
merchant_context: &domain::MerchantContext,
creds_identifier: Option<&str>,
) -> RouterResult<types::AddAccessTokenResult> {
Box::pin(access_token::add_access_token(
state,
connector,
merchant_context,
self,
creds_identifier,
))
.await
}
async fn build_flow_specific_connector_request(
&mut self,
_state: &SessionState,
_connector: &api::ConnectorData,
_call_connector_action: payments::CallConnectorAction,
) -> RouterResult<(Option<services::Request>, bool)> {
Err(ApiErrorResponse::NotImplemented {
message: NotImplementedMessage::Reason("Flow not supported".to_string()),
}
.into())
}
}
|
crates/router/src/core/payments/flows/reject_flow.rs
|
router::src::core::payments::flows::reject_flow
| 835
| true
|
// File: crates/router/src/core/payments/flows/session_update_flow.rs
// Module: router::src::core::payments::flows::session_update_flow
use async_trait::async_trait;
use super::ConstructFlowSpecificData;
use crate::{
core::{
errors::{ConnectorErrorExt, RouterResult},
payments::{self, access_token, helpers, transformers, Feature, PaymentData},
},
routes::SessionState,
services,
types::{self, api, domain},
};
#[async_trait]
impl
ConstructFlowSpecificData<
api::SdkSessionUpdate,
types::SdkPaymentsSessionUpdateData,
types::PaymentsResponseData,
> for PaymentData<api::SdkSessionUpdate>
{
#[cfg(feature = "v1")]
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
merchant_context: &domain::MerchantContext,
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
_merchant_recipient_data: Option<types::MerchantRecipientData>,
_header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
_payment_method: Option<common_enums::PaymentMethod>,
_payment_method_type: Option<common_enums::PaymentMethodType>,
) -> RouterResult<types::SdkSessionUpdateRouterData> {
Box::pin(
transformers::construct_router_data_to_update_calculated_tax::<
api::SdkSessionUpdate,
types::SdkPaymentsSessionUpdateData,
>(
state,
self.clone(),
connector_id,
merchant_context,
customer,
merchant_connector_account,
),
)
.await
}
#[cfg(feature = "v2")]
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
merchant_context: &domain::MerchantContext,
customer: &Option<domain::Customer>,
merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
_merchant_recipient_data: Option<types::MerchantRecipientData>,
_header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
) -> RouterResult<types::SdkSessionUpdateRouterData> {
todo!()
}
}
#[async_trait]
impl Feature<api::SdkSessionUpdate, types::SdkPaymentsSessionUpdateData>
for types::RouterData<
api::SdkSessionUpdate,
types::SdkPaymentsSessionUpdateData,
types::PaymentsResponseData,
>
{
async fn decide_flows<'a>(
self,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
connector_request: Option<services::Request>,
_business_profile: &domain::Profile,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
_return_raw_connector_response: Option<bool>,
) -> RouterResult<Self> {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::SdkSessionUpdate,
types::SdkPaymentsSessionUpdateData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
let resp = services::execute_connector_processing_step(
state,
connector_integration,
&self,
call_connector_action,
connector_request,
None,
)
.await
.to_payment_failed_response()?;
Ok(resp)
}
async fn add_access_token<'a>(
&self,
state: &SessionState,
connector: &api::ConnectorData,
merchant_context: &domain::MerchantContext,
creds_identifier: Option<&str>,
) -> RouterResult<types::AddAccessTokenResult> {
Box::pin(access_token::add_access_token(
state,
connector,
merchant_context,
self,
creds_identifier,
))
.await
}
async fn build_flow_specific_connector_request(
&mut self,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
) -> RouterResult<(Option<services::Request>, bool)> {
let request = match call_connector_action {
payments::CallConnectorAction::Trigger => {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::SdkSessionUpdate,
types::SdkPaymentsSessionUpdateData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
connector_integration
.build_request(self, &state.conf.connectors)
.to_payment_failed_response()?
}
_ => None,
};
Ok((request, true))
}
}
|
crates/router/src/core/payments/flows/session_update_flow.rs
|
router::src::core::payments::flows::session_update_flow
| 997
| true
|
// File: crates/router/src/core/payments/flows/post_session_tokens_flow.rs
// Module: router::src::core::payments::flows::post_session_tokens_flow
use async_trait::async_trait;
use super::ConstructFlowSpecificData;
use crate::{
core::{
errors::{ConnectorErrorExt, RouterResult},
payments::{self, access_token, helpers, transformers, Feature, PaymentData},
},
routes::SessionState,
services,
types::{self, api, domain},
};
#[async_trait]
impl
ConstructFlowSpecificData<
api::PostSessionTokens,
types::PaymentsPostSessionTokensData,
types::PaymentsResponseData,
> for PaymentData<api::PostSessionTokens>
{
#[cfg(feature = "v1")]
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
merchant_context: &domain::MerchantContext,
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
_payment_method: Option<common_enums::PaymentMethod>,
_payment_method_type: Option<common_enums::PaymentMethodType>,
) -> RouterResult<types::PaymentsPostSessionTokensRouterData> {
Box::pin(transformers::construct_payment_router_data::<
api::PostSessionTokens,
types::PaymentsPostSessionTokensData,
>(
state,
self.clone(),
connector_id,
merchant_context,
customer,
merchant_connector_account,
merchant_recipient_data,
header_payload,
None,
None,
))
.await
}
#[cfg(feature = "v2")]
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
merchant_context: &domain::MerchantContext,
customer: &Option<domain::Customer>,
merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
) -> RouterResult<types::PaymentsPostSessionTokensRouterData> {
todo!()
}
}
#[async_trait]
impl Feature<api::PostSessionTokens, types::PaymentsPostSessionTokensData>
for types::RouterData<
api::PostSessionTokens,
types::PaymentsPostSessionTokensData,
types::PaymentsResponseData,
>
{
async fn decide_flows<'a>(
self,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
connector_request: Option<services::Request>,
_business_profile: &domain::Profile,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
_return_raw_connector_response: Option<bool>,
) -> RouterResult<Self> {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::PostSessionTokens,
types::PaymentsPostSessionTokensData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
let resp = services::execute_connector_processing_step(
state,
connector_integration,
&self,
call_connector_action,
connector_request,
None,
)
.await
.to_payment_failed_response()?;
Ok(resp)
}
async fn add_access_token<'a>(
&self,
state: &SessionState,
connector: &api::ConnectorData,
merchant_context: &domain::MerchantContext,
creds_identifier: Option<&str>,
) -> RouterResult<types::AddAccessTokenResult> {
Box::pin(access_token::add_access_token(
state,
connector,
merchant_context,
self,
creds_identifier,
))
.await
}
async fn build_flow_specific_connector_request(
&mut self,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
) -> RouterResult<(Option<services::Request>, bool)> {
let request = match call_connector_action {
payments::CallConnectorAction::Trigger => {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::PostSessionTokens,
types::PaymentsPostSessionTokensData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
connector_integration
.build_request(self, &state.conf.connectors)
.to_payment_failed_response()?
}
_ => None,
};
Ok((request, true))
}
}
|
crates/router/src/core/payments/flows/post_session_tokens_flow.rs
|
router::src::core::payments::flows::post_session_tokens_flow
| 1,006
| true
|
// File: crates/router/src/core/payments/flows/authorize_flow.rs
// Module: router::src::core::payments::flows::authorize_flow
use std::str::FromStr;
use async_trait::async_trait;
use common_enums as enums;
use common_types::payments as common_payments_types;
use common_utils::{id_type, ucs_types};
use error_stack::ResultExt;
use external_services::grpc_client;
#[cfg(feature = "v2")]
use hyperswitch_domain_models::payments::PaymentConfirmData;
use hyperswitch_domain_models::{
errors::api_error_response::ApiErrorResponse, payments as domain_payments,
};
use masking::{ExposeInterface, Secret};
use unified_connector_service_client::payments as payments_grpc;
// use router_env::tracing::Instrument;
use super::{ConstructFlowSpecificData, Feature};
use crate::{
core::{
errors::{ConnectorErrorExt, RouterResult},
mandate,
payments::{
self, access_token, customers, helpers, tokenization, transformers, PaymentData,
},
unified_connector_service::{
build_unified_connector_service_auth_metadata,
handle_unified_connector_service_response_for_payment_authorize,
handle_unified_connector_service_response_for_payment_repeat, ucs_logging_wrapper,
},
},
logger,
routes::{metrics, SessionState},
services::{self, api::ConnectorValidation},
types::{
self, api, domain,
transformers::{ForeignFrom, ForeignTryFrom},
},
utils::OptionExt,
};
#[cfg(feature = "v2")]
#[async_trait]
impl
ConstructFlowSpecificData<
api::Authorize,
types::PaymentsAuthorizeData,
types::PaymentsResponseData,
> for PaymentConfirmData<api::Authorize>
{
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
merchant_context: &domain::MerchantContext,
customer: &Option<domain::Customer>,
merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<domain_payments::HeaderPayload>,
) -> RouterResult<
types::RouterData<
api::Authorize,
types::PaymentsAuthorizeData,
types::PaymentsResponseData,
>,
> {
Box::pin(transformers::construct_payment_router_data_for_authorize(
state,
self.clone(),
connector_id,
merchant_context,
customer,
merchant_connector_account,
merchant_recipient_data,
header_payload,
))
.await
}
async fn get_merchant_recipient_data<'a>(
&self,
state: &SessionState,
merchant_context: &domain::MerchantContext,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
connector: &api::ConnectorData,
) -> RouterResult<Option<types::MerchantRecipientData>> {
let is_open_banking = &self
.payment_attempt
.get_payment_method()
.get_required_value("PaymentMethod")?
.eq(&enums::PaymentMethod::OpenBanking);
if *is_open_banking {
payments::get_merchant_bank_data_for_open_banking_connectors(
merchant_connector_account,
merchant_context,
connector,
state,
)
.await
} else {
Ok(None)
}
}
}
#[cfg(feature = "v1")]
#[async_trait]
impl
ConstructFlowSpecificData<
api::Authorize,
types::PaymentsAuthorizeData,
types::PaymentsResponseData,
> for PaymentData<api::Authorize>
{
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
merchant_context: &domain::MerchantContext,
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<domain_payments::HeaderPayload>,
_payment_method: Option<common_enums::PaymentMethod>,
_payment_method_type: Option<common_enums::PaymentMethodType>,
) -> RouterResult<
types::RouterData<
api::Authorize,
types::PaymentsAuthorizeData,
types::PaymentsResponseData,
>,
> {
Box::pin(transformers::construct_payment_router_data::<
api::Authorize,
types::PaymentsAuthorizeData,
>(
state,
self.clone(),
connector_id,
merchant_context,
customer,
merchant_connector_account,
merchant_recipient_data,
header_payload,
None,
None,
))
.await
}
async fn get_merchant_recipient_data<'a>(
&self,
state: &SessionState,
merchant_context: &domain::MerchantContext,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
connector: &api::ConnectorData,
) -> RouterResult<Option<types::MerchantRecipientData>> {
match &self.payment_intent.is_payment_processor_token_flow {
Some(true) => Ok(None),
Some(false) | None => {
let is_open_banking = &self
.payment_attempt
.get_payment_method()
.get_required_value("PaymentMethod")?
.eq(&enums::PaymentMethod::OpenBanking);
Ok(if *is_open_banking {
payments::get_merchant_bank_data_for_open_banking_connectors(
merchant_connector_account,
merchant_context,
connector,
state,
)
.await?
} else {
None
})
}
}
}
}
#[async_trait]
impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAuthorizeRouterData {
async fn decide_flows<'a>(
mut self,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
connector_request: Option<services::Request>,
business_profile: &domain::Profile,
header_payload: domain_payments::HeaderPayload,
return_raw_connector_response: Option<bool>,
) -> RouterResult<Self> {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::Authorize,
types::PaymentsAuthorizeData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
if self.should_proceed_with_authorize() {
self.decide_authentication_type();
logger::debug!(auth_type=?self.auth_type);
let mut auth_router_data = services::execute_connector_processing_step(
state,
connector_integration,
&self,
call_connector_action.clone(),
connector_request,
return_raw_connector_response,
)
.await
.to_payment_failed_response()?;
// Initiating Integrity check
let integrity_result = helpers::check_integrity_based_on_flow(
&auth_router_data.request,
&auth_router_data.response,
);
auth_router_data.integrity_check = integrity_result;
metrics::PAYMENT_COUNT.add(1, &[]); // Move outside of the if block
match auth_router_data.response.clone() {
Err(_) => Ok(auth_router_data),
Ok(authorize_response) => {
// Check if the Capture API should be called based on the connector and other parameters
if super::should_initiate_capture_flow(
&connector.connector_name,
self.request.customer_acceptance,
self.request.capture_method,
self.request.setup_future_usage,
auth_router_data.status,
) {
auth_router_data = Box::pin(process_capture_flow(
auth_router_data,
authorize_response,
state,
connector,
call_connector_action.clone(),
business_profile,
header_payload,
))
.await?;
}
Ok(auth_router_data)
}
}
} else {
Ok(self.clone())
}
}
async fn add_access_token<'a>(
&self,
state: &SessionState,
connector: &api::ConnectorData,
merchant_context: &domain::MerchantContext,
creds_identifier: Option<&str>,
) -> RouterResult<types::AddAccessTokenResult> {
Box::pin(access_token::add_access_token(
state,
connector,
merchant_context,
self,
creds_identifier,
))
.await
}
async fn add_session_token<'a>(
self,
state: &SessionState,
connector: &api::ConnectorData,
) -> RouterResult<Self>
where
Self: Sized,
{
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::AuthorizeSessionToken,
types::AuthorizeSessionTokenData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
let authorize_data = &types::PaymentsAuthorizeSessionTokenRouterData::foreign_from((
&self,
types::AuthorizeSessionTokenData::foreign_from(&self),
));
let resp = services::execute_connector_processing_step(
state,
connector_integration,
authorize_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.to_payment_failed_response()?;
let mut router_data = self;
router_data.session_token = resp.session_token;
Ok(router_data)
}
async fn add_payment_method_token<'a>(
&mut self,
state: &SessionState,
connector: &api::ConnectorData,
tokenization_action: &payments::TokenizationAction,
should_continue_payment: bool,
) -> RouterResult<types::PaymentMethodTokenResult> {
let request = self.request.clone();
tokenization::add_payment_method_token(
state,
connector,
tokenization_action,
self,
types::PaymentMethodTokenizationData::try_from(request)?,
should_continue_payment,
)
.await
}
async fn preprocessing_steps<'a>(
self,
state: &SessionState,
connector: &api::ConnectorData,
) -> RouterResult<Self> {
authorize_preprocessing_steps(state, &self, true, connector).await
}
async fn postprocessing_steps<'a>(
self,
state: &SessionState,
connector: &api::ConnectorData,
) -> RouterResult<Self> {
authorize_postprocessing_steps(state, &self, true, connector).await
}
async fn create_connector_customer<'a>(
&self,
state: &SessionState,
connector: &api::ConnectorData,
) -> RouterResult<Option<String>> {
customers::create_connector_customer(
state,
connector,
self,
types::ConnectorCustomerData::try_from(self)?,
)
.await
}
async fn build_flow_specific_connector_request(
&mut self,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
) -> RouterResult<(Option<services::Request>, bool)> {
match call_connector_action {
payments::CallConnectorAction::Trigger => {
connector
.connector
.validate_connector_against_payment_request(
self.request.capture_method,
self.payment_method,
self.request.payment_method_type,
)
.to_payment_failed_response()?;
// Check if the connector supports mandate payment
// if the payment_method_type does not support mandate for the given connector, downgrade the setup future usage to on session
if self.request.setup_future_usage
== Some(diesel_models::enums::FutureUsage::OffSession)
&& !self
.request
.payment_method_type
.and_then(|payment_method_type| {
state
.conf
.mandates
.supported_payment_methods
.0
.get(&enums::PaymentMethod::from(payment_method_type))
.and_then(|supported_pm_for_mandates| {
supported_pm_for_mandates.0.get(&payment_method_type).map(
|supported_connector_for_mandates| {
supported_connector_for_mandates
.connector_list
.contains(&connector.connector_name)
},
)
})
})
.unwrap_or(false)
{
// downgrade the setup future usage to on session
self.request.setup_future_usage =
Some(diesel_models::enums::FutureUsage::OnSession);
};
if crate::connector::utils::PaymentsAuthorizeRequestData::is_customer_initiated_mandate_payment(
&self.request,
) {
connector
.connector
.validate_mandate_payment(
self.request.payment_method_type,
self.request.payment_method_data.clone(),
)
.to_payment_failed_response()?;
};
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::Authorize,
types::PaymentsAuthorizeData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
metrics::EXECUTE_PRETASK_COUNT.add(
1,
router_env::metric_attributes!(
("connector", connector.connector_name.to_string()),
("flow", format!("{:?}", api::Authorize)),
),
);
logger::debug!(completed_pre_tasks=?true);
if self.should_proceed_with_authorize() {
self.decide_authentication_type();
logger::debug!(auth_type=?self.auth_type);
Ok((
connector_integration
.build_request(self, &state.conf.connectors)
.to_payment_failed_response()?,
true,
))
} else {
Ok((None, false))
}
}
_ => Ok((None, true)),
}
}
async fn create_order_at_connector(
&mut self,
state: &SessionState,
connector: &api::ConnectorData,
should_continue_payment: bool,
) -> RouterResult<Option<types::CreateOrderResult>> {
if connector
.connector_name
.requires_order_creation_before_payment(self.payment_method)
&& should_continue_payment
{
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::CreateOrder,
types::CreateOrderRequestData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
let request_data = types::CreateOrderRequestData::try_from(self.request.clone())?;
let response_data: Result<types::PaymentsResponseData, types::ErrorResponse> =
Err(types::ErrorResponse::default());
let createorder_router_data =
helpers::router_data_type_conversion::<_, api::CreateOrder, _, _, _, _>(
self.clone(),
request_data,
response_data,
);
let resp = services::execute_connector_processing_step(
state,
connector_integration,
&createorder_router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.to_payment_failed_response()?;
let create_order_resp = match resp.response {
Ok(res) => {
if let types::PaymentsResponseData::PaymentsCreateOrderResponse { order_id } =
res
{
Ok(order_id)
} else {
Err(error_stack::report!(ApiErrorResponse::InternalServerError)
.attach_printable(format!(
"Unexpected response format from connector: {res:?}",
)))?
}
}
Err(error) => Err(error),
};
Ok(Some(types::CreateOrderResult {
create_order_result: create_order_resp,
}))
} else {
// If the connector does not require order creation, return None
Ok(None)
}
}
fn update_router_data_with_create_order_response(
&mut self,
create_order_result: types::CreateOrderResult,
) {
match create_order_result.create_order_result {
Ok(order_id) => {
self.request.order_id = Some(order_id.clone()); // ? why this is assigned here and ucs also wants this to populate data
self.response =
Ok(types::PaymentsResponseData::PaymentsCreateOrderResponse { order_id });
}
Err(err) => {
self.response = Err(err.clone());
}
}
}
async fn call_unified_connector_service<'a>(
&mut self,
state: &SessionState,
header_payload: &domain_payments::HeaderPayload,
lineage_ids: grpc_client::LineageIds,
#[cfg(feature = "v1")] merchant_connector_account: helpers::MerchantConnectorAccountType,
#[cfg(feature = "v2")]
merchant_connector_account: domain::MerchantConnectorAccountTypeDetails,
merchant_context: &domain::MerchantContext,
unified_connector_service_execution_mode: enums::ExecutionMode,
) -> RouterResult<()> {
if self.request.mandate_id.is_some() {
Box::pin(call_unified_connector_service_repeat_payment(
self,
state,
header_payload,
lineage_ids,
merchant_connector_account,
merchant_context,
unified_connector_service_execution_mode,
))
.await
} else {
Box::pin(call_unified_connector_service_authorize(
self,
state,
header_payload,
lineage_ids,
merchant_connector_account,
merchant_context,
unified_connector_service_execution_mode,
))
.await
}
}
}
pub trait RouterDataAuthorize {
fn decide_authentication_type(&mut self);
/// to decide if we need to proceed with authorize or not, Eg: If any of the pretask returns `redirection_response` then we should not proceed with authorize call
fn should_proceed_with_authorize(&self) -> bool;
}
impl RouterDataAuthorize for types::PaymentsAuthorizeRouterData {
fn decide_authentication_type(&mut self) {
if let hyperswitch_domain_models::payment_method_data::PaymentMethodData::Wallet(
hyperswitch_domain_models::payment_method_data::WalletData::GooglePay(google_pay_data),
) = &self.request.payment_method_data
{
if let Some(assurance_details) = google_pay_data.info.assurance_details.as_ref() {
// Step up the transaction to 3DS when either assurance_details.card_holder_authenticated or assurance_details.account_verified is false
if !assurance_details.card_holder_authenticated
|| !assurance_details.account_verified
{
logger::info!("Googlepay transaction stepped up to 3DS");
self.auth_type = diesel_models::enums::AuthenticationType::ThreeDs;
}
}
}
if self.auth_type == diesel_models::enums::AuthenticationType::ThreeDs
&& !self.request.enrolled_for_3ds
{
self.auth_type = diesel_models::enums::AuthenticationType::NoThreeDs
}
}
/// to decide if we need to proceed with authorize or not, Eg: If any of the pretask returns `redirection_response` then we should not proceed with authorize call
fn should_proceed_with_authorize(&self) -> bool {
match &self.response {
Ok(types::PaymentsResponseData::TransactionResponse {
redirection_data, ..
}) => !redirection_data.is_some(),
_ => true,
}
}
}
impl mandate::MandateBehaviour for types::PaymentsAuthorizeData {
fn get_amount(&self) -> i64 {
self.amount
}
fn get_mandate_id(&self) -> Option<&api_models::payments::MandateIds> {
self.mandate_id.as_ref()
}
fn get_payment_method_data(&self) -> domain::payments::PaymentMethodData {
self.payment_method_data.clone()
}
fn get_setup_future_usage(&self) -> Option<diesel_models::enums::FutureUsage> {
self.setup_future_usage
}
fn get_setup_mandate_details(
&self,
) -> Option<&hyperswitch_domain_models::mandates::MandateData> {
self.setup_mandate_details.as_ref()
}
fn set_mandate_id(&mut self, new_mandate_id: Option<api_models::payments::MandateIds>) {
self.mandate_id = new_mandate_id;
}
fn get_customer_acceptance(&self) -> Option<common_payments_types::CustomerAcceptance> {
self.customer_acceptance.clone()
}
}
pub async fn authorize_preprocessing_steps<F: Clone>(
state: &SessionState,
router_data: &types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>,
confirm: bool,
connector: &api::ConnectorData,
) -> RouterResult<types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>> {
if confirm {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::PreProcessing,
types::PaymentsPreProcessingData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
let preprocessing_request_data =
types::PaymentsPreProcessingData::try_from(router_data.request.to_owned())?;
let preprocessing_response_data: Result<types::PaymentsResponseData, types::ErrorResponse> =
Err(types::ErrorResponse::default());
let preprocessing_router_data =
helpers::router_data_type_conversion::<_, api::PreProcessing, _, _, _, _>(
router_data.clone(),
preprocessing_request_data,
preprocessing_response_data,
);
let resp = services::execute_connector_processing_step(
state,
connector_integration,
&preprocessing_router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.to_payment_failed_response()?;
metrics::PREPROCESSING_STEPS_COUNT.add(
1,
router_env::metric_attributes!(
("connector", connector.connector_name.to_string()),
("payment_method", router_data.payment_method.to_string()),
(
"payment_method_type",
router_data
.request
.payment_method_type
.map(|inner| inner.to_string())
.unwrap_or("null".to_string()),
),
),
);
let mut authorize_router_data = helpers::router_data_type_conversion::<_, F, _, _, _, _>(
resp.clone(),
router_data.request.to_owned(),
resp.response.clone(),
);
if connector.connector_name == api_models::enums::Connector::Airwallex {
authorize_router_data.reference_id = resp.reference_id;
} else if connector.connector_name == api_models::enums::Connector::Nuvei {
let (enrolled_for_3ds, related_transaction_id) = match &authorize_router_data.response {
Ok(types::PaymentsResponseData::ThreeDSEnrollmentResponse {
enrolled_v2,
related_transaction_id,
}) => (*enrolled_v2, related_transaction_id.clone()),
_ => (false, None),
};
authorize_router_data.request.enrolled_for_3ds = enrolled_for_3ds;
authorize_router_data.request.related_transaction_id = related_transaction_id;
} else if connector.connector_name == api_models::enums::Connector::Shift4 {
if resp.request.enrolled_for_3ds {
authorize_router_data.response = resp.response;
authorize_router_data.status = resp.status;
} else {
authorize_router_data.request.enrolled_for_3ds = false;
}
}
Ok(authorize_router_data)
} else {
Ok(router_data.clone())
}
}
pub async fn authorize_postprocessing_steps<F: Clone>(
state: &SessionState,
router_data: &types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>,
confirm: bool,
connector: &api::ConnectorData,
) -> RouterResult<types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>> {
if confirm {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::PostProcessing,
types::PaymentsPostProcessingData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
let postprocessing_request_data =
types::PaymentsPostProcessingData::try_from(router_data.to_owned())?;
let postprocessing_response_data: Result<
types::PaymentsResponseData,
types::ErrorResponse,
> = Err(types::ErrorResponse::default());
let postprocessing_router_data =
helpers::router_data_type_conversion::<_, api::PostProcessing, _, _, _, _>(
router_data.clone(),
postprocessing_request_data,
postprocessing_response_data,
);
let resp = services::execute_connector_processing_step(
state,
connector_integration,
&postprocessing_router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.to_payment_failed_response()?;
let authorize_router_data = helpers::router_data_type_conversion::<_, F, _, _, _, _>(
resp.clone(),
router_data.request.to_owned(),
resp.response,
);
Ok(authorize_router_data)
} else {
Ok(router_data.clone())
}
}
impl<F>
ForeignTryFrom<types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>>
for types::PaymentsCaptureData
{
type Error = error_stack::Report<ApiErrorResponse>;
fn foreign_try_from(
item: types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let response = item
.response
.map_err(|err| ApiErrorResponse::ExternalConnectorError {
code: err.code,
message: err.message,
connector: item.connector.clone(),
status_code: err.status_code,
reason: err.reason,
})?;
Ok(Self {
amount_to_capture: item.request.amount,
currency: item.request.currency,
connector_transaction_id: types::PaymentsResponseData::get_connector_transaction_id(
&response,
)?,
payment_amount: item.request.amount,
multiple_capture_data: None,
connector_meta: types::PaymentsResponseData::get_connector_metadata(&response)
.map(|secret| secret.expose()),
browser_info: None,
metadata: None,
capture_method: item.request.capture_method,
minor_payment_amount: item.request.minor_amount,
minor_amount_to_capture: item.request.minor_amount,
integrity_object: None,
split_payments: item.request.split_payments,
webhook_url: item.request.webhook_url,
})
}
}
async fn process_capture_flow(
mut router_data: types::RouterData<
api::Authorize,
types::PaymentsAuthorizeData,
types::PaymentsResponseData,
>,
authorize_response: types::PaymentsResponseData,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
business_profile: &domain::Profile,
header_payload: domain_payments::HeaderPayload,
) -> RouterResult<
types::RouterData<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData>,
> {
// Convert RouterData into Capture RouterData
let capture_router_data = helpers::router_data_type_conversion(
router_data.clone(),
types::PaymentsCaptureData::foreign_try_from(router_data.clone())?,
Err(types::ErrorResponse::default()),
);
// Call capture request
let post_capture_router_data = super::call_capture_request(
capture_router_data,
state,
connector,
call_connector_action,
business_profile,
header_payload,
)
.await;
// Process capture response
let (updated_status, updated_response) =
super::handle_post_capture_response(authorize_response, post_capture_router_data)?;
router_data.status = updated_status;
router_data.response = Ok(updated_response);
Ok(router_data)
}
async fn call_unified_connector_service_authorize(
router_data: &mut types::RouterData<
api::Authorize,
types::PaymentsAuthorizeData,
types::PaymentsResponseData,
>,
state: &SessionState,
header_payload: &domain_payments::HeaderPayload,
lineage_ids: grpc_client::LineageIds,
#[cfg(feature = "v1")] merchant_connector_account: helpers::MerchantConnectorAccountType,
#[cfg(feature = "v2")] merchant_connector_account: domain::MerchantConnectorAccountTypeDetails,
merchant_context: &domain::MerchantContext,
unified_connector_service_execution_mode: enums::ExecutionMode,
) -> RouterResult<()> {
let client = state
.grpc_client
.unified_connector_service_client
.clone()
.ok_or(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to fetch Unified Connector Service client")?;
let payment_authorize_request =
payments_grpc::PaymentServiceAuthorizeRequest::foreign_try_from(&*router_data)
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to construct Payment Authorize Request")?;
let connector_auth_metadata =
build_unified_connector_service_auth_metadata(merchant_connector_account, merchant_context)
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to construct request metadata")?;
let merchant_order_reference_id = header_payload
.x_reference_id
.clone()
.map(|id| id_type::PaymentReferenceId::from_str(id.as_str()))
.transpose()
.inspect_err(|err| logger::warn!(error=?err, "Invalid Merchant ReferenceId found"))
.ok()
.flatten()
.map(ucs_types::UcsReferenceId::Payment);
let headers_builder = state
.get_grpc_headers_ucs(unified_connector_service_execution_mode)
.external_vault_proxy_metadata(None)
.merchant_reference_id(merchant_order_reference_id)
.lineage_ids(lineage_ids);
let updated_router_data = Box::pin(ucs_logging_wrapper(
router_data.clone(),
state,
payment_authorize_request,
headers_builder,
|mut router_data, payment_authorize_request, grpc_headers| async move {
let response = client
.payment_authorize(
payment_authorize_request,
connector_auth_metadata,
grpc_headers,
)
.await
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to authorize payment")?;
let payment_authorize_response = response.into_inner();
let (router_data_response, status_code) =
handle_unified_connector_service_response_for_payment_authorize(
payment_authorize_response.clone(),
)
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to deserialize UCS response")?;
let router_data_response = router_data_response.map(|(response, status)| {
router_data.status = status;
response
});
router_data.response = router_data_response;
router_data.raw_connector_response = payment_authorize_response
.raw_connector_response
.clone()
.map(Secret::new);
router_data.connector_http_status_code = Some(status_code);
Ok((router_data, payment_authorize_response))
},
))
.await?;
// Copy back the updated data
*router_data = updated_router_data;
Ok(())
}
async fn call_unified_connector_service_repeat_payment(
router_data: &mut types::RouterData<
api::Authorize,
types::PaymentsAuthorizeData,
types::PaymentsResponseData,
>,
state: &SessionState,
header_payload: &domain_payments::HeaderPayload,
lineage_ids: grpc_client::LineageIds,
#[cfg(feature = "v1")] merchant_connector_account: helpers::MerchantConnectorAccountType,
#[cfg(feature = "v2")] merchant_connector_account: domain::MerchantConnectorAccountTypeDetails,
merchant_context: &domain::MerchantContext,
unified_connector_service_execution_mode: enums::ExecutionMode,
) -> RouterResult<()> {
let client = state
.grpc_client
.unified_connector_service_client
.clone()
.ok_or(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to fetch Unified Connector Service client")?;
let payment_repeat_request =
payments_grpc::PaymentServiceRepeatEverythingRequest::foreign_try_from(&*router_data)
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to construct Payment Repeat Request")?;
let connector_auth_metadata =
build_unified_connector_service_auth_metadata(merchant_connector_account, merchant_context)
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to construct request metadata")?;
let merchant_order_reference_id = header_payload
.x_reference_id
.clone()
.map(|id| id_type::PaymentReferenceId::from_str(id.as_str()))
.transpose()
.inspect_err(|err| logger::warn!(error=?err, "Invalid Merchant ReferenceId found"))
.ok()
.flatten()
.map(ucs_types::UcsReferenceId::Payment);
let headers_builder = state
.get_grpc_headers_ucs(unified_connector_service_execution_mode)
.external_vault_proxy_metadata(None)
.merchant_reference_id(merchant_order_reference_id)
.lineage_ids(lineage_ids);
let updated_router_data = Box::pin(ucs_logging_wrapper(
router_data.clone(),
state,
payment_repeat_request,
headers_builder,
|mut router_data, payment_repeat_request, grpc_headers| async move {
let response = client
.payment_repeat(
payment_repeat_request,
connector_auth_metadata.clone(),
grpc_headers,
)
.await
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to repeat payment")?;
let payment_repeat_response = response.into_inner();
let (router_data_response, status_code) =
handle_unified_connector_service_response_for_payment_repeat(
payment_repeat_response.clone(),
)
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to deserialize UCS response")?;
let router_data_response = router_data_response.map(|(response, status)| {
router_data.status = status;
response
});
router_data.response = router_data_response;
router_data.raw_connector_response = payment_repeat_response
.raw_connector_response
.clone()
.map(Secret::new);
router_data.connector_http_status_code = Some(status_code);
Ok((router_data, payment_repeat_response))
},
))
.await?;
// Copy back the updated data
*router_data = updated_router_data;
Ok(())
}
|
crates/router/src/core/payments/flows/authorize_flow.rs
|
router::src::core::payments::flows::authorize_flow
| 7,218
| true
|
// File: crates/router/src/core/payments/flows/capture_flow.rs
// Module: router::src::core::payments::flows::capture_flow
use async_trait::async_trait;
use super::ConstructFlowSpecificData;
use crate::{
core::{
errors::{ConnectorErrorExt, RouterResult},
payments::{self, access_token, helpers, transformers, Feature, PaymentData},
},
routes::SessionState,
services,
types::{self, api, domain},
};
#[cfg(feature = "v1")]
#[async_trait]
impl
ConstructFlowSpecificData<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData>
for PaymentData<api::Capture>
{
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
merchant_context: &domain::MerchantContext,
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
_payment_method: Option<common_enums::PaymentMethod>,
_payment_method_type: Option<common_enums::PaymentMethodType>,
) -> RouterResult<types::PaymentsCaptureRouterData> {
Box::pin(transformers::construct_payment_router_data::<
api::Capture,
types::PaymentsCaptureData,
>(
state,
self.clone(),
connector_id,
merchant_context,
customer,
merchant_connector_account,
merchant_recipient_data,
header_payload,
None,
None,
))
.await
}
}
#[cfg(feature = "v2")]
#[async_trait]
impl
ConstructFlowSpecificData<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData>
for hyperswitch_domain_models::payments::PaymentCaptureData<api::Capture>
{
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
merchant_context: &domain::MerchantContext,
customer: &Option<domain::Customer>,
merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
) -> RouterResult<
types::RouterData<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData>,
> {
Box::pin(transformers::construct_payment_router_data_for_capture(
state,
self.clone(),
connector_id,
merchant_context,
customer,
merchant_connector_account,
merchant_recipient_data,
header_payload,
))
.await
}
}
#[async_trait]
impl Feature<api::Capture, types::PaymentsCaptureData>
for types::RouterData<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData>
{
async fn decide_flows<'a>(
self,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
connector_request: Option<services::Request>,
_business_profile: &domain::Profile,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
_return_raw_connector_response: Option<bool>,
) -> RouterResult<Self> {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::Capture,
types::PaymentsCaptureData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
let mut new_router_data = services::execute_connector_processing_step(
state,
connector_integration,
&self,
call_connector_action,
connector_request,
None,
)
.await
.to_payment_failed_response()?;
// Initiating Integrity check
let integrity_result = helpers::check_integrity_based_on_flow(
&new_router_data.request,
&new_router_data.response,
);
new_router_data.integrity_check = integrity_result;
Ok(new_router_data)
}
async fn add_access_token<'a>(
&self,
state: &SessionState,
connector: &api::ConnectorData,
merchant_context: &domain::MerchantContext,
creds_identifier: Option<&str>,
) -> RouterResult<types::AddAccessTokenResult> {
Box::pin(access_token::add_access_token(
state,
connector,
merchant_context,
self,
creds_identifier,
))
.await
}
async fn build_flow_specific_connector_request(
&mut self,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
) -> RouterResult<(Option<services::Request>, bool)> {
let request = match call_connector_action {
payments::CallConnectorAction::Trigger => {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::Capture,
types::PaymentsCaptureData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
connector_integration
.build_request(self, &state.conf.connectors)
.to_payment_failed_response()?
}
_ => None,
};
Ok((request, true))
}
}
|
crates/router/src/core/payments/flows/capture_flow.rs
|
router::src::core::payments::flows::capture_flow
| 1,129
| true
|
// File: crates/router/src/core/fraud_check/operation.rs
// Module: router::src::core::fraud_check::operation
pub mod fraud_check_post;
pub mod fraud_check_pre;
use async_trait::async_trait;
use common_enums::FrmSuggestion;
use error_stack::{report, ResultExt};
pub use self::{fraud_check_post::FraudCheckPost, fraud_check_pre::FraudCheckPre};
use super::{
types::{ConnectorDetailsCore, FrmConfigsObject, PaymentToFrmData},
FrmData,
};
use crate::{
core::errors::{self, RouterResult},
routes::{app::ReqState, SessionState},
types::{domain, fraud_check::FrmRouterData},
};
pub type BoxedFraudCheckOperation<F, D> = Box<dyn FraudCheckOperation<F, D> + Send + Sync>;
pub trait FraudCheckOperation<F, D>: Send + std::fmt::Debug {
fn to_get_tracker(&self) -> RouterResult<&(dyn GetTracker<PaymentToFrmData> + Send + Sync)> {
Err(report!(errors::ApiErrorResponse::InternalServerError))
.attach_printable_lazy(|| format!("get tracker interface not found for {self:?}"))
}
fn to_domain(&self) -> RouterResult<&dyn Domain<F, D>> {
Err(report!(errors::ApiErrorResponse::InternalServerError))
.attach_printable_lazy(|| format!("domain interface not found for {self:?}"))
}
fn to_update_tracker(&self) -> RouterResult<&(dyn UpdateTracker<FrmData, F, D> + Send + Sync)> {
Err(report!(errors::ApiErrorResponse::InternalServerError))
.attach_printable_lazy(|| format!("get tracker interface not found for {self:?}"))
}
}
#[async_trait]
pub trait GetTracker<D>: Send {
async fn get_trackers<'a>(
&'a self,
state: &'a SessionState,
payment_data: D,
frm_connector_details: ConnectorDetailsCore,
) -> RouterResult<Option<FrmData>>;
}
#[async_trait]
#[allow(clippy::too_many_arguments)]
pub trait Domain<F, D>: Send + Sync {
async fn post_payment_frm<'a>(
&'a self,
state: &'a SessionState,
req_state: ReqState,
payment_data: &mut D,
frm_data: &mut FrmData,
merchant_context: &domain::MerchantContext,
customer: &Option<domain::Customer>,
) -> RouterResult<Option<FrmRouterData>>
where
F: Send + Clone;
async fn pre_payment_frm<'a>(
&'a self,
state: &'a SessionState,
payment_data: &mut D,
frm_data: &mut FrmData,
merchant_context: &domain::MerchantContext,
customer: &Option<domain::Customer>,
) -> RouterResult<FrmRouterData>
where
F: Send + Clone;
// To execute several tasks conditionally based on the result of post_flow.
// Eg: If the /sale(post flow) is returning the transaction as fraud we can execute refund in post task
#[allow(clippy::too_many_arguments)]
async fn execute_post_tasks(
&self,
_state: &SessionState,
_req_state: ReqState,
frm_data: &mut FrmData,
_merchant_context: &domain::MerchantContext,
_frm_configs: FrmConfigsObject,
_frm_suggestion: &mut Option<FrmSuggestion>,
_payment_data: &mut D,
_customer: &Option<domain::Customer>,
_should_continue_capture: &mut bool,
) -> RouterResult<Option<FrmData>>
where
F: Send + Clone,
{
return Ok(Some(frm_data.to_owned()));
}
}
#[async_trait]
pub trait UpdateTracker<Fd, F: Clone, D>: Send {
async fn update_tracker<'b>(
&'b self,
state: &SessionState,
key_store: &domain::MerchantKeyStore,
frm_data: Fd,
payment_data: &mut D,
_frm_suggestion: Option<FrmSuggestion>,
frm_router_data: FrmRouterData,
) -> RouterResult<Fd>;
}
|
crates/router/src/core/fraud_check/operation.rs
|
router::src::core::fraud_check::operation
| 902
| true
|
// File: crates/router/src/core/fraud_check/types.rs
// Module: router::src::core::fraud_check::types
use api_models::{
enums as api_enums,
enums::{PaymentMethod, PaymentMethodType},
payments::Amount,
refunds::RefundResponse,
};
use common_enums::FrmSuggestion;
use common_utils::pii::SecretSerdeValue;
use hyperswitch_domain_models::payments::{payment_attempt::PaymentAttempt, PaymentIntent};
pub use hyperswitch_domain_models::{
router_request_types::fraud_check::{
Address, Destination, FrmFulfillmentRequest, FulfillmentStatus, Fulfillments, Product,
},
types::OrderDetailsWithAmount,
};
use masking::Serialize;
use serde::Deserialize;
use utoipa::ToSchema;
use super::operation::BoxedFraudCheckOperation;
use crate::types::{
domain::MerchantAccount,
storage::{enums as storage_enums, fraud_check::FraudCheck},
PaymentAddress,
};
#[derive(Clone, Default, Debug)]
pub struct PaymentIntentCore {
pub payment_id: common_utils::id_type::PaymentId,
}
#[derive(Clone, Debug)]
pub struct PaymentAttemptCore {
pub attempt_id: String,
pub payment_details: Option<PaymentDetails>,
pub amount: Amount,
}
#[derive(Clone, Debug, Serialize)]
pub struct PaymentDetails {
pub amount: i64,
pub currency: Option<storage_enums::Currency>,
pub payment_method: Option<PaymentMethod>,
pub payment_method_type: Option<PaymentMethodType>,
pub refund_transaction_id: Option<String>,
}
#[derive(Clone, Default, Debug)]
pub struct FrmMerchantAccount {
pub merchant_id: common_utils::id_type::MerchantId,
}
#[derive(Clone, Debug)]
pub struct FrmData {
pub payment_intent: PaymentIntent,
pub payment_attempt: PaymentAttempt,
pub merchant_account: MerchantAccount,
pub fraud_check: FraudCheck,
pub address: PaymentAddress,
pub connector_details: ConnectorDetailsCore,
pub order_details: Option<Vec<OrderDetailsWithAmount>>,
pub refund: Option<RefundResponse>,
pub frm_metadata: Option<SecretSerdeValue>,
}
#[derive(Debug)]
pub struct FrmInfo<F, D> {
pub fraud_check_operation: BoxedFraudCheckOperation<F, D>,
pub frm_data: Option<FrmData>,
pub suggested_action: Option<FrmSuggestion>,
}
#[derive(Clone, Debug)]
pub struct ConnectorDetailsCore {
pub connector_name: String,
pub profile_id: common_utils::id_type::ProfileId,
}
#[derive(Clone)]
pub struct PaymentToFrmData {
pub amount: Amount,
pub payment_intent: PaymentIntent,
pub payment_attempt: PaymentAttempt,
pub merchant_account: MerchantAccount,
pub address: PaymentAddress,
pub connector_details: ConnectorDetailsCore,
pub order_details: Option<Vec<OrderDetailsWithAmount>>,
pub frm_metadata: Option<SecretSerdeValue>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FrmConfigsObject {
pub frm_enabled_pm: Option<PaymentMethod>,
pub frm_enabled_gateway: Option<api_models::enums::Connector>,
pub frm_preferred_flow_type: api_enums::FrmPreferredFlowTypes,
}
#[derive(Debug, Deserialize, Serialize, Clone, ToSchema)]
#[serde(deny_unknown_fields)]
#[serde_with::skip_serializing_none]
#[serde(rename_all = "camelCase")]
pub struct FrmFulfillmentSignifydApiRequest {
///unique order_id for the order_details in the transaction
#[schema(max_length = 255, example = "pay_qiYfHcDou1ycIaxVXKHF")]
pub order_id: String,
///denotes the status of the fulfillment... can be one of PARTIAL, COMPLETE, REPLACEMENT, CANCELED
#[schema(value_type = Option<FulfillmentStatus>, example = "COMPLETE")]
pub fulfillment_status: Option<FulfillmentStatus>,
///contains details of the fulfillment
#[schema(value_type = Vec<Fulfillments>)]
pub fulfillments: Vec<Fulfillments>,
}
#[derive(Debug, ToSchema, Clone, Serialize)]
pub struct FrmFulfillmentResponse {
///unique order_id for the transaction
#[schema(max_length = 255, example = "pay_qiYfHcDou1ycIaxVXKHF")]
pub order_id: String,
///shipment_ids used in the fulfillment overall...also data from previous fulfillments for the same transactions/order is sent
#[schema(example = r#"["ship_101", "ship_102"]"#)]
pub shipment_ids: Vec<String>,
}
#[derive(Debug, Deserialize, Serialize, Clone, ToSchema)]
#[serde(deny_unknown_fields)]
#[serde_with::skip_serializing_none]
#[serde(rename_all = "camelCase")]
pub struct FrmFulfillmentSignifydApiResponse {
///unique order_id for the transaction
#[schema(max_length = 255, example = "pay_qiYfHcDou1ycIaxVXKHF")]
pub order_id: String,
///shipment_ids used in the fulfillment overall...also data from previous fulfillments for the same transactions/order is sent
#[schema(example = r#"["ship_101","ship_102"]"#)]
pub shipment_ids: Vec<String>,
}
pub const CANCEL_INITIATED: &str = "Cancel Initiated with the processor";
|
crates/router/src/core/fraud_check/types.rs
|
router::src::core::fraud_check::types
| 1,169
| true
|
// File: crates/router/src/core/fraud_check/flows.rs
// Module: router::src::core::fraud_check::flows
pub mod checkout_flow;
pub mod fulfillment_flow;
pub mod record_return;
pub mod sale_flow;
pub mod transaction_flow;
use async_trait::async_trait;
use crate::{
core::{
errors::RouterResult,
payments::{self, flows::ConstructFlowSpecificData},
},
routes::SessionState,
services,
types::{
api::{Connector, FraudCheckConnectorData},
domain,
fraud_check::FraudCheckResponseData,
},
};
#[async_trait]
pub trait FeatureFrm<F, T> {
async fn decide_frm_flows<'a>(
self,
state: &SessionState,
connector: &FraudCheckConnectorData,
call_connector_action: payments::CallConnectorAction,
merchant_context: &domain::MerchantContext,
) -> RouterResult<Self>
where
Self: Sized,
F: Clone,
dyn Connector: services::ConnectorIntegration<F, T, FraudCheckResponseData>;
}
|
crates/router/src/core/fraud_check/flows.rs
|
router::src::core::fraud_check::flows
| 228
| true
|
// File: crates/router/src/core/fraud_check/operation/fraud_check_pre.rs
// Module: router::src::core::fraud_check::operation::fraud_check_pre
use async_trait::async_trait;
use common_enums::FrmSuggestion;
use common_utils::ext_traits::Encode;
use diesel_models::enums::FraudCheckLastStep;
use router_env::{instrument, tracing};
use uuid::Uuid;
use super::{Domain, FraudCheckOperation, GetTracker, UpdateTracker};
use crate::{
core::{
errors::RouterResult,
fraud_check::{
self as frm_core,
types::{FrmData, PaymentDetails, PaymentToFrmData},
ConnectorDetailsCore,
},
payments,
},
errors,
routes::app::ReqState,
types::{
api::fraud_check as frm_api,
domain,
fraud_check::{
FraudCheckCheckoutData, FraudCheckResponseData, FraudCheckTransactionData, FrmRequest,
FrmResponse, FrmRouterData,
},
storage::{
enums::{FraudCheckStatus, FraudCheckType},
fraud_check::{FraudCheckNew, FraudCheckUpdate},
},
ResponseId,
},
SessionState,
};
#[derive(Debug, Clone, Copy)]
pub struct FraudCheckPre;
impl<F, D> FraudCheckOperation<F, D> for &FraudCheckPre
where
F: Clone + Send,
D: payments::OperationSessionGetters<F> + Send + Sync + Clone,
{
fn to_get_tracker(&self) -> RouterResult<&(dyn GetTracker<PaymentToFrmData> + Send + Sync)> {
Ok(*self)
}
fn to_domain(&self) -> RouterResult<&dyn Domain<F, D>> {
Ok(*self)
}
fn to_update_tracker(&self) -> RouterResult<&(dyn UpdateTracker<FrmData, F, D> + Send + Sync)> {
Ok(*self)
}
}
impl<F, D> FraudCheckOperation<F, D> for FraudCheckPre
where
F: Clone + Send,
D: payments::OperationSessionGetters<F> + Send + Sync + Clone,
{
fn to_get_tracker(&self) -> RouterResult<&(dyn GetTracker<PaymentToFrmData> + Send + Sync)> {
Ok(self)
}
fn to_domain(&self) -> RouterResult<&dyn Domain<F, D>> {
Ok(self)
}
fn to_update_tracker(&self) -> RouterResult<&(dyn UpdateTracker<FrmData, F, D> + Send + Sync)> {
Ok(self)
}
}
#[async_trait]
impl GetTracker<PaymentToFrmData> for FraudCheckPre {
#[cfg(feature = "v2")]
#[instrument(skip_all)]
async fn get_trackers<'a>(
&'a self,
state: &'a SessionState,
payment_data: PaymentToFrmData,
frm_connector_details: ConnectorDetailsCore,
) -> RouterResult<Option<FrmData>> {
todo!()
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn get_trackers<'a>(
&'a self,
state: &'a SessionState,
payment_data: PaymentToFrmData,
frm_connector_details: ConnectorDetailsCore,
) -> RouterResult<Option<FrmData>> {
let db = &*state.store;
let payment_details: Option<serde_json::Value> = PaymentDetails::from(payment_data.clone())
.encode_to_value()
.ok();
let existing_fraud_check = db
.find_fraud_check_by_payment_id_if_present(
payment_data.payment_intent.get_id().to_owned(),
payment_data.merchant_account.get_id().clone(),
)
.await
.ok();
let fraud_check = match existing_fraud_check {
Some(Some(fraud_check)) => Ok(fraud_check),
_ => {
db.insert_fraud_check_response(FraudCheckNew {
frm_id: Uuid::new_v4().simple().to_string(),
payment_id: payment_data.payment_intent.get_id().to_owned(),
merchant_id: payment_data.merchant_account.get_id().clone(),
attempt_id: payment_data.payment_attempt.attempt_id.clone(),
created_at: common_utils::date_time::now(),
frm_name: frm_connector_details.connector_name,
frm_transaction_id: None,
frm_transaction_type: FraudCheckType::PreFrm,
frm_status: FraudCheckStatus::Pending,
frm_score: None,
frm_reason: None,
frm_error: None,
payment_details,
metadata: None,
modified_at: common_utils::date_time::now(),
last_step: FraudCheckLastStep::Processing,
payment_capture_method: payment_data.payment_attempt.capture_method,
})
.await
}
};
match fraud_check {
Ok(fraud_check_value) => {
let frm_data = FrmData {
payment_intent: payment_data.payment_intent,
payment_attempt: payment_data.payment_attempt,
merchant_account: payment_data.merchant_account,
address: payment_data.address,
fraud_check: fraud_check_value,
connector_details: payment_data.connector_details,
order_details: payment_data.order_details,
refund: None,
frm_metadata: payment_data.frm_metadata,
};
Ok(Some(frm_data))
}
Err(error) => {
router_env::logger::error!("inserting into fraud_check table failed {error:?}");
Ok(None)
}
}
}
}
#[async_trait]
impl<F, D> Domain<F, D> for FraudCheckPre
where
F: Clone + Send,
D: payments::OperationSessionGetters<F> + Send + Sync + Clone,
{
#[cfg(feature = "v2")]
#[instrument(skip_all)]
async fn post_payment_frm<'a>(
&'a self,
_state: &'a SessionState,
_req_state: ReqState,
_payment_data: &mut D,
_frm_data: &mut FrmData,
_merchant_context: &domain::MerchantContext,
_customer: &Option<domain::Customer>,
) -> RouterResult<Option<FrmRouterData>> {
todo!()
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn post_payment_frm<'a>(
&'a self,
state: &'a SessionState,
_req_state: ReqState,
payment_data: &mut D,
frm_data: &mut FrmData,
merchant_context: &domain::MerchantContext,
customer: &Option<domain::Customer>,
) -> RouterResult<Option<FrmRouterData>> {
let router_data = frm_core::call_frm_service::<F, frm_api::Transaction, _, D>(
state,
payment_data,
&mut frm_data.to_owned(),
merchant_context,
customer,
)
.await?;
frm_data.fraud_check.last_step = FraudCheckLastStep::TransactionOrRecordRefund;
Ok(Some(FrmRouterData {
merchant_id: router_data.merchant_id,
connector: router_data.connector,
payment_id: router_data.payment_id.clone(),
attempt_id: router_data.attempt_id,
request: FrmRequest::Transaction(FraudCheckTransactionData {
amount: router_data.request.amount,
order_details: router_data.request.order_details,
currency: router_data.request.currency,
payment_method: Some(router_data.payment_method),
error_code: router_data.request.error_code,
error_message: router_data.request.error_message,
connector_transaction_id: router_data.request.connector_transaction_id,
connector: router_data.request.connector,
}),
response: FrmResponse::Transaction(router_data.response),
}))
}
async fn pre_payment_frm<'a>(
&'a self,
state: &'a SessionState,
payment_data: &mut D,
frm_data: &mut FrmData,
merchant_context: &domain::MerchantContext,
customer: &Option<domain::Customer>,
) -> RouterResult<FrmRouterData> {
let router_data = frm_core::call_frm_service::<F, frm_api::Checkout, _, D>(
state,
payment_data,
&mut frm_data.to_owned(),
merchant_context,
customer,
)
.await?;
frm_data.fraud_check.last_step = FraudCheckLastStep::CheckoutOrSale;
Ok(FrmRouterData {
merchant_id: router_data.merchant_id,
connector: router_data.connector,
payment_id: router_data.payment_id.clone(),
attempt_id: router_data.attempt_id,
request: FrmRequest::Checkout(Box::new(FraudCheckCheckoutData {
amount: router_data.request.amount,
order_details: router_data.request.order_details,
currency: router_data.request.currency,
browser_info: router_data.request.browser_info,
payment_method_data: router_data.request.payment_method_data,
email: router_data.request.email,
gateway: router_data.request.gateway,
})),
response: FrmResponse::Checkout(router_data.response),
})
}
}
#[async_trait]
impl<F, D> UpdateTracker<FrmData, F, D> for FraudCheckPre
where
F: Clone + Send,
D: payments::OperationSessionGetters<F> + Send + Sync + Clone,
{
async fn update_tracker<'b>(
&'b self,
state: &SessionState,
_key_store: &domain::MerchantKeyStore,
mut frm_data: FrmData,
payment_data: &mut D,
_frm_suggestion: Option<FrmSuggestion>,
frm_router_data: FrmRouterData,
) -> RouterResult<FrmData> {
let frm_check_update = match frm_router_data.response {
FrmResponse::Checkout(response) => match response {
Err(err) => Some(FraudCheckUpdate::ErrorUpdate {
status: FraudCheckStatus::TransactionFailure,
error_message: Some(Some(err.message)),
}),
Ok(payments_response) => match payments_response {
FraudCheckResponseData::TransactionResponse {
resource_id,
connector_metadata,
status,
reason,
score,
} => {
let connector_transaction_id = match resource_id {
ResponseId::NoResponseId => None,
ResponseId::ConnectorTransactionId(id) => Some(id),
ResponseId::EncodedData(id) => Some(id),
};
let fraud_check_update = FraudCheckUpdate::ResponseUpdate {
frm_status: status,
frm_transaction_id: connector_transaction_id,
frm_reason: reason,
frm_score: score,
metadata: connector_metadata,
modified_at: common_utils::date_time::now(),
last_step: frm_data.fraud_check.last_step,
payment_capture_method: frm_data.fraud_check.payment_capture_method,
};
Some(fraud_check_update)
}
FraudCheckResponseData::FulfillmentResponse {
order_id: _,
shipment_ids: _,
} => None,
FraudCheckResponseData::RecordReturnResponse {
resource_id: _,
connector_metadata: _,
return_id: _,
} => Some(FraudCheckUpdate::ErrorUpdate {
status: FraudCheckStatus::TransactionFailure,
error_message: Some(Some(
"Error: Got Record Return Response response in current Checkout flow"
.to_string(),
)),
}),
},
},
FrmResponse::Transaction(response) => match response {
Err(err) => Some(FraudCheckUpdate::ErrorUpdate {
status: FraudCheckStatus::TransactionFailure,
error_message: Some(Some(err.message)),
}),
Ok(payments_response) => match payments_response {
FraudCheckResponseData::TransactionResponse {
resource_id,
connector_metadata,
status,
reason,
score,
} => {
let connector_transaction_id = match resource_id {
ResponseId::NoResponseId => None,
ResponseId::ConnectorTransactionId(id) => Some(id),
ResponseId::EncodedData(id) => Some(id),
};
let frm_status = payment_data
.get_frm_message()
.as_ref()
.map_or(status, |frm_data| frm_data.frm_status);
let fraud_check_update = FraudCheckUpdate::ResponseUpdate {
frm_status,
frm_transaction_id: connector_transaction_id,
frm_reason: reason,
frm_score: score,
metadata: connector_metadata,
modified_at: common_utils::date_time::now(),
last_step: frm_data.fraud_check.last_step,
payment_capture_method: None,
};
Some(fraud_check_update)
}
FraudCheckResponseData::FulfillmentResponse {
order_id: _,
shipment_ids: _,
} => None,
FraudCheckResponseData::RecordReturnResponse {
resource_id: _,
connector_metadata: _,
return_id: _,
} => Some(FraudCheckUpdate::ErrorUpdate {
status: FraudCheckStatus::TransactionFailure,
error_message: Some(Some(
"Error: Got Record Return Response response in current Checkout flow"
.to_string(),
)),
}),
},
},
FrmResponse::Sale(_response)
| FrmResponse::Fulfillment(_response)
| FrmResponse::RecordReturn(_response) => Some(FraudCheckUpdate::ErrorUpdate {
status: FraudCheckStatus::TransactionFailure,
error_message: Some(Some(
"Error: Got Pre(Sale) flow response in current post flow".to_string(),
)),
}),
};
let db = &*state.store;
frm_data.fraud_check = match frm_check_update {
Some(fraud_check_update) => db
.update_fraud_check_response_with_attempt_id(
frm_data.clone().fraud_check,
fraud_check_update,
)
.await
.map_err(|error| error.change_context(errors::ApiErrorResponse::PaymentNotFound))?,
None => frm_data.clone().fraud_check,
};
Ok(frm_data)
}
}
|
crates/router/src/core/fraud_check/operation/fraud_check_pre.rs
|
router::src::core::fraud_check::operation::fraud_check_pre
| 2,952
| true
|
// File: crates/router/src/core/fraud_check/operation/fraud_check_post.rs
// Module: router::src::core::fraud_check::operation::fraud_check_post
use async_trait::async_trait;
use common_enums::{CaptureMethod, FrmSuggestion};
use common_utils::ext_traits::Encode;
use hyperswitch_domain_models::payments::{
payment_attempt::PaymentAttemptUpdate, payment_intent::PaymentIntentUpdate, HeaderPayload,
};
use router_env::{instrument, logger, tracing};
use super::{Domain, FraudCheckOperation, GetTracker, UpdateTracker};
use crate::{
consts,
core::{
errors::{RouterResult, StorageErrorExt},
fraud_check::{
self as frm_core,
types::{FrmData, PaymentDetails, PaymentToFrmData, CANCEL_INITIATED},
ConnectorDetailsCore, FrmConfigsObject,
},
payments,
},
errors,
routes::app::ReqState,
services::{self, api},
types::{
api::{
enums::{AttemptStatus, IntentStatus},
fraud_check as frm_api, payments as payment_types, Capture, Void,
},
domain,
fraud_check::{
FraudCheckResponseData, FraudCheckSaleData, FrmRequest, FrmResponse, FrmRouterData,
},
storage::{
enums::{FraudCheckLastStep, FraudCheckStatus, FraudCheckType, MerchantDecision},
fraud_check::{FraudCheckNew, FraudCheckUpdate},
},
ResponseId,
},
utils, SessionState,
};
#[derive(Debug, Clone, Copy)]
pub struct FraudCheckPost;
impl<F, D> FraudCheckOperation<F, D> for &FraudCheckPost
where
F: Clone + Send,
D: payments::OperationSessionGetters<F>
+ payments::OperationSessionSetters<F>
+ Send
+ Sync
+ Clone,
{
fn to_get_tracker(&self) -> RouterResult<&(dyn GetTracker<PaymentToFrmData> + Send + Sync)> {
Ok(*self)
}
fn to_domain(&self) -> RouterResult<&dyn Domain<F, D>> {
Ok(*self)
}
fn to_update_tracker(&self) -> RouterResult<&(dyn UpdateTracker<FrmData, F, D> + Send + Sync)> {
Ok(*self)
}
}
impl<F, D> FraudCheckOperation<F, D> for FraudCheckPost
where
F: Clone + Send,
D: payments::OperationSessionGetters<F>
+ payments::OperationSessionSetters<F>
+ Send
+ Sync
+ Clone,
{
fn to_get_tracker(&self) -> RouterResult<&(dyn GetTracker<PaymentToFrmData> + Send + Sync)> {
Ok(self)
}
fn to_domain(&self) -> RouterResult<&dyn Domain<F, D>> {
Ok(self)
}
fn to_update_tracker(&self) -> RouterResult<&(dyn UpdateTracker<FrmData, F, D> + Send + Sync)> {
Ok(self)
}
}
#[async_trait]
impl GetTracker<PaymentToFrmData> for FraudCheckPost {
#[cfg(feature = "v2")]
async fn get_trackers<'a>(
&'a self,
state: &'a SessionState,
payment_data: PaymentToFrmData,
frm_connector_details: ConnectorDetailsCore,
) -> RouterResult<Option<FrmData>> {
todo!()
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn get_trackers<'a>(
&'a self,
state: &'a SessionState,
payment_data: PaymentToFrmData,
frm_connector_details: ConnectorDetailsCore,
) -> RouterResult<Option<FrmData>> {
let db = &*state.store;
let payment_details: Option<serde_json::Value> = PaymentDetails::from(payment_data.clone())
.encode_to_value()
.ok();
let existing_fraud_check = db
.find_fraud_check_by_payment_id_if_present(
payment_data.payment_intent.get_id().to_owned(),
payment_data.merchant_account.get_id().clone(),
)
.await
.ok();
let fraud_check = match existing_fraud_check {
Some(Some(fraud_check)) => Ok(fraud_check),
_ => {
db.insert_fraud_check_response(FraudCheckNew {
frm_id: utils::generate_id(consts::ID_LENGTH, "frm"),
payment_id: payment_data.payment_intent.get_id().to_owned(),
merchant_id: payment_data.merchant_account.get_id().clone(),
attempt_id: payment_data.payment_attempt.attempt_id.clone(),
created_at: common_utils::date_time::now(),
frm_name: frm_connector_details.connector_name,
frm_transaction_id: None,
frm_transaction_type: FraudCheckType::PostFrm,
frm_status: FraudCheckStatus::Pending,
frm_score: None,
frm_reason: None,
frm_error: None,
payment_details,
metadata: None,
modified_at: common_utils::date_time::now(),
last_step: FraudCheckLastStep::Processing,
payment_capture_method: payment_data.payment_attempt.capture_method,
})
.await
}
};
match fraud_check {
Ok(fraud_check_value) => {
let frm_data = FrmData {
payment_intent: payment_data.payment_intent,
payment_attempt: payment_data.payment_attempt,
merchant_account: payment_data.merchant_account,
address: payment_data.address,
fraud_check: fraud_check_value,
connector_details: payment_data.connector_details,
order_details: payment_data.order_details,
refund: None,
frm_metadata: payment_data.frm_metadata,
};
Ok(Some(frm_data))
}
Err(error) => {
router_env::logger::error!("inserting into fraud_check table failed {error:?}");
Ok(None)
}
}
}
}
#[async_trait]
impl<F, D> Domain<F, D> for FraudCheckPost
where
F: Clone + Send,
D: payments::OperationSessionGetters<F>
+ payments::OperationSessionSetters<F>
+ Send
+ Sync
+ Clone,
{
#[instrument(skip_all)]
async fn post_payment_frm<'a>(
&'a self,
state: &'a SessionState,
_req_state: ReqState,
payment_data: &mut D,
frm_data: &mut FrmData,
merchant_context: &domain::MerchantContext,
customer: &Option<domain::Customer>,
) -> RouterResult<Option<FrmRouterData>> {
if frm_data.fraud_check.last_step != FraudCheckLastStep::Processing {
logger::debug!("post_flow::Sale Skipped");
return Ok(None);
}
let router_data = frm_core::call_frm_service::<F, frm_api::Sale, _, D>(
state,
payment_data,
&mut frm_data.to_owned(),
merchant_context,
customer,
)
.await?;
frm_data.fraud_check.last_step = FraudCheckLastStep::CheckoutOrSale;
Ok(Some(FrmRouterData {
merchant_id: router_data.merchant_id,
connector: router_data.connector,
payment_id: router_data.payment_id.clone(),
attempt_id: router_data.attempt_id,
request: FrmRequest::Sale(FraudCheckSaleData {
amount: router_data.request.amount,
order_details: router_data.request.order_details,
currency: router_data.request.currency,
email: router_data.request.email,
}),
response: FrmResponse::Sale(router_data.response),
}))
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
async fn execute_post_tasks(
&self,
_state: &SessionState,
_req_state: ReqState,
_frm_data: &mut FrmData,
_merchant_context: &domain::MerchantContext,
_frm_configs: FrmConfigsObject,
_frm_suggestion: &mut Option<FrmSuggestion>,
_payment_data: &mut D,
_customer: &Option<domain::Customer>,
_should_continue_capture: &mut bool,
) -> RouterResult<Option<FrmData>> {
todo!()
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn execute_post_tasks(
&self,
state: &SessionState,
req_state: ReqState,
frm_data: &mut FrmData,
merchant_context: &domain::MerchantContext,
_frm_configs: FrmConfigsObject,
frm_suggestion: &mut Option<FrmSuggestion>,
payment_data: &mut D,
customer: &Option<domain::Customer>,
_should_continue_capture: &mut bool,
) -> RouterResult<Option<FrmData>> {
if matches!(frm_data.fraud_check.frm_status, FraudCheckStatus::Fraud)
&& matches!(
frm_data.fraud_check.last_step,
FraudCheckLastStep::CheckoutOrSale
)
{
*frm_suggestion = Some(FrmSuggestion::FrmCancelTransaction);
let cancel_req = api_models::payments::PaymentsCancelRequest {
payment_id: frm_data.payment_intent.get_id().to_owned(),
cancellation_reason: frm_data.fraud_check.frm_error.clone(),
merchant_connector_details: None,
};
let cancel_res = Box::pin(payments::payments_core::<
Void,
payment_types::PaymentsResponse,
_,
_,
_,
payments::PaymentData<Void>,
>(
state.clone(),
req_state.clone(),
merchant_context.clone(),
None,
payments::PaymentCancel,
cancel_req,
api::AuthFlow::Merchant,
payments::CallConnectorAction::Trigger,
None,
HeaderPayload::default(),
))
.await?;
logger::debug!("payment_id : {:?} has been cancelled since it has been found fraudulent by configured frm connector",payment_data.get_payment_attempt().payment_id);
if let services::ApplicationResponse::JsonWithHeaders((payments_response, _)) =
cancel_res
{
payment_data.set_payment_intent_status(payments_response.status);
}
let _router_data = frm_core::call_frm_service::<F, frm_api::RecordReturn, _, D>(
state,
payment_data,
&mut frm_data.to_owned(),
merchant_context,
customer,
)
.await?;
frm_data.fraud_check.last_step = FraudCheckLastStep::TransactionOrRecordRefund;
} else if matches!(
frm_data.fraud_check.frm_status,
FraudCheckStatus::ManualReview
) {
*frm_suggestion = Some(FrmSuggestion::FrmManualReview);
} else if matches!(frm_data.fraud_check.frm_status, FraudCheckStatus::Legit)
&& matches!(
frm_data.fraud_check.payment_capture_method,
Some(CaptureMethod::Automatic) | Some(CaptureMethod::SequentialAutomatic)
)
{
let capture_request = api_models::payments::PaymentsCaptureRequest {
payment_id: frm_data.payment_intent.get_id().to_owned(),
merchant_id: None,
amount_to_capture: None,
refund_uncaptured_amount: None,
statement_descriptor_suffix: None,
statement_descriptor_prefix: None,
merchant_connector_details: None,
};
let capture_response = Box::pin(payments::payments_core::<
Capture,
payment_types::PaymentsResponse,
_,
_,
_,
payments::PaymentData<Capture>,
>(
state.clone(),
req_state.clone(),
merchant_context.clone(),
None,
payments::PaymentCapture,
capture_request,
api::AuthFlow::Merchant,
payments::CallConnectorAction::Trigger,
None,
HeaderPayload::default(),
))
.await?;
logger::debug!("payment_id : {:?} has been captured since it has been found legit by configured frm connector",payment_data.get_payment_attempt().payment_id);
if let services::ApplicationResponse::JsonWithHeaders((payments_response, _)) =
capture_response
{
payment_data.set_payment_intent_status(payments_response.status);
}
};
return Ok(Some(frm_data.to_owned()));
}
#[instrument(skip_all)]
async fn pre_payment_frm<'a>(
&'a self,
state: &'a SessionState,
payment_data: &mut D,
frm_data: &mut FrmData,
merchant_context: &domain::MerchantContext,
customer: &Option<domain::Customer>,
) -> RouterResult<FrmRouterData> {
let router_data = frm_core::call_frm_service::<F, frm_api::Sale, _, D>(
state,
payment_data,
&mut frm_data.to_owned(),
merchant_context,
customer,
)
.await?;
Ok(FrmRouterData {
merchant_id: router_data.merchant_id,
connector: router_data.connector,
payment_id: router_data.payment_id,
attempt_id: router_data.attempt_id,
request: FrmRequest::Sale(FraudCheckSaleData {
amount: router_data.request.amount,
order_details: router_data.request.order_details,
currency: router_data.request.currency,
email: router_data.request.email,
}),
response: FrmResponse::Sale(router_data.response),
})
}
}
#[async_trait]
impl<F, D> UpdateTracker<FrmData, F, D> for FraudCheckPost
where
F: Clone + Send,
D: payments::OperationSessionGetters<F>
+ payments::OperationSessionSetters<F>
+ Send
+ Sync
+ Clone,
{
#[cfg(feature = "v2")]
async fn update_tracker<'b>(
&'b self,
state: &SessionState,
key_store: &domain::MerchantKeyStore,
mut frm_data: FrmData,
payment_data: &mut D,
frm_suggestion: Option<FrmSuggestion>,
frm_router_data: FrmRouterData,
) -> RouterResult<FrmData> {
todo!()
}
#[cfg(feature = "v1")]
async fn update_tracker<'b>(
&'b self,
state: &SessionState,
key_store: &domain::MerchantKeyStore,
mut frm_data: FrmData,
payment_data: &mut D,
frm_suggestion: Option<FrmSuggestion>,
frm_router_data: FrmRouterData,
) -> RouterResult<FrmData> {
let db = &*state.store;
let key_manager_state = &state.into();
let frm_check_update = match frm_router_data.response {
FrmResponse::Sale(response) => match response {
Err(err) => Some(FraudCheckUpdate::ErrorUpdate {
status: FraudCheckStatus::TransactionFailure,
error_message: Some(Some(err.message)),
}),
Ok(payments_response) => match payments_response {
FraudCheckResponseData::TransactionResponse {
resource_id,
connector_metadata,
status,
reason,
score,
} => {
let connector_transaction_id = match resource_id {
ResponseId::NoResponseId => None,
ResponseId::ConnectorTransactionId(id) => Some(id),
ResponseId::EncodedData(id) => Some(id),
};
let fraud_check_update = FraudCheckUpdate::ResponseUpdate {
frm_status: status,
frm_transaction_id: connector_transaction_id,
frm_reason: reason,
frm_score: score,
metadata: connector_metadata,
modified_at: common_utils::date_time::now(),
last_step: frm_data.fraud_check.last_step,
payment_capture_method: frm_data.fraud_check.payment_capture_method,
};
Some(fraud_check_update)
},
FraudCheckResponseData::RecordReturnResponse { resource_id: _, connector_metadata: _, return_id: _ } => {
Some(FraudCheckUpdate::ErrorUpdate {
status: FraudCheckStatus::TransactionFailure,
error_message: Some(Some(
"Error: Got Record Return Response response in current Sale flow".to_string(),
)),
})
}
FraudCheckResponseData::FulfillmentResponse {
order_id: _,
shipment_ids: _,
} => None,
},
},
FrmResponse::Fulfillment(response) => match response {
Err(err) => Some(FraudCheckUpdate::ErrorUpdate {
status: FraudCheckStatus::TransactionFailure,
error_message: Some(Some(err.message)),
}),
Ok(payments_response) => match payments_response {
FraudCheckResponseData::TransactionResponse {
resource_id,
connector_metadata,
status,
reason,
score,
} => {
let connector_transaction_id = match resource_id {
ResponseId::NoResponseId => None,
ResponseId::ConnectorTransactionId(id) => Some(id),
ResponseId::EncodedData(id) => Some(id),
};
let fraud_check_update = FraudCheckUpdate::ResponseUpdate {
frm_status: status,
frm_transaction_id: connector_transaction_id,
frm_reason: reason,
frm_score: score,
metadata: connector_metadata,
modified_at: common_utils::date_time::now(),
last_step: frm_data.fraud_check.last_step,
payment_capture_method: frm_data.fraud_check.payment_capture_method,
};
Some(fraud_check_update)
}
FraudCheckResponseData::FulfillmentResponse {
order_id: _,
shipment_ids: _,
} => None,
FraudCheckResponseData::RecordReturnResponse { resource_id: _, connector_metadata: _, return_id: _ } => None,
},
},
FrmResponse::RecordReturn(response) => match response {
Err(err) => Some(FraudCheckUpdate::ErrorUpdate {
status: FraudCheckStatus::TransactionFailure,
error_message: Some(Some(err.message)),
}),
Ok(payments_response) => match payments_response {
FraudCheckResponseData::TransactionResponse {
resource_id: _,
connector_metadata: _,
status: _,
reason: _,
score: _,
} => {
Some(FraudCheckUpdate::ErrorUpdate {
status: FraudCheckStatus::TransactionFailure,
error_message: Some(Some(
"Error: Got Transaction Response response in current Record Return flow".to_string(),
)),
})
},
FraudCheckResponseData::FulfillmentResponse {order_id: _, shipment_ids: _ } => {
None
},
FraudCheckResponseData::RecordReturnResponse { resource_id, connector_metadata, return_id: _ } => {
let connector_transaction_id = match resource_id {
ResponseId::NoResponseId => None,
ResponseId::ConnectorTransactionId(id) => Some(id),
ResponseId::EncodedData(id) => Some(id),
};
let fraud_check_update = FraudCheckUpdate::ResponseUpdate {
frm_status: frm_data.fraud_check.frm_status,
frm_transaction_id: connector_transaction_id,
frm_reason: frm_data.fraud_check.frm_reason.clone(),
frm_score: frm_data.fraud_check.frm_score,
metadata: connector_metadata,
modified_at: common_utils::date_time::now(),
last_step: frm_data.fraud_check.last_step,
payment_capture_method: frm_data.fraud_check.payment_capture_method,
};
Some(fraud_check_update)
}
},
},
FrmResponse::Checkout(_) | FrmResponse::Transaction(_) => {
Some(FraudCheckUpdate::ErrorUpdate {
status: FraudCheckStatus::TransactionFailure,
error_message: Some(Some(
"Error: Got Pre(Sale) flow response in current post flow".to_string(),
)),
})
}
};
if let Some(frm_suggestion) = frm_suggestion {
let (payment_attempt_status, payment_intent_status, merchant_decision, error_message) =
match frm_suggestion {
FrmSuggestion::FrmCancelTransaction => (
AttemptStatus::Failure,
IntentStatus::Failed,
Some(MerchantDecision::Rejected.to_string()),
Some(Some(CANCEL_INITIATED.to_string())),
),
FrmSuggestion::FrmManualReview => (
AttemptStatus::Unresolved,
IntentStatus::RequiresMerchantAction,
None,
None,
),
FrmSuggestion::FrmAuthorizeTransaction => (
AttemptStatus::Authorized,
IntentStatus::RequiresCapture,
None,
None,
),
};
let payment_attempt_update = PaymentAttemptUpdate::RejectUpdate {
status: payment_attempt_status,
error_code: Some(Some(frm_data.fraud_check.frm_status.to_string())),
error_message,
updated_by: frm_data.merchant_account.storage_scheme.to_string(),
};
#[cfg(feature = "v1")]
let payment_attempt = db
.update_payment_attempt_with_attempt_id(
payment_data.get_payment_attempt().clone(),
payment_attempt_update,
frm_data.merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
#[cfg(feature = "v2")]
let payment_attempt = db
.update_payment_attempt_with_attempt_id(
key_manager_state,
key_store,
payment_data.get_payment_attempt().clone(),
payment_attempt_update,
frm_data.merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
payment_data.set_payment_attempt(payment_attempt);
let payment_intent = db
.update_payment_intent(
key_manager_state,
payment_data.get_payment_intent().clone(),
PaymentIntentUpdate::RejectUpdate {
status: payment_intent_status,
merchant_decision,
updated_by: frm_data.merchant_account.storage_scheme.to_string(),
},
key_store,
frm_data.merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
payment_data.set_payment_intent(payment_intent);
}
frm_data.fraud_check = match frm_check_update {
Some(fraud_check_update) => db
.update_fraud_check_response_with_attempt_id(
frm_data.fraud_check.clone(),
fraud_check_update,
)
.await
.map_err(|error| error.change_context(errors::ApiErrorResponse::PaymentNotFound))?,
None => frm_data.fraud_check.clone(),
};
Ok(frm_data)
}
}
|
crates/router/src/core/fraud_check/operation/fraud_check_post.rs
|
router::src::core::fraud_check::operation::fraud_check_post
| 4,731
| true
|
// File: crates/router/src/core/fraud_check/flows/checkout_flow.rs
// Module: router::src::core::fraud_check::flows::checkout_flow
use async_trait::async_trait;
use common_utils::{ext_traits::ValueExt, pii::Email};
use error_stack::ResultExt;
use masking::ExposeInterface;
use super::{ConstructFlowSpecificData, FeatureFrm};
use crate::{
core::{
errors::{ConnectorErrorExt, RouterResult},
fraud_check::types::FrmData,
payments::{self, helpers},
},
errors, services,
types::{
api::fraud_check::{self as frm_api, FraudCheckConnectorData},
domain,
fraud_check::{FraudCheckCheckoutData, FraudCheckResponseData, FrmCheckoutRouterData},
storage::enums as storage_enums,
BrowserInformation, ConnectorAuthType, MerchantRecipientData, ResponseId, RouterData,
},
SessionState,
};
#[async_trait]
impl ConstructFlowSpecificData<frm_api::Checkout, FraudCheckCheckoutData, FraudCheckResponseData>
for FrmData
{
#[cfg(feature = "v2")]
async fn construct_router_data<'a>(
&self,
_state: &SessionState,
_connector_id: &str,
_merchant_context: &domain::MerchantContext,
_customer: &Option<domain::Customer>,
_merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
_merchant_recipient_data: Option<MerchantRecipientData>,
_header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
) -> RouterResult<RouterData<frm_api::Checkout, FraudCheckCheckoutData, FraudCheckResponseData>>
{
todo!()
}
#[cfg(feature = "v1")]
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
merchant_context: &domain::MerchantContext,
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
_merchant_recipient_data: Option<MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
_payment_method: Option<common_enums::PaymentMethod>,
_payment_method_type: Option<common_enums::PaymentMethodType>,
) -> RouterResult<RouterData<frm_api::Checkout, FraudCheckCheckoutData, FraudCheckResponseData>>
{
use crate::connector::utils::PaymentsAttemptData;
let status = storage_enums::AttemptStatus::Pending;
let auth_type: ConnectorAuthType = merchant_connector_account
.get_connector_account_details()
.parse_value("ConnectorAuthType")
.change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: "ConnectorAuthType".to_string(),
})?;
let browser_info: Option<BrowserInformation> = self.payment_attempt.get_browser_info().ok();
let customer_id = customer.to_owned().map(|customer| customer.customer_id);
let router_data = RouterData {
flow: std::marker::PhantomData,
merchant_id: merchant_context.get_merchant_account().get_id().clone(),
customer_id,
tenant_id: state.tenant.tenant_id.clone(),
connector: connector_id.to_string(),
payment_id: self.payment_intent.payment_id.get_string_repr().to_owned(),
attempt_id: self.payment_attempt.attempt_id.clone(),
status,
payment_method: self
.payment_attempt
.payment_method
.ok_or(errors::ApiErrorResponse::PaymentMethodNotFound)?,
payment_method_type: self.payment_attempt.payment_method_type,
connector_auth_type: auth_type,
description: None,
payment_method_status: None,
address: self.address.clone(),
auth_type: storage_enums::AuthenticationType::NoThreeDs,
connector_meta_data: None,
connector_wallets_details: None,
amount_captured: None,
minor_amount_captured: None,
request: FraudCheckCheckoutData {
amount: self
.payment_attempt
.net_amount
.get_total_amount()
.get_amount_as_i64(),
order_details: self.order_details.clone(),
currency: self.payment_attempt.currency,
browser_info,
payment_method_data: self
.payment_attempt
.payment_method_data
.as_ref()
.map(|pm_data| {
pm_data
.clone()
.parse_value::<api_models::payments::AdditionalPaymentData>(
"AdditionalPaymentData",
)
})
.transpose()
.unwrap_or_default(),
email: customer
.clone()
.and_then(|customer_data| {
customer_data
.email
.map(|email| Email::try_from(email.into_inner().expose()))
})
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "customer.customer_data.email",
})?,
gateway: self.payment_attempt.connector.clone(),
}, // self.order_details
response: Ok(FraudCheckResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId("".to_string()),
connector_metadata: None,
status: storage_enums::FraudCheckStatus::Pending,
score: None,
reason: None,
}),
access_token: None,
session_token: None,
reference_id: None,
payment_method_token: None,
connector_customer: None,
preprocessing_id: None,
connector_request_reference_id: uuid::Uuid::new_v4().to_string(),
test_mode: None,
recurring_mandate_payment_data: None,
#[cfg(feature = "payouts")]
payout_method_data: None,
#[cfg(feature = "payouts")]
quote_id: None,
payment_method_balance: None,
connector_http_status_code: None,
external_latency: None,
connector_api_version: None,
apple_pay_flow: None,
frm_metadata: self.frm_metadata.clone(),
refund_id: None,
dispute_id: None,
connector_response: None,
integrity_check: Ok(()),
additional_merchant_data: None,
header_payload,
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)
}
}
#[async_trait]
impl FeatureFrm<frm_api::Checkout, FraudCheckCheckoutData> for FrmCheckoutRouterData {
async fn decide_frm_flows<'a>(
mut self,
state: &SessionState,
connector: &FraudCheckConnectorData,
call_connector_action: payments::CallConnectorAction,
merchant_context: &domain::MerchantContext,
) -> RouterResult<Self> {
decide_frm_flow(
&mut self,
state,
connector,
call_connector_action,
merchant_context,
)
.await
}
}
pub async fn decide_frm_flow(
router_data: &mut FrmCheckoutRouterData,
state: &SessionState,
connector: &FraudCheckConnectorData,
call_connector_action: payments::CallConnectorAction,
_merchant_context: &domain::MerchantContext,
) -> RouterResult<FrmCheckoutRouterData> {
let connector_integration: services::BoxedFrmConnectorIntegrationInterface<
frm_api::Checkout,
FraudCheckCheckoutData,
FraudCheckResponseData,
> = connector.connector.get_connector_integration();
let resp = services::execute_connector_processing_step(
state,
connector_integration,
router_data,
call_connector_action,
None,
None,
)
.await
.to_payment_failed_response()?;
Ok(resp)
}
|
crates/router/src/core/fraud_check/flows/checkout_flow.rs
|
router::src::core::fraud_check::flows::checkout_flow
| 1,674
| true
|
// File: crates/router/src/core/fraud_check/flows/transaction_flow.rs
// Module: router::src::core::fraud_check::flows::transaction_flow
use async_trait::async_trait;
use common_utils::ext_traits::ValueExt;
use error_stack::ResultExt;
use crate::{
core::{
errors::{ConnectorErrorExt, RouterResult},
fraud_check::{FeatureFrm, FrmData},
payments::{self, flows::ConstructFlowSpecificData, helpers},
},
errors, services,
types::{
api::fraud_check as frm_api,
domain,
fraud_check::{
FraudCheckResponseData, FraudCheckTransactionData, FrmTransactionRouterData,
},
storage::enums as storage_enums,
ConnectorAuthType, MerchantRecipientData, ResponseId, RouterData,
},
SessionState,
};
#[async_trait]
impl
ConstructFlowSpecificData<
frm_api::Transaction,
FraudCheckTransactionData,
FraudCheckResponseData,
> for FrmData
{
#[cfg(feature = "v2")]
async fn construct_router_data<'a>(
&self,
_state: &SessionState,
_connector_id: &str,
_merchant_context: &domain::MerchantContext,
_customer: &Option<domain::Customer>,
_merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
_merchant_recipient_data: Option<MerchantRecipientData>,
_header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
) -> RouterResult<
RouterData<frm_api::Transaction, FraudCheckTransactionData, FraudCheckResponseData>,
> {
todo!()
}
#[cfg(feature = "v1")]
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
merchant_context: &domain::MerchantContext,
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
_merchant_recipient_data: Option<MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
_payment_method: Option<common_enums::PaymentMethod>,
_payment_method_type: Option<common_enums::PaymentMethodType>,
) -> RouterResult<
RouterData<frm_api::Transaction, FraudCheckTransactionData, FraudCheckResponseData>,
> {
let status = storage_enums::AttemptStatus::Pending;
let auth_type: ConnectorAuthType = merchant_connector_account
.get_connector_account_details()
.parse_value("ConnectorAuthType")
.change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: "ConnectorAuthType".to_string(),
})?;
let customer_id = customer.to_owned().map(|customer| customer.customer_id);
let payment_method = self.payment_attempt.payment_method;
let currency = self.payment_attempt.currency;
let router_data = RouterData {
flow: std::marker::PhantomData,
merchant_id: merchant_context.get_merchant_account().get_id().clone(),
tenant_id: state.tenant.tenant_id.clone(),
customer_id,
connector: connector_id.to_string(),
payment_id: self.payment_intent.payment_id.get_string_repr().to_owned(),
attempt_id: self.payment_attempt.attempt_id.clone(),
status,
payment_method: self
.payment_attempt
.payment_method
.ok_or(errors::ApiErrorResponse::PaymentMethodNotFound)?,
payment_method_type: self.payment_attempt.payment_method_type,
connector_auth_type: auth_type,
description: None,
address: self.address.clone(),
auth_type: storage_enums::AuthenticationType::NoThreeDs,
connector_meta_data: None,
connector_wallets_details: None,
amount_captured: None,
minor_amount_captured: None,
request: FraudCheckTransactionData {
amount: self
.payment_attempt
.net_amount
.get_total_amount()
.get_amount_as_i64(),
order_details: self.order_details.clone(),
currency,
payment_method,
error_code: self.payment_attempt.error_code.clone(),
error_message: self.payment_attempt.error_message.clone(),
connector_transaction_id: self
.payment_attempt
.get_connector_payment_id()
.map(ToString::to_string),
connector: self.payment_attempt.connector.clone(),
}, // self.order_details
response: Ok(FraudCheckResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId("".to_string()),
connector_metadata: None,
status: storage_enums::FraudCheckStatus::Pending,
score: None,
reason: None,
}),
access_token: None,
session_token: None,
reference_id: None,
payment_method_token: None,
connector_customer: None,
preprocessing_id: None,
connector_request_reference_id: uuid::Uuid::new_v4().to_string(),
test_mode: None,
recurring_mandate_payment_data: None,
#[cfg(feature = "payouts")]
payout_method_data: None,
#[cfg(feature = "payouts")]
quote_id: None,
payment_method_balance: None,
connector_http_status_code: None,
external_latency: None,
connector_api_version: None,
payment_method_status: None,
apple_pay_flow: None,
frm_metadata: self.frm_metadata.clone(),
refund_id: None,
dispute_id: None,
connector_response: None,
integrity_check: Ok(()),
additional_merchant_data: None,
header_payload,
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)
}
}
#[async_trait]
impl FeatureFrm<frm_api::Transaction, FraudCheckTransactionData> for FrmTransactionRouterData {
async fn decide_frm_flows<'a>(
mut self,
state: &SessionState,
connector: &frm_api::FraudCheckConnectorData,
call_connector_action: payments::CallConnectorAction,
merchant_context: &domain::MerchantContext,
) -> RouterResult<Self> {
decide_frm_flow(
&mut self,
state,
connector,
call_connector_action,
merchant_context,
)
.await
}
}
pub async fn decide_frm_flow(
router_data: &mut FrmTransactionRouterData,
state: &SessionState,
connector: &frm_api::FraudCheckConnectorData,
call_connector_action: payments::CallConnectorAction,
_merchant_context: &domain::MerchantContext,
) -> RouterResult<FrmTransactionRouterData> {
let connector_integration: services::BoxedFrmConnectorIntegrationInterface<
frm_api::Transaction,
FraudCheckTransactionData,
FraudCheckResponseData,
> = connector.connector.get_connector_integration();
let resp = services::execute_connector_processing_step(
state,
connector_integration,
router_data,
call_connector_action,
None,
None,
)
.await
.to_payment_failed_response()?;
Ok(resp)
}
|
crates/router/src/core/fraud_check/flows/transaction_flow.rs
|
router::src::core::fraud_check::flows::transaction_flow
| 1,553
| true
|
// File: crates/router/src/core/fraud_check/flows/sale_flow.rs
// Module: router::src::core::fraud_check::flows::sale_flow
use async_trait::async_trait;
use common_utils::{ext_traits::ValueExt, pii::Email};
use error_stack::ResultExt;
use masking::ExposeInterface;
use crate::{
core::{
errors::{ConnectorErrorExt, RouterResult},
fraud_check::{FeatureFrm, FraudCheckConnectorData, FrmData},
payments::{self, flows::ConstructFlowSpecificData, helpers},
},
errors, services,
types::{
api::fraud_check as frm_api,
domain,
fraud_check::{FraudCheckResponseData, FraudCheckSaleData, FrmSaleRouterData},
storage::enums as storage_enums,
ConnectorAuthType, MerchantRecipientData, ResponseId, RouterData,
},
SessionState,
};
#[async_trait]
impl ConstructFlowSpecificData<frm_api::Sale, FraudCheckSaleData, FraudCheckResponseData>
for FrmData
{
#[cfg(feature = "v2")]
async fn construct_router_data<'a>(
&self,
_state: &SessionState,
_connector_id: &str,
_merchant_context: &domain::MerchantContext,
_customer: &Option<domain::Customer>,
_merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
_merchant_recipient_data: Option<MerchantRecipientData>,
_header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
) -> RouterResult<RouterData<frm_api::Sale, FraudCheckSaleData, FraudCheckResponseData>> {
todo!()
}
#[cfg(feature = "v1")]
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
merchant_context: &domain::MerchantContext,
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
_merchant_recipient_data: Option<MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
_payment_method: Option<common_enums::PaymentMethod>,
_payment_method_type: Option<common_enums::PaymentMethodType>,
) -> RouterResult<RouterData<frm_api::Sale, FraudCheckSaleData, FraudCheckResponseData>> {
let status = storage_enums::AttemptStatus::Pending;
let auth_type: ConnectorAuthType = merchant_connector_account
.get_connector_account_details()
.parse_value("ConnectorAuthType")
.change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: "ConnectorAuthType".to_string(),
})?;
let customer_id = customer.to_owned().map(|customer| customer.customer_id);
let router_data = RouterData {
flow: std::marker::PhantomData,
merchant_id: merchant_context.get_merchant_account().get_id().clone(),
customer_id,
connector: connector_id.to_string(),
payment_id: self.payment_intent.payment_id.get_string_repr().to_owned(),
attempt_id: self.payment_attempt.attempt_id.clone(),
tenant_id: state.tenant.tenant_id.clone(),
status,
payment_method: self
.payment_attempt
.payment_method
.ok_or(errors::ApiErrorResponse::PaymentMethodNotFound)?,
payment_method_type: self.payment_attempt.payment_method_type,
connector_auth_type: auth_type,
description: None,
address: self.address.clone(),
auth_type: storage_enums::AuthenticationType::NoThreeDs,
connector_meta_data: None,
connector_wallets_details: None,
amount_captured: None,
minor_amount_captured: None,
request: FraudCheckSaleData {
amount: self
.payment_attempt
.net_amount
.get_total_amount()
.get_amount_as_i64(),
order_details: self.order_details.clone(),
currency: self.payment_attempt.currency,
email: customer
.clone()
.and_then(|customer_data| {
customer_data
.email
.map(|email| Email::try_from(email.into_inner().expose()))
})
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "customer.customer_data.email",
})?,
},
response: Ok(FraudCheckResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId("".to_string()),
connector_metadata: None,
status: storage_enums::FraudCheckStatus::Pending,
score: None,
reason: None,
}),
access_token: None,
session_token: None,
reference_id: None,
payment_method_token: None,
connector_customer: None,
preprocessing_id: None,
payment_method_status: None,
connector_request_reference_id: uuid::Uuid::new_v4().to_string(),
test_mode: None,
recurring_mandate_payment_data: None,
#[cfg(feature = "payouts")]
payout_method_data: None,
#[cfg(feature = "payouts")]
quote_id: None,
payment_method_balance: None,
connector_http_status_code: None,
external_latency: None,
connector_api_version: None,
apple_pay_flow: None,
frm_metadata: self.frm_metadata.clone(),
refund_id: None,
dispute_id: None,
connector_response: None,
integrity_check: Ok(()),
additional_merchant_data: None,
header_payload,
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)
}
}
#[async_trait]
impl FeatureFrm<frm_api::Sale, FraudCheckSaleData> for FrmSaleRouterData {
async fn decide_frm_flows<'a>(
mut self,
state: &SessionState,
connector: &FraudCheckConnectorData,
call_connector_action: payments::CallConnectorAction,
merchant_context: &domain::MerchantContext,
) -> RouterResult<Self> {
decide_frm_flow(
&mut self,
state,
connector,
call_connector_action,
merchant_context,
)
.await
}
}
pub async fn decide_frm_flow(
router_data: &mut FrmSaleRouterData,
state: &SessionState,
connector: &FraudCheckConnectorData,
call_connector_action: payments::CallConnectorAction,
_merchant_context: &domain::MerchantContext,
) -> RouterResult<FrmSaleRouterData> {
let connector_integration: services::BoxedFrmConnectorIntegrationInterface<
frm_api::Sale,
FraudCheckSaleData,
FraudCheckResponseData,
> = connector.connector.get_connector_integration();
let resp = services::execute_connector_processing_step(
state,
connector_integration,
router_data,
call_connector_action,
None,
None,
)
.await
.to_payment_failed_response()?;
Ok(resp)
}
|
crates/router/src/core/fraud_check/flows/sale_flow.rs
|
router::src::core::fraud_check::flows::sale_flow
| 1,540
| true
|
// File: crates/router/src/core/fraud_check/flows/record_return.rs
// Module: router::src::core::fraud_check::flows::record_return
use async_trait::async_trait;
use common_utils::ext_traits::ValueExt;
use error_stack::ResultExt;
use crate::{
connector::signifyd::transformers::RefundMethod,
core::{
errors::{ConnectorErrorExt, RouterResult},
fraud_check::{FeatureFrm, FraudCheckConnectorData, FrmData},
payments::{self, flows::ConstructFlowSpecificData, helpers},
},
errors, services,
types::{
api::RecordReturn,
domain,
fraud_check::{
FraudCheckRecordReturnData, FraudCheckResponseData, FrmRecordReturnRouterData,
},
storage::enums as storage_enums,
ConnectorAuthType, MerchantRecipientData, ResponseId, RouterData,
},
utils, SessionState,
};
#[async_trait]
impl ConstructFlowSpecificData<RecordReturn, FraudCheckRecordReturnData, FraudCheckResponseData>
for FrmData
{
#[cfg(feature = "v2")]
async fn construct_router_data<'a>(
&self,
_state: &SessionState,
_connector_id: &str,
_merchant_context: &domain::MerchantContext,
_customer: &Option<domain::Customer>,
_merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
_merchant_recipient_data: Option<MerchantRecipientData>,
_header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
) -> RouterResult<RouterData<RecordReturn, FraudCheckRecordReturnData, FraudCheckResponseData>>
{
todo!()
}
#[cfg(feature = "v1")]
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
merchant_context: &domain::MerchantContext,
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
_merchant_recipient_data: Option<MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
_payment_method: Option<common_enums::PaymentMethod>,
_payment_method_type: Option<common_enums::PaymentMethodType>,
) -> RouterResult<RouterData<RecordReturn, FraudCheckRecordReturnData, FraudCheckResponseData>>
{
let status = storage_enums::AttemptStatus::Pending;
let auth_type: ConnectorAuthType = merchant_connector_account
.get_connector_account_details()
.parse_value("ConnectorAuthType")
.change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: "ConnectorAuthType".to_string(),
})?;
let customer_id = customer.to_owned().map(|customer| customer.customer_id);
let currency = self.payment_attempt.clone().currency;
let router_data = RouterData {
flow: std::marker::PhantomData,
merchant_id: merchant_context.get_merchant_account().get_id().clone(),
tenant_id: state.tenant.tenant_id.clone(),
customer_id,
connector: connector_id.to_string(),
payment_id: self.payment_intent.payment_id.get_string_repr().to_owned(),
attempt_id: self.payment_attempt.attempt_id.clone(),
status,
payment_method: utils::OptionExt::get_required_value(
self.payment_attempt.payment_method,
"payment_method",
)?,
payment_method_type: self.payment_attempt.payment_method_type,
connector_auth_type: auth_type,
description: None,
address: self.address.clone(),
auth_type: storage_enums::AuthenticationType::NoThreeDs,
connector_meta_data: None,
connector_wallets_details: None,
amount_captured: None,
minor_amount_captured: None,
request: FraudCheckRecordReturnData {
amount: self
.payment_attempt
.net_amount
.get_total_amount()
.get_amount_as_i64(),
refund_method: RefundMethod::OriginalPaymentInstrument, //we dont consume this data now in payments...hence hardcoded
currency,
refund_transaction_id: self.refund.clone().map(|refund| refund.refund_id),
}, // self.order_details
response: Ok(FraudCheckResponseData::RecordReturnResponse {
resource_id: ResponseId::ConnectorTransactionId("".to_string()),
connector_metadata: None,
return_id: None,
}),
access_token: None,
session_token: None,
reference_id: None,
payment_method_token: None,
connector_customer: None,
preprocessing_id: None,
payment_method_status: None,
connector_request_reference_id: uuid::Uuid::new_v4().to_string(),
test_mode: None,
recurring_mandate_payment_data: None,
#[cfg(feature = "payouts")]
payout_method_data: None,
#[cfg(feature = "payouts")]
quote_id: None,
payment_method_balance: None,
connector_http_status_code: None,
external_latency: None,
connector_api_version: None,
apple_pay_flow: None,
frm_metadata: None,
refund_id: None,
dispute_id: None,
connector_response: None,
integrity_check: Ok(()),
additional_merchant_data: None,
header_payload,
connector_mandate_request_reference_id: None,
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)
}
}
#[async_trait]
impl FeatureFrm<RecordReturn, FraudCheckRecordReturnData> for FrmRecordReturnRouterData {
async fn decide_frm_flows<'a>(
mut self,
state: &SessionState,
connector: &FraudCheckConnectorData,
call_connector_action: payments::CallConnectorAction,
merchant_context: &domain::MerchantContext,
) -> RouterResult<Self> {
decide_frm_flow(
&mut self,
state,
connector,
call_connector_action,
merchant_context,
)
.await
}
}
pub async fn decide_frm_flow(
router_data: &mut FrmRecordReturnRouterData,
state: &SessionState,
connector: &FraudCheckConnectorData,
call_connector_action: payments::CallConnectorAction,
_merchant_context: &domain::MerchantContext,
) -> RouterResult<FrmRecordReturnRouterData> {
let connector_integration: services::BoxedFrmConnectorIntegrationInterface<
RecordReturn,
FraudCheckRecordReturnData,
FraudCheckResponseData,
> = connector.connector.get_connector_integration();
let resp = services::execute_connector_processing_step(
state,
connector_integration,
router_data,
call_connector_action,
None,
None,
)
.await
.to_payment_failed_response()?;
Ok(resp)
}
|
crates/router/src/core/fraud_check/flows/record_return.rs
|
router::src::core::fraud_check::flows::record_return
| 1,496
| true
|
// File: crates/router/src/core/fraud_check/flows/fulfillment_flow.rs
// Module: router::src::core::fraud_check::flows::fulfillment_flow
use common_utils::ext_traits::{OptionExt, ValueExt};
use error_stack::ResultExt;
use router_env::tracing::{self, instrument};
use crate::{
core::{
errors::RouterResult, fraud_check::frm_core_types::FrmFulfillmentRequest,
payments::helpers, utils as core_utils,
},
errors,
types::{
domain,
fraud_check::{FraudCheckFulfillmentData, FrmFulfillmentRouterData},
storage, ConnectorAuthType, ErrorResponse, PaymentAddress, RouterData,
},
utils, SessionState,
};
#[cfg(feature = "v2")]
pub async fn construct_fulfillment_router_data<'a>(
_state: &'a SessionState,
_payment_intent: &'a storage::PaymentIntent,
_payment_attempt: &storage::PaymentAttempt,
_merchant_context: &domain::MerchantContext,
_connector: String,
_fulfillment_request: FrmFulfillmentRequest,
) -> RouterResult<FrmFulfillmentRouterData> {
todo!()
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
pub async fn construct_fulfillment_router_data<'a>(
state: &'a SessionState,
payment_intent: &'a storage::PaymentIntent,
payment_attempt: &storage::PaymentAttempt,
merchant_context: &domain::MerchantContext,
connector: String,
fulfillment_request: FrmFulfillmentRequest,
) -> RouterResult<FrmFulfillmentRouterData> {
let profile_id = payment_intent
.profile_id
.as_ref()
.get_required_value("profile_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("profile_id is not set in payment_intent")?
.clone();
let connector_id = connector.clone();
let merchant_connector_account = helpers::get_merchant_connector_account(
state,
merchant_context.get_merchant_account().get_id(),
None,
merchant_context.get_merchant_key_store(),
&profile_id,
&connector,
None,
)
.await?;
let test_mode: Option<bool> = merchant_connector_account.is_test_mode_on();
let auth_type: ConnectorAuthType = merchant_connector_account
.get_connector_account_details()
.parse_value("ConnectorAuthType")
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let payment_method =
utils::OptionExt::get_required_value(payment_attempt.payment_method, "payment_method")?;
let router_data = RouterData {
flow: std::marker::PhantomData,
merchant_id: merchant_context.get_merchant_account().get_id().clone(),
tenant_id: state.tenant.tenant_id.clone(),
connector,
payment_id: payment_attempt.payment_id.get_string_repr().to_owned(),
attempt_id: payment_attempt.attempt_id.clone(),
status: payment_attempt.status,
payment_method,
payment_method_type: payment_attempt.payment_method_type,
connector_auth_type: auth_type,
description: None,
address: PaymentAddress::default(),
auth_type: payment_attempt.authentication_type.unwrap_or_default(),
connector_meta_data: merchant_connector_account.get_metadata(),
connector_wallets_details: merchant_connector_account.get_connector_wallets_details(),
amount_captured: payment_intent
.amount_captured
.map(|amt| amt.get_amount_as_i64()),
minor_amount_captured: payment_intent.amount_captured,
payment_method_status: None,
request: FraudCheckFulfillmentData {
amount: payment_attempt
.net_amount
.get_total_amount()
.get_amount_as_i64(),
order_details: payment_intent.order_details.clone(),
fulfillment_req: fulfillment_request,
},
response: Err(ErrorResponse::default()),
access_token: None,
session_token: None,
reference_id: None,
payment_method_token: None,
connector_customer: None,
customer_id: None,
recurring_mandate_payment_data: None,
preprocessing_id: None,
payment_method_balance: None,
connector_request_reference_id: core_utils::get_connector_request_reference_id(
&state.conf,
merchant_context.get_merchant_account().get_id(),
payment_intent,
payment_attempt,
&connector_id,
)?,
#[cfg(feature = "payouts")]
payout_method_data: None,
#[cfg(feature = "payouts")]
quote_id: None,
test_mode,
connector_api_version: None,
connector_http_status_code: None,
external_latency: None,
apple_pay_flow: None,
frm_metadata: None,
refund_id: None,
dispute_id: None,
connector_response: None,
integrity_check: Ok(()),
additional_merchant_data: None,
header_payload: None,
connector_mandate_request_reference_id: None,
authentication_id: None,
psd2_sca_exemption_type: None,
raw_connector_response: None,
is_payment_id_from_merchant: None,
l2_l3_data: None,
minor_amount_capturable: None,
authorized_amount: None,
};
Ok(router_data)
}
|
crates/router/src/core/fraud_check/flows/fulfillment_flow.rs
|
router::src::core::fraud_check::flows::fulfillment_flow
| 1,120
| true
|
// File: crates/router/src/core/proxy/utils.rs
// Module: router::src::core::proxy::utils
use api_models::{payment_methods::PaymentMethodId, proxy as proxy_api_models};
use common_utils::{
ext_traits::{Encode, OptionExt},
id_type,
};
use error_stack::ResultExt;
use hyperswitch_domain_models::payment_methods;
use masking::Mask;
use serde_json::Value;
use x509_parser::nom::{
bytes::complete::{tag, take_while1},
character::complete::{char, multispace0},
sequence::{delimited, preceded, terminated},
IResult,
};
use crate::{
core::{
errors::{self, RouterResult},
payment_methods::vault,
},
routes::SessionState,
types::{domain, payment_methods as pm_types},
};
pub struct ProxyRequestWrapper(pub proxy_api_models::ProxyRequest);
pub enum ProxyRecord {
PaymentMethodRecord(Box<domain::PaymentMethod>),
TokenizationRecord(Box<domain::Tokenization>),
}
impl ProxyRequestWrapper {
pub async fn get_proxy_record(
&self,
state: &SessionState,
key_store: &domain::MerchantKeyStore,
storage_scheme: common_enums::enums::MerchantStorageScheme,
) -> RouterResult<ProxyRecord> {
let token = &self.0.token;
match self.0.token_type {
proxy_api_models::TokenType::PaymentMethodId => {
let pm_id = PaymentMethodId {
payment_method_id: token.clone(),
};
let pm_id =
id_type::GlobalPaymentMethodId::generate_from_string(pm_id.payment_method_id)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to generate GlobalPaymentMethodId")?;
let payment_method_record = state
.store
.find_payment_method(&((state).into()), key_store, &pm_id, storage_scheme)
.await
.change_context(errors::ApiErrorResponse::PaymentMethodNotFound)?;
Ok(ProxyRecord::PaymentMethodRecord(Box::new(
payment_method_record,
)))
}
proxy_api_models::TokenType::TokenizationId => {
let token_id = id_type::GlobalTokenId::from_string(token.clone().as_str())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Error while coneverting from string to GlobalTokenId type",
)?;
let db = state.store.as_ref();
let key_manager_state = &(state).into();
let tokenization_record = db
.get_entity_id_vault_id_by_token_id(&token_id, key_store, key_manager_state)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error while fetching tokenization record from vault")?;
Ok(ProxyRecord::TokenizationRecord(Box::new(
tokenization_record,
)))
}
}
}
pub fn get_headers(&self) -> Vec<(String, masking::Maskable<String>)> {
self.0
.headers
.as_map()
.iter()
.map(|(key, value)| (key.clone(), value.clone().into_masked()))
.collect()
}
pub fn get_destination_url(&self) -> &str {
self.0.destination_url.as_str()
}
pub fn get_method(&self) -> common_utils::request::Method {
self.0.method
}
}
impl ProxyRecord {
fn get_vault_id(&self) -> RouterResult<payment_methods::VaultId> {
match self {
Self::PaymentMethodRecord(payment_method) => payment_method
.locker_id
.clone()
.get_required_value("vault_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Locker id not present in Payment Method Entry"),
Self::TokenizationRecord(tokenization_record) => Ok(
payment_methods::VaultId::generate(tokenization_record.locker_id.clone()),
),
}
}
fn get_customer_id(&self) -> id_type::GlobalCustomerId {
match self {
Self::PaymentMethodRecord(payment_method) => payment_method.customer_id.clone(),
Self::TokenizationRecord(tokenization_record) => {
tokenization_record.customer_id.clone()
}
}
}
pub async fn get_vault_data(
&self,
state: &SessionState,
merchant_context: domain::MerchantContext,
) -> RouterResult<Value> {
match self {
Self::PaymentMethodRecord(_) => {
let vault_resp = vault::retrieve_payment_method_from_vault_internal(
state,
&merchant_context,
&self.get_vault_id()?,
&self.get_customer_id(),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error while fetching data from vault")?;
Ok(vault_resp
.data
.encode_to_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to serialize vault data")?)
}
Self::TokenizationRecord(_) => {
let vault_request = pm_types::VaultRetrieveRequest {
entity_id: self.get_customer_id(),
vault_id: self.get_vault_id()?,
};
let vault_data = vault::retrieve_value_from_vault(state, vault_request)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to retrieve vault data")?;
Ok(vault_data.get("data").cloned().unwrap_or(Value::Null))
}
}
}
}
#[derive(Debug)]
pub struct TokenReference {
pub field: String,
}
pub fn parse_token(input: &str) -> IResult<&str, TokenReference> {
let (input, field) = delimited(
tag("{{"),
preceded(
multispace0,
preceded(
char('$'),
terminated(
take_while1(|c: char| c.is_alphanumeric() || c == '_'),
multispace0,
),
),
),
tag("}}"),
)(input)?;
Ok((
input,
TokenReference {
field: field.to_string(),
},
))
}
pub fn contains_token(s: &str) -> bool {
s.contains("{{") && s.contains("$") && s.contains("}}")
}
|
crates/router/src/core/proxy/utils.rs
|
router::src::core::proxy::utils
| 1,350
| true
|
// File: crates/router/src/core/card_testing_guard/utils.rs
// Module: router::src::core::card_testing_guard::utils
use error_stack::ResultExt;
use hyperswitch_domain_models::{
card_testing_guard_data::CardTestingGuardData, router_request_types::BrowserInformation,
};
use masking::{PeekInterface, Secret};
use router_env::logger;
use super::errors;
use crate::{
core::{errors::RouterResult, payments::helpers},
routes::SessionState,
services,
types::domain,
utils::crypto::{self, SignMessage},
};
pub async fn validate_card_testing_guard_checks(
state: &SessionState,
#[cfg(feature = "v1")] browser_info: Option<&serde_json::Value>,
#[cfg(feature = "v2")] browser_info: Option<&BrowserInformation>,
card_number: cards::CardNumber,
customer_id: &Option<common_utils::id_type::CustomerId>,
business_profile: &domain::Profile,
) -> RouterResult<Option<CardTestingGuardData>> {
match &business_profile.card_testing_guard_config {
Some(card_testing_guard_config) => {
let fingerprint = generate_fingerprint(card_number, business_profile).await?;
let card_testing_guard_expiry = card_testing_guard_config.card_testing_guard_expiry;
let mut card_ip_blocking_cache_key = String::new();
let mut guest_user_card_blocking_cache_key = String::new();
let mut customer_id_blocking_cache_key = String::new();
if card_testing_guard_config.is_card_ip_blocking_enabled {
if let Some(browser_info) = browser_info {
#[cfg(feature = "v1")]
{
let browser_info =
serde_json::from_value::<BrowserInformation>(browser_info.clone())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("could not parse browser_info")?;
if let Some(browser_info_ip) = browser_info.ip_address {
card_ip_blocking_cache_key =
helpers::validate_card_ip_blocking_for_business_profile(
state,
browser_info_ip,
fingerprint.clone(),
card_testing_guard_config,
)
.await?;
}
}
#[cfg(feature = "v2")]
{
if let Some(browser_info_ip) = browser_info.ip_address {
card_ip_blocking_cache_key =
helpers::validate_card_ip_blocking_for_business_profile(
state,
browser_info_ip,
fingerprint.clone(),
card_testing_guard_config,
)
.await?;
}
}
}
}
if card_testing_guard_config.is_guest_user_card_blocking_enabled {
guest_user_card_blocking_cache_key =
helpers::validate_guest_user_card_blocking_for_business_profile(
state,
fingerprint.clone(),
customer_id.clone(),
card_testing_guard_config,
)
.await?;
}
if card_testing_guard_config.is_customer_id_blocking_enabled {
if let Some(customer_id) = customer_id.clone() {
customer_id_blocking_cache_key =
helpers::validate_customer_id_blocking_for_business_profile(
state,
customer_id.clone(),
business_profile.get_id(),
card_testing_guard_config,
)
.await?;
}
}
Ok(Some(CardTestingGuardData {
is_card_ip_blocking_enabled: card_testing_guard_config.is_card_ip_blocking_enabled,
card_ip_blocking_cache_key,
is_guest_user_card_blocking_enabled: card_testing_guard_config
.is_guest_user_card_blocking_enabled,
guest_user_card_blocking_cache_key,
is_customer_id_blocking_enabled: card_testing_guard_config
.is_customer_id_blocking_enabled,
customer_id_blocking_cache_key,
card_testing_guard_expiry,
}))
}
None => Ok(None),
}
}
pub async fn generate_fingerprint(
card_number: cards::CardNumber,
business_profile: &domain::Profile,
) -> RouterResult<Secret<String>> {
let card_testing_secret_key = &business_profile.card_testing_secret_key;
match card_testing_secret_key {
Some(card_testing_secret_key) => {
let card_number_fingerprint = crypto::HmacSha512::sign_message(
&crypto::HmacSha512,
card_testing_secret_key.get_inner().peek().as_bytes(),
card_number.clone().get_card_no().as_bytes(),
)
.attach_printable("error in pm fingerprint creation")
.map_or_else(
|err| {
logger::error!(error=?err);
None
},
Some,
)
.map(hex::encode);
card_number_fingerprint.map(Secret::new).ok_or_else(|| {
error_stack::report!(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error while masking fingerprint")
})
}
None => Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable("card testing secret key not configured")?,
}
}
pub async fn increment_blocked_count_in_cache(
state: &SessionState,
card_testing_guard_data: Option<CardTestingGuardData>,
) -> RouterResult<()> {
if let Some(card_testing_guard_data) = card_testing_guard_data.clone() {
if card_testing_guard_data.is_card_ip_blocking_enabled
&& !card_testing_guard_data
.card_ip_blocking_cache_key
.is_empty()
{
let _ = services::card_testing_guard::increment_blocked_count_in_cache(
state,
&card_testing_guard_data.card_ip_blocking_cache_key,
card_testing_guard_data.card_testing_guard_expiry.into(),
)
.await;
}
if card_testing_guard_data.is_guest_user_card_blocking_enabled
&& !card_testing_guard_data
.guest_user_card_blocking_cache_key
.is_empty()
{
let _ = services::card_testing_guard::increment_blocked_count_in_cache(
state,
&card_testing_guard_data.guest_user_card_blocking_cache_key,
card_testing_guard_data.card_testing_guard_expiry.into(),
)
.await;
}
if card_testing_guard_data.is_customer_id_blocking_enabled
&& !card_testing_guard_data
.customer_id_blocking_cache_key
.is_empty()
{
let _ = services::card_testing_guard::increment_blocked_count_in_cache(
state,
&card_testing_guard_data.customer_id_blocking_cache_key,
card_testing_guard_data.card_testing_guard_expiry.into(),
)
.await;
}
}
Ok(())
}
|
crates/router/src/core/card_testing_guard/utils.rs
|
router::src::core::card_testing_guard::utils
| 1,317
| true
|
// File: crates/router/src/core/connector_onboarding/paypal.rs
// Module: router::src::core::connector_onboarding::paypal
use api_models::{admin::MerchantConnectorUpdate, connector_onboarding as api};
use common_utils::ext_traits::Encode;
use error_stack::ResultExt;
pub use external_services::http_client;
use masking::{ExposeInterface, PeekInterface, Secret};
use crate::{
core::{
admin,
errors::{ApiErrorResponse, RouterResult},
},
services::{ApplicationResponse, Request},
types::{self as oss_types, api as oss_api_types, api::connector_onboarding as types},
utils::connector_onboarding as utils,
SessionState,
};
fn build_referral_url(state: SessionState) -> String {
format!(
"{}v2/customer/partner-referrals",
state.conf.connectors.paypal.base_url
)
}
async fn build_referral_request(
state: SessionState,
tracking_id: String,
return_url: String,
) -> RouterResult<Request> {
let access_token = utils::paypal::generate_access_token(state.clone()).await?;
let request_body = types::paypal::PartnerReferralRequest::new(tracking_id, return_url);
utils::paypal::build_paypal_post_request(
build_referral_url(state),
request_body,
access_token.token.expose(),
)
}
pub async fn get_action_url_from_paypal(
state: SessionState,
tracking_id: String,
return_url: String,
) -> RouterResult<String> {
let referral_request = Box::pin(build_referral_request(
state.clone(),
tracking_id,
return_url,
))
.await?;
let referral_response = http_client::send_request(&state.conf.proxy, referral_request, None)
.await
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to send request to paypal referrals")?;
let parsed_response: types::paypal::PartnerReferralResponse = referral_response
.json()
.await
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to parse paypal response")?;
parsed_response.extract_action_url()
}
fn merchant_onboarding_status_url(state: SessionState, tracking_id: String) -> String {
let partner_id = state
.conf
.connector_onboarding
.get_inner()
.paypal
.partner_id
.to_owned();
format!(
"{}v1/customer/partners/{}/merchant-integrations?tracking_id={}",
state.conf.connectors.paypal.base_url,
partner_id.expose(),
tracking_id
)
}
pub async fn sync_merchant_onboarding_status(
state: SessionState,
tracking_id: String,
) -> RouterResult<api::OnboardingStatus> {
let access_token = utils::paypal::generate_access_token(state.clone()).await?;
let Some(seller_status_response) =
find_paypal_merchant_by_tracking_id(state.clone(), tracking_id, &access_token).await?
else {
return Ok(api::OnboardingStatus::PayPal(
api::PayPalOnboardingStatus::AccountNotFound,
));
};
let merchant_details_url = seller_status_response
.extract_merchant_details_url(&state.conf.connectors.paypal.base_url)?;
let merchant_details_request =
utils::paypal::build_paypal_get_request(merchant_details_url, access_token.token.expose())?;
let merchant_details_response =
http_client::send_request(&state.conf.proxy, merchant_details_request, None)
.await
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to send request to paypal merchant details")?;
let parsed_response: types::paypal::SellerStatusDetailsResponse = merchant_details_response
.json()
.await
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to parse paypal merchant details response")?;
let eligibity = parsed_response.get_eligibility_status().await?;
Ok(api::OnboardingStatus::PayPal(eligibity))
}
async fn find_paypal_merchant_by_tracking_id(
state: SessionState,
tracking_id: String,
access_token: &oss_types::AccessToken,
) -> RouterResult<Option<types::paypal::SellerStatusResponse>> {
let seller_status_request = utils::paypal::build_paypal_get_request(
merchant_onboarding_status_url(state.clone(), tracking_id),
access_token.token.peek().to_string(),
)?;
let seller_status_response =
http_client::send_request(&state.conf.proxy, seller_status_request, None)
.await
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to send request to paypal onboarding status")?;
if seller_status_response.status().is_success() {
return Ok(Some(
seller_status_response
.json()
.await
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to parse paypal onboarding status response")?,
));
}
Ok(None)
}
pub async fn update_mca(
state: &SessionState,
merchant_id: common_utils::id_type::MerchantId,
connector_id: common_utils::id_type::MerchantConnectorAccountId,
auth_details: oss_types::ConnectorAuthType,
) -> RouterResult<oss_api_types::MerchantConnectorResponse> {
let connector_auth_json = auth_details
.encode_to_value()
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Error while deserializing connector_account_details")?;
#[cfg(feature = "v1")]
let request = MerchantConnectorUpdate {
connector_type: common_enums::ConnectorType::PaymentProcessor,
connector_account_details: Some(Secret::new(connector_auth_json)),
disabled: Some(false),
status: Some(common_enums::ConnectorStatus::Active),
connector_label: None,
payment_methods_enabled: None,
metadata: None,
frm_configs: None,
connector_webhook_details: None,
pm_auth_config: None,
test_mode: None,
additional_merchant_data: None,
connector_wallets_details: None,
};
#[cfg(feature = "v2")]
let request = MerchantConnectorUpdate {
connector_type: common_enums::ConnectorType::PaymentProcessor,
connector_account_details: Some(Secret::new(connector_auth_json)),
disabled: Some(false),
status: Some(common_enums::ConnectorStatus::Active),
connector_label: None,
payment_methods_enabled: None,
metadata: None,
frm_configs: None,
connector_webhook_details: None,
pm_auth_config: None,
merchant_id: merchant_id.clone(),
additional_merchant_data: None,
connector_wallets_details: None,
feature_metadata: None,
};
let mca_response =
admin::update_connector(state.clone(), &merchant_id, None, &connector_id, request).await?;
match mca_response {
ApplicationResponse::Json(mca_data) => Ok(mca_data),
_ => Err(ApiErrorResponse::InternalServerError.into()),
}
}
|
crates/router/src/core/connector_onboarding/paypal.rs
|
router::src::core::connector_onboarding::paypal
| 1,492
| true
|
// File: crates/router/src/core/disputes/transformers.rs
// Module: router::src::core::disputes::transformers
use api_models::disputes::EvidenceType;
use common_utils::errors::CustomResult;
use error_stack::ResultExt;
use crate::{
core::{errors, files::helpers::retrieve_file_and_provider_file_id_from_file_id},
routes::SessionState,
types::{
api::{self, DisputeEvidence},
domain,
transformers::ForeignFrom,
SubmitEvidenceRequestData,
},
};
pub async fn get_evidence_request_data(
state: &SessionState,
merchant_context: &domain::MerchantContext,
evidence_request: api_models::disputes::SubmitEvidenceRequest,
dispute: &diesel_models::dispute::Dispute,
) -> CustomResult<SubmitEvidenceRequestData, errors::ApiErrorResponse> {
let cancellation_policy_file_info = retrieve_file_and_provider_file_id_from_file_id(
state,
evidence_request.cancellation_policy,
None,
merchant_context,
api::FileDataRequired::NotRequired,
)
.await?;
let customer_communication_file_info = retrieve_file_and_provider_file_id_from_file_id(
state,
evidence_request.customer_communication,
None,
merchant_context,
api::FileDataRequired::NotRequired,
)
.await?;
let customer_sifnature_file_info = retrieve_file_and_provider_file_id_from_file_id(
state,
evidence_request.customer_signature,
None,
merchant_context,
api::FileDataRequired::NotRequired,
)
.await?;
let receipt_file_info = retrieve_file_and_provider_file_id_from_file_id(
state,
evidence_request.receipt,
None,
merchant_context,
api::FileDataRequired::NotRequired,
)
.await?;
let refund_policy_file_info = retrieve_file_and_provider_file_id_from_file_id(
state,
evidence_request.refund_policy,
None,
merchant_context,
api::FileDataRequired::NotRequired,
)
.await?;
let service_documentation_file_info = retrieve_file_and_provider_file_id_from_file_id(
state,
evidence_request.service_documentation,
None,
merchant_context,
api::FileDataRequired::NotRequired,
)
.await?;
let shipping_documentation_file_info = retrieve_file_and_provider_file_id_from_file_id(
state,
evidence_request.shipping_documentation,
None,
merchant_context,
api::FileDataRequired::NotRequired,
)
.await?;
let invoice_showing_distinct_transactions_file_info =
retrieve_file_and_provider_file_id_from_file_id(
state,
evidence_request.invoice_showing_distinct_transactions,
None,
merchant_context,
api::FileDataRequired::NotRequired,
)
.await?;
let recurring_transaction_agreement_file_info =
retrieve_file_and_provider_file_id_from_file_id(
state,
evidence_request.recurring_transaction_agreement,
None,
merchant_context,
api::FileDataRequired::NotRequired,
)
.await?;
let uncategorized_file_info = retrieve_file_and_provider_file_id_from_file_id(
state,
evidence_request.uncategorized_file,
None,
merchant_context,
api::FileDataRequired::NotRequired,
)
.await?;
Ok(SubmitEvidenceRequestData {
dispute_id: dispute.dispute_id.clone(),
dispute_status: dispute.dispute_status,
connector_dispute_id: dispute.connector_dispute_id.clone(),
access_activity_log: evidence_request.access_activity_log,
billing_address: evidence_request.billing_address,
cancellation_policy: cancellation_policy_file_info.file_data,
cancellation_policy_provider_file_id: cancellation_policy_file_info.provider_file_id,
cancellation_policy_disclosure: evidence_request.cancellation_policy_disclosure,
cancellation_rebuttal: evidence_request.cancellation_rebuttal,
customer_communication: customer_communication_file_info.file_data,
customer_communication_provider_file_id: customer_communication_file_info.provider_file_id,
customer_email_address: evidence_request.customer_email_address,
customer_name: evidence_request.customer_name,
customer_purchase_ip: evidence_request.customer_purchase_ip,
customer_signature: customer_sifnature_file_info.file_data,
customer_signature_provider_file_id: customer_sifnature_file_info.provider_file_id,
product_description: evidence_request.product_description,
receipt: receipt_file_info.file_data,
receipt_provider_file_id: receipt_file_info.provider_file_id,
refund_policy: refund_policy_file_info.file_data,
refund_policy_provider_file_id: refund_policy_file_info.provider_file_id,
refund_policy_disclosure: evidence_request.refund_policy_disclosure,
refund_refusal_explanation: evidence_request.refund_refusal_explanation,
service_date: evidence_request.service_date,
service_documentation: service_documentation_file_info.file_data,
service_documentation_provider_file_id: service_documentation_file_info.provider_file_id,
shipping_address: evidence_request.shipping_address,
shipping_carrier: evidence_request.shipping_carrier,
shipping_date: evidence_request.shipping_date,
shipping_documentation: shipping_documentation_file_info.file_data,
shipping_documentation_provider_file_id: shipping_documentation_file_info.provider_file_id,
shipping_tracking_number: evidence_request.shipping_tracking_number,
invoice_showing_distinct_transactions: invoice_showing_distinct_transactions_file_info
.file_data,
invoice_showing_distinct_transactions_provider_file_id:
invoice_showing_distinct_transactions_file_info.provider_file_id,
recurring_transaction_agreement: recurring_transaction_agreement_file_info.file_data,
recurring_transaction_agreement_provider_file_id: recurring_transaction_agreement_file_info
.provider_file_id,
uncategorized_file: uncategorized_file_info.file_data,
uncategorized_file_provider_file_id: uncategorized_file_info.provider_file_id,
uncategorized_text: evidence_request.uncategorized_text,
cancellation_policy_file_type: cancellation_policy_file_info.file_type,
customer_communication_file_type: customer_communication_file_info.file_type,
customer_signature_file_type: customer_sifnature_file_info.file_type,
receipt_file_type: receipt_file_info.file_type,
refund_policy_file_type: refund_policy_file_info.file_type,
service_documentation_file_type: service_documentation_file_info.file_type,
shipping_documentation_file_type: shipping_documentation_file_info.file_type,
invoice_showing_distinct_transactions_file_type:
invoice_showing_distinct_transactions_file_info.file_type,
recurring_transaction_agreement_file_type: recurring_transaction_agreement_file_info
.file_type,
uncategorized_file_type: uncategorized_file_info.file_type,
})
}
pub fn update_dispute_evidence(
dispute_evidence: DisputeEvidence,
evidence_type: api::EvidenceType,
file_id: String,
) -> DisputeEvidence {
match evidence_type {
api::EvidenceType::CancellationPolicy => DisputeEvidence {
cancellation_policy: Some(file_id),
..dispute_evidence
},
api::EvidenceType::CustomerCommunication => DisputeEvidence {
customer_communication: Some(file_id),
..dispute_evidence
},
api::EvidenceType::CustomerSignature => DisputeEvidence {
customer_signature: Some(file_id),
..dispute_evidence
},
api::EvidenceType::Receipt => DisputeEvidence {
receipt: Some(file_id),
..dispute_evidence
},
api::EvidenceType::RefundPolicy => DisputeEvidence {
refund_policy: Some(file_id),
..dispute_evidence
},
api::EvidenceType::ServiceDocumentation => DisputeEvidence {
service_documentation: Some(file_id),
..dispute_evidence
},
api::EvidenceType::ShippingDocumentation => DisputeEvidence {
shipping_documentation: Some(file_id),
..dispute_evidence
},
api::EvidenceType::InvoiceShowingDistinctTransactions => DisputeEvidence {
invoice_showing_distinct_transactions: Some(file_id),
..dispute_evidence
},
api::EvidenceType::RecurringTransactionAgreement => DisputeEvidence {
recurring_transaction_agreement: Some(file_id),
..dispute_evidence
},
api::EvidenceType::UncategorizedFile => DisputeEvidence {
uncategorized_file: Some(file_id),
..dispute_evidence
},
}
}
pub async fn get_dispute_evidence_block(
state: &SessionState,
merchant_context: &domain::MerchantContext,
evidence_type: EvidenceType,
file_id: String,
) -> CustomResult<api_models::disputes::DisputeEvidenceBlock, errors::ApiErrorResponse> {
let file_metadata = state
.store
.find_file_metadata_by_merchant_id_file_id(
merchant_context.get_merchant_account().get_id(),
&file_id,
)
.await
.change_context(errors::ApiErrorResponse::FileNotFound)
.attach_printable("Unable to retrieve file_metadata")?;
let file_metadata_response =
api_models::files::FileMetadataResponse::foreign_from(file_metadata);
Ok(api_models::disputes::DisputeEvidenceBlock {
evidence_type,
file_metadata_response,
})
}
pub fn delete_evidence_file(
dispute_evidence: DisputeEvidence,
evidence_type: EvidenceType,
) -> DisputeEvidence {
match evidence_type {
EvidenceType::CancellationPolicy => DisputeEvidence {
cancellation_policy: None,
..dispute_evidence
},
EvidenceType::CustomerCommunication => DisputeEvidence {
customer_communication: None,
..dispute_evidence
},
EvidenceType::CustomerSignature => DisputeEvidence {
customer_signature: None,
..dispute_evidence
},
EvidenceType::Receipt => DisputeEvidence {
receipt: None,
..dispute_evidence
},
EvidenceType::RefundPolicy => DisputeEvidence {
refund_policy: None,
..dispute_evidence
},
EvidenceType::ServiceDocumentation => DisputeEvidence {
service_documentation: None,
..dispute_evidence
},
EvidenceType::ShippingDocumentation => DisputeEvidence {
shipping_documentation: None,
..dispute_evidence
},
EvidenceType::InvoiceShowingDistinctTransactions => DisputeEvidence {
invoice_showing_distinct_transactions: None,
..dispute_evidence
},
EvidenceType::RecurringTransactionAgreement => DisputeEvidence {
recurring_transaction_agreement: None,
..dispute_evidence
},
EvidenceType::UncategorizedFile => DisputeEvidence {
uncategorized_file: None,
..dispute_evidence
},
}
}
pub async fn get_dispute_evidence_vec(
state: &SessionState,
merchant_context: domain::MerchantContext,
dispute_evidence: DisputeEvidence,
) -> CustomResult<Vec<api_models::disputes::DisputeEvidenceBlock>, errors::ApiErrorResponse> {
let mut dispute_evidence_blocks: Vec<api_models::disputes::DisputeEvidenceBlock> = vec![];
if let Some(cancellation_policy_block) = dispute_evidence.cancellation_policy {
dispute_evidence_blocks.push(
get_dispute_evidence_block(
state,
&merchant_context,
EvidenceType::CancellationPolicy,
cancellation_policy_block,
)
.await?,
)
}
if let Some(customer_communication_block) = dispute_evidence.customer_communication {
dispute_evidence_blocks.push(
get_dispute_evidence_block(
state,
&merchant_context,
EvidenceType::CustomerCommunication,
customer_communication_block,
)
.await?,
)
}
if let Some(customer_signature_block) = dispute_evidence.customer_signature {
dispute_evidence_blocks.push(
get_dispute_evidence_block(
state,
&merchant_context,
EvidenceType::CustomerSignature,
customer_signature_block,
)
.await?,
)
}
if let Some(receipt_block) = dispute_evidence.receipt {
dispute_evidence_blocks.push(
get_dispute_evidence_block(
state,
&merchant_context,
EvidenceType::Receipt,
receipt_block,
)
.await?,
)
}
if let Some(refund_policy_block) = dispute_evidence.refund_policy {
dispute_evidence_blocks.push(
get_dispute_evidence_block(
state,
&merchant_context,
EvidenceType::RefundPolicy,
refund_policy_block,
)
.await?,
)
}
if let Some(service_documentation_block) = dispute_evidence.service_documentation {
dispute_evidence_blocks.push(
get_dispute_evidence_block(
state,
&merchant_context,
EvidenceType::ServiceDocumentation,
service_documentation_block,
)
.await?,
)
}
if let Some(shipping_documentation_block) = dispute_evidence.shipping_documentation {
dispute_evidence_blocks.push(
get_dispute_evidence_block(
state,
&merchant_context,
EvidenceType::ShippingDocumentation,
shipping_documentation_block,
)
.await?,
)
}
if let Some(invoice_showing_distinct_transactions_block) =
dispute_evidence.invoice_showing_distinct_transactions
{
dispute_evidence_blocks.push(
get_dispute_evidence_block(
state,
&merchant_context,
EvidenceType::InvoiceShowingDistinctTransactions,
invoice_showing_distinct_transactions_block,
)
.await?,
)
}
if let Some(recurring_transaction_agreement_block) =
dispute_evidence.recurring_transaction_agreement
{
dispute_evidence_blocks.push(
get_dispute_evidence_block(
state,
&merchant_context,
EvidenceType::RecurringTransactionAgreement,
recurring_transaction_agreement_block,
)
.await?,
)
}
if let Some(uncategorized_file_block) = dispute_evidence.uncategorized_file {
dispute_evidence_blocks.push(
get_dispute_evidence_block(
state,
&merchant_context,
EvidenceType::UncategorizedFile,
uncategorized_file_block,
)
.await?,
)
}
Ok(dispute_evidence_blocks)
}
|
crates/router/src/core/disputes/transformers.rs
|
router::src::core::disputes::transformers
| 2,987
| true
|
// File: crates/router/src/core/three_ds_decision_rule/utils.rs
// Module: router::src::core::three_ds_decision_rule::utils
use api_models::three_ds_decision_rule as api_threedsecure;
use common_types::three_ds_decision_rule_engine::ThreeDSDecision;
use euclid::backend::inputs as dsl_inputs;
use crate::{consts::PSD2_COUNTRIES, types::transformers::ForeignFrom};
// function to apply PSD2 validations to the decision
pub fn apply_psd2_validations_during_execute(
decision: ThreeDSDecision,
request: &api_models::three_ds_decision_rule::ThreeDsDecisionRuleExecuteRequest,
) -> ThreeDSDecision {
let issuer_in_psd2 = request
.issuer
.as_ref()
.and_then(|issuer| issuer.country)
.map(|country| PSD2_COUNTRIES.contains(&country))
.unwrap_or(false);
let acquirer_in_psd2 = request
.acquirer
.as_ref()
.and_then(|acquirer| acquirer.country)
.map(|country| PSD2_COUNTRIES.contains(&country))
.unwrap_or(false);
if issuer_in_psd2 && acquirer_in_psd2 {
// If both issuer and acquirer are in PSD2 region
match decision {
// If the decision is to enforce no 3DS, override it to enforce 3DS
ThreeDSDecision::NoThreeDs => ThreeDSDecision::ChallengeRequested,
_ => decision,
}
} else {
// If PSD2 doesn't apply, exemptions cannot be applied
match decision {
ThreeDSDecision::NoThreeDs => ThreeDSDecision::NoThreeDs,
// For all other decisions (including exemptions), enforce challenge as exemptions are only valid in PSD2 regions
_ => ThreeDSDecision::ChallengeRequested,
}
}
}
impl ForeignFrom<api_threedsecure::PaymentData> for dsl_inputs::PaymentInput {
fn foreign_from(request_payment_data: api_threedsecure::PaymentData) -> Self {
Self {
amount: request_payment_data.amount,
currency: request_payment_data.currency,
authentication_type: None,
capture_method: None,
business_country: None,
billing_country: None,
business_label: None,
setup_future_usage: None,
card_bin: None,
}
}
}
impl ForeignFrom<Option<api_threedsecure::PaymentMethodMetaData>>
for dsl_inputs::PaymentMethodInput
{
fn foreign_from(
request_payment_method_metadata: Option<api_threedsecure::PaymentMethodMetaData>,
) -> Self {
Self {
payment_method: None,
payment_method_type: None,
card_network: request_payment_method_metadata.and_then(|pm| pm.card_network),
}
}
}
impl ForeignFrom<api_threedsecure::CustomerDeviceData> for dsl_inputs::CustomerDeviceDataInput {
fn foreign_from(request_customer_device_data: api_threedsecure::CustomerDeviceData) -> Self {
Self {
platform: request_customer_device_data.platform,
device_type: request_customer_device_data.device_type,
display_size: request_customer_device_data.display_size,
}
}
}
impl ForeignFrom<api_threedsecure::IssuerData> for dsl_inputs::IssuerDataInput {
fn foreign_from(request_issuer_data: api_threedsecure::IssuerData) -> Self {
Self {
name: request_issuer_data.name,
country: request_issuer_data.country,
}
}
}
impl ForeignFrom<api_threedsecure::AcquirerData> for dsl_inputs::AcquirerDataInput {
fn foreign_from(request_acquirer_data: api_threedsecure::AcquirerData) -> Self {
Self {
country: request_acquirer_data.country,
fraud_rate: request_acquirer_data.fraud_rate,
}
}
}
impl ForeignFrom<api_threedsecure::ThreeDsDecisionRuleExecuteRequest> for dsl_inputs::BackendInput {
fn foreign_from(request: api_threedsecure::ThreeDsDecisionRuleExecuteRequest) -> Self {
Self {
metadata: None,
payment: dsl_inputs::PaymentInput::foreign_from(request.payment),
payment_method: dsl_inputs::PaymentMethodInput::foreign_from(request.payment_method),
mandate: dsl_inputs::MandateData {
mandate_acceptance_type: None,
mandate_type: None,
payment_type: None,
},
acquirer_data: request.acquirer.map(ForeignFrom::foreign_from),
customer_device_data: request.customer_device.map(ForeignFrom::foreign_from),
issuer_data: request.issuer.map(ForeignFrom::foreign_from),
}
}
}
|
crates/router/src/core/three_ds_decision_rule/utils.rs
|
router::src::core::three_ds_decision_rule::utils
| 997
| true
|
// File: crates/router/src/core/user_role/role.rs
// Module: router::src::core::user_role::role
use std::{cmp, collections::HashSet, ops::Not};
use api_models::user_role::role as role_api;
use common_enums::{EntityType, ParentGroup, PermissionGroup};
use common_utils::generate_id_with_default_len;
use diesel_models::role::{ListRolesByEntityPayload, RoleNew, RoleUpdate};
use error_stack::{report, ResultExt};
use crate::{
core::errors::{StorageErrorExt, UserErrors, UserResponse},
routes::{app::ReqState, SessionState},
services::{
authentication::{blacklist, UserFromToken},
authorization::{
permission_groups::{ParentGroupExt, PermissionGroupExt},
roles::{self, predefined_roles::PREDEFINED_ROLES},
},
ApplicationResponse,
},
types::domain::user::RoleName,
utils,
};
pub async fn get_role_from_token_with_groups(
state: SessionState,
user_from_token: UserFromToken,
) -> UserResponse<Vec<PermissionGroup>> {
let role_info = user_from_token
.get_role_info_from_db(&state)
.await
.attach_printable("Invalid role_id in JWT")?;
let permissions = role_info.get_permission_groups().to_vec();
Ok(ApplicationResponse::Json(permissions))
}
pub async fn get_groups_and_resources_for_role_from_token(
state: SessionState,
user_from_token: UserFromToken,
) -> UserResponse<role_api::GroupsAndResources> {
let role_info = user_from_token.get_role_info_from_db(&state).await?;
let groups = role_info
.get_permission_groups()
.into_iter()
.collect::<Vec<_>>();
let resources = groups
.iter()
.flat_map(|group| group.resources())
.collect::<HashSet<_>>()
.into_iter()
.collect();
Ok(ApplicationResponse::Json(role_api::GroupsAndResources {
groups,
resources,
}))
}
pub async fn get_parent_groups_info_for_role_from_token(
state: SessionState,
user_from_token: UserFromToken,
) -> UserResponse<Vec<role_api::ParentGroupInfo>> {
let role_info = user_from_token.get_role_info_from_db(&state).await?;
let groups = role_info
.get_permission_groups()
.into_iter()
.collect::<Vec<_>>();
let parent_groups = utils::user_role::permission_groups_to_parent_group_info(
&groups,
role_info.get_entity_type(),
);
Ok(ApplicationResponse::Json(parent_groups))
}
pub async fn create_role(
state: SessionState,
user_from_token: UserFromToken,
req: role_api::CreateRoleRequest,
_req_state: ReqState,
) -> UserResponse<role_api::RoleInfoWithGroupsResponse> {
let now = common_utils::date_time::now();
let user_entity_type = user_from_token
.get_role_info_from_db(&state)
.await
.attach_printable("Invalid role_id in JWT")?
.get_entity_type();
let role_entity_type = req.entity_type.unwrap_or(EntityType::Merchant);
if matches!(role_entity_type, EntityType::Organization) {
return Err(report!(UserErrors::InvalidRoleOperation))
.attach_printable("User trying to create org level custom role");
}
let requestor_entity_from_role_scope = EntityType::from(req.role_scope);
if requestor_entity_from_role_scope < role_entity_type {
return Err(report!(UserErrors::InvalidRoleOperation)).attach_printable(format!(
"User is trying to create role of type {role_entity_type} and scope {requestor_entity_from_role_scope}",
));
}
let max_from_scope_and_entity = cmp::max(requestor_entity_from_role_scope, role_entity_type);
if user_entity_type < max_from_scope_and_entity {
return Err(report!(UserErrors::InvalidRoleOperation)).attach_printable(format!(
"{user_entity_type} is trying to create of scope {requestor_entity_from_role_scope} and of type {role_entity_type}",
));
}
let role_name = RoleName::new(req.role_name)?;
utils::user_role::validate_role_groups(&req.groups)?;
utils::user_role::validate_role_name(
&state,
&role_name,
&user_from_token.merchant_id,
&user_from_token.org_id,
user_from_token
.tenant_id
.as_ref()
.unwrap_or(&state.tenant.tenant_id),
&user_from_token.profile_id,
&role_entity_type,
)
.await?;
let (org_id, merchant_id, profile_id) = match role_entity_type {
EntityType::Organization | EntityType::Tenant => (user_from_token.org_id, None, None),
EntityType::Merchant => (
user_from_token.org_id,
Some(user_from_token.merchant_id),
None,
),
EntityType::Profile => (
user_from_token.org_id,
Some(user_from_token.merchant_id),
Some(user_from_token.profile_id),
),
};
let role = state
.global_store
.insert_role(RoleNew {
role_id: generate_id_with_default_len("role"),
role_name: role_name.get_role_name(),
merchant_id,
org_id,
groups: req.groups,
scope: req.role_scope,
entity_type: role_entity_type,
created_by: user_from_token.user_id.clone(),
last_modified_by: user_from_token.user_id,
created_at: now,
last_modified_at: now,
profile_id,
tenant_id: user_from_token.tenant_id.unwrap_or(state.tenant.tenant_id),
})
.await
.to_duplicate_response(UserErrors::RoleNameAlreadyExists)?;
Ok(ApplicationResponse::Json(
role_api::RoleInfoWithGroupsResponse {
groups: role.groups,
role_id: role.role_id,
role_name: role.role_name,
role_scope: role.scope,
entity_type: role.entity_type,
},
))
}
pub async fn create_role_v2(
state: SessionState,
user_from_token: UserFromToken,
req: role_api::CreateRoleV2Request,
_req_state: ReqState,
) -> UserResponse<role_api::RoleInfoResponseWithParentsGroup> {
let now = common_utils::date_time::now();
let user_entity_type = user_from_token
.get_role_info_from_db(&state)
.await
.attach_printable("Invalid role_id in JWT")?
.get_entity_type();
let role_entity_type = req.entity_type.unwrap_or(EntityType::Merchant);
if matches!(role_entity_type, EntityType::Organization) {
return Err(report!(UserErrors::InvalidRoleOperation))
.attach_printable("User trying to create org level custom role");
}
let requestor_entity_from_role_scope = EntityType::from(req.role_scope);
if requestor_entity_from_role_scope < role_entity_type {
return Err(report!(UserErrors::InvalidRoleOperation)).attach_printable(format!(
"User is trying to create role of type {role_entity_type} and scope {requestor_entity_from_role_scope}",
));
}
let max_from_scope_and_entity = cmp::max(requestor_entity_from_role_scope, role_entity_type);
if user_entity_type < max_from_scope_and_entity {
return Err(report!(UserErrors::InvalidRoleOperation)).attach_printable(format!(
"{user_entity_type} is trying to create of scope {requestor_entity_from_role_scope} and of type {role_entity_type}",
));
}
let role_name = RoleName::new(req.role_name.clone())?;
let permission_groups =
utils::user_role::parent_group_info_request_to_permission_groups(&req.parent_groups)?;
utils::user_role::validate_role_groups(&permission_groups)?;
utils::user_role::validate_role_name(
&state,
&role_name,
&user_from_token.merchant_id,
&user_from_token.org_id,
user_from_token
.tenant_id
.as_ref()
.unwrap_or(&state.tenant.tenant_id),
&user_from_token.profile_id,
&role_entity_type,
)
.await?;
let (org_id, merchant_id, profile_id) = match role_entity_type {
EntityType::Organization | EntityType::Tenant => (user_from_token.org_id, None, None),
EntityType::Merchant => (
user_from_token.org_id,
Some(user_from_token.merchant_id),
None,
),
EntityType::Profile => (
user_from_token.org_id,
Some(user_from_token.merchant_id),
Some(user_from_token.profile_id),
),
};
let role = state
.global_store
.insert_role(RoleNew {
role_id: generate_id_with_default_len("role"),
role_name: role_name.get_role_name(),
merchant_id,
org_id,
groups: permission_groups,
scope: req.role_scope,
entity_type: role_entity_type,
created_by: user_from_token.user_id.clone(),
last_modified_by: user_from_token.user_id,
created_at: now,
last_modified_at: now,
profile_id,
tenant_id: user_from_token.tenant_id.unwrap_or(state.tenant.tenant_id),
})
.await
.to_duplicate_response(UserErrors::RoleNameAlreadyExists)?;
let parent_group_details =
utils::user_role::permission_groups_to_parent_group_info(&role.groups, role.entity_type);
let parent_group_descriptions: Vec<role_api::ParentGroupDescription> = parent_group_details
.into_iter()
.filter_map(|group_details| {
let description = utils::user_role::resources_to_description(
group_details.resources,
role.entity_type,
)?;
Some(role_api::ParentGroupDescription {
name: group_details.name,
description,
scopes: group_details.scopes,
})
})
.collect();
Ok(ApplicationResponse::Json(
role_api::RoleInfoResponseWithParentsGroup {
role_id: role.role_id,
role_name: role.role_name,
role_scope: role.scope,
entity_type: role.entity_type,
parent_groups: parent_group_descriptions,
},
))
}
pub async fn get_role_with_groups(
state: SessionState,
user_from_token: UserFromToken,
role: role_api::GetRoleRequest,
) -> UserResponse<role_api::RoleInfoWithGroupsResponse> {
let role_info = roles::RoleInfo::from_role_id_org_id_tenant_id(
&state,
&role.role_id,
&user_from_token.org_id,
user_from_token
.tenant_id
.as_ref()
.unwrap_or(&state.tenant.tenant_id),
)
.await
.to_not_found_response(UserErrors::InvalidRoleId)?;
if role_info.is_internal() {
return Err(UserErrors::InvalidRoleId.into());
}
Ok(ApplicationResponse::Json(
role_api::RoleInfoWithGroupsResponse {
groups: role_info.get_permission_groups().to_vec(),
role_id: role.role_id,
role_name: role_info.get_role_name().to_string(),
role_scope: role_info.get_scope(),
entity_type: role_info.get_entity_type(),
},
))
}
pub async fn get_parent_info_for_role(
state: SessionState,
user_from_token: UserFromToken,
role: role_api::GetRoleRequest,
) -> UserResponse<role_api::RoleInfoWithParents> {
let role_info = roles::RoleInfo::from_role_id_org_id_tenant_id(
&state,
&role.role_id,
&user_from_token.org_id,
user_from_token
.tenant_id
.as_ref()
.unwrap_or(&state.tenant.tenant_id),
)
.await
.to_not_found_response(UserErrors::InvalidRoleId)?;
if role_info.is_internal() {
return Err(UserErrors::InvalidRoleId.into());
}
let parent_groups = ParentGroup::get_descriptions_for_groups(
role_info.get_entity_type(),
role_info.get_permission_groups().to_vec(),
)
.ok_or(UserErrors::InternalServerError)
.attach_printable(format!(
"No group descriptions found for role_id: {}",
role.role_id
))?
.into_iter()
.map(
|(parent_group, description)| role_api::ParentGroupDescription {
name: parent_group.clone(),
description,
scopes: role_info
.get_permission_groups()
.iter()
.filter_map(|group| (group.parent() == parent_group).then_some(group.scope()))
// TODO: Remove this hashset conversion when merchant access
// and organization access groups are removed
.collect::<HashSet<_>>()
.into_iter()
.collect(),
},
)
.collect();
Ok(ApplicationResponse::Json(role_api::RoleInfoWithParents {
role_id: role.role_id,
parent_groups,
role_name: role_info.get_role_name().to_string(),
role_scope: role_info.get_scope(),
}))
}
pub async fn update_role(
state: SessionState,
user_from_token: UserFromToken,
req: role_api::UpdateRoleRequest,
role_id: &str,
) -> UserResponse<role_api::RoleInfoWithGroupsResponse> {
let role_name = req.role_name.map(RoleName::new).transpose()?;
let role_info = roles::RoleInfo::from_role_id_in_lineage(
&state,
role_id,
&user_from_token.merchant_id,
&user_from_token.org_id,
&user_from_token.profile_id,
user_from_token
.tenant_id
.as_ref()
.unwrap_or(&state.tenant.tenant_id),
)
.await
.to_not_found_response(UserErrors::InvalidRoleOperation)?;
let user_role_info = user_from_token.get_role_info_from_db(&state).await?;
let requested_entity_from_role_scope = EntityType::from(role_info.get_scope());
let requested_role_entity_type = role_info.get_entity_type();
let max_from_scope_and_entity =
cmp::max(requested_entity_from_role_scope, requested_role_entity_type);
if user_role_info.get_entity_type() < max_from_scope_and_entity {
return Err(report!(UserErrors::InvalidRoleOperation)).attach_printable(format!(
"{} is trying to update of scope {} and of type {}",
user_role_info.get_entity_type(),
requested_entity_from_role_scope,
requested_role_entity_type
));
}
if let Some(ref role_name) = role_name {
utils::user_role::validate_role_name(
&state,
role_name,
&user_from_token.merchant_id,
&user_from_token.org_id,
user_from_token
.tenant_id
.as_ref()
.unwrap_or(&state.tenant.tenant_id),
&user_from_token.profile_id,
&role_info.get_entity_type(),
)
.await?;
}
if let Some(ref groups) = req.groups {
utils::user_role::validate_role_groups(groups)?;
}
let updated_role = state
.global_store
.update_role_by_role_id(
role_id,
RoleUpdate::UpdateDetails {
groups: req.groups,
role_name: role_name.map(RoleName::get_role_name),
last_modified_at: common_utils::date_time::now(),
last_modified_by: user_from_token.user_id,
},
)
.await
.to_duplicate_response(UserErrors::RoleNameAlreadyExists)?;
blacklist::insert_role_in_blacklist(&state, role_id).await?;
Ok(ApplicationResponse::Json(
role_api::RoleInfoWithGroupsResponse {
groups: updated_role.groups,
role_id: updated_role.role_id,
role_name: updated_role.role_name,
role_scope: updated_role.scope,
entity_type: updated_role.entity_type,
},
))
}
pub async fn list_roles_with_info(
state: SessionState,
user_from_token: UserFromToken,
request: role_api::ListRolesQueryParams,
) -> UserResponse<role_api::ListRolesResponse> {
let user_role_info = user_from_token
.get_role_info_from_db(&state)
.await
.attach_printable("Invalid role_id in JWT")?;
if user_role_info.is_internal() {
return Err(UserErrors::InvalidRoleOperationWithMessage(
"Internal roles are not allowed for this operation".to_string(),
)
.into());
}
let mut role_info_vec = PREDEFINED_ROLES
.values()
.filter(|role| role.is_internal().not())
.cloned()
.collect::<Vec<_>>();
let user_role_entity = user_role_info.get_entity_type();
let is_lineage_data_required = request.entity_type.is_none();
let tenant_id = user_from_token
.tenant_id
.as_ref()
.unwrap_or(&state.tenant.tenant_id)
.to_owned();
let custom_roles =
match utils::user_role::get_min_entity(user_role_entity, request.entity_type)? {
EntityType::Tenant | EntityType::Organization => state
.global_store
.generic_list_roles_by_entity_type(
ListRolesByEntityPayload::Organization,
is_lineage_data_required,
tenant_id,
user_from_token.org_id,
)
.await
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to get roles")?,
EntityType::Merchant => state
.global_store
.generic_list_roles_by_entity_type(
ListRolesByEntityPayload::Merchant(user_from_token.merchant_id),
is_lineage_data_required,
tenant_id,
user_from_token.org_id,
)
.await
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to get roles")?,
EntityType::Profile => state
.global_store
.generic_list_roles_by_entity_type(
ListRolesByEntityPayload::Profile(
user_from_token.merchant_id,
user_from_token.profile_id,
),
is_lineage_data_required,
tenant_id,
user_from_token.org_id,
)
.await
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to get roles")?,
};
role_info_vec.extend(custom_roles.into_iter().map(roles::RoleInfo::from));
if request.groups == Some(true) {
let list_role_info_response = role_info_vec
.into_iter()
.filter_map(|role_info| {
let is_lower_entity = user_role_entity >= role_info.get_entity_type();
let request_filter = request
.entity_type
.is_none_or(|entity_type| entity_type == role_info.get_entity_type());
(is_lower_entity && request_filter).then_some({
let permission_groups = role_info.get_permission_groups();
let parent_group_details =
utils::user_role::permission_groups_to_parent_group_info(
&permission_groups,
role_info.get_entity_type(),
);
let parent_group_descriptions: Vec<role_api::ParentGroupDescription> =
parent_group_details
.into_iter()
.filter_map(|group_details| {
let description = utils::user_role::resources_to_description(
group_details.resources,
role_info.get_entity_type(),
)?;
Some(role_api::ParentGroupDescription {
name: group_details.name,
description,
scopes: group_details.scopes,
})
})
.collect();
role_api::RoleInfoResponseWithParentsGroup {
role_id: role_info.get_role_id().to_string(),
role_name: role_info.get_role_name().to_string(),
entity_type: role_info.get_entity_type(),
parent_groups: parent_group_descriptions,
role_scope: role_info.get_scope(),
}
})
})
.collect::<Vec<_>>();
Ok(ApplicationResponse::Json(
role_api::ListRolesResponse::WithParentGroups(list_role_info_response),
))
}
// TODO: To be deprecated
else {
let list_role_info_response = role_info_vec
.into_iter()
.filter_map(|role_info| {
let is_lower_entity = user_role_entity >= role_info.get_entity_type();
let request_filter = request
.entity_type
.is_none_or(|entity_type| entity_type == role_info.get_entity_type());
(is_lower_entity && request_filter).then_some(role_api::RoleInfoResponseNew {
role_id: role_info.get_role_id().to_string(),
role_name: role_info.get_role_name().to_string(),
groups: role_info.get_permission_groups().to_vec(),
entity_type: role_info.get_entity_type(),
scope: role_info.get_scope(),
})
})
.collect::<Vec<_>>();
Ok(ApplicationResponse::Json(
role_api::ListRolesResponse::WithGroups(list_role_info_response),
))
}
}
pub async fn list_roles_at_entity_level(
state: SessionState,
user_from_token: UserFromToken,
req: role_api::ListRolesAtEntityLevelRequest,
check_type: role_api::RoleCheckType,
) -> UserResponse<Vec<role_api::MinimalRoleInfo>> {
let user_entity_type = user_from_token
.get_role_info_from_db(&state)
.await
.attach_printable("Invalid role_id in JWT")?
.get_entity_type();
if req.entity_type > user_entity_type {
return Err(UserErrors::InvalidRoleOperationWithMessage(
"User is attempting to request list roles above the current entity level".to_string(),
)
.into());
}
let mut role_info_vec = PREDEFINED_ROLES.values().cloned().collect::<Vec<_>>();
let tenant_id = user_from_token
.tenant_id
.as_ref()
.unwrap_or(&state.tenant.tenant_id)
.to_owned();
let is_lineage_data_required = false;
let custom_roles = match req.entity_type {
EntityType::Tenant | EntityType::Organization => state
.global_store
.generic_list_roles_by_entity_type(
ListRolesByEntityPayload::Organization,
is_lineage_data_required,
tenant_id,
user_from_token.org_id,
)
.await
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to get roles")?,
EntityType::Merchant => state
.global_store
.generic_list_roles_by_entity_type(
ListRolesByEntityPayload::Merchant(user_from_token.merchant_id),
is_lineage_data_required,
tenant_id,
user_from_token.org_id,
)
.await
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to get roles")?,
EntityType::Profile => state
.global_store
.generic_list_roles_by_entity_type(
ListRolesByEntityPayload::Profile(
user_from_token.merchant_id,
user_from_token.profile_id,
),
is_lineage_data_required,
tenant_id,
user_from_token.org_id,
)
.await
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to get roles")?,
};
role_info_vec.extend(custom_roles.into_iter().map(roles::RoleInfo::from));
let list_minimal_role_info = role_info_vec
.into_iter()
.filter_map(|role_info| {
let check_type = match check_type {
role_api::RoleCheckType::Invite => role_info.is_invitable(),
role_api::RoleCheckType::Update => role_info.is_updatable(),
};
if check_type && role_info.get_entity_type() == req.entity_type {
Some(role_api::MinimalRoleInfo {
role_id: role_info.get_role_id().to_string(),
role_name: role_info.get_role_name().to_string(),
})
} else {
None
}
})
.collect::<Vec<_>>();
Ok(ApplicationResponse::Json(list_minimal_role_info))
}
|
crates/router/src/core/user_role/role.rs
|
router::src::core::user_role::role
| 5,128
| true
|
// File: crates/router/src/core/utils/customer_validation.rs
// Module: router::src::core::utils::customer_validation
use crate::core::errors::{self, CustomResult};
pub const CUSTOMER_LIST_LOWER_LIMIT: u16 = 1;
pub const CUSTOMER_LIST_UPPER_LIMIT: u16 = 100;
pub const CUSTOMER_LIST_DEFAULT_LIMIT: u16 = 10;
pub fn validate_customer_list_limit(
limit: Option<u16>,
) -> CustomResult<u16, errors::ApiErrorResponse> {
match limit {
Some(l) if (CUSTOMER_LIST_LOWER_LIMIT..=CUSTOMER_LIST_UPPER_LIMIT).contains(&l) => Ok(l),
Some(_) => Err(errors::ApiErrorResponse::InvalidRequestData {
message: format!(
"limit should be between {} and {}",
CUSTOMER_LIST_LOWER_LIMIT, CUSTOMER_LIST_UPPER_LIMIT
),
}
.into()),
None => Ok(CUSTOMER_LIST_DEFAULT_LIMIT),
}
}
|
crates/router/src/core/utils/customer_validation.rs
|
router::src::core::utils::customer_validation
| 210
| true
|
// File: crates/router/src/core/utils/refunds_validator.rs
// Module: router::src::core::utils::refunds_validator
use diesel_models::refund as diesel_refund;
use error_stack::report;
use router_env::{instrument, tracing};
use time::PrimitiveDateTime;
use crate::{
core::errors::{self, CustomResult, RouterResult},
types::{
self,
api::enums as api_enums,
storage::{self, enums},
},
utils::{self, OptionExt},
};
// Limit constraints for refunds list flow
pub const LOWER_LIMIT: i64 = 1;
pub const UPPER_LIMIT: i64 = 100;
pub const DEFAULT_LIMIT: i64 = 10;
#[derive(Debug, thiserror::Error)]
pub enum RefundValidationError {
#[error("The payment attempt was not successful")]
UnsuccessfulPaymentAttempt,
#[error("The refund amount exceeds the amount captured")]
RefundAmountExceedsPaymentAmount,
#[error("The order has expired")]
OrderExpired,
#[error("The maximum refund count for this payment attempt")]
MaxRefundCountReached,
#[error("There is already another refund request for this payment attempt")]
DuplicateRefund,
}
#[instrument(skip_all)]
pub fn validate_success_transaction(
transaction: &storage::PaymentAttempt,
) -> CustomResult<(), RefundValidationError> {
if transaction.status != enums::AttemptStatus::Charged {
Err(report!(RefundValidationError::UnsuccessfulPaymentAttempt))?
}
Ok(())
}
#[instrument(skip_all)]
pub fn validate_refund_amount(
amount_captured: i64,
all_refunds: &[diesel_refund::Refund],
refund_amount: i64,
) -> CustomResult<(), RefundValidationError> {
let total_refunded_amount: i64 = all_refunds
.iter()
.filter_map(|refund| {
if refund.refund_status != enums::RefundStatus::Failure
&& refund.refund_status != enums::RefundStatus::TransactionFailure
{
Some(refund.refund_amount.get_amount_as_i64())
} else {
None
}
})
.sum();
utils::when(
refund_amount > (amount_captured - total_refunded_amount),
|| {
Err(report!(
RefundValidationError::RefundAmountExceedsPaymentAmount
))
},
)
}
#[instrument(skip_all)]
pub fn validate_payment_order_age(
created_at: &PrimitiveDateTime,
refund_max_age: i64,
) -> CustomResult<(), RefundValidationError> {
let current_time = common_utils::date_time::now();
utils::when(
(current_time - *created_at).whole_days() > refund_max_age,
|| Err(report!(RefundValidationError::OrderExpired)),
)
}
#[instrument(skip_all)]
pub fn validate_maximum_refund_against_payment_attempt(
all_refunds: &[diesel_refund::Refund],
refund_max_attempts: usize,
) -> CustomResult<(), RefundValidationError> {
utils::when(all_refunds.len() > refund_max_attempts, || {
Err(report!(RefundValidationError::MaxRefundCountReached))
})
}
pub fn validate_refund_list(limit: Option<i64>) -> CustomResult<i64, errors::ApiErrorResponse> {
match limit {
Some(limit_val) => {
if !(LOWER_LIMIT..=UPPER_LIMIT).contains(&limit_val) {
Err(errors::ApiErrorResponse::InvalidRequestData {
message: "limit should be in between 1 and 100".to_string(),
}
.into())
} else {
Ok(limit_val)
}
}
None => Ok(DEFAULT_LIMIT),
}
}
#[cfg(feature = "v1")]
pub fn validate_for_valid_refunds(
payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt,
connector: api_models::enums::Connector,
) -> RouterResult<()> {
let payment_method = payment_attempt
.payment_method
.as_ref()
.get_required_value("payment_method")?;
match payment_method {
diesel_models::enums::PaymentMethod::PayLater
| diesel_models::enums::PaymentMethod::Wallet => {
let payment_method_type = payment_attempt
.payment_method_type
.get_required_value("payment_method_type")?;
utils::when(
matches!(
(connector, payment_method_type),
(
api_models::enums::Connector::Braintree,
diesel_models::enums::PaymentMethodType::Paypal,
)
),
|| {
Err(errors::ApiErrorResponse::RefundNotPossible {
connector: connector.to_string(),
}
.into())
},
)
}
_ => Ok(()),
}
}
#[cfg(feature = "v2")]
pub fn validate_for_valid_refunds(
payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt,
connector: api_models::enums::Connector,
) -> RouterResult<()> {
let payment_method_type = payment_attempt.payment_method_type;
match payment_method_type {
diesel_models::enums::PaymentMethod::PayLater
| diesel_models::enums::PaymentMethod::Wallet => {
let payment_method_subtype = payment_attempt.payment_method_subtype;
utils::when(
matches!(
(connector, payment_method_subtype),
(
api_models::enums::Connector::Braintree,
diesel_models::enums::PaymentMethodType::Paypal,
)
),
|| {
Err(errors::ApiErrorResponse::RefundNotPossible {
connector: connector.to_string(),
}
.into())
},
)
}
_ => Ok(()),
}
}
pub fn validate_stripe_charge_refund(
charge_type_option: Option<api_enums::PaymentChargeType>,
split_refund_request: &Option<common_types::refunds::SplitRefund>,
) -> RouterResult<types::ChargeRefundsOptions> {
let charge_type = charge_type_option.ok_or_else(|| {
report!(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Missing `charge_type` in PaymentAttempt.")
})?;
let refund_request = match split_refund_request {
Some(common_types::refunds::SplitRefund::StripeSplitRefund(stripe_split_refund)) => {
stripe_split_refund
}
_ => Err(errors::ApiErrorResponse::MissingRequiredField {
field_name: "stripe_split_refund",
})?,
};
let options = match charge_type {
api_enums::PaymentChargeType::Stripe(api_enums::StripeChargeType::Direct) => {
types::ChargeRefundsOptions::Direct(types::DirectChargeRefund {
revert_platform_fee: refund_request
.revert_platform_fee
.get_required_value("revert_platform_fee")?,
})
}
api_enums::PaymentChargeType::Stripe(api_enums::StripeChargeType::Destination) => {
types::ChargeRefundsOptions::Destination(types::DestinationChargeRefund {
revert_platform_fee: refund_request
.revert_platform_fee
.get_required_value("revert_platform_fee")?,
revert_transfer: refund_request
.revert_transfer
.get_required_value("revert_transfer")?,
})
}
};
Ok(options)
}
pub fn validate_adyen_charge_refund(
adyen_split_payment_response: &common_types::domain::AdyenSplitData,
adyen_split_refund_request: &common_types::domain::AdyenSplitData,
) -> RouterResult<()> {
if adyen_split_refund_request.store != adyen_split_payment_response.store {
return Err(report!(errors::ApiErrorResponse::InvalidDataValue {
field_name: "split_payments.adyen_split_payment.store",
}));
};
for refund_split_item in adyen_split_refund_request.split_items.iter() {
let refund_split_reference = refund_split_item.reference.clone();
let matching_payment_split_item = adyen_split_payment_response
.split_items
.iter()
.find(|payment_split_item| refund_split_reference == payment_split_item.reference);
if let Some(payment_split_item) = matching_payment_split_item {
if let Some((refund_amount, payment_amount)) =
refund_split_item.amount.zip(payment_split_item.amount)
{
if refund_amount > payment_amount {
return Err(report!(errors::ApiErrorResponse::InvalidRequestData {
message: format!(
"Invalid refund amount for split item, reference: {refund_split_reference}",
),
}));
}
}
if let Some((refund_account, payment_account)) = refund_split_item
.account
.as_ref()
.zip(payment_split_item.account.as_ref())
{
if !refund_account.eq(payment_account) {
return Err(report!(errors::ApiErrorResponse::InvalidRequestData {
message: format!(
"Invalid refund account for split item, reference: {refund_split_reference}",
),
}));
}
}
if refund_split_item.split_type != payment_split_item.split_type {
return Err(report!(errors::ApiErrorResponse::InvalidRequestData {
message: format!(
"Invalid refund split_type for split item, reference: {refund_split_reference}",
),
}));
}
} else {
return Err(report!(errors::ApiErrorResponse::InvalidRequestData {
message: format!(
"No matching payment split item found for reference: {refund_split_reference}",
),
}));
}
}
Ok(())
}
pub fn validate_xendit_charge_refund(
xendit_split_payment_response: &common_types::payments::XenditChargeResponseData,
xendit_split_refund_request: &common_types::domain::XenditSplitSubMerchantData,
) -> RouterResult<Option<String>> {
match xendit_split_payment_response {
common_types::payments::XenditChargeResponseData::MultipleSplits(
payment_sub_merchant_data,
) => {
if payment_sub_merchant_data.for_user_id
!= Some(xendit_split_refund_request.for_user_id.clone())
{
return Err(errors::ApiErrorResponse::InvalidDataValue {
field_name: "xendit_split_refund.for_user_id does not match xendit_split_payment.for_user_id",
}.into());
}
Ok(Some(xendit_split_refund_request.for_user_id.clone()))
}
common_types::payments::XenditChargeResponseData::SingleSplit(
payment_sub_merchant_data,
) => {
if payment_sub_merchant_data.for_user_id != xendit_split_refund_request.for_user_id {
return Err(errors::ApiErrorResponse::InvalidDataValue {
field_name: "xendit_split_refund.for_user_id does not match xendit_split_payment.for_user_id",
}.into());
}
Ok(Some(xendit_split_refund_request.for_user_id.clone()))
}
}
}
|
crates/router/src/core/utils/refunds_validator.rs
|
router::src::core::utils::refunds_validator
| 2,324
| true
|
// File: crates/router/src/core/utils/refunds_transformers.rs
// Module: router::src::core::utils::refunds_transformers
pub struct SplitRefundInput {
pub refund_request: Option<common_types::refunds::SplitRefund>,
pub payment_charges: Option<common_types::payments::ConnectorChargeResponseData>,
pub split_payment_request: Option<common_types::payments::SplitPaymentsRequest>,
pub charge_id: Option<String>,
}
|
crates/router/src/core/utils/refunds_transformers.rs
|
router::src::core::utils::refunds_transformers
| 98
| true
|
// File: crates/router/src/core/user/theme.rs
// Module: router::src::core::user::theme
use api_models::user::theme as theme_api;
use common_enums::EntityType;
use common_utils::{
ext_traits::{ByteSliceExt, Encode},
types::user::ThemeLineage,
};
use diesel_models::user::theme::{ThemeNew, ThemeUpdate};
use error_stack::ResultExt;
use hyperswitch_domain_models::api::ApplicationResponse;
use masking::ExposeInterface;
use rdkafka::message::ToBytes;
use uuid::Uuid;
use crate::{
core::errors::{StorageErrorExt, UserErrors, UserResponse},
routes::SessionState,
services::authentication::UserFromToken,
utils::user::theme as theme_utils,
};
// TODO: To be deprecated
pub async fn get_theme_using_lineage(
state: SessionState,
lineage: ThemeLineage,
) -> UserResponse<theme_api::GetThemeResponse> {
let theme = state
.store
.find_theme_by_lineage(lineage)
.await
.to_not_found_response(UserErrors::ThemeNotFound)?;
let file = theme_utils::retrieve_file_from_theme_bucket(
&state,
&theme_utils::get_theme_file_key(&theme.theme_id),
)
.await?;
let parsed_data = file
.to_bytes()
.parse_struct("ThemeData")
.change_context(UserErrors::InternalServerError)?;
Ok(ApplicationResponse::Json(theme_api::GetThemeResponse {
email_config: theme.email_config(),
theme_id: theme.theme_id,
theme_name: theme.theme_name,
entity_type: theme.entity_type,
tenant_id: theme.tenant_id,
org_id: theme.org_id,
merchant_id: theme.merchant_id,
profile_id: theme.profile_id,
theme_data: parsed_data,
}))
}
// TODO: To be deprecated
pub async fn get_theme_using_theme_id(
state: SessionState,
theme_id: String,
) -> UserResponse<theme_api::GetThemeResponse> {
let theme = state
.store
.find_theme_by_theme_id(theme_id.clone())
.await
.to_not_found_response(UserErrors::ThemeNotFound)?;
let file = theme_utils::retrieve_file_from_theme_bucket(
&state,
&theme_utils::get_theme_file_key(&theme_id),
)
.await?;
let parsed_data = file
.to_bytes()
.parse_struct("ThemeData")
.change_context(UserErrors::InternalServerError)?;
Ok(ApplicationResponse::Json(theme_api::GetThemeResponse {
email_config: theme.email_config(),
theme_id: theme.theme_id,
theme_name: theme.theme_name,
entity_type: theme.entity_type,
tenant_id: theme.tenant_id,
org_id: theme.org_id,
merchant_id: theme.merchant_id,
profile_id: theme.profile_id,
theme_data: parsed_data,
}))
}
// TODO: To be deprecated
pub async fn upload_file_to_theme_storage(
state: SessionState,
theme_id: String,
request: theme_api::UploadFileRequest,
) -> UserResponse<()> {
let db_theme = state
.store
.find_theme_by_theme_id(theme_id)
.await
.to_not_found_response(UserErrors::ThemeNotFound)?;
theme_utils::upload_file_to_theme_bucket(
&state,
&theme_utils::get_specific_file_key(&db_theme.theme_id, &request.asset_name),
request.asset_data.expose(),
)
.await?;
Ok(ApplicationResponse::StatusOk)
}
// TODO: To be deprecated
pub async fn create_theme(
state: SessionState,
request: theme_api::CreateThemeRequest,
) -> UserResponse<theme_api::GetThemeResponse> {
theme_utils::validate_lineage(&state, &request.lineage).await?;
let email_config = if cfg!(feature = "email") {
request.email_config.ok_or(UserErrors::MissingEmailConfig)?
} else {
request
.email_config
.unwrap_or(state.conf.theme.email_config.clone())
};
let new_theme = ThemeNew::new(
Uuid::new_v4().to_string(),
request.theme_name,
request.lineage,
email_config,
);
let db_theme = state
.store
.insert_theme(new_theme)
.await
.to_duplicate_response(UserErrors::ThemeAlreadyExists)?;
theme_utils::upload_file_to_theme_bucket(
&state,
&theme_utils::get_theme_file_key(&db_theme.theme_id),
request
.theme_data
.encode_to_vec()
.change_context(UserErrors::InternalServerError)?,
)
.await?;
let file = theme_utils::retrieve_file_from_theme_bucket(
&state,
&theme_utils::get_theme_file_key(&db_theme.theme_id),
)
.await?;
let parsed_data = file
.to_bytes()
.parse_struct("ThemeData")
.change_context(UserErrors::InternalServerError)?;
Ok(ApplicationResponse::Json(theme_api::GetThemeResponse {
email_config: db_theme.email_config(),
theme_id: db_theme.theme_id,
entity_type: db_theme.entity_type,
tenant_id: db_theme.tenant_id,
org_id: db_theme.org_id,
merchant_id: db_theme.merchant_id,
profile_id: db_theme.profile_id,
theme_name: db_theme.theme_name,
theme_data: parsed_data,
}))
}
// TODO: To be deprecated
pub async fn update_theme(
state: SessionState,
theme_id: String,
request: theme_api::UpdateThemeRequest,
) -> UserResponse<theme_api::GetThemeResponse> {
let db_theme = match request.email_config {
Some(email_config) => {
let theme_update = ThemeUpdate::EmailConfig { email_config };
state
.store
.update_theme_by_theme_id(theme_id.clone(), theme_update)
.await
.to_not_found_response(UserErrors::ThemeNotFound)?
}
None => state
.store
.find_theme_by_theme_id(theme_id)
.await
.to_not_found_response(UserErrors::ThemeNotFound)?,
};
if let Some(theme_data) = request.theme_data {
theme_utils::upload_file_to_theme_bucket(
&state,
&theme_utils::get_theme_file_key(&db_theme.theme_id),
theme_data
.encode_to_vec()
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to parse ThemeData")?,
)
.await?;
}
let file = theme_utils::retrieve_file_from_theme_bucket(
&state,
&theme_utils::get_theme_file_key(&db_theme.theme_id),
)
.await?;
let parsed_data = file
.to_bytes()
.parse_struct("ThemeData")
.change_context(UserErrors::InternalServerError)?;
Ok(ApplicationResponse::Json(theme_api::GetThemeResponse {
email_config: db_theme.email_config(),
theme_id: db_theme.theme_id,
entity_type: db_theme.entity_type,
tenant_id: db_theme.tenant_id,
org_id: db_theme.org_id,
merchant_id: db_theme.merchant_id,
profile_id: db_theme.profile_id,
theme_name: db_theme.theme_name,
theme_data: parsed_data,
}))
}
// TODO: To be deprecated
pub async fn delete_theme(state: SessionState, theme_id: String) -> UserResponse<()> {
state
.store
.delete_theme_by_theme_id(theme_id.clone())
.await
.to_not_found_response(UserErrors::ThemeNotFound)?;
// TODO (#6717): Delete theme folder from the theme storage.
// Currently there is no simple or easy way to delete a whole folder from S3.
// So, we are not deleting the theme folder from the theme storage.
Ok(ApplicationResponse::StatusOk)
}
pub async fn create_user_theme(
state: SessionState,
user_from_token: UserFromToken,
request: theme_api::CreateUserThemeRequest,
) -> UserResponse<theme_api::GetThemeResponse> {
let email_config = if cfg!(feature = "email") {
request.email_config.ok_or(UserErrors::MissingEmailConfig)?
} else {
request
.email_config
.unwrap_or(state.conf.theme.email_config.clone())
};
let lineage = theme_utils::get_theme_lineage_from_user_token(
&user_from_token,
&state,
&request.entity_type,
)
.await?;
let new_theme = ThemeNew::new(
Uuid::new_v4().to_string(),
request.theme_name,
lineage,
email_config,
);
let db_theme = state
.store
.insert_theme(new_theme)
.await
.to_duplicate_response(UserErrors::ThemeAlreadyExists)?;
theme_utils::upload_file_to_theme_bucket(
&state,
&theme_utils::get_theme_file_key(&db_theme.theme_id),
request
.theme_data
.encode_to_vec()
.change_context(UserErrors::InternalServerError)?,
)
.await?;
let file = theme_utils::retrieve_file_from_theme_bucket(
&state,
&theme_utils::get_theme_file_key(&db_theme.theme_id),
)
.await?;
let parsed_data = file
.to_bytes()
.parse_struct("ThemeData")
.change_context(UserErrors::InternalServerError)?;
Ok(ApplicationResponse::Json(theme_api::GetThemeResponse {
email_config: db_theme.email_config(),
theme_id: db_theme.theme_id,
entity_type: db_theme.entity_type,
tenant_id: db_theme.tenant_id,
org_id: db_theme.org_id,
merchant_id: db_theme.merchant_id,
profile_id: db_theme.profile_id,
theme_name: db_theme.theme_name,
theme_data: parsed_data,
}))
}
pub async fn delete_user_theme(
state: SessionState,
user_from_token: UserFromToken,
theme_id: String,
) -> UserResponse<()> {
let db_theme = state
.store
.find_theme_by_theme_id(theme_id.clone())
.await
.to_not_found_response(UserErrors::ThemeNotFound)?;
let user_role_info = user_from_token
.get_role_info_from_db(&state)
.await
.attach_printable("Invalid role_id in JWT")?;
let user_entity_type = user_role_info.get_entity_type();
theme_utils::can_user_access_theme(&user_from_token, &user_entity_type, &db_theme).await?;
state
.store
.delete_theme_by_theme_id(theme_id.clone())
.await
.to_not_found_response(UserErrors::ThemeNotFound)?;
// TODO (#6717): Delete theme folder from the theme storage.
// Currently there is no simple or easy way to delete a whole folder from S3.
// So, we are not deleting the theme folder from the theme storage.
Ok(ApplicationResponse::StatusOk)
}
pub async fn update_user_theme(
state: SessionState,
theme_id: String,
user_from_token: UserFromToken,
request: theme_api::UpdateThemeRequest,
) -> UserResponse<theme_api::GetThemeResponse> {
let db_theme = state
.store
.find_theme_by_theme_id(theme_id.clone())
.await
.to_not_found_response(UserErrors::ThemeNotFound)?;
let user_role_info = user_from_token
.get_role_info_from_db(&state)
.await
.attach_printable("Invalid role_id in JWT")?;
let user_entity_type = user_role_info.get_entity_type();
theme_utils::can_user_access_theme(&user_from_token, &user_entity_type, &db_theme).await?;
let db_theme = match request.email_config {
Some(email_config) => {
let theme_update = ThemeUpdate::EmailConfig { email_config };
state
.store
.update_theme_by_theme_id(theme_id.clone(), theme_update)
.await
.change_context(UserErrors::InternalServerError)?
}
None => db_theme,
};
if let Some(theme_data) = request.theme_data {
theme_utils::upload_file_to_theme_bucket(
&state,
&theme_utils::get_theme_file_key(&db_theme.theme_id),
theme_data
.encode_to_vec()
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to parse ThemeData")?,
)
.await?;
}
let file = theme_utils::retrieve_file_from_theme_bucket(
&state,
&theme_utils::get_theme_file_key(&db_theme.theme_id),
)
.await?;
let parsed_data = file
.to_bytes()
.parse_struct("ThemeData")
.change_context(UserErrors::InternalServerError)?;
Ok(ApplicationResponse::Json(theme_api::GetThemeResponse {
email_config: db_theme.email_config(),
theme_id: db_theme.theme_id,
entity_type: db_theme.entity_type,
tenant_id: db_theme.tenant_id,
org_id: db_theme.org_id,
merchant_id: db_theme.merchant_id,
profile_id: db_theme.profile_id,
theme_name: db_theme.theme_name,
theme_data: parsed_data,
}))
}
pub async fn upload_file_to_user_theme_storage(
state: SessionState,
theme_id: String,
user_from_token: UserFromToken,
request: theme_api::UploadFileRequest,
) -> UserResponse<()> {
let db_theme = state
.store
.find_theme_by_theme_id(theme_id)
.await
.to_not_found_response(UserErrors::ThemeNotFound)?;
let user_role_info = user_from_token
.get_role_info_from_db(&state)
.await
.attach_printable("Invalid role_id in JWT")?;
let user_entity_type = user_role_info.get_entity_type();
theme_utils::can_user_access_theme(&user_from_token, &user_entity_type, &db_theme).await?;
theme_utils::upload_file_to_theme_bucket(
&state,
&theme_utils::get_specific_file_key(&db_theme.theme_id, &request.asset_name),
request.asset_data.expose(),
)
.await?;
Ok(ApplicationResponse::StatusOk)
}
pub async fn list_all_themes_in_lineage(
state: SessionState,
user: UserFromToken,
entity_type: EntityType,
) -> UserResponse<Vec<theme_api::GetThemeResponse>> {
let lineage =
theme_utils::get_theme_lineage_from_user_token(&user, &state, &entity_type).await?;
let db_themes = state
.store
.list_themes_at_and_under_lineage(lineage)
.await
.change_context(UserErrors::InternalServerError)?;
let mut themes = Vec::new();
for theme in db_themes {
match theme_utils::retrieve_file_from_theme_bucket(
&state,
&theme_utils::get_theme_file_key(&theme.theme_id),
)
.await
{
Ok(file) => {
match file
.to_bytes()
.parse_struct("ThemeData")
.change_context(UserErrors::InternalServerError)
{
Ok(parsed_data) => {
themes.push(theme_api::GetThemeResponse {
email_config: theme.email_config(),
theme_id: theme.theme_id,
theme_name: theme.theme_name,
entity_type: theme.entity_type,
tenant_id: theme.tenant_id,
org_id: theme.org_id,
merchant_id: theme.merchant_id,
profile_id: theme.profile_id,
theme_data: parsed_data,
});
}
Err(_) => {
return Err(UserErrors::ErrorRetrievingFile.into());
}
}
}
Err(_) => {
return Err(UserErrors::ErrorRetrievingFile.into());
}
}
}
Ok(ApplicationResponse::Json(themes))
}
pub async fn get_user_theme_using_theme_id(
state: SessionState,
user_from_token: UserFromToken,
theme_id: String,
) -> UserResponse<theme_api::GetThemeResponse> {
let db_theme = state
.store
.find_theme_by_theme_id(theme_id.clone())
.await
.to_not_found_response(UserErrors::ThemeNotFound)?;
let user_role_info = user_from_token
.get_role_info_from_db(&state)
.await
.attach_printable("Invalid role_id in JWT")?;
let user_role_entity = user_role_info.get_entity_type();
theme_utils::can_user_access_theme(&user_from_token, &user_role_entity, &db_theme).await?;
let file = theme_utils::retrieve_file_from_theme_bucket(
&state,
&theme_utils::get_theme_file_key(&theme_id),
)
.await?;
let parsed_data = file
.to_bytes()
.parse_struct("ThemeData")
.change_context(UserErrors::InternalServerError)?;
Ok(ApplicationResponse::Json(theme_api::GetThemeResponse {
email_config: db_theme.email_config(),
theme_id: db_theme.theme_id,
theme_name: db_theme.theme_name,
entity_type: db_theme.entity_type,
tenant_id: db_theme.tenant_id,
org_id: db_theme.org_id,
merchant_id: db_theme.merchant_id,
profile_id: db_theme.profile_id,
theme_data: parsed_data,
}))
}
pub async fn get_user_theme_using_lineage(
state: SessionState,
user_from_token: UserFromToken,
entity_type: EntityType,
) -> UserResponse<theme_api::GetThemeResponse> {
let lineage =
theme_utils::get_theme_lineage_from_user_token(&user_from_token, &state, &entity_type)
.await?;
let theme = state
.store
.find_theme_by_lineage(lineage)
.await
.to_not_found_response(UserErrors::ThemeNotFound)?;
let file = theme_utils::retrieve_file_from_theme_bucket(
&state,
&theme_utils::get_theme_file_key(&theme.theme_id),
)
.await?;
let parsed_data = file
.to_bytes()
.parse_struct("ThemeData")
.change_context(UserErrors::InternalServerError)?;
Ok(ApplicationResponse::Json(theme_api::GetThemeResponse {
email_config: theme.email_config(),
theme_id: theme.theme_id,
theme_name: theme.theme_name,
entity_type: theme.entity_type,
tenant_id: theme.tenant_id,
org_id: theme.org_id,
merchant_id: theme.merchant_id,
profile_id: theme.profile_id,
theme_data: parsed_data,
}))
}
|
crates/router/src/core/user/theme.rs
|
router::src::core::user::theme
| 3,987
| true
|
// File: crates/router/src/core/user/dashboard_metadata.rs
// Module: router::src::core::user::dashboard_metadata
use api_models::user::dashboard_metadata::{self as api, GetMultipleMetaDataPayload};
#[cfg(feature = "email")]
use common_enums::EntityType;
use diesel_models::{
enums::DashboardMetadata as DBEnum, user::dashboard_metadata::DashboardMetadata,
};
use error_stack::{report, ResultExt};
use hyperswitch_interfaces::crm::CrmPayload;
#[cfg(feature = "email")]
use masking::ExposeInterface;
use masking::{PeekInterface, Secret};
use router_env::logger;
use crate::{
core::errors::{UserErrors, UserResponse, UserResult},
routes::{app::ReqState, SessionState},
services::{authentication::UserFromToken, ApplicationResponse},
types::domain::{self, user::dashboard_metadata as types, MerchantKeyStore},
utils::user::{self as user_utils, dashboard_metadata as utils},
};
#[cfg(feature = "email")]
use crate::{services::email::types as email_types, utils::user::theme as theme_utils};
pub async fn set_metadata(
state: SessionState,
user: UserFromToken,
request: api::SetMetaDataRequest,
_req_state: ReqState,
) -> UserResponse<()> {
let metadata_value = parse_set_request(request)?;
let metadata_key = DBEnum::from(&metadata_value);
insert_metadata(&state, user, metadata_key, metadata_value).await?;
Ok(ApplicationResponse::StatusOk)
}
pub async fn get_multiple_metadata(
state: SessionState,
user: UserFromToken,
request: GetMultipleMetaDataPayload,
_req_state: ReqState,
) -> UserResponse<Vec<api::GetMetaDataResponse>> {
let metadata_keys: Vec<DBEnum> = request.results.into_iter().map(parse_get_request).collect();
let metadata = fetch_metadata(&state, &user, metadata_keys.clone()).await?;
let mut response = Vec::with_capacity(metadata_keys.len());
for key in metadata_keys {
let data = metadata.iter().find(|ele| ele.data_key == key);
let resp;
if data.is_none() && utils::is_backfill_required(key) {
let backfill_data = backfill_metadata(&state, &user, &key).await?;
resp = into_response(backfill_data.as_ref(), key)?;
} else {
resp = into_response(data, key)?;
}
response.push(resp);
}
Ok(ApplicationResponse::Json(response))
}
fn parse_set_request(data_enum: api::SetMetaDataRequest) -> UserResult<types::MetaData> {
match data_enum {
api::SetMetaDataRequest::ProductionAgreement(req) => {
let ip_address = req
.ip_address
.ok_or(report!(UserErrors::InternalServerError))
.attach_printable("Error Getting Ip Address")?;
Ok(types::MetaData::ProductionAgreement(
types::ProductionAgreementValue {
version: req.version,
ip_address,
timestamp: common_utils::date_time::now(),
},
))
}
api::SetMetaDataRequest::SetupProcessor(req) => Ok(types::MetaData::SetupProcessor(req)),
api::SetMetaDataRequest::ConfigureEndpoint => Ok(types::MetaData::ConfigureEndpoint(true)),
api::SetMetaDataRequest::SetupComplete => Ok(types::MetaData::SetupComplete(true)),
api::SetMetaDataRequest::FirstProcessorConnected(req) => {
Ok(types::MetaData::FirstProcessorConnected(req))
}
api::SetMetaDataRequest::SecondProcessorConnected(req) => {
Ok(types::MetaData::SecondProcessorConnected(req))
}
api::SetMetaDataRequest::ConfiguredRouting(req) => {
Ok(types::MetaData::ConfiguredRouting(req))
}
api::SetMetaDataRequest::TestPayment(req) => Ok(types::MetaData::TestPayment(req)),
api::SetMetaDataRequest::IntegrationMethod(req) => {
Ok(types::MetaData::IntegrationMethod(req))
}
api::SetMetaDataRequest::ConfigurationType(req) => {
Ok(types::MetaData::ConfigurationType(req))
}
api::SetMetaDataRequest::IntegrationCompleted => {
Ok(types::MetaData::IntegrationCompleted(true))
}
api::SetMetaDataRequest::SPRoutingConfigured(req) => {
Ok(types::MetaData::SPRoutingConfigured(req))
}
api::SetMetaDataRequest::Feedback(req) => Ok(types::MetaData::Feedback(req)),
api::SetMetaDataRequest::ProdIntent(req) => Ok(types::MetaData::ProdIntent(req)),
api::SetMetaDataRequest::SPTestPayment => Ok(types::MetaData::SPTestPayment(true)),
api::SetMetaDataRequest::DownloadWoocom => Ok(types::MetaData::DownloadWoocom(true)),
api::SetMetaDataRequest::ConfigureWoocom => Ok(types::MetaData::ConfigureWoocom(true)),
api::SetMetaDataRequest::SetupWoocomWebhook => {
Ok(types::MetaData::SetupWoocomWebhook(true))
}
api::SetMetaDataRequest::IsMultipleConfiguration => {
Ok(types::MetaData::IsMultipleConfiguration(true))
}
api::SetMetaDataRequest::IsChangePasswordRequired => {
Ok(types::MetaData::IsChangePasswordRequired(true))
}
api::SetMetaDataRequest::OnboardingSurvey(req) => {
Ok(types::MetaData::OnboardingSurvey(req))
}
api::SetMetaDataRequest::ReconStatus(req) => Ok(types::MetaData::ReconStatus(req)),
}
}
fn parse_get_request(data_enum: api::GetMetaDataRequest) -> DBEnum {
match data_enum {
api::GetMetaDataRequest::ProductionAgreement => DBEnum::ProductionAgreement,
api::GetMetaDataRequest::SetupProcessor => DBEnum::SetupProcessor,
api::GetMetaDataRequest::ConfigureEndpoint => DBEnum::ConfigureEndpoint,
api::GetMetaDataRequest::SetupComplete => DBEnum::SetupComplete,
api::GetMetaDataRequest::FirstProcessorConnected => DBEnum::FirstProcessorConnected,
api::GetMetaDataRequest::SecondProcessorConnected => DBEnum::SecondProcessorConnected,
api::GetMetaDataRequest::ConfiguredRouting => DBEnum::ConfiguredRouting,
api::GetMetaDataRequest::TestPayment => DBEnum::TestPayment,
api::GetMetaDataRequest::IntegrationMethod => DBEnum::IntegrationMethod,
api::GetMetaDataRequest::ConfigurationType => DBEnum::ConfigurationType,
api::GetMetaDataRequest::IntegrationCompleted => DBEnum::IntegrationCompleted,
api::GetMetaDataRequest::StripeConnected => DBEnum::StripeConnected,
api::GetMetaDataRequest::PaypalConnected => DBEnum::PaypalConnected,
api::GetMetaDataRequest::SPRoutingConfigured => DBEnum::SpRoutingConfigured,
api::GetMetaDataRequest::Feedback => DBEnum::Feedback,
api::GetMetaDataRequest::ProdIntent => DBEnum::ProdIntent,
api::GetMetaDataRequest::SPTestPayment => DBEnum::SpTestPayment,
api::GetMetaDataRequest::DownloadWoocom => DBEnum::DownloadWoocom,
api::GetMetaDataRequest::ConfigureWoocom => DBEnum::ConfigureWoocom,
api::GetMetaDataRequest::SetupWoocomWebhook => DBEnum::SetupWoocomWebhook,
api::GetMetaDataRequest::IsMultipleConfiguration => DBEnum::IsMultipleConfiguration,
api::GetMetaDataRequest::IsChangePasswordRequired => DBEnum::IsChangePasswordRequired,
api::GetMetaDataRequest::OnboardingSurvey => DBEnum::OnboardingSurvey,
api::GetMetaDataRequest::ReconStatus => DBEnum::ReconStatus,
}
}
fn into_response(
data: Option<&DashboardMetadata>,
data_type: DBEnum,
) -> UserResult<api::GetMetaDataResponse> {
match data_type {
DBEnum::ProductionAgreement => Ok(api::GetMetaDataResponse::ProductionAgreement(
data.is_some(),
)),
DBEnum::SetupProcessor => {
let resp = utils::deserialize_to_response(data)?;
Ok(api::GetMetaDataResponse::SetupProcessor(resp))
}
DBEnum::ConfigureEndpoint => {
Ok(api::GetMetaDataResponse::ConfigureEndpoint(data.is_some()))
}
DBEnum::SetupComplete => Ok(api::GetMetaDataResponse::SetupComplete(data.is_some())),
DBEnum::FirstProcessorConnected => {
let resp = utils::deserialize_to_response(data)?;
Ok(api::GetMetaDataResponse::FirstProcessorConnected(resp))
}
DBEnum::SecondProcessorConnected => {
let resp = utils::deserialize_to_response(data)?;
Ok(api::GetMetaDataResponse::SecondProcessorConnected(resp))
}
DBEnum::ConfiguredRouting => {
let resp = utils::deserialize_to_response(data)?;
Ok(api::GetMetaDataResponse::ConfiguredRouting(resp))
}
DBEnum::TestPayment => {
let resp = utils::deserialize_to_response(data)?;
Ok(api::GetMetaDataResponse::TestPayment(resp))
}
DBEnum::IntegrationMethod => {
let resp = utils::deserialize_to_response(data)?;
Ok(api::GetMetaDataResponse::IntegrationMethod(resp))
}
DBEnum::ConfigurationType => {
let resp = utils::deserialize_to_response(data)?;
Ok(api::GetMetaDataResponse::ConfigurationType(resp))
}
DBEnum::IntegrationCompleted => Ok(api::GetMetaDataResponse::IntegrationCompleted(
data.is_some(),
)),
DBEnum::StripeConnected => {
let resp = utils::deserialize_to_response(data)?;
Ok(api::GetMetaDataResponse::StripeConnected(resp))
}
DBEnum::PaypalConnected => {
let resp = utils::deserialize_to_response(data)?;
Ok(api::GetMetaDataResponse::PaypalConnected(resp))
}
DBEnum::SpRoutingConfigured => {
let resp = utils::deserialize_to_response(data)?;
Ok(api::GetMetaDataResponse::SPRoutingConfigured(resp))
}
DBEnum::Feedback => {
let resp = utils::deserialize_to_response(data)?;
Ok(api::GetMetaDataResponse::Feedback(resp))
}
DBEnum::ProdIntent => {
let resp = utils::deserialize_to_response(data)?;
Ok(api::GetMetaDataResponse::ProdIntent(resp))
}
DBEnum::SpTestPayment => Ok(api::GetMetaDataResponse::SPTestPayment(data.is_some())),
DBEnum::DownloadWoocom => Ok(api::GetMetaDataResponse::DownloadWoocom(data.is_some())),
DBEnum::ConfigureWoocom => Ok(api::GetMetaDataResponse::ConfigureWoocom(data.is_some())),
DBEnum::SetupWoocomWebhook => {
Ok(api::GetMetaDataResponse::SetupWoocomWebhook(data.is_some()))
}
DBEnum::IsMultipleConfiguration => Ok(api::GetMetaDataResponse::IsMultipleConfiguration(
data.is_some(),
)),
DBEnum::IsChangePasswordRequired => Ok(api::GetMetaDataResponse::IsChangePasswordRequired(
data.is_some(),
)),
DBEnum::OnboardingSurvey => {
let resp = utils::deserialize_to_response(data)?;
Ok(api::GetMetaDataResponse::OnboardingSurvey(resp))
}
DBEnum::ReconStatus => {
let resp = utils::deserialize_to_response(data)?;
Ok(api::GetMetaDataResponse::ReconStatus(resp))
}
}
}
async fn insert_metadata(
state: &SessionState,
user: UserFromToken,
metadata_key: DBEnum,
metadata_value: types::MetaData,
) -> UserResult<DashboardMetadata> {
match metadata_value {
types::MetaData::ProductionAgreement(data) => {
utils::insert_merchant_scoped_metadata_to_db(
state,
user.user_id,
user.merchant_id,
user.org_id,
metadata_key,
data,
)
.await
}
types::MetaData::SetupProcessor(data) => {
utils::insert_merchant_scoped_metadata_to_db(
state,
user.user_id,
user.merchant_id,
user.org_id,
metadata_key,
data,
)
.await
}
types::MetaData::ConfigureEndpoint(data) => {
utils::insert_merchant_scoped_metadata_to_db(
state,
user.user_id,
user.merchant_id,
user.org_id,
metadata_key,
data,
)
.await
}
types::MetaData::SetupComplete(data) => {
utils::insert_merchant_scoped_metadata_to_db(
state,
user.user_id,
user.merchant_id,
user.org_id,
metadata_key,
data,
)
.await
}
types::MetaData::FirstProcessorConnected(data) => {
utils::insert_merchant_scoped_metadata_to_db(
state,
user.user_id,
user.merchant_id,
user.org_id,
metadata_key,
data,
)
.await
}
types::MetaData::SecondProcessorConnected(data) => {
utils::insert_merchant_scoped_metadata_to_db(
state,
user.user_id,
user.merchant_id,
user.org_id,
metadata_key,
data,
)
.await
}
types::MetaData::ConfiguredRouting(data) => {
utils::insert_merchant_scoped_metadata_to_db(
state,
user.user_id,
user.merchant_id,
user.org_id,
metadata_key,
data,
)
.await
}
types::MetaData::TestPayment(data) => {
utils::insert_merchant_scoped_metadata_to_db(
state,
user.user_id,
user.merchant_id,
user.org_id,
metadata_key,
data,
)
.await
}
types::MetaData::IntegrationMethod(data) => {
let mut metadata = utils::insert_merchant_scoped_metadata_to_db(
state,
user.user_id.clone(),
user.merchant_id.clone(),
user.org_id.clone(),
metadata_key,
data.clone(),
)
.await;
if utils::is_update_required(&metadata) {
metadata = utils::update_merchant_scoped_metadata(
state,
user.user_id,
user.merchant_id,
user.org_id,
metadata_key,
data,
)
.await
.change_context(UserErrors::InternalServerError);
}
metadata
}
types::MetaData::ConfigurationType(data) => {
let mut metadata = utils::insert_merchant_scoped_metadata_to_db(
state,
user.user_id.clone(),
user.merchant_id.clone(),
user.org_id.clone(),
metadata_key,
data.clone(),
)
.await;
if utils::is_update_required(&metadata) {
metadata = utils::update_merchant_scoped_metadata(
state,
user.user_id,
user.merchant_id,
user.org_id,
metadata_key,
data,
)
.await
.change_context(UserErrors::InternalServerError);
}
metadata
}
types::MetaData::IntegrationCompleted(data) => {
utils::insert_merchant_scoped_metadata_to_db(
state,
user.user_id,
user.merchant_id,
user.org_id,
metadata_key,
data,
)
.await
}
types::MetaData::StripeConnected(data) => {
utils::insert_merchant_scoped_metadata_to_db(
state,
user.user_id,
user.merchant_id,
user.org_id,
metadata_key,
data,
)
.await
}
types::MetaData::PaypalConnected(data) => {
utils::insert_merchant_scoped_metadata_to_db(
state,
user.user_id,
user.merchant_id,
user.org_id,
metadata_key,
data,
)
.await
}
types::MetaData::SPRoutingConfigured(data) => {
utils::insert_merchant_scoped_metadata_to_db(
state,
user.user_id,
user.merchant_id,
user.org_id,
metadata_key,
data,
)
.await
}
types::MetaData::Feedback(data) => {
let mut metadata = utils::insert_user_scoped_metadata_to_db(
state,
user.user_id.clone(),
user.merchant_id.clone(),
user.org_id.clone(),
metadata_key,
data.clone(),
)
.await;
if utils::is_update_required(&metadata) {
metadata = utils::update_user_scoped_metadata(
state,
user.user_id,
user.merchant_id,
user.org_id,
metadata_key,
data,
)
.await
.change_context(UserErrors::InternalServerError);
}
metadata
}
types::MetaData::ProdIntent(data) => {
let mut metadata = utils::insert_merchant_scoped_metadata_to_db(
state,
user.user_id.clone(),
user.merchant_id.clone(),
user.org_id.clone(),
metadata_key,
data.clone(),
)
.await;
if utils::is_update_required(&metadata) {
metadata = utils::update_merchant_scoped_metadata(
state,
user.user_id.clone(),
user.merchant_id.clone(),
user.org_id.clone(),
metadata_key,
data.clone(),
)
.await
.change_context(UserErrors::InternalServerError);
}
#[cfg(feature = "email")]
{
let user_data = user.get_user_from_db(state).await?;
let user_email = domain::UserEmail::from_pii_email(user_data.get_email())
.change_context(UserErrors::InternalServerError)?
.get_secret()
.expose();
if utils::is_prod_email_required(&data, user_email) {
let theme = theme_utils::get_most_specific_theme_using_token_and_min_entity(
state,
&user,
EntityType::Merchant,
)
.await?;
let email_contents = email_types::BizEmailProd::new(
state,
data.clone(),
theme.as_ref().map(|theme| theme.theme_id.clone()),
theme
.map(|theme| theme.email_config())
.unwrap_or(state.conf.theme.email_config.clone()),
)?;
let send_email_result = state
.email_client
.compose_and_send_email(
user_utils::get_base_url(state),
Box::new(email_contents),
state.conf.proxy.https_url.as_ref(),
)
.await;
logger::info!(prod_intent_email=?send_email_result);
}
}
// Hubspot integration
let hubspot_body = state
.crm_client
.make_body(CrmPayload {
legal_business_name: data.legal_business_name.map(|s| s.into_inner()),
business_label: data.business_label.map(|s| s.into_inner()),
business_location: data.business_location,
display_name: data.display_name.map(|s| s.into_inner()),
poc_email: data.poc_email.map(|s| Secret::new(s.peek().clone())),
business_type: data.business_type.map(|s| s.into_inner()),
business_identifier: data.business_identifier.map(|s| s.into_inner()),
business_website: data.business_website.map(|s| s.into_inner()),
poc_name: data
.poc_name
.map(|s| Secret::new(s.peek().clone().into_inner())),
poc_contact: data
.poc_contact
.map(|s| Secret::new(s.peek().clone().into_inner())),
comments: data.comments.map(|s| s.into_inner()),
is_completed: data.is_completed,
business_country_name: data.business_country_name.map(|s| s.into_inner()),
})
.await;
let base_url = user_utils::get_base_url(state);
let hubspot_request = state
.crm_client
.make_request(hubspot_body, base_url.to_string())
.await;
let _ = state
.crm_client
.send_request(&state.conf.proxy, hubspot_request)
.await
.inspect_err(|err| {
logger::error!(
"An error occurred while sending data to hubspot for user_id {}: {:?}",
user.user_id,
err
);
});
metadata
}
types::MetaData::SPTestPayment(data) => {
utils::insert_merchant_scoped_metadata_to_db(
state,
user.user_id,
user.merchant_id,
user.org_id,
metadata_key,
data,
)
.await
}
types::MetaData::DownloadWoocom(data) => {
utils::insert_merchant_scoped_metadata_to_db(
state,
user.user_id,
user.merchant_id,
user.org_id,
metadata_key,
data,
)
.await
}
types::MetaData::ConfigureWoocom(data) => {
utils::insert_merchant_scoped_metadata_to_db(
state,
user.user_id,
user.merchant_id,
user.org_id,
metadata_key,
data,
)
.await
}
types::MetaData::SetupWoocomWebhook(data) => {
utils::insert_merchant_scoped_metadata_to_db(
state,
user.user_id,
user.merchant_id,
user.org_id,
metadata_key,
data,
)
.await
}
types::MetaData::IsMultipleConfiguration(data) => {
utils::insert_merchant_scoped_metadata_to_db(
state,
user.user_id,
user.merchant_id,
user.org_id,
metadata_key,
data,
)
.await
}
types::MetaData::IsChangePasswordRequired(data) => {
utils::insert_user_scoped_metadata_to_db(
state,
user.user_id,
user.merchant_id,
user.org_id,
metadata_key,
data,
)
.await
}
types::MetaData::OnboardingSurvey(data) => {
utils::insert_merchant_scoped_metadata_to_db(
state,
user.user_id,
user.merchant_id,
user.org_id,
metadata_key,
data,
)
.await
}
types::MetaData::ReconStatus(data) => {
let mut metadata = utils::insert_merchant_scoped_metadata_to_db(
state,
user.user_id.clone(),
user.merchant_id.clone(),
user.org_id.clone(),
metadata_key,
data.clone(),
)
.await;
if utils::is_update_required(&metadata) {
metadata = utils::update_merchant_scoped_metadata(
state,
user.user_id,
user.merchant_id,
user.org_id,
metadata_key,
data,
)
.await;
}
metadata
}
}
}
async fn fetch_metadata(
state: &SessionState,
user: &UserFromToken,
metadata_keys: Vec<DBEnum>,
) -> UserResult<Vec<DashboardMetadata>> {
let mut dashboard_metadata = Vec::with_capacity(metadata_keys.len());
let (merchant_scoped_enums, user_scoped_enums) =
utils::separate_metadata_type_based_on_scope(metadata_keys);
if !merchant_scoped_enums.is_empty() {
let mut res = utils::get_merchant_scoped_metadata_from_db(
state,
user.merchant_id.to_owned(),
user.org_id.to_owned(),
merchant_scoped_enums,
)
.await?;
dashboard_metadata.append(&mut res);
}
if !user_scoped_enums.is_empty() {
let mut res = utils::get_user_scoped_metadata_from_db(
state,
user.user_id.to_owned(),
user.merchant_id.to_owned(),
user.org_id.to_owned(),
user_scoped_enums,
)
.await?;
dashboard_metadata.append(&mut res);
}
Ok(dashboard_metadata)
}
pub async fn backfill_metadata(
state: &SessionState,
user: &UserFromToken,
key: &DBEnum,
) -> UserResult<Option<DashboardMetadata>> {
let key_store = state
.store
.get_merchant_key_store_by_merchant_id(
&state.into(),
&user.merchant_id,
&state.store.get_master_key().to_vec().into(),
)
.await
.change_context(UserErrors::InternalServerError)?;
match key {
DBEnum::StripeConnected => {
let mca = if let Some(stripe_connected) = get_merchant_connector_account_by_name(
state,
&user.merchant_id,
api_models::enums::RoutableConnectors::Stripe
.to_string()
.as_str(),
&key_store,
)
.await?
{
stripe_connected
} else if let Some(stripe_test_connected) = get_merchant_connector_account_by_name(
state,
&user.merchant_id,
//TODO: Use Enum with proper feature flag
"stripe_test",
&key_store,
)
.await?
{
stripe_test_connected
} else {
return Ok(None);
};
#[cfg(feature = "v1")]
let processor_name = mca.connector_name.clone();
#[cfg(feature = "v2")]
let processor_name = mca.connector_name.to_string().clone();
Some(
insert_metadata(
state,
user.to_owned(),
DBEnum::StripeConnected,
types::MetaData::StripeConnected(api::ProcessorConnected {
processor_id: mca.get_id(),
processor_name,
}),
)
.await,
)
.transpose()
}
DBEnum::PaypalConnected => {
let mca = if let Some(paypal_connected) = get_merchant_connector_account_by_name(
state,
&user.merchant_id,
api_models::enums::RoutableConnectors::Paypal
.to_string()
.as_str(),
&key_store,
)
.await?
{
paypal_connected
} else if let Some(paypal_test_connected) = get_merchant_connector_account_by_name(
state,
&user.merchant_id,
//TODO: Use Enum with proper feature flag
"paypal_test",
&key_store,
)
.await?
{
paypal_test_connected
} else {
return Ok(None);
};
#[cfg(feature = "v1")]
let processor_name = mca.connector_name.clone();
#[cfg(feature = "v2")]
let processor_name = mca.connector_name.to_string().clone();
Some(
insert_metadata(
state,
user.to_owned(),
DBEnum::PaypalConnected,
types::MetaData::PaypalConnected(api::ProcessorConnected {
processor_id: mca.get_id(),
processor_name,
}),
)
.await,
)
.transpose()
}
_ => Ok(None),
}
}
pub async fn get_merchant_connector_account_by_name(
state: &SessionState,
merchant_id: &common_utils::id_type::MerchantId,
connector_name: &str,
key_store: &MerchantKeyStore,
) -> UserResult<Option<domain::MerchantConnectorAccount>> {
#[cfg(feature = "v1")]
{
state
.store
.find_merchant_connector_account_by_merchant_id_connector_name(
&state.into(),
merchant_id,
connector_name,
key_store,
)
.await
.map_err(|e| {
e.change_context(UserErrors::InternalServerError)
.attach_printable("DB Error Fetching DashboardMetaData")
})
.map(|data| data.first().cloned())
}
#[cfg(feature = "v2")]
{
let _ = state;
let _ = merchant_id;
let _ = connector_name;
let _ = key_store;
todo!()
}
}
|
crates/router/src/core/user/dashboard_metadata.rs
|
router::src::core::user::dashboard_metadata
| 5,858
| true
|
// File: crates/router/src/core/user/sample_data.rs
// Module: router::src::core::user::sample_data
use api_models::user::sample_data::SampleDataRequest;
use common_utils::errors::ReportSwitchExt;
use diesel_models::{DisputeNew, RefundNew};
use error_stack::ResultExt;
use hyperswitch_domain_models::payments::PaymentIntent;
pub type SampleDataApiResponse<T> = SampleDataResult<ApplicationResponse<T>>;
use crate::{
core::errors::sample_data::{SampleDataError, SampleDataResult},
routes::{app::ReqState, SessionState},
services::{authentication::UserFromToken, ApplicationResponse},
utils,
};
#[cfg(feature = "v1")]
pub async fn generate_sample_data_for_user(
state: SessionState,
user_from_token: UserFromToken,
req: SampleDataRequest,
_req_state: ReqState,
) -> SampleDataApiResponse<()> {
let sample_data = utils::user::sample_data::generate_sample_data(
&state,
req,
&user_from_token.merchant_id,
&user_from_token.org_id,
)
.await?;
let key_store = state
.store
.get_merchant_key_store_by_merchant_id(
&(&state).into(),
&user_from_token.merchant_id,
&state.store.get_master_key().to_vec().into(),
)
.await
.change_context(SampleDataError::InternalServerError)
.attach_printable("Not able to fetch merchant key store")?; // If not able to fetch merchant key store for any reason, this should be an internal server error
let (payment_intents, payment_attempts, refunds, disputes): (
Vec<PaymentIntent>,
Vec<diesel_models::user::sample_data::PaymentAttemptBatchNew>,
Vec<RefundNew>,
Vec<DisputeNew>,
) = sample_data.into_iter().fold(
(Vec::new(), Vec::new(), Vec::new(), Vec::new()),
|(mut pi, mut pa, mut rf, mut dp), (payment_intent, payment_attempt, refund, dispute)| {
pi.push(payment_intent);
pa.push(payment_attempt);
if let Some(refund) = refund {
rf.push(refund);
}
if let Some(dispute) = dispute {
dp.push(dispute);
}
(pi, pa, rf, dp)
},
);
state
.store
.insert_payment_intents_batch_for_sample_data(&(&state).into(), payment_intents, &key_store)
.await
.switch()?;
state
.store
.insert_payment_attempts_batch_for_sample_data(payment_attempts)
.await
.switch()?;
state
.store
.insert_refunds_batch_for_sample_data(refunds)
.await
.switch()?;
state
.store
.insert_disputes_batch_for_sample_data(disputes)
.await
.switch()?;
Ok(ApplicationResponse::StatusOk)
}
#[cfg(feature = "v1")]
pub async fn delete_sample_data_for_user(
state: SessionState,
user_from_token: UserFromToken,
_req: SampleDataRequest,
_req_state: ReqState,
) -> SampleDataApiResponse<()> {
let merchant_id_del = user_from_token.merchant_id;
let key_manager_state = &(&state).into();
let key_store = state
.store
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&merchant_id_del,
&state.store.get_master_key().to_vec().into(),
)
.await
.change_context(SampleDataError::InternalServerError)
.attach_printable("Not able to fetch merchant key store")?; // If not able to fetch merchant key store for any reason, this should be an internal server error
state
.store
.delete_payment_intents_for_sample_data(key_manager_state, &merchant_id_del, &key_store)
.await
.switch()?;
state
.store
.delete_payment_attempts_for_sample_data(&merchant_id_del)
.await
.switch()?;
state
.store
.delete_refunds_for_sample_data(&merchant_id_del)
.await
.switch()?;
state
.store
.delete_disputes_for_sample_data(&merchant_id_del)
.await
.switch()?;
Ok(ApplicationResponse::StatusOk)
}
|
crates/router/src/core/user/sample_data.rs
|
router::src::core::user::sample_data
| 960
| true
|
// File: crates/router/src/core/blocklist/transformers.rs
// Module: router::src::core::blocklist::transformers
use api_models::{blocklist, enums as api_enums};
use common_utils::{
ext_traits::{Encode, StringExt},
request::RequestContent,
};
use error_stack::ResultExt;
use josekit::jwe;
use masking::{PeekInterface, StrongSecret};
use router_env::{instrument, tracing};
use crate::{
configs::settings,
core::{
errors::{self, CustomResult},
payment_methods::transformers as payment_methods,
},
headers, routes,
services::{api as services, encryption, EncryptionAlgorithm},
types::{storage, transformers::ForeignFrom},
utils::ConnectorResponseExt,
};
const LOCKER_FINGERPRINT_PATH: &str = "/cards/fingerprint";
impl ForeignFrom<storage::Blocklist> for blocklist::AddToBlocklistResponse {
fn foreign_from(from: storage::Blocklist) -> Self {
Self {
fingerprint_id: from.fingerprint_id,
data_kind: from.data_kind,
created_at: from.created_at,
}
}
}
async fn generate_fingerprint_request(
jwekey: &settings::Jwekey,
locker: &settings::Locker,
payload: &blocklist::GenerateFingerprintRequest,
locker_choice: api_enums::LockerChoice,
) -> CustomResult<services::Request, errors::VaultError> {
let payload = payload
.encode_to_vec()
.change_context(errors::VaultError::RequestEncodingFailed)?;
let private_key = jwekey.vault_private_key.peek().as_bytes();
let jws = encryption::jws_sign_payload(&payload, &locker.locker_signing_key_id, private_key)
.await
.change_context(errors::VaultError::RequestEncodingFailed)?;
let jwe_payload = generate_jwe_payload_for_request(jwekey, &jws, locker_choice).await?;
let mut url = match locker_choice {
api_enums::LockerChoice::HyperswitchCardVault => locker.host.to_owned(),
};
url.push_str(LOCKER_FINGERPRINT_PATH);
let mut request = services::Request::new(services::Method::Post, &url);
request.add_header(headers::CONTENT_TYPE, "application/json".into());
request.set_body(RequestContent::Json(Box::new(jwe_payload)));
Ok(request)
}
async fn generate_jwe_payload_for_request(
jwekey: &settings::Jwekey,
jws: &str,
locker_choice: api_enums::LockerChoice,
) -> CustomResult<encryption::JweBody, errors::VaultError> {
let jws_payload: Vec<&str> = jws.split('.').collect();
let generate_jws_body = |payload: Vec<&str>| -> Option<encryption::JwsBody> {
Some(encryption::JwsBody {
header: payload.first()?.to_string(),
payload: payload.get(1)?.to_string(),
signature: payload.get(2)?.to_string(),
})
};
let jws_body =
generate_jws_body(jws_payload).ok_or(errors::VaultError::GenerateFingerprintFailed)?;
let payload = jws_body
.encode_to_vec()
.change_context(errors::VaultError::GenerateFingerprintFailed)?;
let public_key = match locker_choice {
api_enums::LockerChoice::HyperswitchCardVault => {
jwekey.vault_encryption_key.peek().as_bytes()
}
};
let jwe_encrypted =
encryption::encrypt_jwe(&payload, public_key, EncryptionAlgorithm::A256GCM, None)
.await
.change_context(errors::VaultError::SaveCardFailed)
.attach_printable("Error on jwe encrypt")?;
let jwe_payload: Vec<&str> = jwe_encrypted.split('.').collect();
let generate_jwe_body = |payload: Vec<&str>| -> Option<encryption::JweBody> {
Some(encryption::JweBody {
header: payload.first()?.to_string(),
iv: payload.get(2)?.to_string(),
encrypted_payload: payload.get(3)?.to_string(),
tag: payload.get(4)?.to_string(),
encrypted_key: payload.get(1)?.to_string(),
})
};
let jwe_body =
generate_jwe_body(jwe_payload).ok_or(errors::VaultError::GenerateFingerprintFailed)?;
Ok(jwe_body)
}
#[instrument(skip_all)]
pub async fn generate_fingerprint(
state: &routes::SessionState,
card_number: StrongSecret<String>,
hash_key: StrongSecret<String>,
locker_choice: api_enums::LockerChoice,
) -> CustomResult<blocklist::GenerateFingerprintResponsePayload, errors::VaultError> {
let payload = blocklist::GenerateFingerprintRequest {
card: blocklist::Card { card_number },
hash_key,
};
let generate_fingerprint_resp =
call_to_locker_for_fingerprint(state, &payload, locker_choice).await?;
Ok(generate_fingerprint_resp)
}
#[instrument(skip_all)]
async fn call_to_locker_for_fingerprint(
state: &routes::SessionState,
payload: &blocklist::GenerateFingerprintRequest,
locker_choice: api_enums::LockerChoice,
) -> CustomResult<blocklist::GenerateFingerprintResponsePayload, errors::VaultError> {
let locker = &state.conf.locker;
let jwekey = state.conf.jwekey.get_inner();
let request = generate_fingerprint_request(jwekey, locker, payload, locker_choice).await?;
let response = services::call_connector_api(state, request, "call_locker_to_get_fingerprint")
.await
.change_context(errors::VaultError::GenerateFingerprintFailed);
let jwe_body: encryption::JweBody = response
.get_response_inner("JweBody")
.change_context(errors::VaultError::GenerateFingerprintFailed)?;
let decrypted_payload = decrypt_generate_fingerprint_response_payload(
jwekey,
jwe_body,
Some(locker_choice),
locker.decryption_scheme.clone(),
)
.await
.change_context(errors::VaultError::GenerateFingerprintFailed)
.attach_printable("Error getting decrypted fingerprint response payload")?;
let generate_fingerprint_response: blocklist::GenerateFingerprintResponsePayload =
decrypted_payload
.parse_struct("GenerateFingerprintResponse")
.change_context(errors::VaultError::ResponseDeserializationFailed)?;
Ok(generate_fingerprint_response)
}
async fn decrypt_generate_fingerprint_response_payload(
jwekey: &settings::Jwekey,
jwe_body: encryption::JweBody,
locker_choice: Option<api_enums::LockerChoice>,
decryption_scheme: settings::DecryptionScheme,
) -> CustomResult<String, errors::VaultError> {
let target_locker = locker_choice.unwrap_or(api_enums::LockerChoice::HyperswitchCardVault);
let public_key = match target_locker {
api_enums::LockerChoice::HyperswitchCardVault => {
jwekey.vault_encryption_key.peek().as_bytes()
}
};
let private_key = jwekey.vault_private_key.peek().as_bytes();
let jwt = payment_methods::get_dotted_jwe(jwe_body);
let alg = match decryption_scheme {
settings::DecryptionScheme::RsaOaep => jwe::RSA_OAEP,
settings::DecryptionScheme::RsaOaep256 => jwe::RSA_OAEP_256,
};
let jwe_decrypted = encryption::decrypt_jwe(
&jwt,
encryption::KeyIdCheck::SkipKeyIdCheck,
private_key,
alg,
)
.await
.change_context(errors::VaultError::SaveCardFailed)
.attach_printable("Jwe Decryption failed for JweBody for vault")?;
let jws = jwe_decrypted
.parse_struct("JwsBody")
.change_context(errors::VaultError::ResponseDeserializationFailed)?;
let jws_body = payment_methods::get_dotted_jws(jws);
encryption::verify_sign(jws_body, public_key)
.change_context(errors::VaultError::SaveCardFailed)
.attach_printable("Jws Decryption failed for JwsBody for vault")
}
|
crates/router/src/core/blocklist/transformers.rs
|
router::src::core::blocklist::transformers
| 1,798
| true
|
// File: crates/router/src/core/blocklist/utils.rs
// Module: router::src::core::blocklist::utils
use api_models::blocklist as api_blocklist;
use common_enums::MerchantDecision;
use common_utils::errors::CustomResult;
use diesel_models::configs;
use error_stack::ResultExt;
use masking::StrongSecret;
use super::{errors, transformers::generate_fingerprint, SessionState};
use crate::{
consts,
core::{
errors::{RouterResult, StorageErrorExt},
payments::PaymentData,
},
logger,
types::{domain, storage, transformers::ForeignInto},
utils,
};
pub async fn delete_entry_from_blocklist(
state: &SessionState,
merchant_id: &common_utils::id_type::MerchantId,
request: api_blocklist::DeleteFromBlocklistRequest,
) -> RouterResult<api_blocklist::DeleteFromBlocklistResponse> {
let blocklist_entry = match request {
api_blocklist::DeleteFromBlocklistRequest::CardBin(bin) => {
delete_card_bin_blocklist_entry(state, &bin, merchant_id).await?
}
api_blocklist::DeleteFromBlocklistRequest::ExtendedCardBin(xbin) => {
delete_card_bin_blocklist_entry(state, &xbin, merchant_id).await?
}
api_blocklist::DeleteFromBlocklistRequest::Fingerprint(fingerprint_id) => state
.store
.delete_blocklist_entry_by_merchant_id_fingerprint_id(merchant_id, &fingerprint_id)
.await
.to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError {
message: "no blocklist record for the given fingerprint id was found".to_string(),
})?,
};
Ok(blocklist_entry.foreign_into())
}
pub async fn toggle_blocklist_guard_for_merchant(
state: &SessionState,
merchant_id: &common_utils::id_type::MerchantId,
query: api_blocklist::ToggleBlocklistQuery,
) -> CustomResult<api_blocklist::ToggleBlocklistResponse, errors::ApiErrorResponse> {
let key = merchant_id.get_blocklist_guard_key();
let maybe_guard = state.store.find_config_by_key(&key).await;
let new_config = configs::ConfigNew {
key: key.clone(),
config: query.status.to_string(),
};
match maybe_guard {
Ok(_config) => {
let updated_config = configs::ConfigUpdate::Update {
config: Some(query.status.to_string()),
};
state
.store
.update_config_by_key(&key, updated_config)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error enabling the blocklist guard")?;
}
Err(e) if e.current_context().is_db_not_found() => {
state
.store
.insert_config(new_config)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error enabling the blocklist guard")?;
}
Err(error) => {
logger::error!(?error);
Err(error)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error enabling the blocklist guard")?;
}
};
let guard_status = if query.status { "enabled" } else { "disabled" };
Ok(api_blocklist::ToggleBlocklistResponse {
blocklist_guard_status: guard_status.to_string(),
})
}
pub async fn list_blocklist_entries_for_merchant(
state: &SessionState,
merchant_id: &common_utils::id_type::MerchantId,
query: api_blocklist::ListBlocklistQuery,
) -> RouterResult<Vec<api_blocklist::BlocklistResponse>> {
state
.store
.list_blocklist_entries_by_merchant_id_data_kind(
merchant_id,
query.data_kind,
query.limit.into(),
query.offset.into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError {
message: "no blocklist records found".to_string(),
})
.map(|v| v.into_iter().map(ForeignInto::foreign_into).collect())
}
fn validate_card_bin(bin: &str) -> RouterResult<()> {
if bin.len() == 6 && bin.chars().all(|c| c.is_ascii_digit()) {
Ok(())
} else {
Err(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "data".to_string(),
expected_format: "a 6 digit number".to_string(),
}
.into())
}
}
fn validate_extended_card_bin(bin: &str) -> RouterResult<()> {
if bin.len() == 8 && bin.chars().all(|c| c.is_ascii_digit()) {
Ok(())
} else {
Err(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "data".to_string(),
expected_format: "an 8 digit number".to_string(),
}
.into())
}
}
pub async fn insert_entry_into_blocklist(
state: &SessionState,
merchant_id: &common_utils::id_type::MerchantId,
to_block: api_blocklist::AddToBlocklistRequest,
) -> RouterResult<api_blocklist::AddToBlocklistResponse> {
let blocklist_entry = match &to_block {
api_blocklist::AddToBlocklistRequest::CardBin(bin) => {
validate_card_bin(bin)?;
duplicate_check_insert_bin(
bin,
state,
merchant_id,
common_enums::BlocklistDataKind::CardBin,
)
.await?
}
api_blocklist::AddToBlocklistRequest::ExtendedCardBin(bin) => {
validate_extended_card_bin(bin)?;
duplicate_check_insert_bin(
bin,
state,
merchant_id,
common_enums::BlocklistDataKind::ExtendedCardBin,
)
.await?
}
api_blocklist::AddToBlocklistRequest::Fingerprint(fingerprint_id) => {
let blocklist_entry_result = state
.store
.find_blocklist_entry_by_merchant_id_fingerprint_id(merchant_id, fingerprint_id)
.await;
match blocklist_entry_result {
Ok(_) => {
return Err(errors::ApiErrorResponse::PreconditionFailed {
message: "data associated with the given fingerprint is already blocked"
.to_string(),
}
.into());
}
// if it is a db not found error, we can proceed as normal
Err(inner) if inner.current_context().is_db_not_found() => {}
err @ Err(_) => {
err.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("error fetching blocklist entry from table")?;
}
}
state
.store
.insert_blocklist_entry(storage::BlocklistNew {
merchant_id: merchant_id.to_owned(),
fingerprint_id: fingerprint_id.clone(),
data_kind: api_models::enums::enums::BlocklistDataKind::PaymentMethod,
metadata: None,
created_at: common_utils::date_time::now(),
})
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed to add fingerprint to blocklist")?
}
};
Ok(blocklist_entry.foreign_into())
}
pub async fn get_merchant_fingerprint_secret(
state: &SessionState,
merchant_id: &common_utils::id_type::MerchantId,
) -> RouterResult<String> {
let key = merchant_id.get_merchant_fingerprint_secret_key();
let config_fetch_result = state.store.find_config_by_key(&key).await;
match config_fetch_result {
Ok(config) => Ok(config.config),
Err(e) if e.current_context().is_db_not_found() => {
let new_fingerprint_secret =
utils::generate_id(consts::FINGERPRINT_SECRET_LENGTH, "fs");
let new_config = storage::ConfigNew {
key,
config: new_fingerprint_secret.clone(),
};
state
.store
.insert_config(new_config)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to create new fingerprint secret for merchant")?;
Ok(new_fingerprint_secret)
}
Err(e) => Err(e)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("error fetching merchant fingerprint secret"),
}
}
async fn duplicate_check_insert_bin(
bin: &str,
state: &SessionState,
merchant_id: &common_utils::id_type::MerchantId,
data_kind: common_enums::BlocklistDataKind,
) -> RouterResult<storage::Blocklist> {
let blocklist_entry_result = state
.store
.find_blocklist_entry_by_merchant_id_fingerprint_id(merchant_id, bin)
.await;
match blocklist_entry_result {
Ok(_) => {
return Err(errors::ApiErrorResponse::PreconditionFailed {
message: "provided bin is already blocked".to_string(),
}
.into());
}
Err(e) if e.current_context().is_db_not_found() => {}
err @ Err(_) => {
return err
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to fetch blocklist entry");
}
}
state
.store
.insert_blocklist_entry(storage::BlocklistNew {
merchant_id: merchant_id.to_owned(),
fingerprint_id: bin.to_string(),
data_kind,
metadata: None,
created_at: common_utils::date_time::now(),
})
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("error inserting pm blocklist item")
}
async fn delete_card_bin_blocklist_entry(
state: &SessionState,
bin: &str,
merchant_id: &common_utils::id_type::MerchantId,
) -> RouterResult<storage::Blocklist> {
state
.store
.delete_blocklist_entry_by_merchant_id_fingerprint_id(merchant_id, bin)
.await
.to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError {
message: "could not find a blocklist entry for the given bin".to_string(),
})
}
pub async fn should_payment_be_blocked(
state: &SessionState,
merchant_context: &domain::MerchantContext,
payment_method_data: &Option<domain::PaymentMethodData>,
) -> CustomResult<bool, errors::ApiErrorResponse> {
let db = &state.store;
let merchant_id = merchant_context.get_merchant_account().get_id();
let merchant_fingerprint_secret = get_merchant_fingerprint_secret(state, merchant_id).await?;
// Hashed Fingerprint to check whether or not this payment should be blocked.
let card_number_fingerprint =
if let Some(domain::PaymentMethodData::Card(card)) = payment_method_data {
generate_fingerprint(
state,
StrongSecret::new(card.card_number.get_card_no()),
StrongSecret::new(merchant_fingerprint_secret.clone()),
api_models::enums::LockerChoice::HyperswitchCardVault,
)
.await
.attach_printable("error in pm fingerprint creation")
.map_or_else(
|error| {
logger::error!(?error);
None
},
Some,
)
.map(|payload| payload.card_fingerprint)
} else {
None
};
// Hashed Cardbin to check whether or not this payment should be blocked.
let card_bin_fingerprint = payment_method_data
.as_ref()
.and_then(|pm_data| match pm_data {
domain::PaymentMethodData::Card(card) => Some(card.card_number.get_card_isin()),
_ => None,
});
// Hashed Extended Cardbin to check whether or not this payment should be blocked.
let extended_card_bin_fingerprint =
payment_method_data
.as_ref()
.and_then(|pm_data| match pm_data {
domain::PaymentMethodData::Card(card) => {
Some(card.card_number.get_extended_card_bin())
}
_ => None,
});
//validating the payment method.
let mut blocklist_futures = Vec::new();
if let Some(card_number_fingerprint) = card_number_fingerprint.as_ref() {
blocklist_futures.push(db.find_blocklist_entry_by_merchant_id_fingerprint_id(
merchant_id,
card_number_fingerprint,
));
}
if let Some(card_bin_fingerprint) = card_bin_fingerprint.as_ref() {
blocklist_futures.push(
db.find_blocklist_entry_by_merchant_id_fingerprint_id(
merchant_id,
card_bin_fingerprint,
),
);
}
if let Some(extended_card_bin_fingerprint) = extended_card_bin_fingerprint.as_ref() {
blocklist_futures.push(db.find_blocklist_entry_by_merchant_id_fingerprint_id(
merchant_id,
extended_card_bin_fingerprint,
));
}
let blocklist_lookups = futures::future::join_all(blocklist_futures).await;
let mut should_payment_be_blocked = false;
for lookup in blocklist_lookups {
match lookup {
Ok(_) => {
should_payment_be_blocked = true;
}
Err(e) => {
logger::error!(blocklist_db_error=?e, "failed db operations for blocklist");
}
}
}
Ok(should_payment_be_blocked)
}
pub async fn validate_data_for_blocklist<F>(
state: &SessionState,
merchant_context: &domain::MerchantContext,
payment_data: &mut PaymentData<F>,
) -> CustomResult<bool, errors::ApiErrorResponse>
where
F: Send + Clone,
{
let db = &state.store;
let should_payment_be_blocked =
should_payment_be_blocked(state, merchant_context, &payment_data.payment_method_data)
.await?;
if should_payment_be_blocked {
// Update db for attempt and intent status.
db.update_payment_intent(
&state.into(),
payment_data.payment_intent.clone(),
storage::PaymentIntentUpdate::RejectUpdate {
status: common_enums::IntentStatus::Failed,
merchant_decision: Some(MerchantDecision::Rejected.to_string()),
updated_by: merchant_context
.get_merchant_account()
.storage_scheme
.to_string(),
},
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)
.attach_printable(
"Failed to update status in Payment Intent to failed due to it being blocklisted",
)?;
// If payment is blocked not showing connector details
let attempt_update = storage::PaymentAttemptUpdate::BlocklistUpdate {
status: common_enums::AttemptStatus::Failure,
error_code: Some(Some("HE-03".to_string())),
error_message: Some(Some("This payment method is blocked".to_string())),
updated_by: merchant_context
.get_merchant_account()
.storage_scheme
.to_string(),
};
db.update_payment_attempt_with_attempt_id(
payment_data.payment_attempt.clone(),
attempt_update,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)
.attach_printable(
"Failed to update status in Payment Attempt to failed, due to it being blocklisted",
)?;
Err(errors::ApiErrorResponse::PaymentBlockedError {
code: 200,
message: "This payment method is blocked".to_string(),
status: "Failed".to_string(),
reason: "Blocked".to_string(),
}
.into())
} else {
payment_data.payment_attempt.fingerprint_id = generate_payment_fingerprint(
state,
payment_data.payment_attempt.merchant_id.clone(),
payment_data.payment_method_data.clone(),
)
.await?;
Ok(false)
}
}
pub async fn generate_payment_fingerprint(
state: &SessionState,
merchant_id: common_utils::id_type::MerchantId,
payment_method_data: Option<domain::PaymentMethodData>,
) -> CustomResult<Option<String>, errors::ApiErrorResponse> {
let merchant_fingerprint_secret = get_merchant_fingerprint_secret(state, &merchant_id).await?;
Ok(
if let Some(domain::PaymentMethodData::Card(card)) = payment_method_data.as_ref() {
generate_fingerprint(
state,
StrongSecret::new(card.card_number.get_card_no()),
StrongSecret::new(merchant_fingerprint_secret),
api_models::enums::LockerChoice::HyperswitchCardVault,
)
.await
.attach_printable("error in pm fingerprint creation")
.map_or_else(
|error| {
logger::error!(?error);
None
},
Some,
)
.map(|payload| payload.card_fingerprint)
} else {
logger::error!("failed to retrieve card fingerprint");
None
},
)
}
|
crates/router/src/core/blocklist/utils.rs
|
router::src::core::blocklist::utils
| 3,627
| true
|
// File: crates/router/src/core/mandate/helpers.rs
// Module: router::src::core::mandate::helpers
use api_models::payments as api_payments;
use common_enums::enums;
use common_types::payments as common_payments_types;
use common_utils::errors::CustomResult;
use diesel_models::Mandate;
use error_stack::ResultExt;
use hyperswitch_domain_models::mandates::MandateData;
use crate::{
core::{errors, payments},
routes::SessionState,
types::{api, domain},
};
#[cfg(feature = "v1")]
pub async fn get_profile_id_for_mandate(
state: &SessionState,
merchant_context: &domain::MerchantContext,
mandate: Mandate,
) -> CustomResult<common_utils::id_type::ProfileId, errors::ApiErrorResponse> {
let profile_id = if let Some(ref payment_id) = mandate.original_payment_id {
let pi = state
.store
.find_payment_intent_by_payment_id_merchant_id(
&state.into(),
payment_id,
merchant_context.get_merchant_account().get_id(),
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
let profile_id =
pi.profile_id
.clone()
.ok_or(errors::ApiErrorResponse::ProfileNotFound {
id: pi
.profile_id
.map(|profile_id| profile_id.get_string_repr().to_owned())
.unwrap_or_else(|| "Profile id is Null".to_string()),
})?;
Ok(profile_id)
} else {
Err(errors::ApiErrorResponse::PaymentNotFound)
}?;
Ok(profile_id)
}
pub fn get_mandate_type(
mandate_data: Option<api_payments::MandateData>,
off_session: Option<bool>,
setup_future_usage: Option<enums::FutureUsage>,
customer_acceptance: Option<common_payments_types::CustomerAcceptance>,
token: Option<String>,
payment_method: Option<enums::PaymentMethod>,
) -> CustomResult<Option<api::MandateTransactionType>, errors::ValidationError> {
match (
mandate_data.clone(),
off_session,
setup_future_usage,
customer_acceptance.or(mandate_data.and_then(|m_data| m_data.customer_acceptance)),
token,
payment_method,
) {
(Some(_), Some(_), Some(enums::FutureUsage::OffSession), Some(_), Some(_), _) => {
Err(errors::ValidationError::InvalidValue {
message: "Expected one out of recurring_details and mandate_data but got both"
.to_string(),
}
.into())
}
(_, _, Some(enums::FutureUsage::OffSession), Some(_), Some(_), _)
| (_, _, Some(enums::FutureUsage::OffSession), Some(_), _, _)
| (Some(_), _, Some(enums::FutureUsage::OffSession), _, _, _) => {
Ok(Some(api::MandateTransactionType::NewMandateTransaction))
}
(_, _, Some(enums::FutureUsage::OffSession), _, Some(_), _)
| (_, Some(_), _, _, _, _)
| (_, _, Some(enums::FutureUsage::OffSession), _, _, Some(enums::PaymentMethod::Wallet)) => {
Ok(Some(
api::MandateTransactionType::RecurringMandateTransaction,
))
}
_ => Ok(None),
}
}
#[derive(Clone)]
pub struct MandateGenericData {
pub token: Option<String>,
pub payment_method: Option<enums::PaymentMethod>,
pub payment_method_type: Option<enums::PaymentMethodType>,
pub mandate_data: Option<MandateData>,
pub recurring_mandate_payment_data:
Option<hyperswitch_domain_models::router_data::RecurringMandatePaymentData>,
pub mandate_connector: Option<payments::MandateConnectorDetails>,
pub payment_method_info: Option<domain::PaymentMethod>,
}
|
crates/router/src/core/mandate/helpers.rs
|
router::src::core::mandate::helpers
| 865
| true
|
// File: crates/router/src/core/mandate/utils.rs
// Module: router::src::core::mandate::utils
use std::marker::PhantomData;
use common_utils::{errors::CustomResult, ext_traits::ValueExt};
use diesel_models::Mandate;
use error_stack::ResultExt;
use crate::{
core::{errors, payments::helpers},
types::{self, domain, PaymentAddress},
SessionState,
};
const IRRELEVANT_ATTEMPT_ID_IN_MANDATE_REVOKE_FLOW: &str =
"irrelevant_attempt_id_in_mandate_revoke_flow";
const IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_MANDATE_REVOKE_FLOW: &str =
"irrelevant_connector_request_reference_id_in_mandate_revoke_flow";
pub async fn construct_mandate_revoke_router_data(
state: &SessionState,
merchant_connector_account: helpers::MerchantConnectorAccountType,
merchant_context: &domain::MerchantContext,
mandate: Mandate,
) -> CustomResult<types::MandateRevokeRouterData, errors::ApiErrorResponse> {
let auth_type: types::ConnectorAuthType = merchant_connector_account
.get_connector_account_details()
.parse_value("ConnectorAuthType")
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let router_data = types::RouterData {
flow: PhantomData,
merchant_id: merchant_context.get_merchant_account().get_id().clone(),
customer_id: Some(mandate.customer_id),
tenant_id: state.tenant.tenant_id.clone(),
connector_customer: None,
connector: mandate.connector,
payment_id: mandate
.original_payment_id
.unwrap_or_else(|| {
common_utils::id_type::PaymentId::get_irrelevant_id("mandate_revoke")
})
.get_string_repr()
.to_owned(),
attempt_id: IRRELEVANT_ATTEMPT_ID_IN_MANDATE_REVOKE_FLOW.to_string(),
status: diesel_models::enums::AttemptStatus::default(),
payment_method: diesel_models::enums::PaymentMethod::default(),
payment_method_type: None,
connector_auth_type: auth_type,
description: None,
address: PaymentAddress::default(),
auth_type: diesel_models::enums::AuthenticationType::default(),
connector_meta_data: None,
connector_wallets_details: None,
amount_captured: None,
minor_amount_captured: None,
access_token: None,
session_token: None,
reference_id: None,
payment_method_token: None,
recurring_mandate_payment_data: None,
preprocessing_id: None,
payment_method_balance: None,
connector_api_version: None,
payment_method_status: None,
request: types::MandateRevokeRequestData {
mandate_id: mandate.mandate_id,
connector_mandate_id: mandate.connector_mandate_id,
},
response: Err(types::ErrorResponse::get_not_implemented()),
connector_request_reference_id:
IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_MANDATE_REVOKE_FLOW.to_string(),
test_mode: None,
connector_http_status_code: None,
external_latency: None,
apple_pay_flow: None,
frm_metadata: None,
#[cfg(feature = "payouts")]
payout_method_data: None,
#[cfg(feature = "payouts")]
quote_id: 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)
}
|
crates/router/src/core/mandate/utils.rs
|
router::src::core::mandate::utils
| 837
| true
|
// File: crates/router/src/core/unified_authentication_service/types.rs
// Module: router::src::core::unified_authentication_service::types
use api_models::payments;
use hyperswitch_domain_models::{
errors::api_error_response::{self as errors, NotImplementedMessage},
router_request_types::{
authentication::MessageCategory,
unified_authentication_service::{
UasAuthenticationRequestData, UasPostAuthenticationRequestData,
UasPreAuthenticationRequestData,
},
BrowserInformation,
},
};
use crate::{
core::{errors::RouterResult, payments::helpers::MerchantConnectorAccountType},
db::domain,
routes::SessionState,
};
pub const CTP_MASTERCARD: &str = "ctp_mastercard";
pub const UNIFIED_AUTHENTICATION_SERVICE: &str = "unified_authentication_service";
pub const IRRELEVANT_ATTEMPT_ID_IN_AUTHENTICATION_FLOW: &str =
"irrelevant_attempt_id_in_AUTHENTICATION_flow";
pub const IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_AUTHENTICATION_FLOW: &str =
"irrelevant_connector_request_reference_id_in_AUTHENTICATION_flow";
pub struct ClickToPay;
pub struct ExternalAuthentication;
#[async_trait::async_trait]
pub trait UnifiedAuthenticationService {
#[allow(clippy::too_many_arguments)]
fn get_pre_authentication_request_data(
_payment_method_data: Option<&domain::PaymentMethodData>,
_service_details: Option<payments::CtpServiceDetails>,
_amount: common_utils::types::MinorUnit,
_currency: Option<common_enums::Currency>,
_merchant_details: Option<&hyperswitch_domain_models::router_request_types::unified_authentication_service::MerchantDetails>,
_billing_address: Option<&hyperswitch_domain_models::address::Address>,
_acquirer_bin: Option<String>,
_acquirer_merchant_id: Option<String>,
_payment_method_type: Option<common_enums::PaymentMethodType>,
) -> RouterResult<UasPreAuthenticationRequestData> {
Err(errors::ApiErrorResponse::NotImplemented {
message: NotImplementedMessage::Reason(
"get_pre_authentication_request_data".to_string(),
),
}
.into())
}
#[allow(clippy::too_many_arguments)]
async fn pre_authentication(
_state: &SessionState,
_merchant_id: &common_utils::id_type::MerchantId,
_payment_id: Option<&common_utils::id_type::PaymentId>,
_payment_method_data: Option<&domain::PaymentMethodData>,
_payment_method_type: Option<common_enums::PaymentMethodType>,
_merchant_connector_account: &MerchantConnectorAccountType,
_connector_name: &str,
_authentication_id: &common_utils::id_type::AuthenticationId,
_payment_method: common_enums::PaymentMethod,
_amount: common_utils::types::MinorUnit,
_currency: Option<common_enums::Currency>,
_service_details: Option<payments::CtpServiceDetails>,
_merchant_details: Option<&hyperswitch_domain_models::router_request_types::unified_authentication_service::MerchantDetails>,
_billing_address: Option<&hyperswitch_domain_models::address::Address>,
_acquirer_bin: Option<String>,
_acquirer_merchant_id: Option<String>,
) -> RouterResult<hyperswitch_domain_models::types::UasPreAuthenticationRouterData> {
Err(errors::ApiErrorResponse::NotImplemented {
message: NotImplementedMessage::Reason("pre_authentication".to_string()),
}
.into())
}
#[allow(clippy::too_many_arguments)]
fn get_authentication_request_data(
_browser_details: Option<BrowserInformation>,
_amount: Option<common_utils::types::MinorUnit>,
_currency: Option<common_enums::Currency>,
_message_category: MessageCategory,
_device_channel: payments::DeviceChannel,
_authentication: diesel_models::authentication::Authentication,
_return_url: Option<String>,
_sdk_information: Option<payments::SdkInformation>,
_threeds_method_comp_ind: payments::ThreeDsCompletionIndicator,
_email: Option<common_utils::pii::Email>,
_webhook_url: String,
) -> RouterResult<UasAuthenticationRequestData> {
Err(errors::ApiErrorResponse::NotImplemented {
message: NotImplementedMessage::Reason(
"get_pre_authentication_request_data".to_string(),
),
}
.into())
}
#[allow(clippy::too_many_arguments)]
async fn authentication(
_state: &SessionState,
_business_profile: &domain::Profile,
_payment_method: &common_enums::PaymentMethod,
_browser_details: Option<BrowserInformation>,
_amount: Option<common_utils::types::MinorUnit>,
_currency: Option<common_enums::Currency>,
_message_category: MessageCategory,
_device_channel: payments::DeviceChannel,
_authentication_data: diesel_models::authentication::Authentication,
_return_url: Option<String>,
_sdk_information: Option<payments::SdkInformation>,
_threeds_method_comp_ind: payments::ThreeDsCompletionIndicator,
_email: Option<common_utils::pii::Email>,
_webhook_url: String,
_merchant_connector_account: &MerchantConnectorAccountType,
_connector_name: &str,
_payment_id: Option<common_utils::id_type::PaymentId>,
) -> RouterResult<hyperswitch_domain_models::types::UasAuthenticationRouterData> {
Err(errors::ApiErrorResponse::NotImplemented {
message: NotImplementedMessage::Reason("authentication".to_string()),
}
.into())
}
fn get_post_authentication_request_data(
_authentication: Option<diesel_models::authentication::Authentication>,
) -> RouterResult<UasPostAuthenticationRequestData> {
Err(errors::ApiErrorResponse::NotImplemented {
message: NotImplementedMessage::Reason("post_authentication".to_string()),
}
.into())
}
#[allow(clippy::too_many_arguments)]
async fn post_authentication(
_state: &SessionState,
_business_profile: &domain::Profile,
_payment_id: Option<&common_utils::id_type::PaymentId>,
_merchant_connector_account: &MerchantConnectorAccountType,
_connector_name: &str,
_authentication_id: &common_utils::id_type::AuthenticationId,
_payment_method: common_enums::PaymentMethod,
_merchant_id: &common_utils::id_type::MerchantId,
_authentication: Option<&diesel_models::authentication::Authentication>,
) -> RouterResult<hyperswitch_domain_models::types::UasPostAuthenticationRouterData> {
Err(errors::ApiErrorResponse::NotImplemented {
message: NotImplementedMessage::Reason("post_authentication".to_string()),
}
.into())
}
#[allow(clippy::too_many_arguments)]
async fn confirmation(
_state: &SessionState,
_authentication_id: Option<&common_utils::id_type::AuthenticationId>,
_currency: Option<common_enums::Currency>,
_status: common_enums::AttemptStatus,
_service_details: Option<payments::CtpServiceDetails>,
_merchant_connector_account: &MerchantConnectorAccountType,
_connector_name: &str,
_payment_method: common_enums::PaymentMethod,
_net_amount: common_utils::types::MinorUnit,
_payment_id: Option<&common_utils::id_type::PaymentId>,
_merchant_id: &common_utils::id_type::MerchantId,
) -> RouterResult<()> {
Err(errors::ApiErrorResponse::NotImplemented {
message: NotImplementedMessage::Reason("confirmation".to_string()),
}
.into())
}
}
|
crates/router/src/core/unified_authentication_service/types.rs
|
router::src::core::unified_authentication_service::types
| 1,629
| true
|
// File: crates/router/src/core/unified_authentication_service/utils.rs
// Module: router::src::core::unified_authentication_service::utils
use std::marker::PhantomData;
use common_enums::enums::PaymentMethod;
use common_utils::ext_traits::{AsyncExt, ValueExt};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
errors::api_error_response::ApiErrorResponse,
ext_traits::OptionExt,
payment_address::PaymentAddress,
router_data::{ConnectorAuthType, ErrorResponse, RouterData},
router_data_v2::UasFlowData,
router_request_types::unified_authentication_service::UasAuthenticationResponseData,
};
use masking::ExposeInterface;
use super::types::{
IRRELEVANT_ATTEMPT_ID_IN_AUTHENTICATION_FLOW,
IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_AUTHENTICATION_FLOW,
};
use crate::{
consts::DEFAULT_SESSION_EXPIRY,
core::{
errors::{utils::ConnectorErrorExt, RouterResult},
payments,
},
services::{self, execute_connector_processing_step},
types::{api, transformers::ForeignFrom},
SessionState,
};
pub async fn do_auth_connector_call<F, Req, Res>(
state: &SessionState,
authentication_connector_name: String,
router_data: RouterData<F, Req, Res>,
) -> RouterResult<RouterData<F, Req, Res>>
where
Req: std::fmt::Debug + Clone + 'static,
Res: std::fmt::Debug + Clone + 'static,
F: std::fmt::Debug + Clone + 'static,
dyn api::Connector + Sync: services::api::ConnectorIntegration<F, Req, Res>,
dyn api::ConnectorV2 + Sync: services::api::ConnectorIntegrationV2<F, UasFlowData, Req, Res>,
{
let connector_data =
api::AuthenticationConnectorData::get_connector_by_name(&authentication_connector_name)?;
let connector_integration: services::BoxedUnifiedAuthenticationServiceInterface<F, Req, Res> =
connector_data.connector.get_connector_integration();
let router_data = execute_connector_processing_step(
state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.to_payment_failed_response()?;
Ok(router_data)
}
#[allow(clippy::too_many_arguments)]
pub fn construct_uas_router_data<F: Clone, Req, Res>(
state: &SessionState,
authentication_connector_name: String,
payment_method: PaymentMethod,
merchant_id: common_utils::id_type::MerchantId,
address: Option<PaymentAddress>,
request_data: Req,
merchant_connector_account: &payments::helpers::MerchantConnectorAccountType,
authentication_id: Option<common_utils::id_type::AuthenticationId>,
payment_id: Option<common_utils::id_type::PaymentId>,
) -> RouterResult<RouterData<F, Req, Res>> {
let auth_type: ConnectorAuthType = merchant_connector_account
.get_connector_account_details()
.parse_value("ConnectorAuthType")
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Error while parsing ConnectorAuthType")?;
Ok(RouterData {
flow: PhantomData,
merchant_id,
customer_id: None,
connector_customer: None,
connector: authentication_connector_name,
payment_id: payment_id
.map(|id| id.get_string_repr().to_owned())
.unwrap_or_default(),
tenant_id: state.tenant.tenant_id.clone(),
attempt_id: IRRELEVANT_ATTEMPT_ID_IN_AUTHENTICATION_FLOW.to_owned(),
status: common_enums::AttemptStatus::default(),
payment_method,
payment_method_type: None,
connector_auth_type: auth_type,
description: None,
address: address.unwrap_or_default(),
auth_type: common_enums::AuthenticationType::default(),
connector_meta_data: merchant_connector_account.get_metadata().clone(),
connector_wallets_details: merchant_connector_account.get_connector_wallets_details(),
amount_captured: None,
minor_amount_captured: None,
access_token: None,
session_token: None,
reference_id: None,
payment_method_token: None,
recurring_mandate_payment_data: None,
preprocessing_id: None,
payment_method_balance: None,
connector_api_version: None,
request: request_data,
response: Err(ErrorResponse::default()),
connector_request_reference_id:
IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_AUTHENTICATION_FLOW.to_owned(),
#[cfg(feature = "payouts")]
payout_method_data: None,
#[cfg(feature = "payouts")]
quote_id: None,
test_mode: None,
connector_http_status_code: None,
external_latency: None,
apple_pay_flow: None,
frm_metadata: None,
dispute_id: None,
refund_id: None,
payment_method_status: None,
connector_response: None,
integrity_check: Ok(()),
additional_merchant_data: None,
header_payload: None,
connector_mandate_request_reference_id: None,
authentication_id,
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,
})
}
#[allow(clippy::too_many_arguments)]
pub async fn external_authentication_update_trackers<F: Clone, Req>(
state: &SessionState,
router_data: RouterData<F, Req, UasAuthenticationResponseData>,
authentication: diesel_models::authentication::Authentication,
acquirer_details: Option<
hyperswitch_domain_models::router_request_types::authentication::AcquirerDetails,
>,
merchant_key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore,
billing_address: Option<common_utils::encryption::Encryption>,
shipping_address: Option<common_utils::encryption::Encryption>,
email: Option<common_utils::encryption::Encryption>,
browser_info: Option<serde_json::Value>,
) -> RouterResult<diesel_models::authentication::Authentication> {
let authentication_update = match router_data.response {
Ok(response) => match response {
UasAuthenticationResponseData::PreAuthentication {
authentication_details,
} => Ok(
diesel_models::authentication::AuthenticationUpdate::PreAuthenticationUpdate {
threeds_server_transaction_id: authentication_details
.threeds_server_transaction_id
.ok_or(ApiErrorResponse::InternalServerError)
.attach_printable(
"missing threeds_server_transaction_id in PreAuthentication Details",
)?,
maximum_supported_3ds_version: authentication_details
.maximum_supported_3ds_version
.ok_or(ApiErrorResponse::InternalServerError)
.attach_printable(
"missing maximum_supported_3ds_version in PreAuthentication Details",
)?,
connector_authentication_id: authentication_details
.connector_authentication_id
.ok_or(ApiErrorResponse::InternalServerError)
.attach_printable(
"missing connector_authentication_id in PreAuthentication Details",
)?,
three_ds_method_data: authentication_details.three_ds_method_data,
three_ds_method_url: authentication_details.three_ds_method_url,
message_version: authentication_details
.message_version
.ok_or(ApiErrorResponse::InternalServerError)
.attach_printable("missing message_version in PreAuthentication Details")?,
connector_metadata: authentication_details.connector_metadata,
authentication_status: common_enums::AuthenticationStatus::Pending,
acquirer_bin: acquirer_details
.as_ref()
.map(|acquirer_details| acquirer_details.acquirer_bin.clone()),
acquirer_merchant_id: acquirer_details
.as_ref()
.map(|acquirer_details| acquirer_details.acquirer_merchant_id.clone()),
acquirer_country_code: acquirer_details
.and_then(|acquirer_details| acquirer_details.acquirer_country_code),
directory_server_id: authentication_details.directory_server_id,
browser_info: Box::new(browser_info),
email,
billing_address,
shipping_address,
},
),
UasAuthenticationResponseData::Authentication {
authentication_details,
} => {
let authentication_status = common_enums::AuthenticationStatus::foreign_from(
authentication_details.trans_status.clone(),
);
authentication_details
.authentication_value
.async_map(|auth_val| {
crate::core::payment_methods::vault::create_tokenize(
state,
auth_val.expose(),
None,
authentication
.authentication_id
.get_string_repr()
.to_string(),
merchant_key_store.key.get_inner(),
)
})
.await
.transpose()?;
Ok(
diesel_models::authentication::AuthenticationUpdate::AuthenticationUpdate {
trans_status: authentication_details.trans_status,
acs_url: authentication_details.authn_flow_type.get_acs_url(),
challenge_request: authentication_details
.authn_flow_type
.get_challenge_request(),
challenge_request_key: authentication_details
.authn_flow_type
.get_challenge_request_key(),
acs_reference_number: authentication_details
.authn_flow_type
.get_acs_reference_number(),
acs_trans_id: authentication_details.authn_flow_type.get_acs_trans_id(),
acs_signed_content: authentication_details
.authn_flow_type
.get_acs_signed_content(),
authentication_type: authentication_details
.authn_flow_type
.get_decoupled_authentication_type(),
authentication_status,
connector_metadata: authentication_details.connector_metadata,
ds_trans_id: authentication_details.ds_trans_id,
eci: authentication_details.eci,
challenge_code: authentication_details.challenge_code,
challenge_cancel: authentication_details.challenge_cancel,
challenge_code_reason: authentication_details.challenge_code_reason,
message_extension: authentication_details.message_extension,
},
)
}
UasAuthenticationResponseData::PostAuthentication {
authentication_details,
} => {
let trans_status = authentication_details
.trans_status
.ok_or(ApiErrorResponse::InternalServerError)
.attach_printable("missing trans_status in PostAuthentication Details")?;
authentication_details
.dynamic_data_details
.and_then(|details| details.dynamic_data_value)
.map(ExposeInterface::expose)
.async_map(|auth_val| {
crate::core::payment_methods::vault::create_tokenize(
state,
auth_val,
None,
authentication
.authentication_id
.get_string_repr()
.to_string(),
merchant_key_store.key.get_inner(),
)
})
.await
.transpose()?;
Ok(
diesel_models::authentication::AuthenticationUpdate::PostAuthenticationUpdate {
authentication_status: common_enums::AuthenticationStatus::foreign_from(
trans_status.clone(),
),
trans_status,
eci: authentication_details.eci,
challenge_cancel: authentication_details.challenge_cancel,
challenge_code_reason: authentication_details.challenge_code_reason,
},
)
}
UasAuthenticationResponseData::Confirmation { .. } => Err(
ApiErrorResponse::InternalServerError,
)
.attach_printable("unexpected api confirmation in external authentication flow."),
},
Err(error) => Ok(
diesel_models::authentication::AuthenticationUpdate::ErrorUpdate {
connector_authentication_id: error.connector_transaction_id,
authentication_status: common_enums::AuthenticationStatus::Failed,
error_message: error
.reason
.map(|reason| format!("message: {}, reason: {}", error.message, reason))
.or(Some(error.message)),
error_code: Some(error.code),
},
),
}?;
state
.store
.update_authentication_by_merchant_id_authentication_id(
authentication,
authentication_update,
)
.await
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Error while updating authentication")
}
pub fn get_checkout_event_status_and_reason(
attempt_status: common_enums::AttemptStatus,
) -> (Option<String>, Option<String>) {
match attempt_status {
common_enums::AttemptStatus::Charged | common_enums::AttemptStatus::Authorized => (
Some("01".to_string()),
Some("The payment was successful".to_string()),
),
_ => (
Some("03".to_string()),
Some("The payment was not successful".to_string()),
),
}
}
pub fn authenticate_authentication_client_secret_and_check_expiry(
req_client_secret: &String,
authentication: &diesel_models::authentication::Authentication,
) -> RouterResult<()> {
let stored_client_secret = authentication
.authentication_client_secret
.clone()
.get_required_value("authentication_client_secret")
.change_context(ApiErrorResponse::MissingRequiredField {
field_name: "client_secret",
})
.attach_printable("client secret not found in db")?;
if req_client_secret != &stored_client_secret {
Err(report!(ApiErrorResponse::ClientSecretInvalid))
} else {
let current_timestamp = common_utils::date_time::now();
let session_expiry = authentication
.created_at
.saturating_add(time::Duration::seconds(DEFAULT_SESSION_EXPIRY));
if current_timestamp > session_expiry {
Err(report!(ApiErrorResponse::ClientSecretExpired))
} else {
Ok(())
}
}
}
|
crates/router/src/core/unified_authentication_service/utils.rs
|
router::src::core::unified_authentication_service::utils
| 2,814
| true
|
// File: crates/router/src/core/unified_connector_service/transformers.rs
// Module: router::src::core::unified_connector_service::transformers
use std::collections::HashMap;
use common_enums::{AttemptStatus, AuthenticationType};
use common_utils::{ext_traits::Encode, request::Method};
use diesel_models::enums as storage_enums;
use error_stack::ResultExt;
use external_services::grpc_client::unified_connector_service::UnifiedConnectorServiceError;
use hyperswitch_domain_models::{
router_data::{ErrorResponse, RouterData},
router_flow_types::{
payments::{Authorize, PSync, SetupMandate},
ExternalVaultProxy,
},
router_request_types::{
AuthenticationData, ExternalVaultProxyPaymentsData, PaymentsAuthorizeData,
PaymentsSyncData, SetupMandateRequestData,
},
router_response_types::{PaymentsResponseData, RedirectForm},
};
pub use hyperswitch_interfaces::{
helpers::ForeignTryFrom,
unified_connector_service::{
transformers::convert_connector_service_status_code, WebhookTransformData,
},
};
use masking::{ExposeInterface, PeekInterface};
use router_env::tracing;
use unified_connector_service_client::payments::{
self as payments_grpc, Identifier, PaymentServiceTransformRequest,
PaymentServiceTransformResponse,
};
use url::Url;
use crate::{
core::{errors, unified_connector_service},
types::transformers,
};
impl transformers::ForeignTryFrom<&RouterData<PSync, PaymentsSyncData, PaymentsResponseData>>
for payments_grpc::PaymentServiceGetRequest
{
type Error = error_stack::Report<UnifiedConnectorServiceError>;
fn foreign_try_from(
router_data: &RouterData<PSync, PaymentsSyncData, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let connector_transaction_id = router_data
.request
.connector_transaction_id
.get_connector_transaction_id()
.map(|id| Identifier {
id_type: Some(payments_grpc::identifier::IdType::Id(id)),
})
.map_err(|e| {
tracing::debug!(
transaction_id_error=?e,
"Failed to extract connector transaction ID for UCS payment sync request"
);
e
})
.ok();
let encoded_data = router_data
.request
.encoded_data
.as_ref()
.map(|data| Identifier {
id_type: Some(payments_grpc::identifier::IdType::EncodedData(
data.to_string(),
)),
});
let connector_ref_id = router_data
.request
.connector_reference_id
.clone()
.map(|id| Identifier {
id_type: Some(payments_grpc::identifier::IdType::Id(id)),
});
Ok(Self {
transaction_id: connector_transaction_id.or(encoded_data),
request_ref_id: connector_ref_id,
access_token: None,
capture_method: None,
handle_response: None,
})
}
}
impl
transformers::ForeignTryFrom<
&RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData>,
> for payments_grpc::PaymentServiceAuthorizeRequest
{
type Error = error_stack::Report<UnifiedConnectorServiceError>;
fn foreign_try_from(
router_data: &RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let currency = payments_grpc::Currency::foreign_try_from(router_data.request.currency)?;
let payment_method = router_data
.request
.payment_method_type
.map(|payment_method_type| {
unified_connector_service::build_unified_connector_service_payment_method(
router_data.request.payment_method_data.clone(),
payment_method_type,
)
})
.transpose()?;
let address = payments_grpc::PaymentAddress::foreign_try_from(router_data.address.clone())?;
let auth_type = payments_grpc::AuthenticationType::foreign_try_from(router_data.auth_type)?;
let browser_info = router_data
.request
.browser_info
.clone()
.map(payments_grpc::BrowserInformation::foreign_try_from)
.transpose()?;
let capture_method = router_data
.request
.capture_method
.map(payments_grpc::CaptureMethod::foreign_try_from)
.transpose()?;
let authentication_data = router_data
.request
.authentication_data
.clone()
.map(payments_grpc::AuthenticationData::foreign_try_from)
.transpose()?;
Ok(Self {
amount: router_data.request.amount,
currency: currency.into(),
payment_method,
return_url: router_data.request.router_return_url.clone(),
address: Some(address),
auth_type: auth_type.into(),
enrolled_for_3ds: router_data.request.enrolled_for_3ds,
request_incremental_authorization: router_data
.request
.request_incremental_authorization,
minor_amount: router_data.request.amount,
email: router_data
.request
.email
.clone()
.map(|e| e.expose().expose().into()),
browser_info,
access_token: None,
session_token: None,
order_tax_amount: router_data
.request
.order_tax_amount
.map(|order_tax_amount| order_tax_amount.get_amount_as_i64()),
customer_name: router_data
.request
.customer_name
.clone()
.map(|customer_name| customer_name.peek().to_owned()),
capture_method: capture_method.map(|capture_method| capture_method.into()),
webhook_url: router_data.request.webhook_url.clone(),
complete_authorize_url: router_data.request.complete_authorize_url.clone(),
setup_future_usage: None,
off_session: None,
customer_acceptance: None,
order_category: router_data.request.order_category.clone(),
payment_experience: None,
authentication_data,
request_extended_authorization: router_data
.request
.request_extended_authorization
.map(|request_extended_authorization| request_extended_authorization.is_true()),
merchant_order_reference_id: router_data.request.merchant_order_reference_id.clone(),
shipping_cost: router_data
.request
.shipping_cost
.map(|shipping_cost| shipping_cost.get_amount_as_i64()),
request_ref_id: Some(Identifier {
id_type: Some(payments_grpc::identifier::IdType::Id(
router_data.connector_request_reference_id.clone(),
)),
}),
connector_customer_id: router_data
.request
.customer_id
.as_ref()
.map(|id| id.get_string_repr().to_string()),
metadata: router_data
.request
.metadata
.as_ref()
.and_then(|val| val.as_object())
.map(|map| {
map.iter()
.filter_map(|(k, v)| v.as_str().map(|s| (k.clone(), s.to_string())))
.collect::<HashMap<String, String>>()
})
.unwrap_or_default(),
test_mode: None,
})
}
}
impl
transformers::ForeignTryFrom<
&RouterData<ExternalVaultProxy, ExternalVaultProxyPaymentsData, PaymentsResponseData>,
> for payments_grpc::PaymentServiceAuthorizeRequest
{
type Error = error_stack::Report<UnifiedConnectorServiceError>;
fn foreign_try_from(
router_data: &RouterData<
ExternalVaultProxy,
ExternalVaultProxyPaymentsData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let currency = payments_grpc::Currency::foreign_try_from(router_data.request.currency)?;
let payment_method = router_data
.request
.payment_method_type
.map(|payment_method_type| {
unified_connector_service::build_unified_connector_service_payment_method_for_external_proxy(
router_data.request.payment_method_data.clone(),
payment_method_type,
)
})
.transpose()?;
let address = payments_grpc::PaymentAddress::foreign_try_from(router_data.address.clone())?;
let auth_type = payments_grpc::AuthenticationType::foreign_try_from(router_data.auth_type)?;
let browser_info = router_data
.request
.browser_info
.clone()
.map(payments_grpc::BrowserInformation::foreign_try_from)
.transpose()?;
let capture_method = router_data
.request
.capture_method
.map(payments_grpc::CaptureMethod::foreign_try_from)
.transpose()?;
let authentication_data = router_data
.request
.authentication_data
.clone()
.map(payments_grpc::AuthenticationData::foreign_try_from)
.transpose()?;
Ok(Self {
amount: router_data.request.amount,
currency: currency.into(),
payment_method,
return_url: router_data.request.router_return_url.clone(),
address: Some(address),
auth_type: auth_type.into(),
enrolled_for_3ds: router_data.request.enrolled_for_3ds,
request_incremental_authorization: router_data
.request
.request_incremental_authorization,
minor_amount: router_data.request.amount,
email: router_data
.request
.email
.clone()
.map(|e| e.expose().expose().into()),
browser_info,
access_token: None,
session_token: None,
order_tax_amount: router_data
.request
.order_tax_amount
.map(|order_tax_amount| order_tax_amount.get_amount_as_i64()),
customer_name: router_data
.request
.customer_name
.clone()
.map(|customer_name| customer_name.peek().to_owned()),
capture_method: capture_method.map(|capture_method| capture_method.into()),
webhook_url: router_data.request.webhook_url.clone(),
complete_authorize_url: router_data.request.complete_authorize_url.clone(),
setup_future_usage: None,
off_session: None,
customer_acceptance: None,
order_category: router_data.request.order_category.clone(),
payment_experience: None,
authentication_data,
request_extended_authorization: router_data
.request
.request_extended_authorization
.map(|request_extended_authorization| request_extended_authorization.is_true()),
merchant_order_reference_id: router_data
.request
.merchant_order_reference_id
.as_ref()
.map(|merchant_order_reference_id| {
merchant_order_reference_id.get_string_repr().to_string()
}),
shipping_cost: router_data
.request
.shipping_cost
.map(|shipping_cost| shipping_cost.get_amount_as_i64()),
request_ref_id: Some(Identifier {
id_type: Some(payments_grpc::identifier::IdType::Id(
router_data.connector_request_reference_id.clone(),
)),
}),
connector_customer_id: router_data
.request
.customer_id
.as_ref()
.map(|id| id.get_string_repr().to_string()),
metadata: router_data
.request
.metadata
.as_ref()
.and_then(|val| val.as_object())
.map(|map| {
map.iter()
.filter_map(|(k, v)| v.as_str().map(|s| (k.clone(), s.to_string())))
.collect::<HashMap<String, String>>()
})
.unwrap_or_default(),
test_mode: None,
})
}
}
impl
transformers::ForeignTryFrom<
&RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
> for payments_grpc::PaymentServiceRegisterRequest
{
type Error = error_stack::Report<UnifiedConnectorServiceError>;
fn foreign_try_from(
router_data: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let currency = payments_grpc::Currency::foreign_try_from(router_data.request.currency)?;
let payment_method = router_data
.request
.payment_method_type
.map(|payment_method_type| {
unified_connector_service::build_unified_connector_service_payment_method(
router_data.request.payment_method_data.clone(),
payment_method_type,
)
})
.transpose()?;
let address = payments_grpc::PaymentAddress::foreign_try_from(router_data.address.clone())?;
let auth_type = payments_grpc::AuthenticationType::foreign_try_from(router_data.auth_type)?;
let browser_info = router_data
.request
.browser_info
.clone()
.map(payments_grpc::BrowserInformation::foreign_try_from)
.transpose()?;
let setup_future_usage = router_data
.request
.setup_future_usage
.map(payments_grpc::FutureUsage::foreign_try_from)
.transpose()?;
let customer_acceptance = router_data
.request
.customer_acceptance
.clone()
.map(payments_grpc::CustomerAcceptance::foreign_try_from)
.transpose()?;
Ok(Self {
request_ref_id: Some(Identifier {
id_type: Some(payments_grpc::identifier::IdType::Id(
router_data.connector_request_reference_id.clone(),
)),
}),
currency: currency.into(),
payment_method,
minor_amount: router_data.request.amount,
email: router_data
.request
.email
.clone()
.map(|e| e.expose().expose().into()),
customer_name: router_data
.request
.customer_name
.clone()
.map(|customer_name| customer_name.peek().to_owned()),
connector_customer_id: router_data
.request
.customer_id
.as_ref()
.map(|id| id.get_string_repr().to_string()),
address: Some(address),
auth_type: auth_type.into(),
enrolled_for_3ds: false,
authentication_data: None,
metadata: router_data
.request
.metadata
.as_ref()
.map(|secret| secret.peek())
.and_then(|val| val.as_object()) //secret
.map(|map| {
map.iter()
.filter_map(|(k, v)| v.as_str().map(|s| (k.clone(), s.to_string())))
.collect::<HashMap<String, String>>()
})
.unwrap_or_default(),
return_url: router_data.request.router_return_url.clone(),
webhook_url: router_data.request.webhook_url.clone(),
complete_authorize_url: router_data.request.complete_authorize_url.clone(),
access_token: None,
session_token: None,
order_tax_amount: None,
order_category: None,
merchant_order_reference_id: None,
shipping_cost: router_data
.request
.shipping_cost
.map(|cost| cost.get_amount_as_i64()),
setup_future_usage: setup_future_usage.map(|s| s.into()),
off_session: router_data.request.off_session,
request_incremental_authorization: router_data
.request
.request_incremental_authorization,
request_extended_authorization: None,
customer_acceptance,
browser_info,
payment_experience: None,
})
}
}
impl
transformers::ForeignTryFrom<
&RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData>,
> for payments_grpc::PaymentServiceRepeatEverythingRequest
{
type Error = error_stack::Report<UnifiedConnectorServiceError>;
fn foreign_try_from(
router_data: &RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let currency = payments_grpc::Currency::foreign_try_from(router_data.request.currency)?;
let browser_info = router_data
.request
.browser_info
.clone()
.map(payments_grpc::BrowserInformation::foreign_try_from)
.transpose()?;
let capture_method = router_data
.request
.capture_method
.map(payments_grpc::CaptureMethod::foreign_try_from)
.transpose()?;
let mandate_reference = match &router_data.request.mandate_id {
Some(mandate) => match &mandate.mandate_reference_id {
Some(api_models::payments::MandateReferenceId::ConnectorMandateId(
connector_mandate_id,
)) => Some(payments_grpc::MandateReference {
mandate_id: connector_mandate_id.get_connector_mandate_id(),
}),
_ => {
return Err(UnifiedConnectorServiceError::MissingRequiredField {
field_name: "connector_mandate_id",
}
.into())
}
},
None => {
return Err(UnifiedConnectorServiceError::MissingRequiredField {
field_name: "connector_mandate_id",
}
.into())
}
};
Ok(Self {
request_ref_id: Some(Identifier {
id_type: Some(payments_grpc::identifier::IdType::Id(
router_data.connector_request_reference_id.clone(),
)),
}),
mandate_reference,
amount: router_data.request.amount,
currency: currency.into(),
minor_amount: router_data.request.amount,
merchant_order_reference_id: router_data.request.merchant_order_reference_id.clone(),
metadata: router_data
.request
.metadata
.as_ref()
.and_then(|val| val.as_object())
.map(|map| {
map.iter()
.filter_map(|(k, v)| v.as_str().map(|s| (k.clone(), s.to_string())))
.collect::<HashMap<String, String>>()
})
.unwrap_or_default(),
webhook_url: router_data.request.webhook_url.clone(),
capture_method: capture_method.map(|capture_method| capture_method.into()),
email: router_data
.request
.email
.clone()
.map(|e| e.expose().expose().into()),
browser_info,
test_mode: None,
payment_method_type: None,
access_token: None,
})
}
}
impl transformers::ForeignTryFrom<payments_grpc::PaymentServiceAuthorizeResponse>
for Result<(PaymentsResponseData, AttemptStatus), ErrorResponse>
{
type Error = error_stack::Report<UnifiedConnectorServiceError>;
fn foreign_try_from(
response: payments_grpc::PaymentServiceAuthorizeResponse,
) -> Result<Self, Self::Error> {
let connector_response_reference_id =
response.response_ref_id.as_ref().and_then(|identifier| {
identifier
.id_type
.clone()
.and_then(|id_type| match id_type {
payments_grpc::identifier::IdType::Id(id) => Some(id),
payments_grpc::identifier::IdType::EncodedData(encoded_data) => {
Some(encoded_data)
}
payments_grpc::identifier::IdType::NoResponseIdMarker(_) => None,
})
});
let resource_id: hyperswitch_domain_models::router_request_types::ResponseId = match response.transaction_id.as_ref().and_then(|id| id.id_type.clone()) {
Some(payments_grpc::identifier::IdType::Id(id)) => hyperswitch_domain_models::router_request_types::ResponseId::ConnectorTransactionId(id),
Some(payments_grpc::identifier::IdType::EncodedData(encoded_data)) => hyperswitch_domain_models::router_request_types::ResponseId::EncodedData(encoded_data),
Some(payments_grpc::identifier::IdType::NoResponseIdMarker(_)) | None => hyperswitch_domain_models::router_request_types::ResponseId::NoResponseId,
};
let (connector_metadata, redirection_data) = match response.redirection_data.clone() {
Some(redirection_data) => match redirection_data.form_type {
Some(ref form_type) => match form_type {
payments_grpc::redirect_form::FormType::Uri(uri) => {
// For UPI intent, store the URI in connector_metadata for SDK UPI intent pattern
let sdk_uri_info = api_models::payments::SdkUpiIntentInformation {
sdk_uri: Url::parse(&uri.uri)
.change_context(UnifiedConnectorServiceError::ParsingFailed)?,
};
(
Some(sdk_uri_info.encode_to_value())
.transpose()
.change_context(UnifiedConnectorServiceError::ParsingFailed)?,
None,
)
}
_ => (
None,
Some(RedirectForm::foreign_try_from(redirection_data)).transpose()?,
),
},
None => (None, None),
},
None => (None, None),
};
let status_code = convert_connector_service_status_code(response.status_code)?;
let response = if response.error_code.is_some() {
let attempt_status = match response.status() {
payments_grpc::PaymentStatus::AttemptStatusUnspecified => None,
_ => Some(AttemptStatus::foreign_try_from(response.status())?),
};
Err(ErrorResponse {
code: response.error_code().to_owned(),
message: response.error_message().to_owned(),
reason: Some(response.error_message().to_owned()),
status_code,
attempt_status,
connector_transaction_id: connector_response_reference_id,
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
let status = AttemptStatus::foreign_try_from(response.status())?;
Ok((
PaymentsResponseData::TransactionResponse {
resource_id,
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(None),
connector_metadata,
network_txn_id: response.network_txn_id.clone(),
connector_response_reference_id,
incremental_authorization_allowed: response.incremental_authorization_allowed,
charges: None,
},
status,
))
};
Ok(response)
}
}
impl transformers::ForeignTryFrom<payments_grpc::PaymentServiceRegisterResponse>
for Result<(PaymentsResponseData, AttemptStatus), ErrorResponse>
{
type Error = error_stack::Report<UnifiedConnectorServiceError>;
fn foreign_try_from(
response: payments_grpc::PaymentServiceRegisterResponse,
) -> Result<Self, Self::Error> {
let connector_response_reference_id =
response.response_ref_id.as_ref().and_then(|identifier| {
identifier
.id_type
.clone()
.and_then(|id_type| match id_type {
payments_grpc::identifier::IdType::Id(id) => Some(id),
payments_grpc::identifier::IdType::EncodedData(encoded_data) => {
Some(encoded_data)
}
payments_grpc::identifier::IdType::NoResponseIdMarker(_) => None,
})
});
let status_code = convert_connector_service_status_code(response.status_code)?;
let response = if response.error_code.is_some() {
let attempt_status = match response.status() {
payments_grpc::PaymentStatus::AttemptStatusUnspecified => None,
_ => Some(AttemptStatus::foreign_try_from(response.status())?),
};
Err(ErrorResponse {
code: response.error_code().to_owned(),
message: response.error_message().to_owned(),
reason: Some(response.error_message().to_owned()),
status_code,
attempt_status,
connector_transaction_id: connector_response_reference_id,
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
let status = AttemptStatus::foreign_try_from(response.status())?;
Ok((PaymentsResponseData::TransactionResponse {
resource_id: response.registration_id.as_ref().and_then(|identifier| {
identifier
.id_type
.clone()
.and_then(|id_type| match id_type {
payments_grpc::identifier::IdType::Id(id) => Some(
hyperswitch_domain_models::router_request_types::ResponseId::ConnectorTransactionId(id),
),
payments_grpc::identifier::IdType::EncodedData(encoded_data) => Some(
hyperswitch_domain_models::router_request_types::ResponseId::ConnectorTransactionId(encoded_data),
),
payments_grpc::identifier::IdType::NoResponseIdMarker(_) => None,
})
}).unwrap_or(hyperswitch_domain_models::router_request_types::ResponseId::NoResponseId),
redirection_data: Box::new(
response
.redirection_data
.clone()
.map(RedirectForm::foreign_try_from)
.transpose()?
),
mandate_reference: Box::new(
response.mandate_reference.map(|grpc_mandate| {
hyperswitch_domain_models::router_response_types::MandateReference {
connector_mandate_id: grpc_mandate.mandate_id,
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
}
})
),
connector_metadata: None,
network_txn_id: response.network_txn_id,
connector_response_reference_id,
incremental_authorization_allowed: response.incremental_authorization_allowed,
charges: None,
}, status))
};
Ok(response)
}
}
impl transformers::ForeignTryFrom<payments_grpc::PaymentServiceRepeatEverythingResponse>
for Result<(PaymentsResponseData, AttemptStatus), ErrorResponse>
{
type Error = error_stack::Report<UnifiedConnectorServiceError>;
fn foreign_try_from(
response: payments_grpc::PaymentServiceRepeatEverythingResponse,
) -> Result<Self, Self::Error> {
let connector_response_reference_id =
response.response_ref_id.as_ref().and_then(|identifier| {
identifier
.id_type
.clone()
.and_then(|id_type| match id_type {
payments_grpc::identifier::IdType::Id(id) => Some(id),
payments_grpc::identifier::IdType::EncodedData(encoded_data) => {
Some(encoded_data)
}
payments_grpc::identifier::IdType::NoResponseIdMarker(_) => None,
})
});
let transaction_id = response.transaction_id.as_ref().and_then(|id| {
id.id_type.clone().and_then(|id_type| match id_type {
payments_grpc::identifier::IdType::Id(id) => Some(id),
payments_grpc::identifier::IdType::EncodedData(encoded_data) => Some(encoded_data),
payments_grpc::identifier::IdType::NoResponseIdMarker(_) => None,
})
});
let status_code = convert_connector_service_status_code(response.status_code)?;
let response = if response.error_code.is_some() {
let attempt_status = match response.status() {
payments_grpc::PaymentStatus::AttemptStatusUnspecified => None,
_ => Some(AttemptStatus::foreign_try_from(response.status())?),
};
Err(ErrorResponse {
code: response.error_code().to_owned(),
message: response.error_message().to_owned(),
reason: Some(response.error_message().to_owned()),
status_code,
attempt_status,
connector_transaction_id: transaction_id,
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
let status = AttemptStatus::foreign_try_from(response.status())?;
Ok((PaymentsResponseData::TransactionResponse {
resource_id: match transaction_id.as_ref() {
Some(transaction_id) => hyperswitch_domain_models::router_request_types::ResponseId::ConnectorTransactionId(transaction_id.clone()),
None => hyperswitch_domain_models::router_request_types::ResponseId::NoResponseId,
},
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: response.network_txn_id.clone(),
connector_response_reference_id,
incremental_authorization_allowed: None,
charges: None,
}, status))
};
Ok(response)
}
}
impl transformers::ForeignTryFrom<common_enums::Currency> for payments_grpc::Currency {
type Error = error_stack::Report<UnifiedConnectorServiceError>;
fn foreign_try_from(currency: common_enums::Currency) -> Result<Self, Self::Error> {
Self::from_str_name(¤cy.to_string()).ok_or_else(|| {
UnifiedConnectorServiceError::RequestEncodingFailedWithReason(
"Failed to parse currency".to_string(),
)
.into()
})
}
}
impl transformers::ForeignTryFrom<common_enums::CardNetwork> for payments_grpc::CardNetwork {
type Error = error_stack::Report<UnifiedConnectorServiceError>;
fn foreign_try_from(card_network: common_enums::CardNetwork) -> Result<Self, Self::Error> {
match card_network {
common_enums::CardNetwork::Visa => Ok(Self::Visa),
common_enums::CardNetwork::Mastercard => Ok(Self::Mastercard),
common_enums::CardNetwork::JCB => Ok(Self::Jcb),
common_enums::CardNetwork::DinersClub => Ok(Self::Diners),
common_enums::CardNetwork::Discover => Ok(Self::Discover),
common_enums::CardNetwork::CartesBancaires => Ok(Self::CartesBancaires),
common_enums::CardNetwork::UnionPay => Ok(Self::Unionpay),
common_enums::CardNetwork::RuPay => Ok(Self::Rupay),
common_enums::CardNetwork::Maestro => Ok(Self::Maestro),
common_enums::CardNetwork::AmericanExpress => Ok(Self::Amex),
_ => Err(
UnifiedConnectorServiceError::RequestEncodingFailedWithReason(
"Card Network not supported".to_string(),
)
.into(),
),
}
}
}
impl transformers::ForeignTryFrom<hyperswitch_domain_models::payment_address::PaymentAddress>
for payments_grpc::PaymentAddress
{
type Error = error_stack::Report<UnifiedConnectorServiceError>;
fn foreign_try_from(
payment_address: hyperswitch_domain_models::payment_address::PaymentAddress,
) -> Result<Self, Self::Error> {
let shipping = payment_address.get_shipping().map(|address| {
let details = address.address.as_ref();
let country = details.and_then(|details| {
details
.country
.as_ref()
.and_then(|c| payments_grpc::CountryAlpha2::from_str_name(&c.to_string()))
.map(|country| country.into())
});
payments_grpc::Address {
first_name: details
.and_then(|d| d.first_name.as_ref().map(|s| s.clone().expose().into())),
last_name: details
.and_then(|d| d.last_name.as_ref().map(|s| s.clone().expose().into())),
line1: details.and_then(|d| d.line1.as_ref().map(|s| s.clone().expose().into())),
line2: details.and_then(|d| d.line2.as_ref().map(|s| s.clone().expose().into())),
line3: details.and_then(|d| d.line3.as_ref().map(|s| s.clone().expose().into())),
city: details.and_then(|d| d.city.as_ref().map(|s| s.clone().into())),
state: details.and_then(|d| d.state.as_ref().map(|s| s.clone().expose().into())),
zip_code: details.and_then(|d| d.zip.as_ref().map(|s| s.clone().expose().into())),
country_alpha2_code: country,
email: address
.email
.as_ref()
.map(|e| e.clone().expose().expose().into()),
phone_number: address
.phone
.as_ref()
.and_then(|phone| phone.number.as_ref().map(|n| n.clone().expose().into())),
phone_country_code: address.phone.as_ref().and_then(|p| p.country_code.clone()),
}
});
let billing = payment_address.get_payment_billing().map(|address| {
let details = address.address.as_ref();
let country = details.and_then(|details| {
details
.country
.as_ref()
.and_then(|c| payments_grpc::CountryAlpha2::from_str_name(&c.to_string()))
.map(|country| country.into())
});
payments_grpc::Address {
first_name: details
.and_then(|d| d.first_name.as_ref().map(|s| s.peek().to_string().into())),
last_name: details
.and_then(|d| d.last_name.as_ref().map(|s| s.peek().to_string().into())),
line1: details.and_then(|d| d.line1.as_ref().map(|s| s.peek().to_string().into())),
line2: details.and_then(|d| d.line2.as_ref().map(|s| s.peek().to_string().into())),
line3: details.and_then(|d| d.line3.as_ref().map(|s| s.peek().to_string().into())),
city: details.and_then(|d| d.city.as_ref().map(|s| s.clone().into())),
state: details.and_then(|d| d.state.as_ref().map(|s| s.peek().to_string().into())),
zip_code: details.and_then(|d| d.zip.as_ref().map(|s| s.peek().to_string().into())),
country_alpha2_code: country,
email: address.email.as_ref().map(|e| e.peek().to_string().into()),
phone_number: address
.phone
.as_ref()
.and_then(|phone| phone.number.as_ref().map(|n| n.peek().to_string().into())),
phone_country_code: address.phone.as_ref().and_then(|p| p.country_code.clone()),
}
});
let unified_payment_method_billing =
payment_address.get_payment_method_billing().map(|address| {
let details = address.address.as_ref();
let country = details.and_then(|details| {
details
.country
.as_ref()
.and_then(|c| payments_grpc::CountryAlpha2::from_str_name(&c.to_string()))
.map(|country| country.into())
});
payments_grpc::Address {
first_name: details
.and_then(|d| d.first_name.as_ref().map(|s| s.peek().to_string().into())),
last_name: details
.and_then(|d| d.last_name.as_ref().map(|s| s.peek().to_string().into())),
line1: details
.and_then(|d| d.line1.as_ref().map(|s| s.peek().to_string().into())),
line2: details
.and_then(|d| d.line2.as_ref().map(|s| s.peek().to_string().into())),
line3: details
.and_then(|d| d.line3.as_ref().map(|s| s.peek().to_string().into())),
city: details.and_then(|d| d.city.as_ref().map(|s| s.clone().into())),
state: details
.and_then(|d| d.state.as_ref().map(|s| s.peek().to_string().into())),
zip_code: details
.and_then(|d| d.zip.as_ref().map(|s| s.peek().to_string().into())),
country_alpha2_code: country,
email: address
.email
.as_ref()
.map(|e| e.clone().expose().expose().into()),
phone_number: address
.phone
.as_ref()
.and_then(|phone| phone.number.as_ref().map(|n| n.clone().expose().into())),
phone_country_code: address.phone.as_ref().and_then(|p| p.country_code.clone()),
}
});
Ok(Self {
shipping_address: shipping,
billing_address: unified_payment_method_billing.or(billing),
})
}
}
impl transformers::ForeignTryFrom<AuthenticationType> for payments_grpc::AuthenticationType {
type Error = error_stack::Report<UnifiedConnectorServiceError>;
fn foreign_try_from(auth_type: AuthenticationType) -> Result<Self, Self::Error> {
match auth_type {
AuthenticationType::ThreeDs => Ok(Self::ThreeDs),
AuthenticationType::NoThreeDs => Ok(Self::NoThreeDs),
}
}
}
impl
transformers::ForeignTryFrom<
hyperswitch_domain_models::router_request_types::BrowserInformation,
> for payments_grpc::BrowserInformation
{
type Error = error_stack::Report<UnifiedConnectorServiceError>;
fn foreign_try_from(
browser_info: hyperswitch_domain_models::router_request_types::BrowserInformation,
) -> Result<Self, Self::Error> {
Ok(Self {
color_depth: browser_info.color_depth.map(|v| v.into()),
java_enabled: browser_info.java_enabled,
java_script_enabled: browser_info.java_script_enabled,
language: browser_info.language,
screen_height: browser_info.screen_height,
screen_width: browser_info.screen_width,
ip_address: browser_info.ip_address.map(|ip| ip.to_string()),
accept_header: browser_info.accept_header,
user_agent: browser_info.user_agent,
os_type: browser_info.os_type,
os_version: browser_info.os_version,
device_model: browser_info.device_model,
accept_language: browser_info.accept_language,
time_zone_offset_minutes: browser_info.time_zone,
referer: browser_info.referer,
})
}
}
impl transformers::ForeignTryFrom<storage_enums::CaptureMethod> for payments_grpc::CaptureMethod {
type Error = error_stack::Report<UnifiedConnectorServiceError>;
fn foreign_try_from(capture_method: storage_enums::CaptureMethod) -> Result<Self, Self::Error> {
match capture_method {
common_enums::CaptureMethod::Automatic => Ok(Self::Automatic),
common_enums::CaptureMethod::Manual => Ok(Self::Manual),
common_enums::CaptureMethod::ManualMultiple => Ok(Self::ManualMultiple),
common_enums::CaptureMethod::Scheduled => Ok(Self::Scheduled),
common_enums::CaptureMethod::SequentialAutomatic => Ok(Self::SequentialAutomatic),
}
}
}
impl transformers::ForeignTryFrom<AuthenticationData> for payments_grpc::AuthenticationData {
type Error = error_stack::Report<UnifiedConnectorServiceError>;
fn foreign_try_from(authentication_data: AuthenticationData) -> Result<Self, Self::Error> {
Ok(Self {
eci: authentication_data.eci,
cavv: authentication_data.cavv.peek().to_string(),
threeds_server_transaction_id: authentication_data.threeds_server_transaction_id.map(
|id| Identifier {
id_type: Some(payments_grpc::identifier::IdType::Id(id)),
},
),
message_version: None,
ds_transaction_id: authentication_data.ds_trans_id,
})
}
}
impl transformers::ForeignTryFrom<payments_grpc::RedirectForm> for RedirectForm {
type Error = error_stack::Report<UnifiedConnectorServiceError>;
fn foreign_try_from(value: payments_grpc::RedirectForm) -> Result<Self, Self::Error> {
match value.form_type {
Some(payments_grpc::redirect_form::FormType::Form(form)) => Ok(Self::Form {
endpoint: form.clone().endpoint,
method: Method::foreign_try_from(form.clone().method())?,
form_fields: form.clone().form_fields,
}),
Some(payments_grpc::redirect_form::FormType::Html(html)) => Ok(Self::Html {
html_data: html.html_data,
}),
Some(payments_grpc::redirect_form::FormType::Uri(_)) => Err(
UnifiedConnectorServiceError::RequestEncodingFailedWithReason(
"URI form type is not implemented".to_string(),
)
.into(),
),
None => Err(
UnifiedConnectorServiceError::RequestEncodingFailedWithReason(
"Missing form type".to_string(),
)
.into(),
),
}
}
}
impl transformers::ForeignTryFrom<payments_grpc::HttpMethod> for Method {
type Error = error_stack::Report<UnifiedConnectorServiceError>;
fn foreign_try_from(value: payments_grpc::HttpMethod) -> Result<Self, Self::Error> {
tracing::debug!("Converting gRPC HttpMethod: {:?}", value);
match value {
payments_grpc::HttpMethod::Get => Ok(Self::Get),
payments_grpc::HttpMethod::Post => Ok(Self::Post),
payments_grpc::HttpMethod::Put => Ok(Self::Put),
payments_grpc::HttpMethod::Delete => Ok(Self::Delete),
payments_grpc::HttpMethod::Unspecified => {
Err(UnifiedConnectorServiceError::ResponseDeserializationFailed)
.attach_printable("Invalid Http Method")
}
}
}
}
impl transformers::ForeignTryFrom<storage_enums::FutureUsage> for payments_grpc::FutureUsage {
type Error = error_stack::Report<UnifiedConnectorServiceError>;
fn foreign_try_from(future_usage: storage_enums::FutureUsage) -> Result<Self, Self::Error> {
match future_usage {
storage_enums::FutureUsage::OnSession => Ok(Self::OnSession),
storage_enums::FutureUsage::OffSession => Ok(Self::OffSession),
}
}
}
impl transformers::ForeignTryFrom<common_types::payments::CustomerAcceptance>
for payments_grpc::CustomerAcceptance
{
type Error = error_stack::Report<UnifiedConnectorServiceError>;
fn foreign_try_from(
customer_acceptance: common_types::payments::CustomerAcceptance,
) -> Result<Self, Self::Error> {
let acceptance_type = match customer_acceptance.acceptance_type {
common_types::payments::AcceptanceType::Online => payments_grpc::AcceptanceType::Online,
common_types::payments::AcceptanceType::Offline => {
payments_grpc::AcceptanceType::Offline
}
};
let online_mandate_details =
customer_acceptance
.online
.map(|online| payments_grpc::OnlineMandate {
ip_address: online.ip_address.map(|ip| ip.peek().to_string()),
user_agent: online.user_agent,
});
Ok(Self {
acceptance_type: acceptance_type.into(),
accepted_at: customer_acceptance
.accepted_at
.map(|dt| dt.assume_utc().unix_timestamp())
.unwrap_or_default(),
online_mandate_details,
})
}
}
impl
transformers::ForeignTryFrom<
&hyperswitch_interfaces::webhooks::IncomingWebhookRequestDetails<'_>,
> for payments_grpc::RequestDetails
{
type Error = error_stack::Report<UnifiedConnectorServiceError>;
fn foreign_try_from(
request_details: &hyperswitch_interfaces::webhooks::IncomingWebhookRequestDetails<'_>,
) -> Result<Self, Self::Error> {
let headers_map = request_details
.headers
.iter()
.map(|(key, value)| {
let value_string = value.to_str().unwrap_or_default().to_string();
(key.as_str().to_string(), value_string)
})
.collect();
Ok(Self {
method: 1, // POST method for webhooks
uri: Some({
let uri_result = request_details
.headers
.get("x-forwarded-path")
.and_then(|h| h.to_str().map_err(|e| {
tracing::warn!(
header_conversion_error=?e,
header_value=?h,
"Failed to convert x-forwarded-path header to string for webhook processing"
);
e
}).ok());
uri_result.unwrap_or_else(|| {
tracing::debug!("x-forwarded-path header not found or invalid, using default '/Unknown'");
"/Unknown"
}).to_string()
}),
body: request_details.body.to_vec(),
headers: headers_map,
query_params: Some(request_details.query_params.clone()),
})
}
}
/// Transform UCS webhook response into webhook event data
pub fn transform_ucs_webhook_response(
response: PaymentServiceTransformResponse,
) -> Result<WebhookTransformData, error_stack::Report<errors::ApiErrorResponse>> {
let event_type =
api_models::webhooks::IncomingWebhookEvent::from_ucs_event_type(response.event_type);
Ok(WebhookTransformData {
event_type,
source_verified: response.source_verified,
webhook_content: response.content,
response_ref_id: response.response_ref_id.and_then(|identifier| {
identifier.id_type.and_then(|id_type| match id_type {
payments_grpc::identifier::IdType::Id(id) => Some(id),
payments_grpc::identifier::IdType::EncodedData(encoded_data) => Some(encoded_data),
payments_grpc::identifier::IdType::NoResponseIdMarker(_) => None,
})
}),
})
}
/// Build UCS webhook transform request from webhook components
pub fn build_webhook_transform_request(
_webhook_body: &[u8],
request_details: &hyperswitch_interfaces::webhooks::IncomingWebhookRequestDetails<'_>,
webhook_secrets: Option<payments_grpc::WebhookSecrets>,
merchant_id: &str,
connector_id: &str,
) -> Result<PaymentServiceTransformRequest, error_stack::Report<errors::ApiErrorResponse>> {
let request_details_grpc =
<payments_grpc::RequestDetails as transformers::ForeignTryFrom<_>>::foreign_try_from(
request_details,
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to transform webhook request details to gRPC format")?;
Ok(PaymentServiceTransformRequest {
request_ref_id: Some(Identifier {
id_type: Some(payments_grpc::identifier::IdType::Id(format!(
"{}_{}_{}",
merchant_id,
connector_id,
time::OffsetDateTime::now_utc().unix_timestamp()
))),
}),
request_details: Some(request_details_grpc),
webhook_secrets,
access_token: None,
})
}
|
crates/router/src/core/unified_connector_service/transformers.rs
|
router::src::core::unified_connector_service::transformers
| 9,841
| true
|
// File: crates/router/src/core/verification/utils.rs
// Module: router::src::core::verification::utils
use common_utils::{errors::CustomResult, id_type::PaymentId};
use error_stack::{Report, ResultExt};
use crate::{
core::{
errors::{self, utils::StorageErrorExt},
utils,
},
logger,
routes::SessionState,
services::authentication::AuthenticationData,
types::{self, storage},
};
pub async fn check_existence_and_add_domain_to_db(
state: &SessionState,
merchant_id: common_utils::id_type::MerchantId,
profile_id_from_auth_layer: Option<common_utils::id_type::ProfileId>,
merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId,
domain_from_req: Vec<String>,
) -> CustomResult<Vec<String>, errors::ApiErrorResponse> {
let key_manager_state = &state.into();
let key_store = state
.store
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&merchant_id,
&state.store.get_master_key().to_vec().into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::InternalServerError)?;
#[cfg(feature = "v1")]
let merchant_connector_account = state
.store
.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
key_manager_state,
&merchant_id,
&merchant_connector_id,
&key_store,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?;
#[cfg(feature = "v2")]
let merchant_connector_account = state
.store
.find_merchant_connector_account_by_id(
key_manager_state,
&merchant_connector_id,
&key_store,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?;
utils::validate_profile_id_from_auth_layer(
profile_id_from_auth_layer,
&merchant_connector_account,
)?;
let mut already_verified_domains = merchant_connector_account
.applepay_verified_domains
.clone()
.unwrap_or_default();
let mut new_verified_domains: Vec<String> = domain_from_req
.into_iter()
.filter(|req_domain| !already_verified_domains.contains(req_domain))
.collect();
already_verified_domains.append(&mut new_verified_domains);
#[cfg(feature = "v1")]
let updated_mca = storage::MerchantConnectorAccountUpdate::Update {
connector_type: None,
connector_name: None,
connector_account_details: Box::new(None),
test_mode: None,
disabled: None,
merchant_connector_id: None,
payment_methods_enabled: None,
metadata: None,
frm_configs: None,
connector_webhook_details: Box::new(None),
applepay_verified_domains: Some(already_verified_domains.clone()),
pm_auth_config: Box::new(None),
connector_label: None,
status: None,
connector_wallets_details: Box::new(None),
additional_merchant_data: Box::new(None),
};
#[cfg(feature = "v2")]
let updated_mca = storage::MerchantConnectorAccountUpdate::Update {
connector_type: None,
connector_account_details: Box::new(None),
disabled: None,
payment_methods_enabled: None,
metadata: None,
frm_configs: None,
connector_webhook_details: Box::new(None),
applepay_verified_domains: Some(already_verified_domains.clone()),
pm_auth_config: Box::new(None),
connector_label: None,
status: None,
connector_wallets_details: Box::new(None),
additional_merchant_data: Box::new(None),
feature_metadata: Box::new(None),
};
state
.store
.update_merchant_connector_account(
key_manager_state,
merchant_connector_account,
updated_mca.into(),
&key_store,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| {
format!(
"Failed while updating MerchantConnectorAccount: id: {merchant_connector_id:?}",
)
})?;
Ok(already_verified_domains.clone())
}
pub fn log_applepay_verification_response_if_error(
response: &Result<Result<types::Response, types::Response>, Report<errors::ApiClientError>>,
) {
if let Err(error) = response.as_ref() {
logger::error!(applepay_domain_verification_error= ?error);
};
response.as_ref().ok().map(|res| {
res.as_ref()
.map_err(|error| logger::error!(applepay_domain_verification_error= ?error))
});
}
#[cfg(feature = "v2")]
pub async fn check_if_profile_id_is_present_in_payment_intent(
payment_id: PaymentId,
state: &SessionState,
auth_data: &AuthenticationData,
) -> CustomResult<(), errors::ApiErrorResponse> {
todo!()
}
#[cfg(feature = "v1")]
pub async fn check_if_profile_id_is_present_in_payment_intent(
payment_id: PaymentId,
state: &SessionState,
auth_data: &AuthenticationData,
) -> CustomResult<(), errors::ApiErrorResponse> {
let db = &*state.store;
let payment_intent = db
.find_payment_intent_by_payment_id_merchant_id(
&state.into(),
&payment_id,
auth_data.merchant_account.get_id(),
&auth_data.key_store,
auth_data.merchant_account.storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::Unauthorized)?;
utils::validate_profile_id_from_auth_layer(auth_data.profile_id.clone(), &payment_intent)
}
|
crates/router/src/core/verification/utils.rs
|
router::src::core::verification::utils
| 1,204
| true
|
// File: crates/router/src/core/revenue_recovery/types.rs
// Module: router::src::core::revenue_recovery::types
use std::{marker::PhantomData, str::FromStr};
use api_models::{
enums as api_enums,
payments::{
AmountDetails, PaymentRevenueRecoveryMetadata, PaymentsUpdateIntentRequest,
ProxyPaymentsRequest,
},
};
use common_utils::{
self,
ext_traits::{OptionExt, ValueExt},
id_type,
};
use diesel_models::{
enums, payment_intent, process_tracker::business_status, types as diesel_types,
};
use error_stack::{self, ResultExt};
use hyperswitch_domain_models::{
api::ApplicationResponse,
business_profile, merchant_connector_account,
merchant_context::{Context, MerchantContext},
payments::{
self as domain_payments, payment_attempt::PaymentAttempt, PaymentConfirmData,
PaymentIntent, PaymentIntentData, PaymentStatusData,
},
router_data_v2::{self, flow_common_types},
router_flow_types,
router_request_types::revenue_recovery as revenue_recovery_request,
router_response_types::revenue_recovery as revenue_recovery_response,
ApiModelToDieselModelConvertor,
};
use time::PrimitiveDateTime;
use super::errors::StorageErrorExt;
use crate::{
core::{
errors::{self, RouterResult},
payments::{self, helpers, operations::Operation, transformers::GenerateResponse},
revenue_recovery::{self as revenue_recovery_core, pcr, perform_calculate_workflow},
webhooks::{
create_event_and_trigger_outgoing_webhook, recovery_incoming as recovery_incoming_flow,
},
},
db::StorageInterface,
logger,
routes::SessionState,
services::{self, connector_integration_interface::RouterDataConversion},
types::{
self, api as api_types, api::payments as payments_types, domain, storage,
transformers::ForeignInto,
},
workflows::{
payment_sync,
revenue_recovery::{self, get_schedule_time_to_retry_mit_payments},
},
};
type RecoveryResult<T> = error_stack::Result<T, errors::RecoveryError>;
pub const REVENUE_RECOVERY: &str = "revenue_recovery";
/// The status of Passive Churn Payments
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
pub enum RevenueRecoveryPaymentsAttemptStatus {
Succeeded,
Failed,
Processing,
InvalidStatus(String),
// Cancelled,
}
impl RevenueRecoveryPaymentsAttemptStatus {
pub(crate) async fn update_pt_status_based_on_attempt_status_for_execute_payment(
&self,
db: &dyn StorageInterface,
execute_task_process: &storage::ProcessTracker,
) -> Result<(), errors::ProcessTrackerError> {
logger::info!("Entering update_pt_status_based_on_attempt_status_for_execute_payment");
match &self {
Self::Succeeded | Self::Failed | Self::Processing => {
// finish the current execute task
db.finish_process_with_business_status(
execute_task_process.clone(),
business_status::EXECUTE_WORKFLOW_COMPLETE_FOR_PSYNC,
)
.await?;
}
Self::InvalidStatus(action) => {
logger::debug!(
"Invalid Attempt Status for the Recovery Payment : {}",
action
);
let pt_update = storage::ProcessTrackerUpdate::StatusUpdate {
status: enums::ProcessTrackerStatus::Review,
business_status: Some(String::from(business_status::EXECUTE_WORKFLOW_COMPLETE)),
};
// update the process tracker status as Review
db.update_process(execute_task_process.clone(), pt_update)
.await?;
}
};
Ok(())
}
#[allow(clippy::too_many_arguments)]
pub(crate) async fn update_pt_status_based_on_attempt_status_for_payments_sync(
&self,
state: &SessionState,
payment_intent: &PaymentIntent,
process_tracker: storage::ProcessTracker,
profile: &domain::Profile,
merchant_context: domain::MerchantContext,
revenue_recovery_payment_data: &storage::revenue_recovery::RevenueRecoveryPaymentData,
payment_attempt: PaymentAttempt,
revenue_recovery_metadata: &mut PaymentRevenueRecoveryMetadata,
) -> Result<(), errors::ProcessTrackerError> {
let connector_customer_id = payment_intent
.extract_connector_customer_id_from_payment_intent()
.change_context(errors::RecoveryError::ValueNotFound)
.attach_printable("Failed to extract customer ID from payment intent")?;
let db = &*state.store;
let recovery_payment_intent =
hyperswitch_domain_models::revenue_recovery::RecoveryPaymentIntent::from(
payment_intent,
);
let recovery_payment_attempt =
hyperswitch_domain_models::revenue_recovery::RecoveryPaymentAttempt::from(
&payment_attempt,
);
let recovery_payment_tuple = recovery_incoming_flow::RecoveryPaymentTuple::new(
&recovery_payment_intent,
&recovery_payment_attempt,
);
let used_token = get_payment_processor_token_id_from_payment_attempt(&payment_attempt);
let retry_count = process_tracker.retry_count;
let psync_response = revenue_recovery_payment_data
.psync_data
.as_ref()
.ok_or(errors::RecoveryError::ValueNotFound)
.attach_printable("Psync data not found in revenue recovery payment data")?;
match self {
Self::Succeeded => {
// finish psync task as the payment was a success
db.as_scheduler()
.finish_process_with_business_status(
process_tracker,
business_status::PSYNC_WORKFLOW_COMPLETE,
)
.await?;
let event_status = common_enums::EventType::PaymentSucceeded;
// publish events to kafka
if let Err(e) = recovery_incoming_flow::RecoveryPaymentTuple::publish_revenue_recovery_event_to_kafka(
state,
&recovery_payment_tuple,
Some(retry_count+1)
)
.await{
router_env::logger::error!(
"Failed to publish revenue recovery event to kafka: {:?}",
e
);
};
// update the status of token in redis
let _update_error_code = storage::revenue_recovery_redis_operation::RedisTokenManager::update_payment_processor_token_error_code_from_process_tracker(
state,
&connector_customer_id,
&None,
// Since this is succeeded payment attempt, 'is_hard_decine' will be false.
&Some(false),
used_token.as_deref(),
)
.await;
// unlocking the token
let _unlock_the_connector_customer_id = storage::revenue_recovery_redis_operation::RedisTokenManager::unlock_connector_customer_status(
state,
&connector_customer_id,
)
.await;
let payments_response = psync_response
.clone()
.generate_response(state, None, None, None, &merchant_context, profile, None)
.change_context(errors::RecoveryError::PaymentsResponseGenerationFailed)
.attach_printable("Failed while generating response for payment")?;
RevenueRecoveryOutgoingWebhook::send_outgoing_webhook_based_on_revenue_recovery_status(
state,
common_enums::EventClass::Payments,
event_status,
payment_intent,
&merchant_context,
profile,
recovery_payment_attempt
.attempt_id
.get_string_repr()
.to_string(),
payments_response
)
.await?;
// Record a successful transaction back to Billing Connector
// TODO: Add support for retrying failed outgoing recordback webhooks
record_back_to_billing_connector(
state,
&payment_attempt,
payment_intent,
&revenue_recovery_payment_data.billing_mca,
)
.await
.change_context(errors::RecoveryError::RecordBackToBillingConnectorFailed)
.attach_printable("Failed to update the process tracker")?;
}
Self::Failed => {
// finish psync task
db.as_scheduler()
.finish_process_with_business_status(
process_tracker.clone(),
business_status::PSYNC_WORKFLOW_COMPLETE,
)
.await?;
// publish events to kafka
if let Err(e) = recovery_incoming_flow::RecoveryPaymentTuple::publish_revenue_recovery_event_to_kafka(
state,
&recovery_payment_tuple,
Some(retry_count+1)
)
.await{
router_env::logger::error!(
"Failed to publish revenue recovery event to kafka : {:?}", e
);
};
let error_code = recovery_payment_attempt.error_code;
let is_hard_decline = revenue_recovery::check_hard_decline(state, &payment_attempt)
.await
.ok();
// update the status of token in redis
let _update_error_code = storage::revenue_recovery_redis_operation::RedisTokenManager::update_payment_processor_token_error_code_from_process_tracker(
state,
&connector_customer_id,
&error_code,
&is_hard_decline,
used_token.as_deref(),
)
.await;
// unlocking the token
let _unlock_the_connector_customer_id = storage::revenue_recovery_redis_operation::RedisTokenManager::unlock_connector_customer_status(
state,
&connector_customer_id,
)
.await;
// Reopen calculate workflow on payment failure
Box::pin(reopen_calculate_workflow_on_payment_failure(
state,
&process_tracker,
profile,
merchant_context,
payment_intent,
revenue_recovery_payment_data,
psync_response.payment_attempt.get_id(),
))
.await?;
}
Self::Processing => {
// do a psync payment
let action = Box::pin(Action::payment_sync_call(
state,
revenue_recovery_payment_data,
payment_intent,
&process_tracker,
profile,
merchant_context,
payment_attempt,
))
.await?;
//handle the response
Box::pin(action.psync_response_handler(
state,
payment_intent,
&process_tracker,
revenue_recovery_metadata,
revenue_recovery_payment_data,
))
.await?;
}
Self::InvalidStatus(status) => logger::debug!(
"Invalid Attempt Status for the Recovery Payment : {}",
status
),
}
Ok(())
}
}
pub enum Decision {
Execute,
Psync(enums::AttemptStatus, id_type::GlobalAttemptId),
InvalidDecision,
ReviewForSuccessfulPayment,
ReviewForFailedPayment(enums::TriggeredBy),
}
impl Decision {
pub async fn get_decision_based_on_params(
state: &SessionState,
intent_status: enums::IntentStatus,
called_connector: enums::PaymentConnectorTransmission,
active_attempt_id: Option<id_type::GlobalAttemptId>,
revenue_recovery_data: &storage::revenue_recovery::RevenueRecoveryPaymentData,
payment_id: &id_type::GlobalPaymentId,
) -> RecoveryResult<Self> {
logger::info!("Entering get_decision_based_on_params");
Ok(match (intent_status, called_connector, active_attempt_id) {
(
enums::IntentStatus::Failed,
enums::PaymentConnectorTransmission::ConnectorCallUnsuccessful,
None,
) => Self::Execute,
(
enums::IntentStatus::Processing,
enums::PaymentConnectorTransmission::ConnectorCallSucceeded,
Some(_),
) => {
let psync_data = revenue_recovery_core::api::call_psync_api(
state,
payment_id,
revenue_recovery_data,
true,
true,
)
.await
.change_context(errors::RecoveryError::PaymentCallFailed)
.attach_printable("Error while executing the Psync call")?;
let payment_attempt = psync_data.payment_attempt;
Self::Psync(payment_attempt.status, payment_attempt.get_id().clone())
}
(
enums::IntentStatus::Failed,
enums::PaymentConnectorTransmission::ConnectorCallUnsuccessful,
Some(_),
) => {
let psync_data = revenue_recovery_core::api::call_psync_api(
state,
payment_id,
revenue_recovery_data,
true,
true,
)
.await
.change_context(errors::RecoveryError::PaymentCallFailed)
.attach_printable("Error while executing the Psync call")?;
let payment_attempt = psync_data.payment_attempt;
let attempt_triggered_by = payment_attempt
.feature_metadata
.and_then(|metadata| {
metadata.revenue_recovery.map(|revenue_recovery_metadata| {
revenue_recovery_metadata.attempt_triggered_by
})
})
.get_required_value("Attempt Triggered By")
.change_context(errors::RecoveryError::ValueNotFound)?;
Self::ReviewForFailedPayment(attempt_triggered_by)
}
(enums::IntentStatus::Succeeded, _, _) => Self::ReviewForSuccessfulPayment,
_ => Self::InvalidDecision,
})
}
}
#[derive(Debug, Clone)]
pub enum Action {
SyncPayment(PaymentAttempt),
RetryPayment(PrimitiveDateTime),
TerminalFailure(PaymentAttempt),
SuccessfulPayment(PaymentAttempt),
ReviewPayment,
ManualReviewAction,
}
impl Action {
#[allow(clippy::too_many_arguments)]
pub async fn execute_payment(
state: &SessionState,
_merchant_id: &id_type::MerchantId,
payment_intent: &PaymentIntent,
process: &storage::ProcessTracker,
profile: &domain::Profile,
merchant_context: domain::MerchantContext,
revenue_recovery_payment_data: &storage::revenue_recovery::RevenueRecoveryPaymentData,
revenue_recovery_metadata: &PaymentRevenueRecoveryMetadata,
latest_attempt_id: &id_type::GlobalAttemptId,
) -> RecoveryResult<Self> {
let connector_customer_id = payment_intent
.extract_connector_customer_id_from_payment_intent()
.change_context(errors::RecoveryError::ValueNotFound)
.attach_printable("Failed to extract customer ID from payment intent")?;
let tracking_data: pcr::RevenueRecoveryWorkflowTrackingData =
serde_json::from_value(process.tracking_data.clone())
.change_context(errors::RecoveryError::ValueNotFound)
.attach_printable("Failed to deserialize the tracking data from process tracker")?;
let last_token_used = payment_intent
.feature_metadata
.as_ref()
.and_then(|fm| fm.payment_revenue_recovery_metadata.as_ref())
.map(|rr| {
rr.billing_connector_payment_details
.payment_processor_token
.clone()
});
let recovery_algorithm = tracking_data.revenue_recovery_retry;
let scheduled_token = match storage::revenue_recovery_redis_operation::RedisTokenManager::get_token_based_on_retry_type(
state,
&connector_customer_id,
recovery_algorithm,
last_token_used.as_deref(),
)
.await {
Ok(scheduled_token_opt) => scheduled_token_opt,
Err(e) => {
logger::error!(
error = ?e,
connector_customer_id = %connector_customer_id,
"Failed to get PSP token status"
);
None
}
};
match scheduled_token {
Some(scheduled_token) => {
let response = revenue_recovery_core::api::call_proxy_api(
state,
payment_intent,
revenue_recovery_payment_data,
revenue_recovery_metadata,
&scheduled_token
.payment_processor_token_details
.payment_processor_token,
)
.await;
let recovery_payment_intent =
hyperswitch_domain_models::revenue_recovery::RecoveryPaymentIntent::from(
payment_intent,
);
// handle proxy api's response
match response {
Ok(payment_data) => match payment_data.payment_attempt.status.foreign_into() {
RevenueRecoveryPaymentsAttemptStatus::Succeeded => {
let recovery_payment_attempt =
hyperswitch_domain_models::revenue_recovery::RecoveryPaymentAttempt::from(
&payment_data.payment_attempt,
);
let recovery_payment_tuple =
recovery_incoming_flow::RecoveryPaymentTuple::new(
&recovery_payment_intent,
&recovery_payment_attempt,
);
// publish events to kafka
if let Err(e) = recovery_incoming_flow::RecoveryPaymentTuple::publish_revenue_recovery_event_to_kafka(
state,
&recovery_payment_tuple,
Some(process.retry_count+1)
)
.await{
router_env::logger::error!(
"Failed to publish revenue recovery event to kafka: {:?}",
e
);
};
let is_hard_decline = revenue_recovery::check_hard_decline(
state,
&payment_data.payment_attempt,
)
.await
.ok();
// update the status of token in redis
let _update_error_code = storage::revenue_recovery_redis_operation::RedisTokenManager::update_payment_processor_token_error_code_from_process_tracker(
state,
&connector_customer_id,
&None,
&is_hard_decline,
Some(&scheduled_token.payment_processor_token_details.payment_processor_token),
)
.await;
// unlocking the token
let _unlock_the_connector_customer_id = storage::revenue_recovery_redis_operation::RedisTokenManager::unlock_connector_customer_status(
state,
&connector_customer_id,
)
.await;
let event_status = common_enums::EventType::PaymentSucceeded;
let payments_response = payment_data
.clone()
.generate_response(
state,
None,
None,
None,
&merchant_context,
profile,
None,
)
.change_context(
errors::RecoveryError::PaymentsResponseGenerationFailed,
)
.attach_printable("Failed while generating response for payment")?;
RevenueRecoveryOutgoingWebhook::send_outgoing_webhook_based_on_revenue_recovery_status(
state,
common_enums::EventClass::Payments,
event_status,
payment_intent,
&merchant_context,
profile,
payment_data.payment_attempt.id.get_string_repr().to_string(),
payments_response
)
.await?;
Ok(Self::SuccessfulPayment(
payment_data.payment_attempt.clone(),
))
}
RevenueRecoveryPaymentsAttemptStatus::Failed => {
let recovery_payment_attempt =
hyperswitch_domain_models::revenue_recovery::RecoveryPaymentAttempt::from(
&payment_data.payment_attempt,
);
let recovery_payment_tuple =
recovery_incoming_flow::RecoveryPaymentTuple::new(
&recovery_payment_intent,
&recovery_payment_attempt,
);
// publish events to kafka
if let Err(e) = recovery_incoming_flow::RecoveryPaymentTuple::publish_revenue_recovery_event_to_kafka(
state,
&recovery_payment_tuple,
Some(process.retry_count+1)
)
.await{
router_env::logger::error!(
"Failed to publish revenue recovery event to kafka: {:?}",
e
);
};
let error_code = payment_data
.payment_attempt
.clone()
.error
.map(|error| error.code);
let is_hard_decline = revenue_recovery::check_hard_decline(
state,
&payment_data.payment_attempt,
)
.await
.ok();
let _update_connector_customer_id = storage::revenue_recovery_redis_operation::RedisTokenManager::update_payment_processor_token_error_code_from_process_tracker(
state,
&connector_customer_id,
&error_code,
&is_hard_decline,
Some(&scheduled_token
.payment_processor_token_details
.payment_processor_token)
,
)
.await;
// unlocking the token
let _unlock_connector_customer_id = storage::revenue_recovery_redis_operation::RedisTokenManager::unlock_connector_customer_status(
state,
&connector_customer_id,
)
.await;
// Reopen calculate workflow on payment failure
Box::pin(reopen_calculate_workflow_on_payment_failure(
state,
process,
profile,
merchant_context,
payment_intent,
revenue_recovery_payment_data,
latest_attempt_id,
))
.await?;
// Return terminal failure to finish the current execute workflow
Ok(Self::TerminalFailure(payment_data.payment_attempt.clone()))
}
RevenueRecoveryPaymentsAttemptStatus::Processing => {
Ok(Self::SyncPayment(payment_data.payment_attempt.clone()))
}
RevenueRecoveryPaymentsAttemptStatus::InvalidStatus(action) => {
logger::info!(?action, "Invalid Payment Status For PCR Payment");
Ok(Self::ManualReviewAction)
}
},
Err(err) =>
// check for an active attempt being constructed or not
{
logger::error!(execute_payment_res=?err);
Ok(Self::ReviewPayment)
}
}
}
None => {
let response = revenue_recovery_core::api::call_psync_api(
state,
payment_intent.get_id(),
revenue_recovery_payment_data,
true,
true,
)
.await;
let payment_status_data = response
.change_context(errors::RecoveryError::PaymentCallFailed)
.attach_printable("Error while executing the Psync call")?;
let payment_attempt = payment_status_data.payment_attempt;
logger::info!(
process_id = %process.id,
connector_customer_id = %connector_customer_id,
"No token available, finishing CALCULATE_WORKFLOW"
);
state
.store
.as_scheduler()
.finish_process_with_business_status(
process.clone(),
business_status::CALCULATE_WORKFLOW_FINISH,
)
.await
.change_context(errors::RecoveryError::ProcessTrackerFailure)
.attach_printable("Failed to finish CALCULATE_WORKFLOW")?;
logger::info!(
process_id = %process.id,
connector_customer_id = %connector_customer_id,
"CALCULATE_WORKFLOW finished successfully"
);
Ok(Self::TerminalFailure(payment_attempt.clone()))
}
}
}
pub async fn execute_payment_task_response_handler(
&self,
state: &SessionState,
payment_intent: &PaymentIntent,
execute_task_process: &storage::ProcessTracker,
revenue_recovery_payment_data: &storage::revenue_recovery::RevenueRecoveryPaymentData,
revenue_recovery_metadata: &mut PaymentRevenueRecoveryMetadata,
) -> Result<(), errors::ProcessTrackerError> {
logger::info!("Entering execute_payment_task_response_handler");
let db = &*state.store;
match self {
Self::SyncPayment(payment_attempt) => {
revenue_recovery_core::insert_psync_pcr_task_to_pt(
revenue_recovery_payment_data.billing_mca.get_id().clone(),
db,
revenue_recovery_payment_data
.merchant_account
.get_id()
.to_owned(),
payment_intent.id.clone(),
revenue_recovery_payment_data.profile.get_id().to_owned(),
payment_attempt.id.clone(),
storage::ProcessTrackerRunner::PassiveRecoveryWorkflow,
revenue_recovery_payment_data.retry_algorithm,
)
.await
.change_context(errors::RecoveryError::ProcessTrackerFailure)
.attach_printable("Failed to create a psync workflow in the process tracker")?;
db.as_scheduler()
.finish_process_with_business_status(
execute_task_process.clone(),
business_status::EXECUTE_WORKFLOW_COMPLETE_FOR_PSYNC,
)
.await
.change_context(errors::RecoveryError::ProcessTrackerFailure)
.attach_printable("Failed to update the process tracker")?;
Ok(())
}
Self::RetryPayment(schedule_time) => {
db.as_scheduler()
.retry_process(execute_task_process.clone(), *schedule_time)
.await?;
// update the connector payment transmission field to Unsuccessful and unset active attempt id
revenue_recovery_metadata.set_payment_transmission_field_for_api_request(
enums::PaymentConnectorTransmission::ConnectorCallUnsuccessful,
);
let payment_update_req =
PaymentsUpdateIntentRequest::update_feature_metadata_and_active_attempt_with_api(
payment_intent
.feature_metadata
.clone()
.unwrap_or_default()
.convert_back()
.set_payment_revenue_recovery_metadata_using_api(
revenue_recovery_metadata.clone(),
),
api_enums::UpdateActiveAttempt::Unset,
);
logger::info!(
"Call made to payments update intent api , with the request body {:?}",
payment_update_req
);
revenue_recovery_core::api::update_payment_intent_api(
state,
payment_intent.id.clone(),
revenue_recovery_payment_data,
payment_update_req,
)
.await
.change_context(errors::RecoveryError::PaymentCallFailed)?;
Ok(())
}
Self::TerminalFailure(payment_attempt) => {
db.as_scheduler()
.finish_process_with_business_status(
execute_task_process.clone(),
business_status::EXECUTE_WORKFLOW_FAILURE,
)
.await
.change_context(errors::RecoveryError::ProcessTrackerFailure)
.attach_printable("Failed to update the process tracker")?;
// TODO: Add support for retrying failed outgoing recordback webhooks
Ok(())
}
Self::SuccessfulPayment(payment_attempt) => {
db.as_scheduler()
.finish_process_with_business_status(
execute_task_process.clone(),
business_status::EXECUTE_WORKFLOW_COMPLETE,
)
.await
.change_context(errors::RecoveryError::ProcessTrackerFailure)
.attach_printable("Failed to update the process tracker")?;
// Record back to billing connector for terminal status
// TODO: Add support for retrying failed outgoing recordback webhooks
record_back_to_billing_connector(
state,
payment_attempt,
payment_intent,
&revenue_recovery_payment_data.billing_mca,
)
.await
.change_context(errors::RecoveryError::RecordBackToBillingConnectorFailed)
.attach_printable("Failed to update the process tracker")?;
Ok(())
}
Self::ReviewPayment => {
// requeue the process tracker in case of error response
let pt_update = storage::ProcessTrackerUpdate::StatusUpdate {
status: enums::ProcessTrackerStatus::Pending,
business_status: Some(String::from(business_status::EXECUTE_WORKFLOW_REQUEUE)),
};
db.as_scheduler()
.update_process(execute_task_process.clone(), pt_update)
.await?;
Ok(())
}
Self::ManualReviewAction => {
logger::debug!("Invalid Payment Status For PCR Payment");
let pt_update = storage::ProcessTrackerUpdate::StatusUpdate {
status: enums::ProcessTrackerStatus::Review,
business_status: Some(String::from(business_status::EXECUTE_WORKFLOW_COMPLETE)),
};
// update the process tracker status as Review
db.as_scheduler()
.update_process(execute_task_process.clone(), pt_update)
.await?;
Ok(())
}
}
}
pub async fn payment_sync_call(
state: &SessionState,
revenue_recovery_payment_data: &storage::revenue_recovery::RevenueRecoveryPaymentData,
payment_intent: &PaymentIntent,
process: &storage::ProcessTracker,
profile: &domain::Profile,
merchant_context: domain::MerchantContext,
payment_attempt: PaymentAttempt,
) -> RecoveryResult<Self> {
logger::info!("Entering payment_sync_call");
let response = revenue_recovery_core::api::call_psync_api(
state,
payment_intent.get_id(),
revenue_recovery_payment_data,
true,
true,
)
.await;
let used_token = get_payment_processor_token_id_from_payment_attempt(&payment_attempt);
match response {
Ok(_payment_data) => match payment_attempt.status.foreign_into() {
RevenueRecoveryPaymentsAttemptStatus::Succeeded => {
let connector_customer_id = payment_intent
.extract_connector_customer_id_from_payment_intent()
.change_context(errors::RecoveryError::ValueNotFound)
.attach_printable("Failed to extract customer ID from payment intent")?;
// update the status of token in redis
let _update_error_code = storage::revenue_recovery_redis_operation::RedisTokenManager::update_payment_processor_token_error_code_from_process_tracker(
state,
&connector_customer_id,
&None,
// Since this is succeeded, 'hard_decine' will be false.
&Some(false),
used_token.as_deref(),
)
.await;
// unlocking the token
let _unlock_the_connector_customer_id = storage::revenue_recovery_redis_operation::RedisTokenManager::unlock_connector_customer_status(
state,
&connector_customer_id,
)
.await;
Ok(Self::SuccessfulPayment(payment_attempt))
}
RevenueRecoveryPaymentsAttemptStatus::Failed => {
let connector_customer_id = payment_intent
.extract_connector_customer_id_from_payment_intent()
.change_context(errors::RecoveryError::ValueNotFound)
.attach_printable("Failed to extract customer ID from payment intent")?;
let error_code = payment_attempt.clone().error.map(|error| error.code);
let is_hard_decline =
revenue_recovery::check_hard_decline(state, &payment_attempt)
.await
.ok();
let _update_error_code = storage::revenue_recovery_redis_operation::RedisTokenManager::update_payment_processor_token_error_code_from_process_tracker(
state,
&connector_customer_id,
&error_code,
&is_hard_decline,
used_token.as_deref(),
)
.await;
// unlocking the token
let _unlock_connector_customer_id = storage::revenue_recovery_redis_operation::RedisTokenManager::unlock_connector_customer_status(
state,
&connector_customer_id,
)
.await;
// Reopen calculate workflow on payment failure
Box::pin(reopen_calculate_workflow_on_payment_failure(
state,
process,
profile,
merchant_context,
payment_intent,
revenue_recovery_payment_data,
payment_attempt.get_id(),
))
.await?;
Ok(Self::TerminalFailure(payment_attempt.clone()))
}
RevenueRecoveryPaymentsAttemptStatus::Processing => {
Ok(Self::SyncPayment(payment_attempt))
}
RevenueRecoveryPaymentsAttemptStatus::InvalidStatus(action) => {
logger::info!(?action, "Invalid Payment Status For PCR PSync Payment");
Ok(Self::ManualReviewAction)
}
},
Err(err) =>
// if there is an error while psync we create a new Review Task
{
logger::error!(sync_payment_response=?err);
Ok(Self::ReviewPayment)
}
}
}
pub async fn psync_response_handler(
&self,
state: &SessionState,
payment_intent: &PaymentIntent,
psync_task_process: &storage::ProcessTracker,
revenue_recovery_metadata: &mut PaymentRevenueRecoveryMetadata,
revenue_recovery_payment_data: &storage::revenue_recovery::RevenueRecoveryPaymentData,
) -> Result<(), errors::ProcessTrackerError> {
logger::info!("Entering psync_response_handler");
let db = &*state.store;
let connector_customer_id = payment_intent
.feature_metadata
.as_ref()
.and_then(|fm| fm.payment_revenue_recovery_metadata.as_ref())
.map(|rr| {
rr.billing_connector_payment_details
.connector_customer_id
.clone()
});
match self {
Self::SyncPayment(payment_attempt) => {
// get a schedule time for psync
// and retry the process if there is a schedule time
// if None mark the pt status as Retries Exceeded and finish the task
payment_sync::recovery_retry_sync_task(
state,
connector_customer_id,
revenue_recovery_metadata.connector.to_string(),
revenue_recovery_payment_data
.merchant_account
.get_id()
.clone(),
psync_task_process.clone(),
)
.await?;
Ok(())
}
Self::RetryPayment(schedule_time) => {
// finish the psync task
db.as_scheduler()
.finish_process_with_business_status(
psync_task_process.clone(),
business_status::PSYNC_WORKFLOW_COMPLETE,
)
.await
.change_context(errors::RecoveryError::ProcessTrackerFailure)
.attach_printable("Failed to update the process tracker")?;
// fetch the execute task
let task = revenue_recovery_core::EXECUTE_WORKFLOW;
let runner = storage::ProcessTrackerRunner::PassiveRecoveryWorkflow;
let process_tracker_id = payment_intent
.get_id()
.get_execute_revenue_recovery_id(task, runner);
let execute_task_process = db
.as_scheduler()
.find_process_by_id(&process_tracker_id)
.await
.change_context(errors::RecoveryError::ProcessTrackerFailure)?
.get_required_value("Process Tracker")?;
// retry the execute tasks
db.as_scheduler()
.retry_process(execute_task_process, *schedule_time)
.await
.change_context(errors::RecoveryError::ProcessTrackerFailure)
.attach_printable("Failed to update the process tracker")?;
Ok(())
}
Self::TerminalFailure(payment_attempt) => {
// TODO: Add support for retrying failed outgoing recordback webhooks
// finish the current psync task
db.as_scheduler()
.finish_process_with_business_status(
psync_task_process.clone(),
business_status::PSYNC_WORKFLOW_COMPLETE,
)
.await
.change_context(errors::RecoveryError::ProcessTrackerFailure)
.attach_printable("Failed to update the process tracker")?;
Ok(())
}
Self::SuccessfulPayment(payment_attempt) => {
// finish the current psync task
db.as_scheduler()
.finish_process_with_business_status(
psync_task_process.clone(),
business_status::PSYNC_WORKFLOW_COMPLETE,
)
.await
.change_context(errors::RecoveryError::ProcessTrackerFailure)
.attach_printable("Failed to update the process tracker")?;
// Record a successful transaction back to Billing Connector
// TODO: Add support for retrying failed outgoing recordback webhooks
record_back_to_billing_connector(
state,
payment_attempt,
payment_intent,
&revenue_recovery_payment_data.billing_mca,
)
.await
.change_context(errors::RecoveryError::RecordBackToBillingConnectorFailed)
.attach_printable("Failed to update the process tracker")?;
Ok(())
}
Self::ReviewPayment => {
// requeue the process tracker task in case of psync api error
let pt_update = storage::ProcessTrackerUpdate::StatusUpdate {
status: enums::ProcessTrackerStatus::Pending,
business_status: Some(String::from(business_status::PSYNC_WORKFLOW_REQUEUE)),
};
db.as_scheduler()
.update_process(psync_task_process.clone(), pt_update)
.await?;
Ok(())
}
Self::ManualReviewAction => {
logger::debug!("Invalid Payment Status For PCR Payment");
let pt_update = storage::ProcessTrackerUpdate::StatusUpdate {
status: enums::ProcessTrackerStatus::Review,
business_status: Some(String::from(business_status::PSYNC_WORKFLOW_COMPLETE)),
};
// update the process tracker status as Review
db.as_scheduler()
.update_process(psync_task_process.clone(), pt_update)
.await
.change_context(errors::RecoveryError::ProcessTrackerFailure)
.attach_printable("Failed to update the process tracker")?;
Ok(())
}
}
}
pub(crate) async fn decide_retry_failure_action(
state: &SessionState,
merchant_id: &id_type::MerchantId,
pt: storage::ProcessTracker,
revenue_recovery_payment_data: &storage::revenue_recovery::RevenueRecoveryPaymentData,
payment_attempt: &PaymentAttempt,
payment_intent: &PaymentIntent,
) -> RecoveryResult<Self> {
let db = &*state.store;
let next_retry_count = pt.retry_count + 1;
let error_message = payment_attempt
.error
.as_ref()
.map(|details| details.message.clone());
let error_code = payment_attempt
.error
.as_ref()
.map(|details| details.code.clone());
let connector_name = payment_attempt
.connector
.clone()
.ok_or(errors::RecoveryError::ValueNotFound)
.attach_printable("unable to derive payment connector from payment attempt")?;
let gsm_record = helpers::get_gsm_record(
state,
error_code,
error_message,
connector_name,
REVENUE_RECOVERY.to_string(),
)
.await;
let is_hard_decline = gsm_record
.and_then(|gsm_record| gsm_record.error_category)
.map(|gsm_error_category| {
gsm_error_category == common_enums::ErrorCategory::HardDecline
})
.unwrap_or(false);
let schedule_time = revenue_recovery_payment_data
.get_schedule_time_based_on_retry_type(
state,
merchant_id,
next_retry_count,
payment_attempt,
payment_intent,
is_hard_decline,
)
.await;
match schedule_time {
Some(schedule_time) => Ok(Self::RetryPayment(schedule_time)),
None => Ok(Self::TerminalFailure(payment_attempt.clone())),
}
}
}
/// Reopen calculate workflow when payment fails
pub async fn reopen_calculate_workflow_on_payment_failure(
state: &SessionState,
process: &storage::ProcessTracker,
profile: &domain::Profile,
merchant_context: domain::MerchantContext,
payment_intent: &PaymentIntent,
revenue_recovery_payment_data: &storage::revenue_recovery::RevenueRecoveryPaymentData,
latest_attempt_id: &id_type::GlobalAttemptId,
) -> RecoveryResult<()> {
let db = &*state.store;
let id = payment_intent.id.clone();
let task = revenue_recovery_core::CALCULATE_WORKFLOW;
let runner = storage::ProcessTrackerRunner::PassiveRecoveryWorkflow;
let old_tracking_data: pcr::RevenueRecoveryWorkflowTrackingData =
serde_json::from_value(process.tracking_data.clone())
.change_context(errors::RecoveryError::ValueNotFound)
.attach_printable("Failed to deserialize the tracking data from process tracker")?;
let new_tracking_data = pcr::RevenueRecoveryWorkflowTrackingData {
payment_attempt_id: latest_attempt_id.clone(),
..old_tracking_data
};
let tracking_data = serde_json::to_value(new_tracking_data)
.change_context(errors::RecoveryError::ValueNotFound)
.attach_printable("Failed to serialize the tracking data for process tracker")?;
// Construct the process tracker ID for CALCULATE_WORKFLOW
let process_tracker_id = format!("{}_{}_{}", runner, task, id.get_string_repr());
logger::info!(
payment_id = %id.get_string_repr(),
process_tracker_id = %process_tracker_id,
"Attempting to reopen CALCULATE_WORKFLOW on payment failure"
);
// Find the existing CALCULATE_WORKFLOW process tracker
let calculate_process = db
.find_process_by_id(&process_tracker_id)
.await
.change_context(errors::RecoveryError::ProcessTrackerFailure)
.attach_printable("Failed to find CALCULATE_WORKFLOW process tracker")?;
match calculate_process {
Some(process) => {
logger::info!(
payment_id = %id.get_string_repr(),
process_tracker_id = %process_tracker_id,
current_status = %process.business_status,
current_retry_count = process.retry_count,
"Found existing CALCULATE_WORKFLOW, updating status and retry count"
);
// Update the process tracker to reopen the calculate workflow
// 1. Change status from "finish" to "pending"
// 2. Increase retry count by 1
// 3. Set business status to QUEUED
// 4. Schedule for immediate execution
let new_retry_count = process.retry_count + 1;
let new_schedule_time = common_utils::date_time::now()
+ time::Duration::seconds(
state
.conf
.revenue_recovery
.recovery_timestamp
.reopen_workflow_buffer_time_in_seconds,
);
let pt_update = storage::ProcessTrackerUpdate::Update {
name: Some(task.to_string()),
retry_count: Some(new_retry_count),
schedule_time: Some(new_schedule_time),
tracking_data: Some(tracking_data),
business_status: Some(String::from(business_status::PENDING)),
status: Some(common_enums::ProcessTrackerStatus::Pending),
updated_at: Some(common_utils::date_time::now()),
};
db.update_process(process.clone(), pt_update)
.await
.change_context(errors::RecoveryError::ProcessTrackerFailure)
.attach_printable("Failed to update CALCULATE_WORKFLOW process tracker")?;
logger::info!(
payment_id = %id.get_string_repr(),
process_tracker_id = %process_tracker_id,
new_retry_count = new_retry_count,
new_schedule_time = %new_schedule_time,
"Successfully reopened CALCULATE_WORKFLOW with increased retry count"
);
}
None => {
logger::info!(
payment_id = %id.get_string_repr(),
process_tracker_id = %process_tracker_id,
"CALCULATE_WORKFLOW process tracker not found, creating new entry"
);
let task = "CALCULATE_WORKFLOW";
let db = &*state.store;
// Create process tracker ID in the format: CALCULATE_WORKFLOW_{payment_intent_id}
let process_tracker_id = format!("{runner}_{task}_{}", id.get_string_repr());
// Set scheduled time to current time + buffer time set in configuration
let schedule_time = common_utils::date_time::now()
+ time::Duration::seconds(
state
.conf
.revenue_recovery
.recovery_timestamp
.reopen_workflow_buffer_time_in_seconds,
);
let new_retry_count = process.retry_count + 1;
// Check if a process tracker entry already exists for this payment intent
let existing_entry = db
.as_scheduler()
.find_process_by_id(&process_tracker_id)
.await
.change_context(errors::RecoveryError::ProcessTrackerFailure)
.attach_printable(
"Failed to check for existing calculate workflow process tracker entry",
)?;
// No entry exists - create a new one
router_env::logger::info!(
"No existing CALCULATE_WORKFLOW task found for payment_intent_id: {}, creating new entry... ",
id.get_string_repr()
);
let tag = ["PCR"];
let runner = storage::ProcessTrackerRunner::PassiveRecoveryWorkflow;
let process_tracker_entry = storage::ProcessTrackerNew::new(
&process_tracker_id,
task,
runner,
tag,
process.tracking_data.clone(),
Some(new_retry_count),
schedule_time,
common_types::consts::API_VERSION,
)
.change_context(errors::RecoveryError::ProcessTrackerFailure)
.attach_printable("Failed to construct calculate workflow process tracker entry")?;
// Insert into process tracker with status New
db.as_scheduler()
.insert_process(process_tracker_entry)
.await
.change_context(errors::RecoveryError::ProcessTrackerFailure)
.attach_printable(
"Failed to enter calculate workflow process_tracker_entry in DB",
)?;
router_env::logger::info!(
"Successfully created new CALCULATE_WORKFLOW task for payment_intent_id: {}",
id.get_string_repr()
);
logger::info!(
payment_id = %id.get_string_repr(),
process_tracker_id = %process_tracker_id,
"Successfully created new CALCULATE_WORKFLOW entry using perform_calculate_workflow"
);
}
}
Ok(())
}
// TODO: Move these to impl based functions
async fn record_back_to_billing_connector(
state: &SessionState,
payment_attempt: &PaymentAttempt,
payment_intent: &PaymentIntent,
billing_mca: &merchant_connector_account::MerchantConnectorAccount,
) -> RecoveryResult<()> {
logger::info!("Entering record_back_to_billing_connector");
let connector_name = billing_mca.connector_name.to_string();
let connector_data = api_types::ConnectorData::get_connector_by_name(
&state.conf.connectors,
&connector_name,
api_types::GetToken::Connector,
Some(billing_mca.get_id()),
)
.change_context(errors::RecoveryError::RecordBackToBillingConnectorFailed)
.attach_printable("invalid connector name received in billing merchant connector account")?;
let connector_integration: services::BoxedRevenueRecoveryRecordBackInterface<
router_flow_types::InvoiceRecordBack,
revenue_recovery_request::InvoiceRecordBackRequest,
revenue_recovery_response::InvoiceRecordBackResponse,
> = connector_data.connector.get_connector_integration();
let router_data = construct_invoice_record_back_router_data(
state,
billing_mca,
payment_attempt,
payment_intent,
)?;
let response = services::execute_connector_processing_step(
state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.change_context(errors::RecoveryError::RecordBackToBillingConnectorFailed)
.attach_printable("Failed while handling response of record back to billing connector")?;
match response.response {
Ok(response) => Ok(response),
error @ Err(_) => {
router_env::logger::error!(?error);
Err(errors::RecoveryError::RecordBackToBillingConnectorFailed)
.attach_printable("Failed while recording back to billing connector")
}
}?;
Ok(())
}
pub fn construct_invoice_record_back_router_data(
state: &SessionState,
billing_mca: &merchant_connector_account::MerchantConnectorAccount,
payment_attempt: &PaymentAttempt,
payment_intent: &PaymentIntent,
) -> RecoveryResult<hyperswitch_domain_models::types::InvoiceRecordBackRouterData> {
logger::info!("Entering construct_invoice_record_back_router_data");
let auth_type: types::ConnectorAuthType =
helpers::MerchantConnectorAccountType::DbVal(Box::new(billing_mca.clone()))
.get_connector_account_details()
.parse_value("ConnectorAuthType")
.change_context(errors::RecoveryError::RecordBackToBillingConnectorFailed)?;
let merchant_reference_id = payment_intent
.merchant_reference_id
.clone()
.ok_or(errors::RecoveryError::RecordBackToBillingConnectorFailed)
.attach_printable(
"Merchant reference id not found while recording back to billing connector",
)?;
let connector_name = billing_mca.get_connector_name_as_string();
let connector = common_enums::connector_enums::Connector::from_str(connector_name.as_str())
.change_context(errors::RecoveryError::RecordBackToBillingConnectorFailed)
.attach_printable("Cannot find connector from the connector_name")?;
let connector_params =
hyperswitch_domain_models::connector_endpoints::Connectors::get_connector_params(
&state.conf.connectors,
connector,
)
.change_context(errors::RecoveryError::RecordBackToBillingConnectorFailed)
.attach_printable(format!(
"cannot find connector params for this connector {connector} in this flow",
))?;
let router_data = router_data_v2::RouterDataV2 {
flow: PhantomData::<router_flow_types::InvoiceRecordBack>,
tenant_id: state.tenant.tenant_id.clone(),
resource_common_data: flow_common_types::InvoiceRecordBackData {
connector_meta_data: None,
},
connector_auth_type: auth_type,
request: revenue_recovery_request::InvoiceRecordBackRequest {
merchant_reference_id,
amount: payment_attempt.get_total_amount(),
currency: payment_intent.amount_details.currency,
payment_method_type: Some(payment_attempt.payment_method_subtype),
attempt_status: payment_attempt.status,
connector_transaction_id: payment_attempt
.connector_payment_id
.as_ref()
.map(|id| common_utils::types::ConnectorTransactionId::TxnId(id.clone())),
connector_params,
},
response: Err(types::ErrorResponse::default()),
};
let old_router_data = flow_common_types::InvoiceRecordBackData::to_old_router_data(router_data)
.change_context(errors::RecoveryError::RecordBackToBillingConnectorFailed)
.attach_printable("Cannot construct record back router data")?;
Ok(old_router_data)
}
pub fn get_payment_processor_token_id_from_payment_attempt(
payment_attempt: &PaymentAttempt,
) -> Option<String> {
let used_token = payment_attempt
.connector_token_details
.as_ref()
.and_then(|t| t.connector_mandate_id.clone());
logger::info!("Used token in the payment attempt : {:?}", used_token);
used_token
}
pub struct RevenueRecoveryOutgoingWebhook;
impl RevenueRecoveryOutgoingWebhook {
#[allow(clippy::too_many_arguments)]
pub async fn send_outgoing_webhook_based_on_revenue_recovery_status(
state: &SessionState,
event_class: common_enums::EventClass,
event_status: common_enums::EventType,
payment_intent: &PaymentIntent,
merchant_context: &domain::MerchantContext,
profile: &domain::Profile,
payment_attempt_id: String,
payments_response: ApplicationResponse<api_models::payments::PaymentsResponse>,
) -> RecoveryResult<()> {
match payments_response {
ApplicationResponse::JsonWithHeaders((response, _headers)) => {
let outgoing_webhook_content =
api_models::webhooks::OutgoingWebhookContent::PaymentDetails(Box::new(
response,
));
create_event_and_trigger_outgoing_webhook(
state.clone(),
profile.clone(),
merchant_context.get_merchant_key_store(),
event_status,
event_class,
payment_attempt_id,
enums::EventObjectType::PaymentDetails,
outgoing_webhook_content,
payment_intent.created_at,
)
.await
.change_context(errors::RecoveryError::InvalidTask)
.attach_printable("Failed to send out going webhook")?;
Ok(())
}
_other_variant => {
// Handle other successful response types if needed
logger::warn!("Unexpected application response variant for outgoing webhook");
Err(errors::RecoveryError::RevenueRecoveryOutgoingWebhookFailed.into())
}
}
}
}
|
crates/router/src/core/revenue_recovery/types.rs
|
router::src::core::revenue_recovery::types
| 10,641
| true
|
// File: crates/router/src/core/revenue_recovery/transformers.rs
// Module: router::src::core::revenue_recovery::transformers
use common_enums::AttemptStatus;
use masking::PeekInterface;
use crate::{
core::revenue_recovery::types::RevenueRecoveryPaymentsAttemptStatus,
types::transformers::ForeignFrom,
};
impl ForeignFrom<AttemptStatus> for RevenueRecoveryPaymentsAttemptStatus {
fn foreign_from(s: AttemptStatus) -> Self {
match s {
AttemptStatus::Authorized
| AttemptStatus::Charged
| AttemptStatus::AutoRefunded
| AttemptStatus::PartiallyAuthorized
| AttemptStatus::PartialCharged
| AttemptStatus::PartialChargedAndChargeable => Self::Succeeded,
AttemptStatus::Started
| AttemptStatus::AuthenticationSuccessful
| AttemptStatus::Authorizing
| AttemptStatus::CodInitiated
| AttemptStatus::VoidInitiated
| AttemptStatus::CaptureInitiated
| AttemptStatus::Pending => Self::Processing,
AttemptStatus::AuthenticationFailed
| AttemptStatus::AuthorizationFailed
| AttemptStatus::VoidFailed
| AttemptStatus::RouterDeclined
| AttemptStatus::CaptureFailed
| AttemptStatus::Failure => Self::Failed,
AttemptStatus::Voided
| AttemptStatus::VoidedPostCharge
| AttemptStatus::ConfirmationAwaited
| AttemptStatus::PaymentMethodAwaited
| AttemptStatus::AuthenticationPending
| AttemptStatus::DeviceDataCollectionPending
| AttemptStatus::Unresolved
| AttemptStatus::IntegrityFailure
| AttemptStatus::Expired => Self::InvalidStatus(s.to_string()),
}
}
}
impl ForeignFrom<api_models::payments::RecoveryPaymentsCreate>
for hyperswitch_domain_models::revenue_recovery::RevenueRecoveryInvoiceData
{
fn foreign_from(data: api_models::payments::RecoveryPaymentsCreate) -> Self {
Self {
amount: data.amount_details.order_amount().into(),
currency: data.amount_details.currency(),
merchant_reference_id: data.merchant_reference_id,
billing_address: data.billing,
retry_count: None,
next_billing_at: None,
billing_started_at: data.billing_started_at,
metadata: data.metadata,
enable_partial_authorization: data.enable_partial_authorization,
}
}
}
impl ForeignFrom<&api_models::payments::RecoveryPaymentsCreate>
for hyperswitch_domain_models::revenue_recovery::RevenueRecoveryAttemptData
{
fn foreign_from(data: &api_models::payments::RecoveryPaymentsCreate) -> Self {
Self {
amount: data.amount_details.order_amount().into(),
currency: data.amount_details.currency(),
merchant_reference_id: data.merchant_reference_id.to_owned(),
connector_transaction_id: data.connector_transaction_id.as_ref().map(|txn_id| {
common_utils::types::ConnectorTransactionId::TxnId(txn_id.peek().to_string())
}),
error_code: data.error.as_ref().map(|error| error.code.clone()),
error_message: data.error.as_ref().map(|error| error.message.clone()),
processor_payment_method_token: data
.payment_method_data
.primary_processor_payment_method_token
.peek()
.to_string(),
connector_customer_id: data.connector_customer_id.peek().to_string(),
connector_account_reference_id: data
.payment_merchant_connector_id
.get_string_repr()
.to_string(),
transaction_created_at: data.transaction_created_at.to_owned(),
status: data.attempt_status,
payment_method_type: data.payment_method_type,
payment_method_sub_type: data.payment_method_sub_type,
network_advice_code: data
.error
.as_ref()
.and_then(|error| error.network_advice_code.clone()),
network_decline_code: data
.error
.as_ref()
.and_then(|error| error.network_decline_code.clone()),
network_error_message: data
.error
.as_ref()
.and_then(|error| error.network_error_message.clone()),
// retry count will be updated whenever there is new attempt is created.
retry_count: None,
invoice_next_billing_time: None,
invoice_billing_started_at_time: data.billing_started_at,
card_info: data
.payment_method_data
.additional_payment_method_info
.clone(),
charge_id: None,
}
}
}
|
crates/router/src/core/revenue_recovery/transformers.rs
|
router::src::core::revenue_recovery::transformers
| 948
| true
|
// File: crates/router/src/core/revenue_recovery/api.rs
// Module: router::src::core::revenue_recovery::api
use actix_web::{web, Responder};
use api_models::{payments as payments_api, payments as api_payments};
use common_utils::id_type;
use error_stack::{report, FutureExt, ResultExt};
use hyperswitch_domain_models::{
merchant_context::{Context, MerchantContext},
payments as payments_domain,
};
use crate::{
core::{
errors::{self, RouterResult},
payments::{self, operations::Operation},
webhooks::recovery_incoming,
},
db::{
errors::{RouterResponse, StorageErrorExt},
storage::revenue_recovery_redis_operation::RedisTokenManager,
},
logger,
routes::{app::ReqState, SessionState},
services,
types::{
api::payments as api_types,
domain,
storage::{self, revenue_recovery as revenue_recovery_types},
transformers::ForeignFrom,
},
};
pub async fn call_psync_api(
state: &SessionState,
global_payment_id: &id_type::GlobalPaymentId,
revenue_recovery_data: &revenue_recovery_types::RevenueRecoveryPaymentData,
force_sync_bool: bool,
expand_attempts_bool: bool,
) -> RouterResult<payments_domain::PaymentStatusData<api_types::PSync>> {
let operation = payments::operations::PaymentGet;
let req = payments_api::PaymentsRetrieveRequest {
force_sync: force_sync_bool,
param: None,
expand_attempts: expand_attempts_bool,
return_raw_connector_response: None,
merchant_connector_details: None,
};
let merchant_context_from_revenue_recovery_data =
MerchantContext::NormalMerchant(Box::new(Context(
revenue_recovery_data.merchant_account.clone(),
revenue_recovery_data.key_store.clone(),
)));
// TODO : Use api handler instead of calling get_tracker and payments_operation_core
// Get the tracker related information. This includes payment intent and payment attempt
let get_tracker_response = operation
.to_get_tracker()?
.get_trackers(
state,
global_payment_id,
&req,
&merchant_context_from_revenue_recovery_data,
&revenue_recovery_data.profile,
&payments_domain::HeaderPayload::default(),
)
.await?;
let (payment_data, _req, _, _, _, _) = Box::pin(payments::payments_operation_core::<
api_types::PSync,
_,
_,
_,
payments_domain::PaymentStatusData<api_types::PSync>,
>(
state,
state.get_req_state(),
merchant_context_from_revenue_recovery_data,
&revenue_recovery_data.profile,
operation,
req,
get_tracker_response,
payments::CallConnectorAction::Trigger,
payments_domain::HeaderPayload::default(),
))
.await?;
Ok(payment_data)
}
pub async fn call_proxy_api(
state: &SessionState,
payment_intent: &payments_domain::PaymentIntent,
revenue_recovery_payment_data: &storage::revenue_recovery::RevenueRecoveryPaymentData,
revenue_recovery: &payments_api::PaymentRevenueRecoveryMetadata,
payment_processor_token: &str,
) -> RouterResult<payments_domain::PaymentConfirmData<api_types::Authorize>> {
let operation = payments::operations::proxy_payments_intent::PaymentProxyIntent;
let recurring_details = api_models::mandates::ProcessorPaymentToken {
processor_payment_token: payment_processor_token.to_string(),
merchant_connector_id: Some(revenue_recovery.get_merchant_connector_id_for_api_request()),
};
let req = payments_api::ProxyPaymentsRequest {
return_url: None,
amount: payments_api::AmountDetails::new(payment_intent.amount_details.clone().into()),
recurring_details,
shipping: None,
browser_info: None,
connector: revenue_recovery.connector.to_string(),
merchant_connector_id: revenue_recovery.get_merchant_connector_id_for_api_request(),
};
logger::info!(
"Call made to payments proxy api , with the request body {:?}",
req
);
let merchant_context_from_revenue_recovery_payment_data =
MerchantContext::NormalMerchant(Box::new(Context(
revenue_recovery_payment_data.merchant_account.clone(),
revenue_recovery_payment_data.key_store.clone(),
)));
// TODO : Use api handler instead of calling get_tracker and payments_operation_core
// Get the tracker related information. This includes payment intent and payment attempt
let get_tracker_response = operation
.to_get_tracker()?
.get_trackers(
state,
payment_intent.get_id(),
&req,
&merchant_context_from_revenue_recovery_payment_data,
&revenue_recovery_payment_data.profile,
&payments_domain::HeaderPayload::default(),
)
.await?;
let (payment_data, _req, _, _) = Box::pin(payments::proxy_for_payments_operation_core::<
api_types::Authorize,
_,
_,
_,
payments_domain::PaymentConfirmData<api_types::Authorize>,
>(
state,
state.get_req_state(),
merchant_context_from_revenue_recovery_payment_data,
revenue_recovery_payment_data.profile.clone(),
operation,
req,
get_tracker_response,
payments::CallConnectorAction::Trigger,
payments_domain::HeaderPayload::default(),
None,
))
.await?;
Ok(payment_data)
}
pub async fn update_payment_intent_api(
state: &SessionState,
global_payment_id: id_type::GlobalPaymentId,
revenue_recovery_payment_data: &storage::revenue_recovery::RevenueRecoveryPaymentData,
update_req: payments_api::PaymentsUpdateIntentRequest,
) -> RouterResult<payments_domain::PaymentIntentData<api_types::PaymentUpdateIntent>> {
// TODO : Use api handler instead of calling payments_intent_operation_core
let operation = payments::operations::PaymentUpdateIntent;
let merchant_context_from_revenue_recovery_payment_data =
MerchantContext::NormalMerchant(Box::new(Context(
revenue_recovery_payment_data.merchant_account.clone(),
revenue_recovery_payment_data.key_store.clone(),
)));
let (payment_data, _req, _) = payments::payments_intent_operation_core::<
api_types::PaymentUpdateIntent,
_,
_,
payments_domain::PaymentIntentData<api_types::PaymentUpdateIntent>,
>(
state,
state.get_req_state(),
merchant_context_from_revenue_recovery_payment_data,
revenue_recovery_payment_data.profile.clone(),
operation,
update_req,
global_payment_id,
payments_domain::HeaderPayload::default(),
)
.await?;
Ok(payment_data)
}
pub async fn record_internal_attempt_api(
state: &SessionState,
payment_intent: &payments_domain::PaymentIntent,
revenue_recovery_payment_data: &storage::revenue_recovery::RevenueRecoveryPaymentData,
revenue_recovery_metadata: &payments_api::PaymentRevenueRecoveryMetadata,
card_info: payments_api::AdditionalCardInfo,
payment_processor_token: &str,
) -> RouterResult<payments_api::PaymentAttemptRecordResponse> {
let revenue_recovery_attempt_data =
recovery_incoming::RevenueRecoveryAttempt::get_revenue_recovery_attempt(
payment_intent,
revenue_recovery_metadata,
&revenue_recovery_payment_data.billing_mca,
card_info,
payment_processor_token,
)
.change_context(errors::ApiErrorResponse::GenericNotFoundError {
message: "get_revenue_recovery_attempt was not constructed".to_string(),
})?;
let request_payload = revenue_recovery_attempt_data
.create_payment_record_request(
state,
&revenue_recovery_payment_data.billing_mca.id,
Some(
revenue_recovery_metadata
.active_attempt_payment_connector_id
.clone(),
),
Some(revenue_recovery_metadata.connector),
common_enums::TriggeredBy::Internal,
)
.await
.change_context(errors::ApiErrorResponse::GenericNotFoundError {
message: "Cannot Create the payment record Request".to_string(),
})?;
let merchant_context_from_revenue_recovery_payment_data =
MerchantContext::NormalMerchant(Box::new(Context(
revenue_recovery_payment_data.merchant_account.clone(),
revenue_recovery_payment_data.key_store.clone(),
)));
let attempt_response = Box::pin(payments::record_attempt_core(
state.clone(),
state.get_req_state(),
merchant_context_from_revenue_recovery_payment_data,
revenue_recovery_payment_data.profile.clone(),
request_payload,
payment_intent.id.clone(),
hyperswitch_domain_models::payments::HeaderPayload::default(),
))
.await;
match attempt_response {
Ok(services::ApplicationResponse::JsonWithHeaders((attempt_response, _))) => {
Ok(attempt_response)
}
Ok(_) => Err(errors::ApiErrorResponse::PaymentNotFound)
.attach_printable("Unexpected response from record attempt core"),
error @ Err(_) => {
router_env::logger::error!(?error);
Err(errors::ApiErrorResponse::PaymentNotFound)
.attach_printable("failed to record attempt for revenue recovery workflow")
}
}
}
pub async fn custom_revenue_recovery_core(
state: SessionState,
req_state: ReqState,
merchant_context: MerchantContext,
profile: domain::Profile,
request: api_models::payments::RecoveryPaymentsCreate,
) -> RouterResponse<payments_api::RecoveryPaymentsResponse> {
let store = state.store.as_ref();
let key_manager_state = &(&state).into();
let payment_merchant_connector_account_id = request.payment_merchant_connector_id.to_owned();
// Find the payment & billing merchant connector id at the top level to avoid multiple DB calls.
let payment_merchant_connector_account = store
.find_merchant_connector_account_by_id(
key_manager_state,
&payment_merchant_connector_account_id,
merchant_context.get_merchant_key_store(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: payment_merchant_connector_account_id
.clone()
.get_string_repr()
.to_string(),
})?;
let billing_connector_account = store
.find_merchant_connector_account_by_id(
key_manager_state,
&request.billing_merchant_connector_id.clone(),
merchant_context.get_merchant_key_store(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: request
.billing_merchant_connector_id
.clone()
.get_string_repr()
.to_string(),
})?;
let recovery_intent =
recovery_incoming::RevenueRecoveryInvoice::get_or_create_custom_recovery_intent(
request.clone(),
&state,
&req_state,
&merchant_context,
&profile,
)
.await
.change_context(errors::ApiErrorResponse::GenericNotFoundError {
message: format!(
"Failed to load recovery intent for merchant reference id : {:?}",
request.merchant_reference_id.to_owned()
)
.to_string(),
})?;
let (revenue_recovery_attempt_data, updated_recovery_intent) =
recovery_incoming::RevenueRecoveryAttempt::load_recovery_attempt_from_api(
request.clone(),
&state,
&req_state,
&merchant_context,
&profile,
recovery_intent.clone(),
payment_merchant_connector_account,
)
.await
.change_context(errors::ApiErrorResponse::GenericNotFoundError {
message: format!(
"Failed to load recovery attempt for merchant reference id : {:?}",
request.merchant_reference_id.to_owned()
)
.to_string(),
})?;
let intent_retry_count = updated_recovery_intent
.feature_metadata
.as_ref()
.and_then(|metadata| metadata.get_retry_count())
.ok_or(report!(errors::ApiErrorResponse::GenericNotFoundError {
message: "Failed to fetch retry count from intent feature metadata".to_string(),
}))?;
router_env::logger::info!("Intent retry count: {:?}", intent_retry_count);
let recovery_action = recovery_incoming::RecoveryAction {
action: request.action.to_owned(),
};
let mca_retry_threshold = billing_connector_account
.get_retry_threshold()
.ok_or(report!(errors::ApiErrorResponse::GenericNotFoundError {
message: "Failed to fetch retry threshold from billing merchant connector account"
.to_string(),
}))?;
recovery_action
.handle_action(
&state,
&profile,
&merchant_context,
&billing_connector_account,
mca_retry_threshold,
intent_retry_count,
&(
Some(revenue_recovery_attempt_data),
updated_recovery_intent.clone(),
),
)
.await
.change_context(errors::ApiErrorResponse::GenericNotFoundError {
message: "Unexpected response from recovery core".to_string(),
})?;
let response = api_models::payments::RecoveryPaymentsResponse {
id: updated_recovery_intent.payment_id.to_owned(),
intent_status: updated_recovery_intent.status.to_owned(),
merchant_reference_id: updated_recovery_intent.merchant_reference_id.to_owned(),
};
Ok(hyperswitch_domain_models::api::ApplicationResponse::Json(
response,
))
}
|
crates/router/src/core/revenue_recovery/api.rs
|
router::src::core::revenue_recovery::api
| 2,771
| true
|
// File: crates/router/src/core/files/helpers.rs
// Module: router::src::core::files::helpers
use actix_multipart::Field;
use common_utils::errors::CustomResult;
use error_stack::ResultExt;
use futures::TryStreamExt;
use hyperswitch_domain_models::router_response_types::disputes::FileInfo;
use crate::{
core::{
errors::{self, utils::ConnectorErrorExt, StorageErrorExt},
payments, utils,
},
routes::SessionState,
services,
types::{self, api, domain, transformers::ForeignTryFrom},
};
pub async fn read_string(field: &mut Field) -> Option<String> {
let bytes = field.try_next().await;
if let Ok(Some(bytes)) = bytes {
String::from_utf8(bytes.to_vec()).ok()
} else {
None
}
}
pub async fn get_file_purpose(field: &mut Field) -> Option<api::FilePurpose> {
let purpose = read_string(field).await;
match purpose.as_deref() {
Some("dispute_evidence") => Some(api::FilePurpose::DisputeEvidence),
_ => None,
}
}
pub async fn validate_file_upload(
state: &SessionState,
merchant_context: domain::MerchantContext,
create_file_request: api::CreateFileRequest,
) -> CustomResult<(), errors::ApiErrorResponse> {
//File Validation based on the purpose of file upload
match create_file_request.purpose {
api::FilePurpose::DisputeEvidence => {
let dispute_id = &create_file_request
.dispute_id
.ok_or(errors::ApiErrorResponse::MissingDisputeId)?;
let dispute = state
.store
.find_dispute_by_merchant_id_dispute_id(
merchant_context.get_merchant_account().get_id(),
dispute_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::DisputeNotFound {
dispute_id: dispute_id.to_string(),
})?;
// Connector is not called for validating the file, connector_id can be passed as None safely
let connector_data = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
&dispute.connector,
api::GetToken::Connector,
None,
)?;
let validation = connector_data.connector.validate_file_upload(
create_file_request.purpose,
create_file_request.file_size,
create_file_request.file_type.clone(),
);
match validation {
Ok(()) => Ok(()),
Err(err) => match err.current_context() {
errors::ConnectorError::FileValidationFailed { reason } => {
Err(errors::ApiErrorResponse::FileValidationFailed {
reason: reason.to_string(),
}
.into())
}
//We are using parent error and ignoring this
_error => Err(err
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("File validation failed"))?,
},
}
}
}
}
pub async fn delete_file_using_file_id(
state: &SessionState,
file_key: String,
merchant_context: &domain::MerchantContext,
) -> CustomResult<(), errors::ApiErrorResponse> {
let file_metadata_object = state
.store
.find_file_metadata_by_merchant_id_file_id(
merchant_context.get_merchant_account().get_id(),
&file_key,
)
.await
.change_context(errors::ApiErrorResponse::FileNotFound)?;
let (provider, provider_file_id) = match (
file_metadata_object.file_upload_provider,
file_metadata_object.provider_file_id,
file_metadata_object.available,
) {
(Some(provider), Some(provider_file_id), true) => (provider, provider_file_id),
_ => Err(errors::ApiErrorResponse::FileNotAvailable)
.attach_printable("File not available")?,
};
match provider {
diesel_models::enums::FileUploadProvider::Router => state
.file_storage_client
.delete_file(&provider_file_id)
.await
.change_context(errors::ApiErrorResponse::InternalServerError),
_ => Err(errors::ApiErrorResponse::FileProviderNotSupported {
message: "Not Supported because provider is not Router".to_string(),
}
.into()),
}
}
pub async fn retrieve_file_from_connector(
state: &SessionState,
file_metadata: diesel_models::file::FileMetadata,
dispute_id: Option<String>,
merchant_context: &domain::MerchantContext,
) -> CustomResult<Vec<u8>, errors::ApiErrorResponse> {
let connector = &types::Connector::foreign_try_from(
file_metadata
.file_upload_provider
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Missing file upload provider")?,
)?
.to_string();
let connector_data = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
connector,
api::GetToken::Connector,
file_metadata.merchant_connector_id.clone(),
)?;
let dispute = match dispute_id {
Some(dispute) => Some(
state
.store
.find_dispute_by_merchant_id_dispute_id(
merchant_context.get_merchant_account().get_id(),
&dispute,
)
.await
.to_not_found_response(errors::ApiErrorResponse::DisputeNotFound {
dispute_id: dispute,
})?,
),
None => None,
};
let connector_integration: services::BoxedFilesConnectorIntegrationInterface<
api::Retrieve,
types::RetrieveFileRequestData,
types::RetrieveFileResponse,
> = connector_data.connector.get_connector_integration();
let router_data = utils::construct_retrieve_file_router_data(
state,
merchant_context,
&file_metadata,
dispute,
connector,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed constructing the retrieve file router data")?;
let response = services::execute_connector_processing_step(
state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.to_files_failed_response()
.attach_printable("Failed while calling retrieve file connector api")?;
let retrieve_file_response =
response
.response
.map_err(|err| errors::ApiErrorResponse::ExternalConnectorError {
code: err.code,
message: err.message,
connector: connector.to_string(),
status_code: err.status_code,
reason: err.reason,
})?;
Ok(retrieve_file_response.file_data)
}
pub async fn retrieve_file_and_provider_file_id_from_file_id(
state: &SessionState,
file_id: Option<String>,
dispute_id: Option<String>,
merchant_context: &domain::MerchantContext,
is_connector_file_data_required: api::FileDataRequired,
) -> CustomResult<FileInfo, errors::ApiErrorResponse> {
match file_id {
None => Ok(FileInfo {
file_data: None,
provider_file_id: None,
file_type: None,
}),
Some(file_key) => {
let file_metadata_object = state
.store
.find_file_metadata_by_merchant_id_file_id(
merchant_context.get_merchant_account().get_id(),
&file_key,
)
.await
.change_context(errors::ApiErrorResponse::FileNotFound)?;
let (provider, provider_file_id) = match (
file_metadata_object.file_upload_provider,
file_metadata_object.provider_file_id.clone(),
file_metadata_object.available,
) {
(Some(provider), Some(provider_file_id), true) => (provider, provider_file_id),
_ => Err(errors::ApiErrorResponse::FileNotAvailable)
.attach_printable("File not available")?,
};
match provider {
diesel_models::enums::FileUploadProvider::Router => Ok(FileInfo {
file_data: Some(
state
.file_storage_client
.retrieve_file(&provider_file_id)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?,
),
provider_file_id: Some(provider_file_id),
file_type: Some(file_metadata_object.file_type),
}),
_ => {
let connector_file_data = match is_connector_file_data_required {
api::FileDataRequired::Required => Some(
retrieve_file_from_connector(
state,
file_metadata_object.clone(),
dispute_id,
merchant_context,
)
.await?,
),
api::FileDataRequired::NotRequired => None,
};
Ok(FileInfo {
file_data: connector_file_data,
provider_file_id: Some(provider_file_id),
file_type: Some(file_metadata_object.file_type),
})
}
}
}
}
}
#[cfg(feature = "v2")]
//Upload file to connector if it supports / store it in S3 and return file_upload_provider, provider_file_id accordingly
pub async fn upload_and_get_provider_provider_file_id_profile_id(
state: &SessionState,
merchant_context: &domain::MerchantContext,
create_file_request: &api::CreateFileRequest,
file_key: String,
) -> CustomResult<
(
String,
api_models::enums::FileUploadProvider,
Option<common_utils::id_type::ProfileId>,
Option<common_utils::id_type::MerchantConnectorAccountId>,
),
errors::ApiErrorResponse,
> {
todo!()
}
#[cfg(feature = "v1")]
//Upload file to connector if it supports / store it in S3 and return file_upload_provider, provider_file_id accordingly
pub async fn upload_and_get_provider_provider_file_id_profile_id(
state: &SessionState,
merchant_context: &domain::MerchantContext,
create_file_request: &api::CreateFileRequest,
file_key: String,
) -> CustomResult<
(
String,
api_models::enums::FileUploadProvider,
Option<common_utils::id_type::ProfileId>,
Option<common_utils::id_type::MerchantConnectorAccountId>,
),
errors::ApiErrorResponse,
> {
match create_file_request.purpose {
api::FilePurpose::DisputeEvidence => {
let dispute_id = create_file_request
.dispute_id
.clone()
.ok_or(errors::ApiErrorResponse::MissingDisputeId)?;
let dispute = state
.store
.find_dispute_by_merchant_id_dispute_id(
merchant_context.get_merchant_account().get_id(),
&dispute_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::DisputeNotFound { dispute_id })?;
let connector_data = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
&dispute.connector,
api::GetToken::Connector,
dispute.merchant_connector_id.clone(),
)?;
if connector_data.connector_name.supports_file_storage_module() {
let payment_intent = state
.store
.find_payment_intent_by_payment_id_merchant_id(
&state.into(),
&dispute.payment_id,
merchant_context.get_merchant_account().get_id(),
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
let payment_attempt = state
.store
.find_payment_attempt_by_attempt_id_merchant_id(
&dispute.attempt_id,
merchant_context.get_merchant_account().get_id(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
let connector_integration: services::BoxedFilesConnectorIntegrationInterface<
api::Upload,
types::UploadFileRequestData,
types::UploadFileResponse,
> = connector_data.connector.get_connector_integration();
let router_data = utils::construct_upload_file_router_data(
state,
&payment_intent,
&payment_attempt,
merchant_context,
create_file_request,
dispute,
&connector_data.connector_name.to_string(),
file_key,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed constructing the upload file router data")?;
let response = services::execute_connector_processing_step(
state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while calling upload file connector api")?;
let upload_file_response = response.response.map_err(|err| {
errors::ApiErrorResponse::ExternalConnectorError {
code: err.code,
message: err.message,
connector: connector_data.connector_name.to_string(),
status_code: err.status_code,
reason: err.reason,
}
})?;
Ok((
upload_file_response.provider_file_id,
api_models::enums::FileUploadProvider::foreign_try_from(
&connector_data.connector_name,
)?,
payment_intent.profile_id,
payment_attempt.merchant_connector_id,
))
} else {
state
.file_storage_client
.upload_file(&file_key, create_file_request.file.clone())
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?;
Ok((
file_key,
api_models::enums::FileUploadProvider::Router,
None,
None,
))
}
}
}
}
|
crates/router/src/core/files/helpers.rs
|
router::src::core::files::helpers
| 2,855
| true
|
// File: crates/router/src/core/payment_link/validator.rs
// Module: router::src::core::payment_link::validator
use actix_http::header;
use api_models::admin::PaymentLinkConfig;
use common_utils::validation::validate_domain_against_allowed_domains;
use error_stack::{report, ResultExt};
use url::Url;
use crate::{
core::errors::{self, RouterResult},
types::storage::PaymentLink,
};
pub fn validate_secure_payment_link_render_request(
request_headers: &header::HeaderMap,
payment_link: &PaymentLink,
payment_link_config: &PaymentLinkConfig,
) -> RouterResult<()> {
let link_id = payment_link.payment_link_id.clone();
let allowed_domains = payment_link_config
.allowed_domains
.clone()
.ok_or(report!(errors::ApiErrorResponse::InvalidRequestUrl))
.attach_printable_lazy(|| {
format!("Secure payment link was not generated for {link_id}\nmissing allowed_domains")
})?;
// Validate secure_link was generated
if payment_link.secure_link.clone().is_none() {
return Err(report!(errors::ApiErrorResponse::InvalidRequestUrl)).attach_printable_lazy(
|| format!("Secure payment link was not generated for {link_id}\nmissing secure_link"),
);
}
// Fetch destination is "iframe"
match request_headers.get("sec-fetch-dest").and_then(|v| v.to_str().ok()) {
Some("iframe") => Ok(()),
Some(requestor) => Err(report!(errors::ApiErrorResponse::AccessForbidden {
resource: "payment_link".to_string(),
}))
.attach_printable_lazy(|| {
format!(
"Access to payment_link [{link_id}] is forbidden when requested through {requestor}",
)
}),
None => Err(report!(errors::ApiErrorResponse::AccessForbidden {
resource: "payment_link".to_string(),
}))
.attach_printable_lazy(|| {
format!(
"Access to payment_link [{link_id}] is forbidden when sec-fetch-dest is not present in request headers",
)
}),
}?;
// Validate origin / referer
let domain_in_req = {
let origin_or_referer = request_headers
.get("origin")
.or_else(|| request_headers.get("referer"))
.and_then(|v| v.to_str().ok())
.ok_or_else(|| {
report!(errors::ApiErrorResponse::AccessForbidden {
resource: "payment_link".to_string(),
})
})
.attach_printable_lazy(|| {
format!(
"Access to payment_link [{link_id}] is forbidden when origin or referer is not present in request headers",
)
})?;
let url = Url::parse(origin_or_referer)
.map_err(|_| {
report!(errors::ApiErrorResponse::AccessForbidden {
resource: "payment_link".to_string(),
})
})
.attach_printable_lazy(|| {
format!("Invalid URL found in request headers {origin_or_referer}")
})?;
url.host_str()
.and_then(|host| url.port().map(|port| format!("{host}:{port}")))
.or_else(|| url.host_str().map(String::from))
.ok_or_else(|| {
report!(errors::ApiErrorResponse::AccessForbidden {
resource: "payment_link".to_string(),
})
})
.attach_printable_lazy(|| {
format!("host or port not found in request headers {url:?}")
})?
};
if validate_domain_against_allowed_domains(&domain_in_req, allowed_domains) {
Ok(())
} else {
Err(report!(errors::ApiErrorResponse::AccessForbidden {
resource: "payment_link".to_string(),
}))
.attach_printable_lazy(|| {
format!(
"Access to payment_link [{link_id}] is forbidden from requestor - {domain_in_req}",
)
})
}
}
|
crates/router/src/core/payment_link/validator.rs
|
router::src::core::payment_link::validator
| 831
| true
|
// File: crates/router/src/core/routing/transformers.rs
// Module: router::src::core::routing::transformers
use api_models::routing::{
DynamicRoutingAlgorithm, MerchantRoutingAlgorithm, RoutingAlgorithmKind,
RoutingAlgorithmWrapper, RoutingDictionaryRecord,
};
#[cfg(feature = "v1")]
use api_models::{
open_router::{OpenRouterDecideGatewayRequest, PaymentInfo, RankingAlgorithm},
routing::RoutableConnectorChoice,
};
use common_utils::ext_traits::ValueExt;
use diesel_models::{
enums as storage_enums,
routing_algorithm::{RoutingAlgorithm, RoutingProfileMetadata},
};
#[cfg(feature = "v1")]
use hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt;
use masking::{PeekInterface, Secret};
use crate::{
core::{errors, routing},
types::transformers::{ForeignFrom, ForeignInto, ForeignTryFrom},
};
impl ForeignFrom<RoutingProfileMetadata> for RoutingDictionaryRecord {
fn foreign_from(value: RoutingProfileMetadata) -> Self {
Self {
id: value.algorithm_id,
profile_id: value.profile_id,
name: value.name,
kind: value.kind.foreign_into(),
description: value.description.unwrap_or_default(),
created_at: value.created_at.assume_utc().unix_timestamp(),
modified_at: value.modified_at.assume_utc().unix_timestamp(),
algorithm_for: Some(value.algorithm_for),
decision_engine_routing_id: None,
}
}
}
impl ForeignFrom<RoutingAlgorithm> for RoutingDictionaryRecord {
fn foreign_from(value: RoutingAlgorithm) -> Self {
Self {
id: value.algorithm_id,
profile_id: value.profile_id,
name: value.name,
kind: value.kind.foreign_into(),
description: value.description.unwrap_or_default(),
created_at: value.created_at.assume_utc().unix_timestamp(),
modified_at: value.modified_at.assume_utc().unix_timestamp(),
algorithm_for: Some(value.algorithm_for),
decision_engine_routing_id: value.decision_engine_routing_id,
}
}
}
impl ForeignTryFrom<RoutingAlgorithm> for MerchantRoutingAlgorithm {
type Error = error_stack::Report<errors::ParsingError>;
fn foreign_try_from(value: RoutingAlgorithm) -> Result<Self, Self::Error> {
let algorithm: RoutingAlgorithmWrapper = match value.kind {
diesel_models::enums::RoutingAlgorithmKind::Dynamic => value
.algorithm_data
.parse_value::<DynamicRoutingAlgorithm>("RoutingAlgorithmDynamic")
.map(RoutingAlgorithmWrapper::Dynamic)?,
_ => value
.algorithm_data
.parse_value::<api_models::routing::StaticRoutingAlgorithm>("RoutingAlgorithm")
.map(RoutingAlgorithmWrapper::Static)?,
};
Ok(Self {
id: value.algorithm_id,
name: value.name,
profile_id: value.profile_id,
description: value.description.unwrap_or_default(),
algorithm,
created_at: value.created_at.assume_utc().unix_timestamp(),
modified_at: value.modified_at.assume_utc().unix_timestamp(),
algorithm_for: value.algorithm_for,
})
}
}
impl ForeignFrom<storage_enums::RoutingAlgorithmKind> for RoutingAlgorithmKind {
fn foreign_from(value: storage_enums::RoutingAlgorithmKind) -> Self {
match value {
storage_enums::RoutingAlgorithmKind::Single => Self::Single,
storage_enums::RoutingAlgorithmKind::Priority => Self::Priority,
storage_enums::RoutingAlgorithmKind::VolumeSplit => Self::VolumeSplit,
storage_enums::RoutingAlgorithmKind::Advanced => Self::Advanced,
storage_enums::RoutingAlgorithmKind::Dynamic => Self::Dynamic,
storage_enums::RoutingAlgorithmKind::ThreeDsDecisionRule => Self::ThreeDsDecisionRule,
}
}
}
impl ForeignFrom<RoutingAlgorithmKind> for storage_enums::RoutingAlgorithmKind {
fn foreign_from(value: RoutingAlgorithmKind) -> Self {
match value {
RoutingAlgorithmKind::Single => Self::Single,
RoutingAlgorithmKind::Priority => Self::Priority,
RoutingAlgorithmKind::VolumeSplit => Self::VolumeSplit,
RoutingAlgorithmKind::Advanced => Self::Advanced,
RoutingAlgorithmKind::Dynamic => Self::Dynamic,
RoutingAlgorithmKind::ThreeDsDecisionRule => Self::ThreeDsDecisionRule,
}
}
}
impl From<&routing::TransactionData<'_>> for storage_enums::TransactionType {
fn from(value: &routing::TransactionData<'_>) -> Self {
match value {
routing::TransactionData::Payment(_) => Self::Payment,
#[cfg(feature = "payouts")]
routing::TransactionData::Payout(_) => Self::Payout,
}
}
}
#[cfg(feature = "v1")]
pub trait OpenRouterDecideGatewayRequestExt {
fn construct_sr_request(
attempt: &PaymentAttempt,
eligible_gateway_list: Vec<RoutableConnectorChoice>,
ranking_algorithm: Option<RankingAlgorithm>,
is_elimination_enabled: bool,
) -> Self
where
Self: Sized;
fn construct_debit_request(
attempt: &PaymentAttempt,
metadata: Option<String>,
card_isin: Option<Secret<String>>,
ranking_algorithm: Option<RankingAlgorithm>,
) -> Self
where
Self: Sized;
}
#[cfg(feature = "v1")]
impl OpenRouterDecideGatewayRequestExt for OpenRouterDecideGatewayRequest {
fn construct_sr_request(
attempt: &PaymentAttempt,
eligible_gateway_list: Vec<RoutableConnectorChoice>,
ranking_algorithm: Option<RankingAlgorithm>,
is_elimination_enabled: bool,
) -> Self {
Self {
payment_info: PaymentInfo {
payment_id: attempt.payment_id.clone(),
amount: attempt.net_amount.get_order_amount(),
currency: attempt.currency.unwrap_or(storage_enums::Currency::USD),
payment_type: "ORDER_PAYMENT".to_string(),
payment_method_type: "UPI".into(), // TODO: once open-router makes this field string, we can send from attempt
payment_method: attempt.payment_method.unwrap_or_default(),
metadata: None,
card_isin: None,
},
merchant_id: attempt.profile_id.clone(),
eligible_gateway_list: Some(
eligible_gateway_list
.into_iter()
.map(|connector| connector.to_string())
.collect(),
),
ranking_algorithm,
elimination_enabled: Some(is_elimination_enabled),
}
}
fn construct_debit_request(
attempt: &PaymentAttempt,
metadata: Option<String>,
card_isin: Option<Secret<String>>,
ranking_algorithm: Option<RankingAlgorithm>,
) -> Self {
Self {
payment_info: PaymentInfo {
payment_id: attempt.payment_id.clone(),
amount: attempt.net_amount.get_total_amount(),
currency: attempt.currency.unwrap_or(storage_enums::Currency::USD),
payment_type: "ORDER_PAYMENT".to_string(),
card_isin: card_isin.map(|value| value.peek().clone()),
metadata,
payment_method_type: "UPI".into(), // TODO: once open-router makes this field string, we can send from attempt
payment_method: attempt.payment_method.unwrap_or_default(),
},
merchant_id: attempt.profile_id.clone(),
// eligible gateway list is not used in debit routing
eligible_gateway_list: None,
ranking_algorithm,
elimination_enabled: None,
}
}
}
|
crates/router/src/core/routing/transformers.rs
|
router::src::core::routing::transformers
| 1,550
| true
|
// File: crates/router/src/core/routing/helpers.rs
// Module: router::src::core::routing::helpers
//! Analysis for usage of all helper functions for use case of routing
//!
//! Functions that are used to perform the retrieval of merchant's
//! routing dict, configs, defaults
use std::fmt::Debug;
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
use std::str::FromStr;
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
use std::sync::Arc;
#[cfg(feature = "v1")]
use api_models::open_router;
use api_models::routing as routing_types;
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
use common_utils::ext_traits::ValueExt;
use common_utils::{ext_traits::Encode, id_type, types::keymanager::KeyManagerState};
use diesel_models::configs;
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
use diesel_models::dynamic_routing_stats::{DynamicRoutingStatsNew, DynamicRoutingStatsUpdate};
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
use diesel_models::routing_algorithm;
use error_stack::ResultExt;
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
use external_services::grpc_client::dynamic_routing::{
contract_routing_client::ContractBasedDynamicRouting,
elimination_based_client::EliminationBasedRouting,
success_rate_client::SuccessBasedDynamicRouting,
};
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
use hyperswitch_domain_models::api::ApplicationResponse;
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
use hyperswitch_interfaces::events::routing_api_logs as routing_events;
#[cfg(feature = "v1")]
use router_env::logger;
#[cfg(feature = "v1")]
use router_env::{instrument, tracing};
use rustc_hash::FxHashSet;
use storage_impl::redis::cache;
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
use storage_impl::redis::cache::Cacheable;
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
use crate::db::errors::StorageErrorExt;
#[cfg(feature = "v2")]
use crate::types::domain::MerchantConnectorAccount;
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
use crate::types::transformers::ForeignFrom;
use crate::{
core::errors::{self, RouterResult},
db::StorageInterface,
routes::SessionState,
types::{domain, storage},
utils::StringExt,
};
#[cfg(feature = "v1")]
use crate::{
core::payments::{
routing::utils::{self as routing_utils, DecisionEngineApiHandler},
OperationSessionGetters, OperationSessionSetters,
},
services,
};
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
use crate::{
core::{metrics as core_metrics, routing},
routes::app::SessionStateInfo,
types::transformers::ForeignInto,
};
pub const SUCCESS_BASED_DYNAMIC_ROUTING_ALGORITHM: &str =
"Success rate based dynamic routing algorithm";
pub const ELIMINATION_BASED_DYNAMIC_ROUTING_ALGORITHM: &str =
"Elimination based dynamic routing algorithm";
pub const CONTRACT_BASED_DYNAMIC_ROUTING_ALGORITHM: &str =
"Contract based dynamic routing algorithm";
pub const DECISION_ENGINE_RULE_CREATE_ENDPOINT: &str = "rule/create";
pub const DECISION_ENGINE_RULE_UPDATE_ENDPOINT: &str = "rule/update";
pub const DECISION_ENGINE_RULE_GET_ENDPOINT: &str = "rule/get";
pub const DECISION_ENGINE_RULE_DELETE_ENDPOINT: &str = "rule/delete";
pub const DECISION_ENGINE_MERCHANT_BASE_ENDPOINT: &str = "merchant-account";
pub const DECISION_ENGINE_MERCHANT_CREATE_ENDPOINT: &str = "merchant-account/create";
/// Provides us with all the configured configs of the Merchant in the ascending time configured
/// manner and chooses the first of them
pub async fn get_merchant_default_config(
db: &dyn StorageInterface,
// Cannot make this as merchant id domain type because, we are passing profile id also here
merchant_id: &str,
transaction_type: &storage::enums::TransactionType,
) -> RouterResult<Vec<routing_types::RoutableConnectorChoice>> {
let key = get_default_config_key(merchant_id, transaction_type);
let maybe_config = db.find_config_by_key(&key).await;
match maybe_config {
Ok(config) => config
.config
.parse_struct("Vec<RoutableConnectors>")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Merchant default config has invalid structure"),
Err(e) if e.current_context().is_db_not_found() => {
let new_config_conns = Vec::<routing_types::RoutableConnectorChoice>::new();
let serialized = new_config_conns
.encode_to_string_of_json()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Error while creating and serializing new merchant default config",
)?;
let new_config = configs::ConfigNew {
key,
config: serialized,
};
db.insert_config(new_config)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error inserting new default routing config into DB")?;
Ok(new_config_conns)
}
Err(e) => Err(e)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error fetching default config for merchant"),
}
}
/// Merchant's already created config can be updated and this change will be reflected
/// in DB as well for the particular updated config
pub async fn update_merchant_default_config(
db: &dyn StorageInterface,
merchant_id: &str,
connectors: Vec<routing_types::RoutableConnectorChoice>,
transaction_type: &storage::enums::TransactionType,
) -> RouterResult<()> {
let key = get_default_config_key(merchant_id, transaction_type);
let config_str = connectors
.encode_to_string_of_json()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to serialize merchant default routing config during update")?;
let config_update = configs::ConfigUpdate::Update {
config: Some(config_str),
};
db.update_config_by_key(&key, config_update)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating the default routing config in DB")?;
Ok(())
}
pub async fn update_merchant_routing_dictionary(
db: &dyn StorageInterface,
merchant_id: &str,
dictionary: routing_types::RoutingDictionary,
) -> RouterResult<()> {
let key = get_routing_dictionary_key(merchant_id);
let dictionary_str = dictionary
.encode_to_string_of_json()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to serialize routing dictionary during update")?;
let config_update = configs::ConfigUpdate::Update {
config: Some(dictionary_str),
};
db.update_config_by_key(&key, config_update)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error saving routing dictionary to DB")?;
Ok(())
}
/// This will help make one of all configured algorithms to be in active state for a particular
/// merchant
#[cfg(feature = "v1")]
pub async fn update_merchant_active_algorithm_ref(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
config_key: cache::CacheKind<'_>,
algorithm_id: routing_types::RoutingAlgorithmRef,
) -> RouterResult<()> {
let ref_value = algorithm_id
.encode_to_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed converting routing algorithm ref to json value")?;
let merchant_account_update = storage::MerchantAccountUpdate::Update {
merchant_name: None,
merchant_details: None,
return_url: None,
webhook_details: None,
sub_merchants_enabled: None,
parent_merchant_id: None,
enable_payment_response_hash: None,
payment_response_hash_key: None,
redirect_to_merchant_with_http_post: None,
publishable_key: None,
locker_id: None,
metadata: None,
routing_algorithm: Some(ref_value),
primary_business_details: None,
intent_fulfillment_time: None,
frm_routing_algorithm: None,
payout_routing_algorithm: None,
default_profile: None,
payment_link_config: None,
pm_collect_link_config: None,
};
let db = &*state.store;
db.update_specific_fields_in_merchant(
&state.into(),
&key_store.merchant_id,
merchant_account_update,
key_store,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update routing algorithm ref in merchant account")?;
cache::redact_from_redis_and_publish(db.get_cache_store().as_ref(), [config_key])
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to invalidate the config cache")?;
Ok(())
}
#[cfg(feature = "v1")]
pub async fn update_profile_active_algorithm_ref(
db: &dyn StorageInterface,
key_manager_state: &KeyManagerState,
merchant_key_store: &domain::MerchantKeyStore,
current_business_profile: domain::Profile,
algorithm_id: routing_types::RoutingAlgorithmRef,
transaction_type: &storage::enums::TransactionType,
) -> RouterResult<()> {
let ref_val = algorithm_id
.encode_to_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to convert routing ref to value")?;
let merchant_id = current_business_profile.merchant_id.clone();
let profile_id = current_business_profile.get_id().to_owned();
let (routing_algorithm, payout_routing_algorithm, three_ds_decision_rule_algorithm) =
match transaction_type {
storage::enums::TransactionType::Payment => (Some(ref_val), None, None),
#[cfg(feature = "payouts")]
storage::enums::TransactionType::Payout => (None, Some(ref_val), None),
storage::enums::TransactionType::ThreeDsAuthentication => (None, None, Some(ref_val)),
};
let business_profile_update = domain::ProfileUpdate::RoutingAlgorithmUpdate {
routing_algorithm,
payout_routing_algorithm,
three_ds_decision_rule_algorithm,
};
db.update_profile_by_profile_id(
key_manager_state,
merchant_key_store,
current_business_profile,
business_profile_update,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update routing algorithm ref in business profile")?;
// Invalidate the routing cache for Payments and Payouts transaction types
if !transaction_type.is_three_ds_authentication() {
let routing_cache_key = cache::CacheKind::Routing(
format!(
"routing_config_{}_{}",
merchant_id.get_string_repr(),
profile_id.get_string_repr(),
)
.into(),
);
cache::redact_from_redis_and_publish(db.get_cache_store().as_ref(), [routing_cache_key])
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to invalidate routing cache")?;
}
Ok(())
}
#[cfg(feature = "v1")]
pub async fn update_business_profile_active_dynamic_algorithm_ref(
db: &dyn StorageInterface,
key_manager_state: &KeyManagerState,
merchant_key_store: &domain::MerchantKeyStore,
current_business_profile: domain::Profile,
dynamic_routing_algorithm_ref: routing_types::DynamicRoutingAlgorithmRef,
) -> RouterResult<()> {
let ref_val = dynamic_routing_algorithm_ref
.encode_to_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to convert dynamic routing ref to value")?;
let business_profile_update = domain::ProfileUpdate::DynamicRoutingAlgorithmUpdate {
dynamic_routing_algorithm: Some(ref_val),
};
db.update_profile_by_profile_id(
key_manager_state,
merchant_key_store,
current_business_profile,
business_profile_update,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update dynamic routing algorithm ref in business profile")?;
Ok(())
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug)]
pub struct RoutingAlgorithmHelpers<'h> {
pub name_mca_id_set: ConnectNameAndMCAIdForProfile<'h>,
pub name_set: ConnectNameForProfile<'h>,
pub routing_algorithm: &'h routing_types::StaticRoutingAlgorithm,
}
#[cfg(feature = "v1")]
pub enum RoutingDecisionData {
DebitRouting(DebitRoutingDecisionData),
}
#[cfg(feature = "v1")]
pub struct DebitRoutingDecisionData {
pub card_network: common_enums::enums::CardNetwork,
pub debit_routing_result: Option<open_router::DebitRoutingOutput>,
}
#[cfg(feature = "v1")]
impl RoutingDecisionData {
pub fn apply_routing_decision<F, D>(&self, payment_data: &mut D)
where
F: Send + Clone,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
{
match self {
Self::DebitRouting(data) => data.apply_debit_routing_decision(payment_data),
}
}
pub fn get_debit_routing_decision_data(
network: common_enums::enums::CardNetwork,
debit_routing_result: Option<open_router::DebitRoutingOutput>,
) -> Self {
Self::DebitRouting(DebitRoutingDecisionData {
card_network: network,
debit_routing_result,
})
}
}
#[cfg(feature = "v1")]
impl DebitRoutingDecisionData {
pub fn apply_debit_routing_decision<F, D>(&self, payment_data: &mut D)
where
F: Send + Clone,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
{
payment_data.set_card_network(self.card_network.clone());
self.debit_routing_result
.as_ref()
.map(|data| payment_data.set_co_badged_card_data(data));
}
}
#[derive(Clone, Debug)]
pub struct ConnectNameAndMCAIdForProfile<'a>(
pub FxHashSet<(
&'a common_enums::connector_enums::Connector,
id_type::MerchantConnectorAccountId,
)>,
);
#[derive(Clone, Debug)]
pub struct ConnectNameForProfile<'a>(pub FxHashSet<&'a common_enums::connector_enums::Connector>);
#[cfg(feature = "v2")]
impl RoutingAlgorithmHelpers<'_> {
fn connector_choice(
&self,
choice: &routing_types::RoutableConnectorChoice,
) -> RouterResult<()> {
if let Some(ref mca_id) = choice.merchant_connector_id {
let connector_choice = common_enums::connector_enums::Connector::from(choice.connector);
error_stack::ensure!(
self.name_mca_id_set.0.contains(&(&connector_choice, mca_id.clone())),
errors::ApiErrorResponse::InvalidRequestData {
message: format!(
"connector with name '{connector_choice}' and merchant connector account id '{mca_id:?}' not found for the given profile",
)
}
);
} else {
let connector_choice = common_enums::connector_enums::Connector::from(choice.connector);
error_stack::ensure!(
self.name_set.0.contains(&connector_choice),
errors::ApiErrorResponse::InvalidRequestData {
message: format!(
"connector with name '{connector_choice}' not found for the given profile",
)
}
);
};
Ok(())
}
pub fn validate_connectors_in_routing_config(&self) -> RouterResult<()> {
match self.routing_algorithm {
routing_types::StaticRoutingAlgorithm::Single(choice) => {
self.connector_choice(choice)?;
}
routing_types::StaticRoutingAlgorithm::Priority(list) => {
for choice in list {
self.connector_choice(choice)?;
}
}
routing_types::StaticRoutingAlgorithm::VolumeSplit(splits) => {
for split in splits {
self.connector_choice(&split.connector)?;
}
}
routing_types::StaticRoutingAlgorithm::Advanced(program) => {
let check_connector_selection =
|selection: &routing_types::ConnectorSelection| -> RouterResult<()> {
match selection {
routing_types::ConnectorSelection::VolumeSplit(splits) => {
for split in splits {
self.connector_choice(&split.connector)?;
}
}
routing_types::ConnectorSelection::Priority(list) => {
for choice in list {
self.connector_choice(choice)?;
}
}
}
Ok(())
};
check_connector_selection(&program.default_selection)?;
for rule in &program.rules {
check_connector_selection(&rule.connector_selection)?;
}
}
routing_types::StaticRoutingAlgorithm::ThreeDsDecisionRule(_) => {
return Err(errors::ApiErrorResponse::InternalServerError).attach_printable(
"Invalid routing algorithm three_ds decision rule received",
)?;
}
}
Ok(())
}
}
#[cfg(feature = "v1")]
pub async fn validate_connectors_in_routing_config(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
merchant_id: &id_type::MerchantId,
profile_id: &id_type::ProfileId,
routing_algorithm: &routing_types::StaticRoutingAlgorithm,
) -> RouterResult<()> {
let all_mcas = state
.store
.find_merchant_connector_account_by_merchant_id_and_disabled_list(
&state.into(),
merchant_id,
true,
key_store,
)
.await
.change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: merchant_id.get_string_repr().to_owned(),
})?;
let name_mca_id_set = all_mcas
.iter()
.filter(|mca| mca.profile_id == *profile_id)
.map(|mca| (&mca.connector_name, mca.get_id()))
.collect::<FxHashSet<_>>();
let name_set = all_mcas
.iter()
.filter(|mca| mca.profile_id == *profile_id)
.map(|mca| &mca.connector_name)
.collect::<FxHashSet<_>>();
let connector_choice = |choice: &routing_types::RoutableConnectorChoice| {
if let Some(ref mca_id) = choice.merchant_connector_id {
error_stack::ensure!(
name_mca_id_set.contains(&(&choice.connector.to_string(), mca_id.clone())),
errors::ApiErrorResponse::InvalidRequestData {
message: format!(
"connector with name '{}' and merchant connector account id '{:?}' not found for the given profile",
choice.connector,
mca_id,
)
}
);
} else {
error_stack::ensure!(
name_set.contains(&choice.connector.to_string()),
errors::ApiErrorResponse::InvalidRequestData {
message: format!(
"connector with name '{}' not found for the given profile",
choice.connector,
)
}
);
}
Ok(())
};
match routing_algorithm {
routing_types::StaticRoutingAlgorithm::Single(choice) => {
connector_choice(choice)?;
}
routing_types::StaticRoutingAlgorithm::Priority(list) => {
for choice in list {
connector_choice(choice)?;
}
}
routing_types::StaticRoutingAlgorithm::VolumeSplit(splits) => {
for split in splits {
connector_choice(&split.connector)?;
}
}
routing_types::StaticRoutingAlgorithm::Advanced(program) => {
let check_connector_selection =
|selection: &routing_types::ConnectorSelection| -> RouterResult<()> {
match selection {
routing_types::ConnectorSelection::VolumeSplit(splits) => {
for split in splits {
connector_choice(&split.connector)?;
}
}
routing_types::ConnectorSelection::Priority(list) => {
for choice in list {
connector_choice(choice)?;
}
}
}
Ok(())
};
check_connector_selection(&program.default_selection)?;
for rule in &program.rules {
check_connector_selection(&rule.connector_selection)?;
}
}
routing_types::StaticRoutingAlgorithm::ThreeDsDecisionRule(_) => {
Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Invalid routing algorithm three_ds decision rule received")?
}
}
Ok(())
}
/// Provides the identifier for the specific merchant's routing_dictionary_key
#[inline(always)]
pub fn get_routing_dictionary_key(merchant_id: &str) -> String {
format!("routing_dict_{merchant_id}")
}
/// Provides the identifier for the specific merchant's default_config
#[inline(always)]
pub fn get_default_config_key(
merchant_id: &str,
transaction_type: &storage::enums::TransactionType,
) -> String {
match transaction_type {
storage::enums::TransactionType::Payment => format!("routing_default_{merchant_id}"),
#[cfg(feature = "payouts")]
storage::enums::TransactionType::Payout => format!("routing_default_po_{merchant_id}"),
storage::enums::TransactionType::ThreeDsAuthentication => {
format!("three_ds_authentication_{merchant_id}")
}
}
}
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
#[async_trait::async_trait]
pub trait DynamicRoutingCache {
async fn get_cached_dynamic_routing_config_for_profile(
state: &SessionState,
key: &str,
) -> Option<Arc<Self>>;
async fn refresh_dynamic_routing_cache<T, F, Fut>(
state: &SessionState,
key: &str,
func: F,
) -> RouterResult<T>
where
F: FnOnce() -> Fut + Send,
T: Cacheable + serde::Serialize + serde::de::DeserializeOwned + Debug + Clone,
Fut: futures::Future<Output = errors::CustomResult<T, errors::StorageError>> + Send;
}
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
#[async_trait::async_trait]
impl DynamicRoutingCache for routing_types::SuccessBasedRoutingConfig {
async fn get_cached_dynamic_routing_config_for_profile(
state: &SessionState,
key: &str,
) -> Option<Arc<Self>> {
cache::SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE
.get_val::<Arc<Self>>(cache::CacheKey {
key: key.to_string(),
prefix: state.tenant.redis_key_prefix.clone(),
})
.await
}
async fn refresh_dynamic_routing_cache<T, F, Fut>(
state: &SessionState,
key: &str,
func: F,
) -> RouterResult<T>
where
F: FnOnce() -> Fut + Send,
T: Cacheable + serde::Serialize + serde::de::DeserializeOwned + Debug + Clone,
Fut: futures::Future<Output = errors::CustomResult<T, errors::StorageError>> + Send,
{
cache::get_or_populate_in_memory(
state.store.get_cache_store().as_ref(),
key,
func,
&cache::SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to populate SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE")
}
}
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
#[async_trait::async_trait]
impl DynamicRoutingCache for routing_types::ContractBasedRoutingConfig {
async fn get_cached_dynamic_routing_config_for_profile(
state: &SessionState,
key: &str,
) -> Option<Arc<Self>> {
cache::CONTRACT_BASED_DYNAMIC_ALGORITHM_CACHE
.get_val::<Arc<Self>>(cache::CacheKey {
key: key.to_string(),
prefix: state.tenant.redis_key_prefix.clone(),
})
.await
}
async fn refresh_dynamic_routing_cache<T, F, Fut>(
state: &SessionState,
key: &str,
func: F,
) -> RouterResult<T>
where
F: FnOnce() -> Fut + Send,
T: Cacheable + serde::Serialize + serde::de::DeserializeOwned + Debug + Clone,
Fut: futures::Future<Output = errors::CustomResult<T, errors::StorageError>> + Send,
{
cache::get_or_populate_in_memory(
state.store.get_cache_store().as_ref(),
key,
func,
&cache::CONTRACT_BASED_DYNAMIC_ALGORITHM_CACHE,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to populate CONTRACT_BASED_DYNAMIC_ALGORITHM_CACHE")
}
}
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
#[async_trait::async_trait]
impl DynamicRoutingCache for routing_types::EliminationRoutingConfig {
async fn get_cached_dynamic_routing_config_for_profile(
state: &SessionState,
key: &str,
) -> Option<Arc<Self>> {
cache::ELIMINATION_BASED_DYNAMIC_ALGORITHM_CACHE
.get_val::<Arc<Self>>(cache::CacheKey {
key: key.to_string(),
prefix: state.tenant.redis_key_prefix.clone(),
})
.await
}
async fn refresh_dynamic_routing_cache<T, F, Fut>(
state: &SessionState,
key: &str,
func: F,
) -> RouterResult<T>
where
F: FnOnce() -> Fut + Send,
T: Cacheable + serde::Serialize + serde::de::DeserializeOwned + Debug + Clone,
Fut: futures::Future<Output = errors::CustomResult<T, errors::StorageError>> + Send,
{
cache::get_or_populate_in_memory(
state.store.get_cache_store().as_ref(),
key,
func,
&cache::ELIMINATION_BASED_DYNAMIC_ALGORITHM_CACHE,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to populate ELIMINATION_BASED_DYNAMIC_ALGORITHM_CACHE")
}
}
/// Cfetch dynamic routing configs
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
#[instrument(skip_all)]
pub async fn fetch_dynamic_routing_configs<T>(
state: &SessionState,
profile_id: &id_type::ProfileId,
routing_id: id_type::RoutingId,
) -> RouterResult<T>
where
T: serde::de::DeserializeOwned
+ Clone
+ DynamicRoutingCache
+ Cacheable
+ serde::Serialize
+ Debug,
{
let key = format!(
"{}_{}",
profile_id.get_string_repr(),
routing_id.get_string_repr()
);
if let Some(config) =
T::get_cached_dynamic_routing_config_for_profile(state, key.as_str()).await
{
Ok(config.as_ref().clone())
} else {
let func = || async {
let routing_algorithm = state
.store
.find_routing_algorithm_by_profile_id_algorithm_id(profile_id, &routing_id)
.await
.change_context(errors::StorageError::ValueNotFound(
"RoutingAlgorithm".to_string(),
))
.attach_printable("unable to retrieve routing_algorithm for profile from db")?;
let dynamic_routing_config = routing_algorithm
.algorithm_data
.parse_value::<T>("dynamic_routing_config")
.change_context(errors::StorageError::DeserializationFailed)
.attach_printable("unable to parse dynamic_routing_config")?;
Ok(dynamic_routing_config)
};
let dynamic_routing_config =
T::refresh_dynamic_routing_cache(state, key.as_str(), func).await?;
Ok(dynamic_routing_config)
}
}
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
#[instrument(skip_all)]
pub async fn update_gateway_score_helper_with_open_router(
state: &SessionState,
payment_attempt: &storage::PaymentAttempt,
profile_id: &id_type::ProfileId,
dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef,
) -> RouterResult<()> {
let is_success_rate_routing_enabled =
dynamic_routing_algo_ref.is_success_rate_routing_enabled();
let is_elimination_enabled = dynamic_routing_algo_ref.is_elimination_enabled();
if is_success_rate_routing_enabled || is_elimination_enabled {
let payment_connector = &payment_attempt.connector.clone().ok_or(
errors::ApiErrorResponse::GenericNotFoundError {
message: "unable to derive payment connector from payment attempt".to_string(),
},
)?;
let routable_connector = routing_types::RoutableConnectorChoice {
choice_kind: api_models::routing::RoutableChoiceKind::FullStruct,
connector: common_enums::RoutableConnectors::from_str(payment_connector.as_str())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to infer routable_connector from connector")?,
merchant_connector_id: payment_attempt.merchant_connector_id.clone(),
};
logger::debug!(
"performing update-gateway-score for gateway with id {} in open_router for profile: {}",
routable_connector,
profile_id.get_string_repr()
);
routing::payments_routing::update_gateway_score_with_open_router(
state,
routable_connector.clone(),
profile_id,
&payment_attempt.merchant_id,
&payment_attempt.payment_id,
payment_attempt.status,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed to update gateway score in open_router service")?;
}
Ok(())
}
/// metrics for success based dynamic routing
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
#[instrument(skip_all)]
pub async fn push_metrics_with_update_window_for_success_based_routing(
state: &SessionState,
payment_attempt: &storage::PaymentAttempt,
routable_connectors: Vec<routing_types::RoutableConnectorChoice>,
profile_id: &id_type::ProfileId,
dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef,
dynamic_routing_config_params_interpolator: DynamicRoutingConfigParamsInterpolator,
) -> RouterResult<()> {
if let Some(success_based_algo_ref) = dynamic_routing_algo_ref.success_based_algorithm {
if success_based_algo_ref.enabled_feature != routing_types::DynamicRoutingFeatures::None {
let client = &state
.grpc_client
.dynamic_routing
.as_ref()
.ok_or(errors::ApiErrorResponse::GenericNotFoundError {
message: "dynamic routing gRPC client not found".to_string(),
})?
.success_rate_client;
let payment_connector = &payment_attempt.connector.clone().ok_or(
errors::ApiErrorResponse::GenericNotFoundError {
message: "unable to derive payment connector from payment attempt".to_string(),
},
)?;
let routable_connector = routing_types::RoutableConnectorChoice {
choice_kind: api_models::routing::RoutableChoiceKind::FullStruct,
connector: common_enums::RoutableConnectors::from_str(payment_connector.as_str())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to infer routable_connector from connector")?,
merchant_connector_id: payment_attempt.merchant_connector_id.clone(),
};
let payment_status_attribute =
get_desired_payment_status_for_dynamic_routing_metrics(payment_attempt.status);
let success_based_routing_configs = fetch_dynamic_routing_configs::<
routing_types::SuccessBasedRoutingConfig,
>(
state,
profile_id,
success_based_algo_ref
.algorithm_id_with_timestamp
.algorithm_id
.ok_or(errors::ApiErrorResponse::GenericNotFoundError {
message: "success_rate algorithm_id not found".to_string(),
})
.attach_printable(
"success_based_routing_algorithm_id not found in business_profile",
)?,
)
.await
.change_context(errors::ApiErrorResponse::GenericNotFoundError {
message: "success_rate based dynamic routing configs not found".to_string(),
})
.attach_printable("unable to retrieve success_rate based dynamic routing configs")?;
let success_based_routing_config_params = dynamic_routing_config_params_interpolator
.get_string_val(
success_based_routing_configs
.params
.as_ref()
.ok_or(errors::RoutingError::SuccessBasedRoutingParamsNotFoundError)
.change_context(errors::ApiErrorResponse::InternalServerError)?,
);
let success_based_connectors = client
.calculate_entity_and_global_success_rate(
profile_id.get_string_repr().into(),
success_based_routing_configs.clone(),
success_based_routing_config_params.clone(),
routable_connectors.clone(),
state.get_grpc_headers(),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"unable to calculate/fetch success rate from dynamic routing service",
)?;
let first_merchant_success_based_connector = &success_based_connectors
.entity_scores_with_labels
.first()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"unable to fetch the first connector from list of connectors obtained from dynamic routing service",
)?;
let (first_merchant_success_based_connector_label, _) = first_merchant_success_based_connector.label
.split_once(':')
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable(format!(
"unable to split connector_name and mca_id from the first connector {:?} obtained from dynamic routing service",
first_merchant_success_based_connector.label
))?;
let first_global_success_based_connector = &success_based_connectors
.global_scores_with_labels
.first()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"unable to fetch the first global connector from list of connectors obtained from dynamic routing service",
)?;
let outcome = get_dynamic_routing_based_metrics_outcome_for_payment(
payment_status_attribute,
payment_connector.to_string(),
first_merchant_success_based_connector_label.to_string(),
);
core_metrics::DYNAMIC_SUCCESS_BASED_ROUTING.add(
1,
router_env::metric_attributes!(
(
"tenant",
state.tenant.tenant_id.get_string_repr().to_owned(),
),
(
"merchant_profile_id",
format!(
"{}:{}",
payment_attempt.merchant_id.get_string_repr(),
payment_attempt.profile_id.get_string_repr()
),
),
(
"merchant_specific_success_based_routing_connector",
first_merchant_success_based_connector_label.to_string(),
),
(
"merchant_specific_success_based_routing_connector_score",
first_merchant_success_based_connector.score.to_string(),
),
(
"global_success_based_routing_connector",
first_global_success_based_connector.label.to_string(),
),
(
"global_success_based_routing_connector_score",
first_global_success_based_connector.score.to_string(),
),
("payment_connector", payment_connector.to_string()),
(
"currency",
payment_attempt
.currency
.map_or_else(|| "None".to_string(), |currency| currency.to_string()),
),
(
"payment_method",
payment_attempt.payment_method.map_or_else(
|| "None".to_string(),
|payment_method| payment_method.to_string(),
),
),
(
"payment_method_type",
payment_attempt.payment_method_type.map_or_else(
|| "None".to_string(),
|payment_method_type| payment_method_type.to_string(),
),
),
(
"capture_method",
payment_attempt.capture_method.map_or_else(
|| "None".to_string(),
|capture_method| capture_method.to_string(),
),
),
(
"authentication_type",
payment_attempt.authentication_type.map_or_else(
|| "None".to_string(),
|authentication_type| authentication_type.to_string(),
),
),
("payment_status", payment_attempt.status.to_string()),
("conclusive_classification", outcome.to_string()),
),
);
logger::debug!("successfully pushed success_based_routing metrics");
let duplicate_stats = state
.store
.find_dynamic_routing_stats_optional_by_attempt_id_merchant_id(
payment_attempt.attempt_id.clone(),
&payment_attempt.merchant_id.to_owned(),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to fetch dynamic_routing_stats entry")?;
if duplicate_stats.is_some() {
let dynamic_routing_update = DynamicRoutingStatsUpdate {
amount: payment_attempt.get_total_amount(),
success_based_routing_connector: first_merchant_success_based_connector_label
.to_string(),
payment_connector: payment_connector.to_string(),
payment_method_type: payment_attempt.payment_method_type,
currency: payment_attempt.currency,
payment_method: payment_attempt.payment_method,
capture_method: payment_attempt.capture_method,
authentication_type: payment_attempt.authentication_type,
payment_status: payment_attempt.status,
conclusive_classification: outcome,
global_success_based_connector: Some(
first_global_success_based_connector.label.to_string(),
),
};
state
.store
.update_dynamic_routing_stats(
payment_attempt.attempt_id.clone(),
&payment_attempt.merchant_id.to_owned(),
dynamic_routing_update,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to update dynamic routing stats to db")?;
} else {
let dynamic_routing_stats = DynamicRoutingStatsNew {
payment_id: payment_attempt.payment_id.to_owned(),
attempt_id: payment_attempt.attempt_id.clone(),
merchant_id: payment_attempt.merchant_id.to_owned(),
profile_id: payment_attempt.profile_id.to_owned(),
amount: payment_attempt.get_total_amount(),
success_based_routing_connector: first_merchant_success_based_connector_label
.to_string(),
payment_connector: payment_connector.to_string(),
payment_method_type: payment_attempt.payment_method_type,
currency: payment_attempt.currency,
payment_method: payment_attempt.payment_method,
capture_method: payment_attempt.capture_method,
authentication_type: payment_attempt.authentication_type,
payment_status: payment_attempt.status,
conclusive_classification: outcome,
created_at: common_utils::date_time::now(),
global_success_based_connector: Some(
first_global_success_based_connector.label.to_string(),
),
};
state
.store
.insert_dynamic_routing_stat_entry(dynamic_routing_stats)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to push dynamic routing stats to db")?;
};
let label_with_status = routing_utils::UpdateLabelWithStatusEventRequest {
label: routable_connector.clone().to_string(),
status: payment_status_attribute == common_enums::AttemptStatus::Charged,
};
let event_request = routing_utils::UpdateSuccessRateWindowEventRequest {
id: payment_attempt.profile_id.get_string_repr().to_string(),
params: success_based_routing_config_params.clone(),
labels_with_status: vec![label_with_status.clone()],
global_labels_with_status: vec![label_with_status],
config: success_based_routing_configs
.config
.as_ref()
.map(routing_utils::UpdateSuccessRateWindowConfig::from),
};
let routing_events_wrapper = routing_utils::RoutingEventsWrapper::new(
state.tenant.tenant_id.clone(),
state.request_id,
payment_attempt.payment_id.get_string_repr().to_string(),
profile_id.to_owned(),
payment_attempt.merchant_id.to_owned(),
"IntelligentRouter: UpdateSuccessRateWindow".to_string(),
Some(event_request.clone()),
true,
false,
);
let closure = || async {
let update_response_result = client
.update_success_rate(
profile_id.get_string_repr().into(),
success_based_routing_configs,
success_based_routing_config_params,
vec![routing_types::RoutableConnectorChoiceWithStatus::new(
routable_connector.clone(),
payment_status_attribute == common_enums::AttemptStatus::Charged,
)],
state.get_grpc_headers(),
)
.await
.change_context(errors::RoutingError::SuccessRateCalculationError)
.attach_printable(
"unable to update success based routing window in dynamic routing service",
);
match update_response_result {
Ok(update_response) => {
let updated_resp =
routing_utils::UpdateSuccessRateWindowEventResponse::try_from(
&update_response,
)
.change_context(errors::RoutingError::RoutingEventsError { message: "Unable to convert to UpdateSuccessRateWindowEventResponse from UpdateSuccessRateWindowResponse".to_string(), status_code: 500 })?;
Ok(Some(updated_resp))
}
Err(err) => {
logger::error!(
"unable to update connector score in dynamic routing service: {:?}",
err.current_context()
);
Err(err)
}
}
};
let events_response = routing_events_wrapper
.construct_event_builder(
"SuccessRateCalculator.UpdateSuccessRateWindow".to_string(),
routing_events::RoutingEngine::IntelligentRouter,
routing_events::ApiMethod::Grpc,
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"SR-Intelligent-Router: Failed to update success rate in Intelligent-Router",
)?
.trigger_event(state, closure)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"SR-Intelligent-Router: Failed to update success rate in Intelligent-Router",
)?;
let _response: routing_utils::UpdateSuccessRateWindowEventResponse = events_response
.response
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"UpdateSuccessRateWindowEventResponse not found in RoutingEventResponse",
)?;
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,
})
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"SR-Intelligent-Router: RoutingEvent not found in RoutingEventsResponse",
)?;
routing_event.set_status_code(200);
routing_event.set_payment_connector(routable_connector); // we can do this inside the event wrap by implementing an interface on the req type
state.event_handler().log_event(&routing_event);
Ok(())
} else {
Ok(())
}
} else {
Ok(())
}
}
/// update window for elimination based dynamic routing
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
#[instrument(skip_all)]
pub async fn update_window_for_elimination_routing(
state: &SessionState,
payment_attempt: &storage::PaymentAttempt,
profile_id: &id_type::ProfileId,
dynamic_algo_ref: routing_types::DynamicRoutingAlgorithmRef,
elimination_routing_configs_params_interpolator: DynamicRoutingConfigParamsInterpolator,
gsm_error_category: common_enums::ErrorCategory,
) -> RouterResult<()> {
if let Some(elimination_algo_ref) = dynamic_algo_ref.elimination_routing_algorithm {
if elimination_algo_ref.enabled_feature != routing_types::DynamicRoutingFeatures::None {
let client = &state
.grpc_client
.dynamic_routing
.as_ref()
.ok_or(errors::ApiErrorResponse::GenericNotFoundError {
message: "dynamic routing gRPC client not found".to_string(),
})?
.elimination_based_client;
let elimination_routing_config = fetch_dynamic_routing_configs::<
routing_types::EliminationRoutingConfig,
>(
state,
profile_id,
elimination_algo_ref
.algorithm_id_with_timestamp
.algorithm_id
.ok_or(errors::ApiErrorResponse::GenericNotFoundError {
message: "elimination routing algorithm_id not found".to_string(),
})
.attach_printable(
"elimination_routing_algorithm_id not found in business_profile",
)?,
)
.await
.change_context(errors::ApiErrorResponse::GenericNotFoundError {
message: "elimination based dynamic routing configs not found".to_string(),
})
.attach_printable("unable to retrieve success_rate based dynamic routing configs")?;
let payment_connector = &payment_attempt.connector.clone().ok_or(
errors::ApiErrorResponse::GenericNotFoundError {
message: "unable to derive payment connector from payment attempt".to_string(),
},
)?;
let elimination_routing_config_params = elimination_routing_configs_params_interpolator
.get_string_val(
elimination_routing_config
.params
.as_ref()
.ok_or(errors::RoutingError::EliminationBasedRoutingParamsNotFoundError)
.change_context(errors::ApiErrorResponse::InternalServerError)?,
);
let labels_with_bucket_name =
vec![routing_types::RoutableConnectorChoiceWithBucketName::new(
routing_types::RoutableConnectorChoice {
choice_kind: api_models::routing::RoutableChoiceKind::FullStruct,
connector: common_enums::RoutableConnectors::from_str(
payment_connector.as_str(),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to infer routable_connector from connector")?,
merchant_connector_id: payment_attempt.merchant_connector_id.clone(),
},
gsm_error_category.to_string(),
)];
let event_request = routing_utils::UpdateEliminationBucketEventRequest {
id: profile_id.get_string_repr().to_string(),
params: elimination_routing_config_params.clone(),
labels_with_bucket_name: labels_with_bucket_name
.iter()
.map(|conn_choice| {
routing_utils::LabelWithBucketNameEventRequest::from(conn_choice)
})
.collect(),
config: elimination_routing_config
.elimination_analyser_config
.as_ref()
.map(routing_utils::EliminationRoutingEventBucketConfig::from),
};
let routing_events_wrapper = routing_utils::RoutingEventsWrapper::new(
state.tenant.tenant_id.clone(),
state.request_id,
payment_attempt.payment_id.get_string_repr().to_string(),
profile_id.to_owned(),
payment_attempt.merchant_id.to_owned(),
"IntelligentRouter: UpdateEliminationBucket".to_string(),
Some(event_request.clone()),
true,
false,
);
let closure = || async {
let update_response_result = client
.update_elimination_bucket_config(
profile_id.get_string_repr().to_string(),
elimination_routing_config_params,
labels_with_bucket_name,
elimination_routing_config.elimination_analyser_config,
state.get_grpc_headers(),
)
.await
.change_context(errors::RoutingError::EliminationRoutingCalculationError)
.attach_printable(
"unable to update elimination based routing buckets in dynamic routing service",
);
match update_response_result {
Ok(resp) => {
let updated_resp =
routing_utils::UpdateEliminationBucketEventResponse::try_from(&resp)
.change_context(errors::RoutingError::RoutingEventsError { message: "Unable to convert to UpdateEliminationBucketEventResponse from UpdateEliminationBucketResponse".to_string(), status_code: 500 })?;
Ok(Some(updated_resp))
}
Err(err) => {
logger::error!(
"unable to update elimination score in dynamic routing service: {:?}",
err.current_context()
);
Err(err)
}
}
};
let events_response = routing_events_wrapper.construct_event_builder( "EliminationAnalyser.UpdateEliminationBucket".to_string(),
routing_events::RoutingEngine::IntelligentRouter,
routing_events::ApiMethod::Grpc)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Elimination-Intelligent-Router: Failed to update elimination bucket in Intelligent-Router")?
.trigger_event(state, closure)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Elimination-Intelligent-Router: Failed to update elimination bucket in Intelligent-Router")?;
let _response: routing_utils::UpdateEliminationBucketEventResponse = events_response
.response
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"UpdateEliminationBucketEventResponse not found in RoutingEventResponse",
)?;
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,
})
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Elimination-Intelligent-Router: RoutingEvent not found in RoutingEventsResponse")?;
routing_event.set_status_code(200);
routing_event.set_payment_connector(routing_types::RoutableConnectorChoice {
choice_kind: api_models::routing::RoutableChoiceKind::FullStruct,
connector: common_enums::RoutableConnectors::from_str(payment_connector.as_str())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to infer routable_connector from connector")?,
merchant_connector_id: payment_attempt.merchant_connector_id.clone(),
});
state.event_handler().log_event(&routing_event);
Ok(())
} else {
Ok(())
}
} else {
Ok(())
}
}
/// metrics for contract based dynamic routing
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
#[instrument(skip_all)]
pub async fn push_metrics_with_update_window_for_contract_based_routing(
state: &SessionState,
payment_attempt: &storage::PaymentAttempt,
routable_connectors: Vec<routing_types::RoutableConnectorChoice>,
profile_id: &id_type::ProfileId,
dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef,
_dynamic_routing_config_params_interpolator: DynamicRoutingConfigParamsInterpolator,
) -> RouterResult<()> {
if let Some(contract_routing_algo_ref) = dynamic_routing_algo_ref.contract_based_routing {
if contract_routing_algo_ref.enabled_feature != routing_types::DynamicRoutingFeatures::None
{
let client = &state
.grpc_client
.dynamic_routing
.as_ref()
.ok_or(errors::ApiErrorResponse::GenericNotFoundError {
message: "dynamic routing gRPC client not found".to_string(),
})?
.contract_based_client;
let payment_connector = &payment_attempt.connector.clone().ok_or(
errors::ApiErrorResponse::GenericNotFoundError {
message: "unable to derive payment connector from payment attempt".to_string(),
},
)?;
let contract_based_routing_config =
fetch_dynamic_routing_configs::<routing_types::ContractBasedRoutingConfig>(
state,
profile_id,
contract_routing_algo_ref
.algorithm_id_with_timestamp
.algorithm_id
.ok_or(errors::ApiErrorResponse::GenericNotFoundError {
message: "contract_routing algorithm_id not found".to_string(),
})
.attach_printable(
"contract_based_routing_algorithm_id not found in business_profile",
)?,
)
.await
.change_context(errors::ApiErrorResponse::GenericNotFoundError {
message: "contract based dynamic routing configs not found".to_string(),
})
.attach_printable("unable to retrieve contract based dynamic routing configs")?;
let mut existing_label_info = None;
contract_based_routing_config
.label_info
.as_ref()
.map(|label_info_vec| {
for label_info in label_info_vec {
if Some(&label_info.mca_id)
== payment_attempt.merchant_connector_id.as_ref()
{
existing_label_info = Some(label_info.clone());
}
}
});
let final_label_info = existing_label_info
.ok_or(errors::ApiErrorResponse::GenericNotFoundError {
message: "LabelInformation from ContractBasedRoutingConfig not found"
.to_string(),
})
.attach_printable(
"unable to get LabelInformation from ContractBasedRoutingConfig",
)?;
logger::debug!(
"contract based routing: matched LabelInformation - {:?}",
final_label_info
);
let request_label_info = routing_types::LabelInformation {
label: final_label_info.label.clone(),
target_count: final_label_info.target_count,
target_time: final_label_info.target_time,
mca_id: final_label_info.mca_id.to_owned(),
};
let payment_status_attribute =
get_desired_payment_status_for_dynamic_routing_metrics(payment_attempt.status);
if payment_status_attribute == common_enums::AttemptStatus::Charged {
let event_request = routing_utils::UpdateContractRequestEventRequest {
id: profile_id.get_string_repr().to_string(),
params: "".to_string(),
labels_information: vec![
routing_utils::ContractLabelInformationEventRequest::from(
&request_label_info,
),
],
};
let routing_events_wrapper = routing_utils::RoutingEventsWrapper::new(
state.tenant.tenant_id.clone(),
state.request_id,
payment_attempt.payment_id.get_string_repr().to_string(),
profile_id.to_owned(),
payment_attempt.merchant_id.to_owned(),
"IntelligentRouter: UpdateContractScore".to_string(),
Some(event_request.clone()),
true,
false,
);
let closure = || async {
let update_response_result = client
.update_contracts(
profile_id.get_string_repr().into(),
vec![request_label_info],
"".to_string(),
vec![],
1,
state.get_grpc_headers(),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"unable to update contract based routing window in dynamic routing service",
);
match update_response_result {
Ok(resp) => {
let updated_resp =
routing_utils::UpdateContractEventResponse::try_from(&resp)
.change_context(errors::RoutingError::RoutingEventsError { message: "Unable to convert to UpdateContractEventResponse from UpdateContractResponse".to_string(), status_code: 500 })?;
Ok(Some(updated_resp))
}
Err(err) => {
logger::error!(
"unable to update elimination score in dynamic routing service: {:?}",
err.current_context()
);
// have to refactor errors
Err(error_stack::report!(
errors::RoutingError::ContractScoreUpdationError
))
}
}
};
let events_response = routing_events_wrapper.construct_event_builder( "ContractScoreCalculator.UpdateContract".to_string(),
routing_events::RoutingEngine::IntelligentRouter,
routing_events::ApiMethod::Grpc)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("ContractRouting-Intelligent-Router: Failed to construct RoutingEventsBuilder")?
.trigger_event(state, closure)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("ContractRouting-Intelligent-Router: Failed to update contract scores in Intelligent-Router")?;
let _response: routing_utils::UpdateContractEventResponse = events_response
.response
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"UpdateContractEventResponse not found in RoutingEventResponse",
)?;
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,
})
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("ContractRouting-Intelligent-Router: RoutingEvent not found in RoutingEventsResponse")?;
routing_event.set_payment_connector(routing_types::RoutableConnectorChoice {
choice_kind: api_models::routing::RoutableChoiceKind::FullStruct,
connector: common_enums::RoutableConnectors::from_str(
final_label_info.label.as_str(),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to infer routable_connector from connector")?,
merchant_connector_id: Some(final_label_info.mca_id.clone()),
});
routing_event.set_status_code(200);
state.event_handler().log_event(&routing_event);
}
let contract_based_connectors = routable_connectors
.into_iter()
.filter(|conn| {
conn.merchant_connector_id.clone() == Some(final_label_info.mca_id.clone())
})
.collect::<Vec<_>>();
let contract_scores = client
.calculate_contract_score(
profile_id.get_string_repr().into(),
contract_based_routing_config.clone(),
"".to_string(),
contract_based_connectors,
state.get_grpc_headers(),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"unable to calculate/fetch contract scores from dynamic routing service",
)?;
let first_contract_based_connector = &contract_scores
.labels_with_score
.first()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"unable to fetch the first connector from list of connectors obtained from dynamic routing service",
)?;
let (first_contract_based_connector, connector_score, current_payment_cnt) = (first_contract_based_connector.label
.split_once(':')
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable(format!(
"unable to split connector_name and mca_id from the first connector {first_contract_based_connector:?} obtained from dynamic routing service",
))?
.0, first_contract_based_connector.score, first_contract_based_connector.current_count );
core_metrics::DYNAMIC_CONTRACT_BASED_ROUTING.add(
1,
router_env::metric_attributes!(
(
"tenant",
state.tenant.tenant_id.get_string_repr().to_owned(),
),
(
"merchant_profile_id",
format!(
"{}:{}",
payment_attempt.merchant_id.get_string_repr(),
payment_attempt.profile_id.get_string_repr()
),
),
(
"contract_based_routing_connector",
first_contract_based_connector.to_string(),
),
(
"contract_based_routing_connector_score",
connector_score.to_string(),
),
(
"current_payment_count_contract_based_routing_connector",
current_payment_cnt.to_string(),
),
("payment_connector", payment_connector.to_string()),
(
"currency",
payment_attempt
.currency
.map_or_else(|| "None".to_string(), |currency| currency.to_string()),
),
(
"payment_method",
payment_attempt.payment_method.map_or_else(
|| "None".to_string(),
|payment_method| payment_method.to_string(),
),
),
(
"payment_method_type",
payment_attempt.payment_method_type.map_or_else(
|| "None".to_string(),
|payment_method_type| payment_method_type.to_string(),
),
),
(
"capture_method",
payment_attempt.capture_method.map_or_else(
|| "None".to_string(),
|capture_method| capture_method.to_string(),
),
),
(
"authentication_type",
payment_attempt.authentication_type.map_or_else(
|| "None".to_string(),
|authentication_type| authentication_type.to_string(),
),
),
("payment_status", payment_attempt.status.to_string()),
),
);
logger::debug!("successfully pushed contract_based_routing metrics");
Ok(())
} else {
Ok(())
}
} else {
Ok(())
}
}
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
fn get_desired_payment_status_for_dynamic_routing_metrics(
attempt_status: common_enums::AttemptStatus,
) -> common_enums::AttemptStatus {
match attempt_status {
common_enums::AttemptStatus::Charged
| common_enums::AttemptStatus::Authorized
| common_enums::AttemptStatus::PartialCharged
| common_enums::AttemptStatus::PartialChargedAndChargeable
| common_enums::AttemptStatus::PartiallyAuthorized => common_enums::AttemptStatus::Charged,
common_enums::AttemptStatus::Failure
| common_enums::AttemptStatus::AuthorizationFailed
| common_enums::AttemptStatus::AuthenticationFailed
| common_enums::AttemptStatus::CaptureFailed
| common_enums::AttemptStatus::RouterDeclined => common_enums::AttemptStatus::Failure,
common_enums::AttemptStatus::Started
| common_enums::AttemptStatus::AuthenticationPending
| common_enums::AttemptStatus::AuthenticationSuccessful
| common_enums::AttemptStatus::Authorizing
| common_enums::AttemptStatus::CodInitiated
| common_enums::AttemptStatus::Voided
| common_enums::AttemptStatus::VoidedPostCharge
| common_enums::AttemptStatus::VoidInitiated
| common_enums::AttemptStatus::CaptureInitiated
| common_enums::AttemptStatus::VoidFailed
| common_enums::AttemptStatus::AutoRefunded
| common_enums::AttemptStatus::Unresolved
| common_enums::AttemptStatus::Pending
| common_enums::AttemptStatus::IntegrityFailure
| common_enums::AttemptStatus::PaymentMethodAwaited
| common_enums::AttemptStatus::ConfirmationAwaited
| common_enums::AttemptStatus::DeviceDataCollectionPending
| common_enums::AttemptStatus::Expired => common_enums::AttemptStatus::Pending,
}
}
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
impl ForeignFrom<common_enums::AttemptStatus> for open_router::TxnStatus {
fn foreign_from(attempt_status: common_enums::AttemptStatus) -> Self {
match attempt_status {
common_enums::AttemptStatus::Started => Self::Started,
common_enums::AttemptStatus::AuthenticationFailed => Self::AuthenticationFailed,
common_enums::AttemptStatus::RouterDeclined => Self::JuspayDeclined,
common_enums::AttemptStatus::AuthenticationPending => Self::PendingVbv,
common_enums::AttemptStatus::AuthenticationSuccessful => Self::VBVSuccessful,
common_enums::AttemptStatus::Authorized
| common_enums::AttemptStatus::PartiallyAuthorized => Self::Authorized,
common_enums::AttemptStatus::AuthorizationFailed => Self::AuthorizationFailed,
common_enums::AttemptStatus::Charged => Self::Charged,
common_enums::AttemptStatus::Authorizing => Self::Authorizing,
common_enums::AttemptStatus::CodInitiated => Self::CODInitiated,
common_enums::AttemptStatus::Voided | common_enums::AttemptStatus::Expired => {
Self::Voided
}
common_enums::AttemptStatus::VoidedPostCharge => Self::VoidedPostCharge,
common_enums::AttemptStatus::VoidInitiated => Self::VoidInitiated,
common_enums::AttemptStatus::CaptureInitiated => Self::CaptureInitiated,
common_enums::AttemptStatus::CaptureFailed => Self::CaptureFailed,
common_enums::AttemptStatus::VoidFailed => Self::VoidFailed,
common_enums::AttemptStatus::AutoRefunded => Self::AutoRefunded,
common_enums::AttemptStatus::PartialCharged => Self::PartialCharged,
common_enums::AttemptStatus::PartialChargedAndChargeable => Self::ToBeCharged,
common_enums::AttemptStatus::Unresolved => Self::Pending,
common_enums::AttemptStatus::Pending
| common_enums::AttemptStatus::IntegrityFailure => Self::Pending,
common_enums::AttemptStatus::Failure => Self::Failure,
common_enums::AttemptStatus::PaymentMethodAwaited => Self::Pending,
common_enums::AttemptStatus::ConfirmationAwaited => Self::Pending,
common_enums::AttemptStatus::DeviceDataCollectionPending => Self::Pending,
}
}
}
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
fn get_dynamic_routing_based_metrics_outcome_for_payment(
payment_status_attribute: common_enums::AttemptStatus,
payment_connector: String,
first_success_based_connector: String,
) -> common_enums::SuccessBasedRoutingConclusiveState {
match payment_status_attribute {
common_enums::AttemptStatus::Charged
if *first_success_based_connector == *payment_connector =>
{
common_enums::SuccessBasedRoutingConclusiveState::TruePositive
}
common_enums::AttemptStatus::Failure
if *first_success_based_connector == *payment_connector =>
{
common_enums::SuccessBasedRoutingConclusiveState::FalsePositive
}
common_enums::AttemptStatus::Failure
if *first_success_based_connector != *payment_connector =>
{
common_enums::SuccessBasedRoutingConclusiveState::TrueNegative
}
common_enums::AttemptStatus::Charged
if *first_success_based_connector != *payment_connector =>
{
common_enums::SuccessBasedRoutingConclusiveState::FalseNegative
}
_ => common_enums::SuccessBasedRoutingConclusiveState::NonDeterministic,
}
}
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
pub async fn disable_dynamic_routing_algorithm(
state: &SessionState,
key_store: domain::MerchantKeyStore,
business_profile: domain::Profile,
dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef,
dynamic_routing_type: routing_types::DynamicRoutingType,
) -> RouterResult<ApplicationResponse<routing_types::RoutingDictionaryRecord>> {
let db = state.store.as_ref();
let key_manager_state = &state.into();
let profile_id = business_profile.get_id().clone();
let (algorithm_id, mut dynamic_routing_algorithm, cache_entries_to_redact) =
match dynamic_routing_type {
routing_types::DynamicRoutingType::SuccessRateBasedRouting => {
let Some(algorithm_ref) = dynamic_routing_algo_ref.success_based_algorithm else {
Err(errors::ApiErrorResponse::PreconditionFailed {
message: "Success rate based routing is already disabled".to_string(),
})?
};
let Some(algorithm_id) = algorithm_ref.algorithm_id_with_timestamp.algorithm_id
else {
Err(errors::ApiErrorResponse::PreconditionFailed {
message: "Algorithm is already inactive".to_string(),
})?
};
let cache_key = format!(
"{}_{}",
business_profile.get_id().get_string_repr(),
algorithm_id.get_string_repr()
);
let cache_entries_to_redact =
vec![cache::CacheKind::SuccessBasedDynamicRoutingCache(
cache_key.into(),
)];
(
algorithm_id,
routing_types::DynamicRoutingAlgorithmRef {
success_based_algorithm: Some(routing_types::SuccessBasedAlgorithm {
algorithm_id_with_timestamp:
routing_types::DynamicAlgorithmWithTimestamp::new(None),
enabled_feature: routing_types::DynamicRoutingFeatures::None,
}),
elimination_routing_algorithm: dynamic_routing_algo_ref
.elimination_routing_algorithm,
contract_based_routing: dynamic_routing_algo_ref.contract_based_routing,
dynamic_routing_volume_split: dynamic_routing_algo_ref
.dynamic_routing_volume_split,
is_merchant_created_in_decision_engine: dynamic_routing_algo_ref
.is_merchant_created_in_decision_engine,
},
cache_entries_to_redact,
)
}
routing_types::DynamicRoutingType::EliminationRouting => {
let Some(algorithm_ref) = dynamic_routing_algo_ref.elimination_routing_algorithm
else {
Err(errors::ApiErrorResponse::PreconditionFailed {
message: "Elimination routing is already disabled".to_string(),
})?
};
let Some(algorithm_id) = algorithm_ref.algorithm_id_with_timestamp.algorithm_id
else {
Err(errors::ApiErrorResponse::PreconditionFailed {
message: "Algorithm is already inactive".to_string(),
})?
};
let cache_key = format!(
"{}_{}",
business_profile.get_id().get_string_repr(),
algorithm_id.get_string_repr()
);
let cache_entries_to_redact =
vec![cache::CacheKind::EliminationBasedDynamicRoutingCache(
cache_key.into(),
)];
(
algorithm_id,
routing_types::DynamicRoutingAlgorithmRef {
success_based_algorithm: dynamic_routing_algo_ref.success_based_algorithm,
dynamic_routing_volume_split: dynamic_routing_algo_ref
.dynamic_routing_volume_split,
elimination_routing_algorithm: Some(
routing_types::EliminationRoutingAlgorithm {
algorithm_id_with_timestamp:
routing_types::DynamicAlgorithmWithTimestamp::new(None),
enabled_feature: routing_types::DynamicRoutingFeatures::None,
},
),
contract_based_routing: dynamic_routing_algo_ref.contract_based_routing,
is_merchant_created_in_decision_engine: dynamic_routing_algo_ref
.is_merchant_created_in_decision_engine,
},
cache_entries_to_redact,
)
}
routing_types::DynamicRoutingType::ContractBasedRouting => {
let Some(algorithm_ref) = dynamic_routing_algo_ref.contract_based_routing else {
Err(errors::ApiErrorResponse::PreconditionFailed {
message: "Contract routing is already disabled".to_string(),
})?
};
let Some(algorithm_id) = algorithm_ref.algorithm_id_with_timestamp.algorithm_id
else {
Err(errors::ApiErrorResponse::PreconditionFailed {
message: "Algorithm is already inactive".to_string(),
})?
};
let cache_key = format!(
"{}_{}",
business_profile.get_id().get_string_repr(),
algorithm_id.get_string_repr()
);
let cache_entries_to_redact =
vec![cache::CacheKind::ContractBasedDynamicRoutingCache(
cache_key.into(),
)];
(
algorithm_id,
routing_types::DynamicRoutingAlgorithmRef {
success_based_algorithm: dynamic_routing_algo_ref.success_based_algorithm,
elimination_routing_algorithm: dynamic_routing_algo_ref
.elimination_routing_algorithm,
dynamic_routing_volume_split: dynamic_routing_algo_ref
.dynamic_routing_volume_split,
contract_based_routing: Some(routing_types::ContractRoutingAlgorithm {
algorithm_id_with_timestamp:
routing_types::DynamicAlgorithmWithTimestamp::new(None),
enabled_feature: routing_types::DynamicRoutingFeatures::None,
}),
is_merchant_created_in_decision_engine: dynamic_routing_algo_ref
.is_merchant_created_in_decision_engine,
},
cache_entries_to_redact,
)
}
};
// Call to DE here
if state.conf.open_router.dynamic_routing_enabled {
disable_decision_engine_dynamic_routing_setup(
state,
business_profile.get_id(),
dynamic_routing_type,
&mut dynamic_routing_algorithm,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to disable dynamic routing setup in decision engine")?;
}
// redact cache for dynamic routing config
let _ = cache::redact_from_redis_and_publish(
state.store.get_cache_store().as_ref(),
cache_entries_to_redact,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"unable to publish into the redact channel for evicting the dynamic routing config cache",
)?;
let record = db
.find_routing_algorithm_by_profile_id_algorithm_id(business_profile.get_id(), &algorithm_id)
.await
.to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?;
let response = record.foreign_into();
update_business_profile_active_dynamic_algorithm_ref(
db,
key_manager_state,
&key_store,
business_profile,
dynamic_routing_algorithm,
)
.await?;
core_metrics::ROUTING_UNLINK_CONFIG_SUCCESS_RESPONSE.add(
1,
router_env::metric_attributes!(("profile_id", profile_id)),
);
Ok(ApplicationResponse::Json(response))
}
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
pub async fn enable_dynamic_routing_algorithm(
state: &SessionState,
key_store: domain::MerchantKeyStore,
business_profile: domain::Profile,
feature_to_enable: routing_types::DynamicRoutingFeatures,
dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef,
dynamic_routing_type: routing_types::DynamicRoutingType,
payload: Option<routing_types::DynamicRoutingPayload>,
) -> RouterResult<ApplicationResponse<routing_types::RoutingDictionaryRecord>> {
let mut dynamic_routing = dynamic_routing_algo_ref.clone();
match dynamic_routing_type {
routing_types::DynamicRoutingType::SuccessRateBasedRouting => {
dynamic_routing
.disable_algorithm_id(routing_types::DynamicRoutingType::ContractBasedRouting);
enable_specific_routing_algorithm(
state,
key_store,
business_profile,
feature_to_enable,
dynamic_routing.clone(),
dynamic_routing_type,
dynamic_routing.success_based_algorithm,
payload,
)
.await
}
routing_types::DynamicRoutingType::EliminationRouting => {
enable_specific_routing_algorithm(
state,
key_store,
business_profile,
feature_to_enable,
dynamic_routing.clone(),
dynamic_routing_type,
dynamic_routing.elimination_routing_algorithm,
payload,
)
.await
}
routing_types::DynamicRoutingType::ContractBasedRouting => {
Err((errors::ApiErrorResponse::InvalidRequestData {
message: "Contract routing cannot be set as default".to_string(),
})
.into())
}
}
}
#[allow(clippy::too_many_arguments)]
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
pub async fn enable_specific_routing_algorithm<A>(
state: &SessionState,
key_store: domain::MerchantKeyStore,
business_profile: domain::Profile,
feature_to_enable: routing_types::DynamicRoutingFeatures,
mut dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef,
dynamic_routing_type: routing_types::DynamicRoutingType,
algo_type: Option<A>,
payload: Option<routing_types::DynamicRoutingPayload>,
) -> RouterResult<ApplicationResponse<routing_types::RoutingDictionaryRecord>>
where
A: routing_types::DynamicRoutingAlgoAccessor + Clone + Debug,
{
//Check for payload
if let Some(payload) = payload {
return create_specific_dynamic_routing_setup(
state,
key_store,
business_profile,
feature_to_enable,
dynamic_routing_algo_ref,
dynamic_routing_type,
payload,
)
.await;
}
// Algorithm wasn't created yet
let Some(mut algo_type) = algo_type else {
return default_specific_dynamic_routing_setup(
state,
key_store,
business_profile,
feature_to_enable,
dynamic_routing_algo_ref,
dynamic_routing_type,
)
.await;
};
// Algorithm was in disabled state
let Some(algo_type_algorithm_id) = algo_type
.clone()
.get_algorithm_id_with_timestamp()
.algorithm_id
else {
return default_specific_dynamic_routing_setup(
state,
key_store,
business_profile,
feature_to_enable,
dynamic_routing_algo_ref,
dynamic_routing_type,
)
.await;
};
let db = state.store.as_ref();
let profile_id = business_profile.get_id().clone();
let algo_type_enabled_features = algo_type.get_enabled_features();
if *algo_type_enabled_features == feature_to_enable {
// algorithm already has the required feature
let routing_algorithm = db
.find_routing_algorithm_by_profile_id_algorithm_id(&profile_id, &algo_type_algorithm_id)
.await
.to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?;
let updated_routing_record = routing_algorithm.foreign_into();
return Ok(ApplicationResponse::Json(updated_routing_record));
};
*algo_type_enabled_features = feature_to_enable;
dynamic_routing_algo_ref.update_enabled_features(dynamic_routing_type, feature_to_enable);
update_business_profile_active_dynamic_algorithm_ref(
db,
&state.into(),
&key_store,
business_profile,
dynamic_routing_algo_ref.clone(),
)
.await?;
let routing_algorithm = db
.find_routing_algorithm_by_profile_id_algorithm_id(&profile_id, &algo_type_algorithm_id)
.await
.to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?;
let updated_routing_record = routing_algorithm.foreign_into();
core_metrics::ROUTING_CREATE_SUCCESS_RESPONSE.add(
1,
router_env::metric_attributes!(("profile_id", profile_id.clone())),
);
Ok(ApplicationResponse::Json(updated_routing_record))
}
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
#[instrument(skip_all)]
pub async fn default_specific_dynamic_routing_setup(
state: &SessionState,
key_store: domain::MerchantKeyStore,
business_profile: domain::Profile,
feature_to_enable: routing_types::DynamicRoutingFeatures,
mut dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef,
dynamic_routing_type: routing_types::DynamicRoutingType,
) -> RouterResult<ApplicationResponse<routing_types::RoutingDictionaryRecord>> {
let db = state.store.as_ref();
let key_manager_state = &state.into();
let profile_id = business_profile.get_id().clone();
let merchant_id = business_profile.merchant_id.clone();
let algorithm_id = common_utils::generate_routing_id_of_default_length();
let timestamp = common_utils::date_time::now();
let algo = match dynamic_routing_type {
routing_types::DynamicRoutingType::SuccessRateBasedRouting => {
let default_success_based_routing_config =
if state.conf.open_router.dynamic_routing_enabled {
routing_types::SuccessBasedRoutingConfig::open_router_config_default()
} else {
routing_types::SuccessBasedRoutingConfig::default()
};
routing_algorithm::RoutingAlgorithm {
algorithm_id: algorithm_id.clone(),
profile_id: profile_id.clone(),
merchant_id,
name: SUCCESS_BASED_DYNAMIC_ROUTING_ALGORITHM.to_string(),
description: None,
kind: diesel_models::enums::RoutingAlgorithmKind::Dynamic,
algorithm_data: serde_json::json!(default_success_based_routing_config),
created_at: timestamp,
modified_at: timestamp,
algorithm_for: common_enums::TransactionType::Payment,
decision_engine_routing_id: None,
}
}
routing_types::DynamicRoutingType::EliminationRouting => {
let default_elimination_routing_config =
if state.conf.open_router.dynamic_routing_enabled {
routing_types::EliminationRoutingConfig::open_router_config_default()
} else {
routing_types::EliminationRoutingConfig::default()
};
routing_algorithm::RoutingAlgorithm {
algorithm_id: algorithm_id.clone(),
profile_id: profile_id.clone(),
merchant_id,
name: ELIMINATION_BASED_DYNAMIC_ROUTING_ALGORITHM.to_string(),
description: None,
kind: diesel_models::enums::RoutingAlgorithmKind::Dynamic,
algorithm_data: serde_json::json!(default_elimination_routing_config),
created_at: timestamp,
modified_at: timestamp,
algorithm_for: common_enums::TransactionType::Payment,
decision_engine_routing_id: None,
}
}
routing_types::DynamicRoutingType::ContractBasedRouting => {
return Err((errors::ApiErrorResponse::InvalidRequestData {
message: "Contract routing cannot be set as default".to_string(),
})
.into())
}
};
// Call to DE here
// Need to map out the cases if this call should always be made or not
if state.conf.open_router.dynamic_routing_enabled {
enable_decision_engine_dynamic_routing_setup(
state,
business_profile.get_id(),
dynamic_routing_type,
&mut dynamic_routing_algo_ref,
None,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to setup decision engine dynamic routing")?;
}
let record = db
.insert_routing_algorithm(algo)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to insert record in routing algorithm table")?;
dynamic_routing_algo_ref.update_algorithm_id(
algorithm_id,
feature_to_enable,
dynamic_routing_type,
);
update_business_profile_active_dynamic_algorithm_ref(
db,
key_manager_state,
&key_store,
business_profile,
dynamic_routing_algo_ref,
)
.await?;
let new_record = record.foreign_into();
core_metrics::ROUTING_CREATE_SUCCESS_RESPONSE.add(
1,
router_env::metric_attributes!(("profile_id", profile_id.clone())),
);
Ok(ApplicationResponse::Json(new_record))
}
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
#[instrument(skip_all)]
pub async fn create_specific_dynamic_routing_setup(
state: &SessionState,
key_store: domain::MerchantKeyStore,
business_profile: domain::Profile,
feature_to_enable: routing_types::DynamicRoutingFeatures,
mut dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef,
dynamic_routing_type: routing_types::DynamicRoutingType,
payload: routing_types::DynamicRoutingPayload,
) -> RouterResult<ApplicationResponse<routing_types::RoutingDictionaryRecord>> {
let db = state.store.as_ref();
let key_manager_state = &state.into();
let profile_id = business_profile.get_id().clone();
let merchant_id = business_profile.merchant_id.clone();
let algorithm_id = common_utils::generate_routing_id_of_default_length();
let timestamp = common_utils::date_time::now();
let algo = match dynamic_routing_type {
routing_types::DynamicRoutingType::SuccessRateBasedRouting => {
let success_config = match &payload {
routing_types::DynamicRoutingPayload::SuccessBasedRoutingPayload(config) => config,
_ => {
return Err((errors::ApiErrorResponse::InvalidRequestData {
message: "Invalid payload type for Success Rate Based Routing".to_string(),
})
.into())
}
};
routing_algorithm::RoutingAlgorithm {
algorithm_id: algorithm_id.clone(),
profile_id: profile_id.clone(),
merchant_id,
name: SUCCESS_BASED_DYNAMIC_ROUTING_ALGORITHM.to_string(),
description: None,
kind: diesel_models::enums::RoutingAlgorithmKind::Dynamic,
algorithm_data: serde_json::json!(success_config),
created_at: timestamp,
modified_at: timestamp,
algorithm_for: common_enums::TransactionType::Payment,
decision_engine_routing_id: None,
}
}
routing_types::DynamicRoutingType::EliminationRouting => {
let elimination_config = match &payload {
routing_types::DynamicRoutingPayload::EliminationRoutingPayload(config) => config,
_ => {
return Err((errors::ApiErrorResponse::InvalidRequestData {
message: "Invalid payload type for Elimination Routing".to_string(),
})
.into())
}
};
routing_algorithm::RoutingAlgorithm {
algorithm_id: algorithm_id.clone(),
profile_id: profile_id.clone(),
merchant_id,
name: ELIMINATION_BASED_DYNAMIC_ROUTING_ALGORITHM.to_string(),
description: None,
kind: diesel_models::enums::RoutingAlgorithmKind::Dynamic,
algorithm_data: serde_json::json!(elimination_config),
created_at: timestamp,
modified_at: timestamp,
algorithm_for: common_enums::TransactionType::Payment,
decision_engine_routing_id: None,
}
}
routing_types::DynamicRoutingType::ContractBasedRouting => {
return Err((errors::ApiErrorResponse::InvalidRequestData {
message: "Contract routing cannot be set as default".to_string(),
})
.into())
}
};
let record = db
.insert_routing_algorithm(algo)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to insert record in routing algorithm table")?;
dynamic_routing_algo_ref.update_feature(feature_to_enable, dynamic_routing_type);
update_business_profile_active_dynamic_algorithm_ref(
db,
key_manager_state,
&key_store,
business_profile,
dynamic_routing_algo_ref,
)
.await?;
let new_record = record.foreign_into();
core_metrics::ROUTING_CREATE_SUCCESS_RESPONSE.add(
1,
router_env::metric_attributes!(("profile_id", profile_id.clone())),
);
Ok(ApplicationResponse::Json(new_record))
}
#[derive(Debug, Clone)]
pub struct DynamicRoutingConfigParamsInterpolator {
pub payment_method: Option<common_enums::PaymentMethod>,
pub payment_method_type: Option<common_enums::PaymentMethodType>,
pub authentication_type: Option<common_enums::AuthenticationType>,
pub currency: Option<common_enums::Currency>,
pub country: Option<common_enums::CountryAlpha2>,
pub card_network: Option<String>,
pub card_bin: Option<String>,
}
impl DynamicRoutingConfigParamsInterpolator {
pub fn new(
payment_method: Option<common_enums::PaymentMethod>,
payment_method_type: Option<common_enums::PaymentMethodType>,
authentication_type: Option<common_enums::AuthenticationType>,
currency: Option<common_enums::Currency>,
country: Option<common_enums::CountryAlpha2>,
card_network: Option<String>,
card_bin: Option<String>,
) -> Self {
Self {
payment_method,
payment_method_type,
authentication_type,
currency,
country,
card_network,
card_bin,
}
}
pub fn get_string_val(
&self,
params: &Vec<routing_types::DynamicRoutingConfigParams>,
) -> String {
let mut parts: Vec<String> = Vec::new();
for param in params {
let val = match param {
routing_types::DynamicRoutingConfigParams::PaymentMethod => self
.payment_method
.as_ref()
.map_or(String::new(), |pm| pm.to_string()),
routing_types::DynamicRoutingConfigParams::PaymentMethodType => self
.payment_method_type
.as_ref()
.map_or(String::new(), |pmt| pmt.to_string()),
routing_types::DynamicRoutingConfigParams::AuthenticationType => self
.authentication_type
.as_ref()
.map_or(String::new(), |at| at.to_string()),
routing_types::DynamicRoutingConfigParams::Currency => self
.currency
.as_ref()
.map_or(String::new(), |cur| cur.to_string()),
routing_types::DynamicRoutingConfigParams::Country => self
.country
.as_ref()
.map_or(String::new(), |cn| cn.to_string()),
routing_types::DynamicRoutingConfigParams::CardNetwork => {
self.card_network.clone().unwrap_or_default()
}
routing_types::DynamicRoutingConfigParams::CardBin => {
self.card_bin.clone().unwrap_or_default()
}
};
if !val.is_empty() {
parts.push(val);
}
}
parts.join(":")
}
}
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
#[instrument(skip_all)]
pub async fn enable_decision_engine_dynamic_routing_setup(
state: &SessionState,
profile_id: &id_type::ProfileId,
dynamic_routing_type: routing_types::DynamicRoutingType,
dynamic_routing_algo_ref: &mut routing_types::DynamicRoutingAlgorithmRef,
payload: Option<routing_types::DynamicRoutingPayload>,
) -> RouterResult<()> {
logger::debug!(
"performing call with open_router for profile {}",
profile_id.get_string_repr()
);
let decision_engine_config_request = match dynamic_routing_type {
routing_types::DynamicRoutingType::SuccessRateBasedRouting => {
let success_based_routing_config = payload
.and_then(|p| match p {
routing_types::DynamicRoutingPayload::SuccessBasedRoutingPayload(config) => {
Some(config)
}
_ => None,
})
.unwrap_or_else(
routing_types::SuccessBasedRoutingConfig::open_router_config_default,
);
open_router::DecisionEngineConfigSetupRequest {
merchant_id: profile_id.get_string_repr().to_string(),
config: open_router::DecisionEngineConfigVariant::SuccessRate(
success_based_routing_config
.get_decision_engine_configs()
.change_context(errors::ApiErrorResponse::GenericNotFoundError {
message: "Decision engine config not found".to_string(),
})
.attach_printable("Decision engine config not found")?,
),
}
}
routing_types::DynamicRoutingType::EliminationRouting => {
let elimination_based_routing_config = payload
.and_then(|p| match p {
routing_types::DynamicRoutingPayload::EliminationRoutingPayload(config) => {
Some(config)
}
_ => None,
})
.unwrap_or_else(
routing_types::EliminationRoutingConfig::open_router_config_default,
);
open_router::DecisionEngineConfigSetupRequest {
merchant_id: profile_id.get_string_repr().to_string(),
config: open_router::DecisionEngineConfigVariant::Elimination(
elimination_based_routing_config
.get_decision_engine_configs()
.change_context(errors::ApiErrorResponse::GenericNotFoundError {
message: "Decision engine config not found".to_string(),
})
.attach_printable("Decision engine config not found")?,
),
}
}
routing_types::DynamicRoutingType::ContractBasedRouting => {
return Err((errors::ApiErrorResponse::InvalidRequestData {
message: "Contract routing cannot be set as default".to_string(),
})
.into())
}
};
// Create merchant in Decision Engine if it is not already created
create_merchant_in_decision_engine_if_not_exists(state, profile_id, dynamic_routing_algo_ref)
.await;
routing_utils::ConfigApiClient::send_decision_engine_request::<_, serde_json::Value>(
state,
services::Method::Post,
DECISION_ENGINE_RULE_CREATE_ENDPOINT,
Some(decision_engine_config_request),
None,
None,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to setup decision engine dynamic routing")?;
Ok(())
}
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
#[instrument(skip_all)]
pub async fn update_decision_engine_dynamic_routing_setup(
state: &SessionState,
profile_id: &id_type::ProfileId,
request: serde_json::Value,
dynamic_routing_type: routing_types::DynamicRoutingType,
dynamic_routing_algo_ref: &mut routing_types::DynamicRoutingAlgorithmRef,
) -> RouterResult<()> {
logger::debug!(
"performing call with open_router for profile {}",
profile_id.get_string_repr()
);
let decision_engine_request = match dynamic_routing_type {
routing_types::DynamicRoutingType::SuccessRateBasedRouting => {
let success_rate_config: routing_types::SuccessBasedRoutingConfig = request
.parse_value("SuccessBasedRoutingConfig")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to deserialize SuccessBasedRoutingConfig")?;
open_router::DecisionEngineConfigSetupRequest {
merchant_id: profile_id.get_string_repr().to_string(),
config: open_router::DecisionEngineConfigVariant::SuccessRate(
success_rate_config
.get_decision_engine_configs()
.change_context(errors::ApiErrorResponse::GenericNotFoundError {
message: "Decision engine config not found".to_string(),
})
.attach_printable("Decision engine config not found")?,
),
}
}
routing_types::DynamicRoutingType::EliminationRouting => {
let elimination_config: routing_types::EliminationRoutingConfig = request
.parse_value("EliminationRoutingConfig")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to deserialize EliminationRoutingConfig")?;
open_router::DecisionEngineConfigSetupRequest {
merchant_id: profile_id.get_string_repr().to_string(),
config: open_router::DecisionEngineConfigVariant::Elimination(
elimination_config
.get_decision_engine_configs()
.change_context(errors::ApiErrorResponse::GenericNotFoundError {
message: "Decision engine config not found".to_string(),
})
.attach_printable("Decision engine config not found")?,
),
}
}
routing_types::DynamicRoutingType::ContractBasedRouting => {
return Err((errors::ApiErrorResponse::InvalidRequestData {
message: "Contract routing cannot be set as default".to_string(),
})
.into())
}
};
// Create merchant in Decision Engine if it is not already created
create_merchant_in_decision_engine_if_not_exists(state, profile_id, dynamic_routing_algo_ref)
.await;
routing_utils::ConfigApiClient::send_decision_engine_request::<_, serde_json::Value>(
state,
services::Method::Post,
DECISION_ENGINE_RULE_UPDATE_ENDPOINT,
Some(decision_engine_request),
None,
None,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to update decision engine dynamic routing")?;
Ok(())
}
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
pub async fn get_decision_engine_active_dynamic_routing_algorithm(
state: &SessionState,
profile_id: &id_type::ProfileId,
dynamic_routing_type: open_router::DecisionEngineDynamicAlgorithmType,
) -> RouterResult<Option<open_router::DecisionEngineConfigSetupRequest>> {
logger::debug!(
"decision_engine_euclid: GET api call for decision active {:?} routing algorithm",
dynamic_routing_type
);
let request = open_router::GetDecisionEngineConfigRequest {
merchant_id: profile_id.get_string_repr().to_owned(),
algorithm: dynamic_routing_type,
};
let response: Option<open_router::DecisionEngineConfigSetupRequest> =
routing_utils::ConfigApiClient::send_decision_engine_request(
state,
services::Method::Post,
DECISION_ENGINE_RULE_GET_ENDPOINT,
Some(request),
None,
None,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get active dynamic algorithm from decision engine")?
.response;
Ok(response)
}
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
#[instrument(skip_all)]
pub async fn disable_decision_engine_dynamic_routing_setup(
state: &SessionState,
profile_id: &id_type::ProfileId,
dynamic_routing_type: routing_types::DynamicRoutingType,
dynamic_routing_algo_ref: &mut routing_types::DynamicRoutingAlgorithmRef,
) -> RouterResult<()> {
logger::debug!(
"performing call with open_router for profile {}",
profile_id.get_string_repr()
);
let decision_engine_request = open_router::FetchRoutingConfig {
merchant_id: profile_id.get_string_repr().to_string(),
algorithm: match dynamic_routing_type {
routing_types::DynamicRoutingType::SuccessRateBasedRouting => {
open_router::AlgorithmType::SuccessRate
}
routing_types::DynamicRoutingType::EliminationRouting => {
open_router::AlgorithmType::Elimination
}
routing_types::DynamicRoutingType::ContractBasedRouting => {
return Err((errors::ApiErrorResponse::InvalidRequestData {
message: "Contract routing is not enabled for decision engine".to_string(),
})
.into())
}
},
};
// Create merchant in Decision Engine if it is not already created
create_merchant_in_decision_engine_if_not_exists(state, profile_id, dynamic_routing_algo_ref)
.await;
routing_utils::ConfigApiClient::send_decision_engine_request::<_, serde_json::Value>(
state,
services::Method::Post,
DECISION_ENGINE_RULE_DELETE_ENDPOINT,
Some(decision_engine_request),
None,
None,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to disable decision engine dynamic routing")?;
Ok(())
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
pub async fn create_merchant_in_decision_engine_if_not_exists(
state: &SessionState,
profile_id: &id_type::ProfileId,
dynamic_routing_algo_ref: &mut routing_types::DynamicRoutingAlgorithmRef,
) {
if !dynamic_routing_algo_ref.is_merchant_created_in_decision_engine {
logger::debug!(
"Creating merchant_account in decision engine for profile {}",
profile_id.get_string_repr()
);
create_decision_engine_merchant(state, profile_id)
.await
.map_err(|err| {
logger::warn!("Merchant creation error in decision_engine: {err:?}");
})
.ok();
// TODO: Update the status based on the status code or error message from the API call
dynamic_routing_algo_ref.update_merchant_creation_status_in_decision_engine(true);
}
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
pub async fn create_decision_engine_merchant(
state: &SessionState,
profile_id: &id_type::ProfileId,
) -> RouterResult<()> {
let merchant_account_req = open_router::MerchantAccount {
merchant_id: profile_id.get_string_repr().to_string(),
gateway_success_rate_based_decider_input: None,
};
routing_utils::ConfigApiClient::send_decision_engine_request::<_, serde_json::Value>(
state,
services::Method::Post,
DECISION_ENGINE_MERCHANT_CREATE_ENDPOINT,
Some(merchant_account_req),
None,
None,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to create merchant account on decision engine")?;
Ok(())
}
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
#[instrument(skip_all)]
pub async fn delete_decision_engine_merchant(
state: &SessionState,
profile_id: &id_type::ProfileId,
) -> RouterResult<()> {
let path = format!(
"{}/{}",
DECISION_ENGINE_MERCHANT_BASE_ENDPOINT,
profile_id.get_string_repr()
);
routing_utils::ConfigApiClient::send_decision_engine_request::<_, serde_json::Value>(
state,
services::Method::Delete,
&path,
None::<id_type::ProfileId>,
None,
None,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to delete merchant account on decision engine")?;
Ok(())
}
pub async fn redact_cgraph_cache(
state: &SessionState,
merchant_id: &id_type::MerchantId,
profile_id: &id_type::ProfileId,
) -> RouterResult<()> {
let cgraph_payouts_key = format!(
"cgraph_po_{}_{}",
merchant_id.get_string_repr(),
profile_id.get_string_repr(),
);
let cgraph_payments_key = format!(
"cgraph_{}_{}",
merchant_id.get_string_repr(),
profile_id.get_string_repr(),
);
let config_payouts_key = cache::CacheKind::CGraph(cgraph_payouts_key.clone().into());
let config_payments_key = cache::CacheKind::CGraph(cgraph_payments_key.clone().into());
cache::redact_from_redis_and_publish(
state.store.get_cache_store().as_ref(),
[config_payouts_key, config_payments_key],
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to invalidate the cgraph cache")?;
Ok(())
}
pub async fn redact_routing_cache(
state: &SessionState,
merchant_id: &id_type::MerchantId,
profile_id: &id_type::ProfileId,
) -> RouterResult<()> {
let routing_payments_key = format!(
"routing_config_{}_{}",
merchant_id.get_string_repr(),
profile_id.get_string_repr(),
);
let routing_payouts_key = format!(
"routing_config_po_{}_{}",
merchant_id.get_string_repr(),
profile_id.get_string_repr(),
);
let routing_payouts_cache_key = cache::CacheKind::Routing(routing_payouts_key.clone().into());
let routing_payments_cache_key = cache::CacheKind::CGraph(routing_payments_key.clone().into());
cache::redact_from_redis_and_publish(
state.store.get_cache_store().as_ref(),
[routing_payouts_cache_key, routing_payments_cache_key],
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to invalidate the routing cache")?;
Ok(())
}
|
crates/router/src/core/routing/helpers.rs
|
router::src::core::routing::helpers
| 21,374
| true
|
// File: crates/router/src/core/errors/customers_error_response.rs
// Module: router::src::core::errors::customers_error_response
use http::StatusCode;
#[derive(Debug, thiserror::Error)]
pub enum CustomersErrorResponse {
#[error("Customer has already been redacted")]
CustomerRedacted,
#[error("Something went wrong")]
InternalServerError,
#[error("Invalid request data: {message}")]
InvalidRequestData { message: String },
#[error("Customer has already been redacted")]
MandateActive,
#[error("Customer does not exist in our records")]
CustomerNotFound,
#[error("Customer with the given customer id already exists")]
CustomerAlreadyExists,
}
impl actix_web::ResponseError for CustomersErrorResponse {
fn status_code(&self) -> StatusCode {
common_utils::errors::ErrorSwitch::<api_models::errors::types::ApiErrorResponse>::switch(
self,
)
.status_code()
}
fn error_response(&self) -> actix_web::HttpResponse {
common_utils::errors::ErrorSwitch::<api_models::errors::types::ApiErrorResponse>::switch(
self,
)
.error_response()
}
}
// should be removed hola bola
|
crates/router/src/core/errors/customers_error_response.rs
|
router::src::core::errors::customers_error_response
| 257
| true
|
// File: crates/router/src/core/errors/transformers.rs
// Module: router::src::core::errors::transformers
use common_utils::errors::ErrorSwitch;
use hyperswitch_domain_models::errors::api_error_response::ApiErrorResponse;
use super::{CustomersErrorResponse, StorageError};
impl ErrorSwitch<api_models::errors::types::ApiErrorResponse> for CustomersErrorResponse {
fn switch(&self) -> api_models::errors::types::ApiErrorResponse {
use api_models::errors::types::{ApiError, ApiErrorResponse as AER};
match self {
Self::CustomerRedacted => AER::BadRequest(ApiError::new(
"IR",
11,
"Customer has already been redacted",
None,
)),
Self::InternalServerError => {
AER::InternalServerError(ApiError::new("HE", 0, "Something went wrong", None))
}
Self::InvalidRequestData { message } => AER::BadRequest(ApiError::new(
"IR",
7,
format!("Invalid value provided:{}", message),
None,
)),
Self::MandateActive => AER::BadRequest(ApiError::new(
"IR",
10,
"Customer has active mandate/subsciption",
None,
)),
Self::CustomerNotFound => AER::NotFound(ApiError::new(
"HE",
2,
"Customer does not exist in our records",
None,
)),
Self::CustomerAlreadyExists => AER::BadRequest(ApiError::new(
"IR",
12,
"Customer with the given `customer_id` already exists",
None,
)),
}
}
}
impl ErrorSwitch<CustomersErrorResponse> for StorageError {
fn switch(&self) -> CustomersErrorResponse {
use CustomersErrorResponse as CER;
match self {
err if err.is_db_not_found() => CER::CustomerNotFound,
Self::CustomerRedacted => CER::CustomerRedacted,
_ => CER::InternalServerError,
}
}
}
impl ErrorSwitch<CustomersErrorResponse> for common_utils::errors::CryptoError {
fn switch(&self) -> CustomersErrorResponse {
CustomersErrorResponse::InternalServerError
}
}
impl ErrorSwitch<CustomersErrorResponse> for ApiErrorResponse {
fn switch(&self) -> CustomersErrorResponse {
use CustomersErrorResponse as CER;
match self {
Self::InternalServerError => CER::InternalServerError,
Self::MandateActive => CER::MandateActive,
Self::CustomerNotFound => CER::CustomerNotFound,
_ => CER::InternalServerError,
}
}
}
|
crates/router/src/core/errors/transformers.rs
|
router::src::core::errors::transformers
| 550
| true
|
// File: crates/router/src/core/errors/user.rs
// Module: router::src::core::errors::user
use common_utils::errors::CustomResult;
use crate::services::ApplicationResponse;
pub type UserResult<T> = CustomResult<T, UserErrors>;
pub type UserResponse<T> = CustomResult<ApplicationResponse<T>, UserErrors>;
pub mod sample_data;
#[derive(Debug, thiserror::Error)]
pub enum UserErrors {
#[error("User InternalServerError")]
InternalServerError,
#[error("InvalidCredentials")]
InvalidCredentials,
#[error("UserNotFound")]
UserNotFound,
#[error("UserExists")]
UserExists,
#[error("LinkInvalid")]
LinkInvalid,
#[error("UnverifiedUser")]
UnverifiedUser,
#[error("InvalidOldPassword")]
InvalidOldPassword,
#[error("EmailParsingError")]
EmailParsingError,
#[error("NameParsingError")]
NameParsingError,
#[error("PasswordParsingError")]
PasswordParsingError,
#[error("UserAlreadyVerified")]
UserAlreadyVerified,
#[error("CompanyNameParsingError")]
CompanyNameParsingError,
#[error("MerchantAccountCreationError: {0}")]
MerchantAccountCreationError(String),
#[error("InvalidEmailError")]
InvalidEmailError,
#[error("DuplicateOrganizationId")]
DuplicateOrganizationId,
#[error("MerchantIdNotFound")]
MerchantIdNotFound,
#[error("MetadataAlreadySet")]
MetadataAlreadySet,
#[error("InvalidRoleId")]
InvalidRoleId,
#[error("InvalidRoleOperation")]
InvalidRoleOperation,
#[error("IpAddressParsingFailed")]
IpAddressParsingFailed,
#[error("InvalidMetadataRequest")]
InvalidMetadataRequest,
#[error("MerchantIdParsingError")]
MerchantIdParsingError,
#[error("ChangePasswordError")]
ChangePasswordError,
#[error("InvalidDeleteOperation")]
InvalidDeleteOperation,
#[error("MaxInvitationsError")]
MaxInvitationsError,
#[error("RoleNotFound")]
RoleNotFound,
#[error("InvalidRoleOperationWithMessage")]
InvalidRoleOperationWithMessage(String),
#[error("RoleNameParsingError")]
RoleNameParsingError,
#[error("RoleNameAlreadyExists")]
RoleNameAlreadyExists,
#[error("TotpNotSetup")]
TotpNotSetup,
#[error("InvalidTotp")]
InvalidTotp,
#[error("TotpRequired")]
TotpRequired,
#[error("InvalidRecoveryCode")]
InvalidRecoveryCode,
#[error("TwoFactorAuthRequired")]
TwoFactorAuthRequired,
#[error("TwoFactorAuthNotSetup")]
TwoFactorAuthNotSetup,
#[error("TOTP secret not found")]
TotpSecretNotFound,
#[error("User auth method already exists")]
UserAuthMethodAlreadyExists,
#[error("Invalid user auth method operation")]
InvalidUserAuthMethodOperation,
#[error("Auth config parsing error")]
AuthConfigParsingError,
#[error("Invalid SSO request")]
SSOFailed,
#[error("profile_id missing in JWT")]
JwtProfileIdMissing,
#[error("Maximum attempts reached for TOTP")]
MaxTotpAttemptsReached,
#[error("Maximum attempts reached for Recovery Code")]
MaxRecoveryCodeAttemptsReached,
#[error("Forbidden tenant id")]
ForbiddenTenantId,
#[error("Error Uploading file to Theme Storage")]
ErrorUploadingFile,
#[error("Error Retrieving file from Theme Storage")]
ErrorRetrievingFile,
#[error("Theme not found")]
ThemeNotFound,
#[error("Theme with lineage already exists")]
ThemeAlreadyExists,
#[error("Invalid field: {0} in lineage")]
InvalidThemeLineage(String),
#[error("Missing required field: email_config")]
MissingEmailConfig,
#[error("Invalid Auth Method Operation: {0}")]
InvalidAuthMethodOperationWithMessage(String),
#[error("Invalid Clone Connector Operation: {0}")]
InvalidCloneConnectorOperation(String),
#[error("Error cloning connector: {0}")]
ErrorCloningConnector(String),
}
impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorResponse> for UserErrors {
fn switch(&self) -> api_models::errors::types::ApiErrorResponse {
use api_models::errors::types::{ApiError, ApiErrorResponse as AER};
let sub_code = "UR";
match self {
Self::InternalServerError => {
AER::InternalServerError(ApiError::new("HE", 0, self.get_error_message(), None))
}
Self::InvalidCredentials => {
AER::Unauthorized(ApiError::new(sub_code, 1, self.get_error_message(), None))
}
Self::UserNotFound => {
AER::Unauthorized(ApiError::new(sub_code, 2, self.get_error_message(), None))
}
Self::UserExists => {
AER::BadRequest(ApiError::new(sub_code, 3, self.get_error_message(), None))
}
Self::LinkInvalid => {
AER::Unauthorized(ApiError::new(sub_code, 4, self.get_error_message(), None))
}
Self::UnverifiedUser => {
AER::Unauthorized(ApiError::new(sub_code, 5, self.get_error_message(), None))
}
Self::InvalidOldPassword => {
AER::BadRequest(ApiError::new(sub_code, 6, self.get_error_message(), None))
}
Self::EmailParsingError => {
AER::BadRequest(ApiError::new(sub_code, 7, self.get_error_message(), None))
}
Self::NameParsingError => {
AER::BadRequest(ApiError::new(sub_code, 8, self.get_error_message(), None))
}
Self::PasswordParsingError => {
AER::BadRequest(ApiError::new(sub_code, 9, self.get_error_message(), None))
}
Self::UserAlreadyVerified => {
AER::Unauthorized(ApiError::new(sub_code, 11, self.get_error_message(), None))
}
Self::CompanyNameParsingError => {
AER::BadRequest(ApiError::new(sub_code, 14, self.get_error_message(), None))
}
Self::MerchantAccountCreationError(_) => AER::InternalServerError(ApiError::new(
sub_code,
15,
self.get_error_message(),
None,
)),
Self::InvalidEmailError => {
AER::BadRequest(ApiError::new(sub_code, 16, self.get_error_message(), None))
}
Self::MerchantIdNotFound => {
AER::BadRequest(ApiError::new(sub_code, 18, self.get_error_message(), None))
}
Self::MetadataAlreadySet => {
AER::BadRequest(ApiError::new(sub_code, 19, self.get_error_message(), None))
}
Self::DuplicateOrganizationId => AER::InternalServerError(ApiError::new(
sub_code,
21,
self.get_error_message(),
None,
)),
Self::InvalidRoleId => {
AER::BadRequest(ApiError::new(sub_code, 22, self.get_error_message(), None))
}
Self::InvalidRoleOperation => {
AER::BadRequest(ApiError::new(sub_code, 23, self.get_error_message(), None))
}
Self::IpAddressParsingFailed => AER::InternalServerError(ApiError::new(
sub_code,
24,
self.get_error_message(),
None,
)),
Self::InvalidMetadataRequest => {
AER::BadRequest(ApiError::new(sub_code, 26, self.get_error_message(), None))
}
Self::MerchantIdParsingError => {
AER::BadRequest(ApiError::new(sub_code, 28, self.get_error_message(), None))
}
Self::ChangePasswordError => {
AER::BadRequest(ApiError::new(sub_code, 29, self.get_error_message(), None))
}
Self::InvalidDeleteOperation => {
AER::BadRequest(ApiError::new(sub_code, 30, self.get_error_message(), None))
}
Self::MaxInvitationsError => {
AER::BadRequest(ApiError::new(sub_code, 31, self.get_error_message(), None))
}
Self::RoleNotFound => {
AER::BadRequest(ApiError::new(sub_code, 32, self.get_error_message(), None))
}
Self::InvalidRoleOperationWithMessage(_) => {
AER::BadRequest(ApiError::new(sub_code, 33, self.get_error_message(), None))
}
Self::RoleNameParsingError => {
AER::BadRequest(ApiError::new(sub_code, 34, self.get_error_message(), None))
}
Self::RoleNameAlreadyExists => {
AER::BadRequest(ApiError::new(sub_code, 35, self.get_error_message(), None))
}
Self::TotpNotSetup => {
AER::BadRequest(ApiError::new(sub_code, 36, self.get_error_message(), None))
}
Self::InvalidTotp => {
AER::BadRequest(ApiError::new(sub_code, 37, self.get_error_message(), None))
}
Self::TotpRequired => {
AER::BadRequest(ApiError::new(sub_code, 38, self.get_error_message(), None))
}
Self::InvalidRecoveryCode => {
AER::BadRequest(ApiError::new(sub_code, 39, self.get_error_message(), None))
}
Self::TwoFactorAuthRequired => {
AER::BadRequest(ApiError::new(sub_code, 40, self.get_error_message(), None))
}
Self::TwoFactorAuthNotSetup => {
AER::BadRequest(ApiError::new(sub_code, 41, self.get_error_message(), None))
}
Self::TotpSecretNotFound => {
AER::BadRequest(ApiError::new(sub_code, 42, self.get_error_message(), None))
}
Self::UserAuthMethodAlreadyExists => {
AER::BadRequest(ApiError::new(sub_code, 43, self.get_error_message(), None))
}
Self::InvalidUserAuthMethodOperation => {
AER::BadRequest(ApiError::new(sub_code, 44, self.get_error_message(), None))
}
Self::AuthConfigParsingError => {
AER::BadRequest(ApiError::new(sub_code, 45, self.get_error_message(), None))
}
Self::SSOFailed => {
AER::BadRequest(ApiError::new(sub_code, 46, self.get_error_message(), None))
}
Self::JwtProfileIdMissing => {
AER::Unauthorized(ApiError::new(sub_code, 47, self.get_error_message(), None))
}
Self::MaxTotpAttemptsReached => {
AER::BadRequest(ApiError::new(sub_code, 48, self.get_error_message(), None))
}
Self::MaxRecoveryCodeAttemptsReached => {
AER::BadRequest(ApiError::new(sub_code, 49, self.get_error_message(), None))
}
Self::ForbiddenTenantId => {
AER::BadRequest(ApiError::new(sub_code, 50, self.get_error_message(), None))
}
Self::ErrorUploadingFile => AER::InternalServerError(ApiError::new(
sub_code,
51,
self.get_error_message(),
None,
)),
Self::ErrorRetrievingFile => AER::InternalServerError(ApiError::new(
sub_code,
52,
self.get_error_message(),
None,
)),
Self::ThemeNotFound => {
AER::NotFound(ApiError::new(sub_code, 53, self.get_error_message(), None))
}
Self::ThemeAlreadyExists => {
AER::BadRequest(ApiError::new(sub_code, 54, self.get_error_message(), None))
}
Self::InvalidThemeLineage(_) => {
AER::BadRequest(ApiError::new(sub_code, 55, self.get_error_message(), None))
}
Self::MissingEmailConfig => {
AER::BadRequest(ApiError::new(sub_code, 56, self.get_error_message(), None))
}
Self::InvalidAuthMethodOperationWithMessage(_) => {
AER::BadRequest(ApiError::new(sub_code, 57, self.get_error_message(), None))
}
Self::InvalidCloneConnectorOperation(_) => {
AER::BadRequest(ApiError::new(sub_code, 58, self.get_error_message(), None))
}
Self::ErrorCloningConnector(_) => AER::InternalServerError(ApiError::new(
sub_code,
59,
self.get_error_message(),
None,
)),
}
}
}
impl UserErrors {
pub fn get_error_message(&self) -> String {
match self {
Self::InternalServerError => "Something went wrong".to_string(),
Self::InvalidCredentials => "Incorrect email or password".to_string(),
Self::UserNotFound => "Email doesn’t exist. Register".to_string(),
Self::UserExists => "An account already exists with this email".to_string(),
Self::LinkInvalid => "Invalid or expired link".to_string(),
Self::UnverifiedUser => "Kindly verify your account".to_string(),
Self::InvalidOldPassword => {
"Old password incorrect. Please enter the correct password".to_string()
}
Self::EmailParsingError => "Invalid Email".to_string(),
Self::NameParsingError => "Invalid Name".to_string(),
Self::PasswordParsingError => "Invalid Password".to_string(),
Self::UserAlreadyVerified => "User already verified".to_string(),
Self::CompanyNameParsingError => "Invalid Company Name".to_string(),
Self::MerchantAccountCreationError(error_message) => error_message.to_string(),
Self::InvalidEmailError => "Invalid Email".to_string(),
Self::MerchantIdNotFound => "Invalid Merchant ID".to_string(),
Self::MetadataAlreadySet => "Metadata already set".to_string(),
Self::DuplicateOrganizationId => {
"An Organization with the id already exists".to_string()
}
Self::InvalidRoleId => "Invalid Role ID".to_string(),
Self::InvalidRoleOperation => "User Role Operation Not Supported".to_string(),
Self::IpAddressParsingFailed => "Something went wrong".to_string(),
Self::InvalidMetadataRequest => "Invalid Metadata Request".to_string(),
Self::MerchantIdParsingError => "Invalid Merchant Id".to_string(),
Self::ChangePasswordError => "Old and new password cannot be same".to_string(),
Self::InvalidDeleteOperation => "Delete Operation Not Supported".to_string(),
Self::MaxInvitationsError => "Maximum invite count per request exceeded".to_string(),
Self::RoleNotFound => "Role Not Found".to_string(),
Self::InvalidRoleOperationWithMessage(error_message) => error_message.to_string(),
Self::RoleNameParsingError => "Invalid Role Name".to_string(),
Self::RoleNameAlreadyExists => "Role name already exists".to_string(),
Self::TotpNotSetup => "TOTP not setup".to_string(),
Self::InvalidTotp => "Invalid TOTP".to_string(),
Self::TotpRequired => "TOTP required".to_string(),
Self::InvalidRecoveryCode => "Invalid Recovery Code".to_string(),
Self::MaxTotpAttemptsReached => "Maximum attempts reached for TOTP".to_string(),
Self::MaxRecoveryCodeAttemptsReached => {
"Maximum attempts reached for Recovery Code".to_string()
}
Self::TwoFactorAuthRequired => "Two factor auth required".to_string(),
Self::TwoFactorAuthNotSetup => "Two factor auth not setup".to_string(),
Self::TotpSecretNotFound => "TOTP secret not found".to_string(),
Self::UserAuthMethodAlreadyExists => "User auth method already exists".to_string(),
Self::InvalidUserAuthMethodOperation => {
"Invalid user auth method operation".to_string()
}
Self::AuthConfigParsingError => "Auth config parsing error".to_string(),
Self::SSOFailed => "Invalid SSO request".to_string(),
Self::JwtProfileIdMissing => "profile_id missing in JWT".to_string(),
Self::ForbiddenTenantId => "Forbidden tenant id".to_string(),
Self::ErrorUploadingFile => "Error Uploading file to Theme Storage".to_string(),
Self::ErrorRetrievingFile => "Error Retrieving file from Theme Storage".to_string(),
Self::ThemeNotFound => "Theme not found".to_string(),
Self::ThemeAlreadyExists => "Theme with lineage already exists".to_string(),
Self::InvalidThemeLineage(field_name) => {
format!("Invalid field: {field_name} in lineage")
}
Self::MissingEmailConfig => "Missing required field: email_config".to_string(),
Self::InvalidAuthMethodOperationWithMessage(operation) => {
format!("Invalid Auth Method Operation: {operation}")
}
Self::InvalidCloneConnectorOperation(operation) => {
format!("Invalid Clone Connector Operation: {operation}")
}
Self::ErrorCloningConnector(error_message) => {
format!("Error cloning connector: {error_message}")
}
}
}
}
|
crates/router/src/core/errors/user.rs
|
router::src::core::errors::user
| 3,683
| true
|
// File: crates/router/src/core/errors/error_handlers.rs
// Module: router::src::core::errors::error_handlers
use actix_web::{body, dev::ServiceResponse, middleware::ErrorHandlerResponse, ResponseError};
use http::StatusCode;
use super::ApiErrorResponse;
use crate::logger;
pub fn custom_error_handlers<B: body::MessageBody + 'static>(
res: ServiceResponse<B>,
) -> actix_web::Result<ErrorHandlerResponse<B>> {
let error_response = match res.status() {
StatusCode::NOT_FOUND => ApiErrorResponse::InvalidRequestUrl,
StatusCode::METHOD_NOT_ALLOWED => ApiErrorResponse::InvalidHttpMethod,
_ => ApiErrorResponse::InternalServerError,
};
let (req, res) = res.into_parts();
logger::warn!(error_response=?res);
let res = match res.error() {
Some(_) => res.map_into_boxed_body(),
None => error_response.error_response(),
};
let res = ServiceResponse::new(req, res)
.map_into_boxed_body()
.map_into_right_body();
Ok(ErrorHandlerResponse::Response(res))
}
// can be used as .default_service for web::resource to modify the default behavior of method_not_found error i.e. raised
// use actix_web::dev::ServiceRequest
// pub async fn default_service_405<E>(req: ServiceRequest) -> Result<ServiceResponse, E> {
// Ok(req.into_response(ApiErrorResponse::InvalidHttpMethod.error_response()))
// }
|
crates/router/src/core/errors/error_handlers.rs
|
router::src::core::errors::error_handlers
| 313
| true
|
// File: crates/router/src/core/errors/utils.rs
// Module: router::src::core::errors::utils
use common_utils::errors::CustomResult;
use crate::{core::errors, logger};
pub trait StorageErrorExt<T, E> {
#[track_caller]
fn to_not_found_response(self, not_found_response: E) -> error_stack::Result<T, E>;
#[track_caller]
fn to_duplicate_response(self, duplicate_response: E) -> error_stack::Result<T, E>;
}
impl<T> StorageErrorExt<T, errors::CustomersErrorResponse>
for error_stack::Result<T, errors::StorageError>
{
#[track_caller]
fn to_not_found_response(
self,
not_found_response: errors::CustomersErrorResponse,
) -> error_stack::Result<T, errors::CustomersErrorResponse> {
self.map_err(|err| match err.current_context() {
error if error.is_db_not_found() => err.change_context(not_found_response),
errors::StorageError::CustomerRedacted => {
err.change_context(errors::CustomersErrorResponse::CustomerRedacted)
}
_ => err.change_context(errors::CustomersErrorResponse::InternalServerError),
})
}
fn to_duplicate_response(
self,
duplicate_response: errors::CustomersErrorResponse,
) -> error_stack::Result<T, errors::CustomersErrorResponse> {
self.map_err(|err| {
if err.current_context().is_db_unique_violation() {
err.change_context(duplicate_response)
} else {
err.change_context(errors::CustomersErrorResponse::InternalServerError)
}
})
}
}
impl<T> StorageErrorExt<T, errors::ApiErrorResponse>
for error_stack::Result<T, errors::StorageError>
{
#[track_caller]
fn to_not_found_response(
self,
not_found_response: errors::ApiErrorResponse,
) -> error_stack::Result<T, errors::ApiErrorResponse> {
self.map_err(|err| {
let new_err = match err.current_context() {
errors::StorageError::ValueNotFound(_) => not_found_response,
errors::StorageError::CustomerRedacted => {
errors::ApiErrorResponse::CustomerRedacted
}
_ => errors::ApiErrorResponse::InternalServerError,
};
err.change_context(new_err)
})
}
#[track_caller]
fn to_duplicate_response(
self,
duplicate_response: errors::ApiErrorResponse,
) -> error_stack::Result<T, errors::ApiErrorResponse> {
self.map_err(|err| {
let new_err = match err.current_context() {
errors::StorageError::DuplicateValue { .. } => duplicate_response,
_ => errors::ApiErrorResponse::InternalServerError,
};
err.change_context(new_err)
})
}
}
pub trait ConnectorErrorExt<T> {
#[track_caller]
fn to_refund_failed_response(self) -> error_stack::Result<T, errors::ApiErrorResponse>;
#[track_caller]
fn to_payment_failed_response(self) -> error_stack::Result<T, errors::ApiErrorResponse>;
#[track_caller]
fn to_setup_mandate_failed_response(self) -> error_stack::Result<T, errors::ApiErrorResponse>;
#[track_caller]
fn to_dispute_failed_response(self) -> error_stack::Result<T, errors::ApiErrorResponse>;
#[track_caller]
fn to_files_failed_response(self) -> error_stack::Result<T, errors::ApiErrorResponse>;
#[cfg(feature = "payouts")]
#[track_caller]
fn to_payout_failed_response(self) -> error_stack::Result<T, errors::ApiErrorResponse>;
#[track_caller]
fn to_vault_failed_response(self) -> error_stack::Result<T, errors::ApiErrorResponse>;
// Validates if the result, is Ok(..) or WebhookEventTypeNotFound all the other error variants
// are cascaded while these two event types are handled via `Option`
#[track_caller]
fn allow_webhook_event_type_not_found(
self,
enabled: bool,
) -> error_stack::Result<Option<T>, errors::ConnectorError>;
}
impl<T> ConnectorErrorExt<T> for error_stack::Result<T, errors::ConnectorError> {
fn to_refund_failed_response(self) -> error_stack::Result<T, errors::ApiErrorResponse> {
self.map_err(|err| match err.current_context() {
errors::ConnectorError::ProcessingStepFailed(Some(bytes)) => {
let response_str = std::str::from_utf8(bytes);
let data = match response_str {
Ok(s) => serde_json::from_str(s)
.map_err(
|error| logger::error!(%error,"Failed to convert response to JSON"),
)
.ok(),
Err(error) => {
logger::error!(%error,"Failed to convert response to UTF8 string");
None
}
};
err.change_context(errors::ApiErrorResponse::RefundFailed { data })
}
errors::ConnectorError::NotImplemented(reason) => {
errors::ApiErrorResponse::NotImplemented {
message: errors::NotImplementedMessage::Reason(reason.to_string()),
}
.into()
}
errors::ConnectorError::NotSupported { message, connector } => {
errors::ApiErrorResponse::NotSupported {
message: format!("{message} is not supported by {connector}"),
}
.into()
}
errors::ConnectorError::CaptureMethodNotSupported => {
errors::ApiErrorResponse::NotSupported {
message: "Capture Method Not Supported".to_owned(),
}
.into()
}
errors::ConnectorError::FailedToObtainIntegrationUrl
| errors::ConnectorError::RequestEncodingFailed
| errors::ConnectorError::RequestEncodingFailedWithReason(_)
| errors::ConnectorError::ParsingFailed
| errors::ConnectorError::ResponseDeserializationFailed
| errors::ConnectorError::UnexpectedResponseError(_)
| errors::ConnectorError::RoutingRulesParsingError
| errors::ConnectorError::FailedToObtainPreferredConnector
| errors::ConnectorError::ProcessingStepFailed(_)
| errors::ConnectorError::InvalidConnectorName
| errors::ConnectorError::InvalidWallet
| errors::ConnectorError::ResponseHandlingFailed
| errors::ConnectorError::MissingRequiredField { .. }
| errors::ConnectorError::MissingRequiredFields { .. }
| errors::ConnectorError::FailedToObtainAuthType
| errors::ConnectorError::FailedToObtainCertificate
| errors::ConnectorError::NoConnectorMetaData
| errors::ConnectorError::NoConnectorWalletDetails
| errors::ConnectorError::FailedToObtainCertificateKey
| errors::ConnectorError::MaxFieldLengthViolated { .. }
| errors::ConnectorError::FlowNotSupported { .. }
| errors::ConnectorError::MissingConnectorMandateID
| errors::ConnectorError::MissingConnectorMandateMetadata
| errors::ConnectorError::MissingConnectorTransactionID
| errors::ConnectorError::MissingConnectorRefundID
| errors::ConnectorError::MissingApplePayTokenData
| errors::ConnectorError::WebhooksNotImplemented
| errors::ConnectorError::WebhookBodyDecodingFailed
| errors::ConnectorError::WebhookSignatureNotFound
| errors::ConnectorError::WebhookSourceVerificationFailed
| errors::ConnectorError::WebhookVerificationSecretNotFound
| errors::ConnectorError::WebhookVerificationSecretInvalid
| errors::ConnectorError::WebhookReferenceIdNotFound
| errors::ConnectorError::WebhookEventTypeNotFound
| errors::ConnectorError::WebhookResourceObjectNotFound
| errors::ConnectorError::WebhookResponseEncodingFailed
| errors::ConnectorError::InvalidDateFormat
| errors::ConnectorError::DateFormattingFailed
| errors::ConnectorError::InvalidDataFormat { .. }
| errors::ConnectorError::MismatchedPaymentData
| errors::ConnectorError::MandatePaymentDataMismatch { .. }
| errors::ConnectorError::InvalidWalletToken { .. }
| errors::ConnectorError::MissingConnectorRelatedTransactionID { .. }
| errors::ConnectorError::FileValidationFailed { .. }
| errors::ConnectorError::MissingConnectorRedirectionPayload { .. }
| errors::ConnectorError::FailedAtConnector { .. }
| errors::ConnectorError::MissingPaymentMethodType
| errors::ConnectorError::InSufficientBalanceInPaymentMethod
| errors::ConnectorError::RequestTimeoutReceived
| errors::ConnectorError::CurrencyNotSupported { .. }
| errors::ConnectorError::InvalidConnectorConfig { .. }
| errors::ConnectorError::AmountConversionFailed
| errors::ConnectorError::GenericError { .. } => {
err.change_context(errors::ApiErrorResponse::RefundFailed { data: None })
}
})
}
fn to_payment_failed_response(self) -> error_stack::Result<T, errors::ApiErrorResponse> {
self.map_err(|err| {
let error = match err.current_context() {
errors::ConnectorError::ProcessingStepFailed(Some(bytes)) => {
let response_str = std::str::from_utf8(bytes);
let data = match response_str {
Ok(s) => serde_json::from_str(s)
.map_err(
|error| logger::error!(%error,"Failed to convert response to JSON"),
)
.ok(),
Err(error) => {
logger::error!(%error,"Failed to convert response to UTF8 string");
None
}
};
errors::ApiErrorResponse::PaymentAuthorizationFailed { data }
}
errors::ConnectorError::MissingRequiredField { field_name } => {
errors::ApiErrorResponse::MissingRequiredField { field_name }
}
errors::ConnectorError::MissingRequiredFields { field_names } => {
errors::ApiErrorResponse::MissingRequiredFields { field_names: field_names.to_vec() }
}
errors::ConnectorError::NotImplemented(reason) => {
errors::ApiErrorResponse::NotImplemented {
message: errors::NotImplementedMessage::Reason(
reason.to_string(),
),
}
}
errors::ConnectorError::MismatchedPaymentData => {
errors::ApiErrorResponse::InvalidDataValue {
field_name:
"payment_method_data, payment_method_type and payment_experience does not match",
}
},
errors::ConnectorError::MandatePaymentDataMismatch {fields}=> {
errors::ApiErrorResponse::MandatePaymentDataMismatch {
fields: fields.to_owned(),
}
},
errors::ConnectorError::NotSupported { message, connector } => {
errors::ApiErrorResponse::NotSupported { message: format!("{message} is not supported by {connector}") }
},
errors::ConnectorError::FlowNotSupported{ flow, connector } => {
errors::ApiErrorResponse::FlowNotSupported { flow: flow.to_owned(), connector: connector.to_owned() }
},
errors::ConnectorError::MaxFieldLengthViolated{ connector, field_name, max_length, received_length} => {
errors::ApiErrorResponse::MaxFieldLengthViolated { connector: connector.to_string(), field_name: field_name.to_string(), max_length: *max_length, received_length: *received_length }
},
errors::ConnectorError::InvalidDataFormat { field_name } => {
errors::ApiErrorResponse::InvalidDataValue { field_name }
},
errors::ConnectorError::CaptureMethodNotSupported => {
errors::ApiErrorResponse::NotSupported {
message: "Capture Method Not Supported".to_owned(),
}
}
errors::ConnectorError::InvalidWalletToken {wallet_name} => errors::ApiErrorResponse::InvalidWalletToken {wallet_name: wallet_name.to_string()},
errors::ConnectorError::CurrencyNotSupported { message, connector} => errors::ApiErrorResponse::CurrencyNotSupported { message: format!("Credentials for the currency {message} are not configured with the connector {connector}/hyperswitch") },
errors::ConnectorError::FailedToObtainAuthType => errors::ApiErrorResponse::InvalidConnectorConfiguration {config: "connector_account_details".to_string()},
errors::ConnectorError::InvalidConnectorConfig { config } => errors::ApiErrorResponse::InvalidConnectorConfiguration { config: config.to_string() },
errors::ConnectorError::FailedToObtainIntegrationUrl |
errors::ConnectorError::RequestEncodingFailed |
errors::ConnectorError::RequestEncodingFailedWithReason(_) |
errors::ConnectorError::ParsingFailed |
errors::ConnectorError::ResponseDeserializationFailed |
errors::ConnectorError::UnexpectedResponseError(_) |
errors::ConnectorError::RoutingRulesParsingError |
errors::ConnectorError::FailedToObtainPreferredConnector |
errors::ConnectorError::InvalidConnectorName |
errors::ConnectorError::InvalidWallet |
errors::ConnectorError::ResponseHandlingFailed |
errors::ConnectorError::FailedToObtainCertificate |
errors::ConnectorError::NoConnectorMetaData | errors::ConnectorError::NoConnectorWalletDetails |
errors::ConnectorError::FailedToObtainCertificateKey |
errors::ConnectorError::MissingConnectorMandateID |
errors::ConnectorError::MissingConnectorMandateMetadata |
errors::ConnectorError::MissingConnectorTransactionID |
errors::ConnectorError::MissingConnectorRefundID |
errors::ConnectorError::MissingApplePayTokenData |
errors::ConnectorError::WebhooksNotImplemented |
errors::ConnectorError::WebhookBodyDecodingFailed |
errors::ConnectorError::WebhookSignatureNotFound |
errors::ConnectorError::WebhookSourceVerificationFailed |
errors::ConnectorError::WebhookVerificationSecretNotFound |
errors::ConnectorError::WebhookVerificationSecretInvalid |
errors::ConnectorError::WebhookReferenceIdNotFound |
errors::ConnectorError::WebhookEventTypeNotFound |
errors::ConnectorError::WebhookResourceObjectNotFound |
errors::ConnectorError::WebhookResponseEncodingFailed |
errors::ConnectorError::InvalidDateFormat |
errors::ConnectorError::DateFormattingFailed |
errors::ConnectorError::MissingConnectorRelatedTransactionID { .. } |
errors::ConnectorError::FileValidationFailed { .. } |
errors::ConnectorError::MissingConnectorRedirectionPayload { .. } |
errors::ConnectorError::FailedAtConnector { .. } |
errors::ConnectorError::MissingPaymentMethodType |
errors::ConnectorError::InSufficientBalanceInPaymentMethod |
errors::ConnectorError::RequestTimeoutReceived |
errors::ConnectorError::ProcessingStepFailed(None)|
errors::ConnectorError::GenericError {..} |
errors::ConnectorError::AmountConversionFailed => errors::ApiErrorResponse::InternalServerError
};
err.change_context(error)
})
}
fn to_setup_mandate_failed_response(self) -> error_stack::Result<T, errors::ApiErrorResponse> {
self.map_err(|err| {
let error = err.current_context();
let data = match error {
errors::ConnectorError::ProcessingStepFailed(Some(bytes)) => {
let response_str = std::str::from_utf8(bytes);
let error_response = match response_str {
Ok(s) => serde_json::from_str(s)
.map_err(
|err| logger::error!(%err, "Failed to convert response to JSON"),
)
.ok(),
Err(err) => {
logger::error!(%err, "Failed to convert response to UTF8 string");
None
}
};
errors::ApiErrorResponse::PaymentAuthorizationFailed {
data: error_response,
}
}
errors::ConnectorError::MissingRequiredField { field_name } => {
errors::ApiErrorResponse::MissingRequiredField { field_name }
}
errors::ConnectorError::FailedToObtainIntegrationUrl => {
errors::ApiErrorResponse::InvalidConnectorConfiguration {
config: "connector_account_details".to_string(),
}
}
errors::ConnectorError::InvalidConnectorConfig { config: field_name } => {
errors::ApiErrorResponse::InvalidConnectorConfiguration {
config: field_name.to_string(),
}
}
errors::ConnectorError::InvalidWalletToken { wallet_name } => {
errors::ApiErrorResponse::InvalidWalletToken {
wallet_name: wallet_name.to_string(),
}
}
errors::ConnectorError::CaptureMethodNotSupported => {
errors::ApiErrorResponse::NotSupported {
message: "Capture Method Not Supported".to_owned(),
}
}
errors::ConnectorError::RequestEncodingFailed
| errors::ConnectorError::RequestEncodingFailedWithReason(_)
| errors::ConnectorError::ParsingFailed
| errors::ConnectorError::ResponseDeserializationFailed
| errors::ConnectorError::UnexpectedResponseError(_)
| errors::ConnectorError::RoutingRulesParsingError
| errors::ConnectorError::FailedToObtainPreferredConnector
| errors::ConnectorError::InvalidConnectorName
| errors::ConnectorError::InvalidWallet
| errors::ConnectorError::ResponseHandlingFailed
| errors::ConnectorError::MissingRequiredFields { .. }
| errors::ConnectorError::FailedToObtainAuthType
| errors::ConnectorError::FailedToObtainCertificate
| errors::ConnectorError::NoConnectorMetaData
| errors::ConnectorError::NoConnectorWalletDetails
| errors::ConnectorError::FailedToObtainCertificateKey
| errors::ConnectorError::NotImplemented(_)
| errors::ConnectorError::NotSupported { .. }
| errors::ConnectorError::MaxFieldLengthViolated { .. }
| errors::ConnectorError::FlowNotSupported { .. }
| errors::ConnectorError::MissingConnectorMandateID
| errors::ConnectorError::MissingConnectorMandateMetadata
| errors::ConnectorError::MissingConnectorTransactionID
| errors::ConnectorError::MissingConnectorRefundID
| errors::ConnectorError::MissingApplePayTokenData
| errors::ConnectorError::WebhooksNotImplemented
| errors::ConnectorError::WebhookBodyDecodingFailed
| errors::ConnectorError::WebhookSignatureNotFound
| errors::ConnectorError::WebhookSourceVerificationFailed
| errors::ConnectorError::WebhookVerificationSecretNotFound
| errors::ConnectorError::WebhookVerificationSecretInvalid
| errors::ConnectorError::WebhookReferenceIdNotFound
| errors::ConnectorError::WebhookEventTypeNotFound
| errors::ConnectorError::WebhookResourceObjectNotFound
| errors::ConnectorError::WebhookResponseEncodingFailed
| errors::ConnectorError::InvalidDateFormat
| errors::ConnectorError::DateFormattingFailed
| errors::ConnectorError::InvalidDataFormat { .. }
| errors::ConnectorError::MismatchedPaymentData
| errors::ConnectorError::MandatePaymentDataMismatch { .. }
| errors::ConnectorError::MissingConnectorRelatedTransactionID { .. }
| errors::ConnectorError::FileValidationFailed { .. }
| errors::ConnectorError::MissingConnectorRedirectionPayload { .. }
| errors::ConnectorError::FailedAtConnector { .. }
| errors::ConnectorError::MissingPaymentMethodType
| errors::ConnectorError::InSufficientBalanceInPaymentMethod
| errors::ConnectorError::RequestTimeoutReceived
| errors::ConnectorError::CurrencyNotSupported { .. }
| errors::ConnectorError::ProcessingStepFailed(None)
| errors::ConnectorError::AmountConversionFailed
| errors::ConnectorError::GenericError { .. } => {
logger::error!(%error,"Setup Mandate flow failed");
errors::ApiErrorResponse::PaymentAuthorizationFailed { data: None }
}
};
err.change_context(data)
})
}
fn to_dispute_failed_response(self) -> error_stack::Result<T, errors::ApiErrorResponse> {
self.map_err(|err| {
let error = match err.current_context() {
errors::ConnectorError::ProcessingStepFailed(Some(bytes)) => {
let response_str = std::str::from_utf8(bytes);
let data = match response_str {
Ok(s) => serde_json::from_str(s)
.map_err(
|error| logger::error!(%error,"Failed to convert response to JSON"),
)
.ok(),
Err(error) => {
logger::error!(%error,"Failed to convert response to UTF8 string");
None
}
};
errors::ApiErrorResponse::DisputeFailed { data }
}
errors::ConnectorError::MissingRequiredField { field_name } => {
errors::ApiErrorResponse::MissingRequiredField { field_name }
}
errors::ConnectorError::MissingRequiredFields { field_names } => {
errors::ApiErrorResponse::MissingRequiredFields {
field_names: field_names.to_vec(),
}
}
_ => errors::ApiErrorResponse::InternalServerError,
};
err.change_context(error)
})
}
fn to_files_failed_response(self) -> error_stack::Result<T, errors::ApiErrorResponse> {
self.map_err(|err| {
let error = match err.current_context() {
errors::ConnectorError::ProcessingStepFailed(Some(bytes)) => {
let response_str = std::str::from_utf8(bytes);
let data = match response_str {
Ok(s) => serde_json::from_str(s)
.map_err(
|error| logger::error!(%error,"Failed to convert response to JSON"),
)
.ok(),
Err(error) => {
logger::error!(%error,"Failed to convert response to UTF8 string");
None
}
};
errors::ApiErrorResponse::DisputeFailed { data }
}
errors::ConnectorError::MissingRequiredField { field_name } => {
errors::ApiErrorResponse::MissingRequiredField { field_name }
}
errors::ConnectorError::MissingRequiredFields { field_names } => {
errors::ApiErrorResponse::MissingRequiredFields {
field_names: field_names.to_vec(),
}
}
_ => errors::ApiErrorResponse::InternalServerError,
};
err.change_context(error)
})
}
#[cfg(feature = "payouts")]
fn to_payout_failed_response(self) -> error_stack::Result<T, errors::ApiErrorResponse> {
self.map_err(|err| {
let error = match err.current_context() {
errors::ConnectorError::ProcessingStepFailed(Some(bytes)) => {
let response_str = std::str::from_utf8(bytes);
let data = match response_str {
Ok(s) => serde_json::from_str(s)
.map_err(
|error| logger::error!(%error,"Failed to convert response to JSON"),
)
.ok(),
Err(error) => {
logger::error!(%error,"Failed to convert response to UTF8 string");
None
}
};
errors::ApiErrorResponse::PayoutFailed { data }
}
errors::ConnectorError::MissingRequiredField { field_name } => {
errors::ApiErrorResponse::MissingRequiredField { field_name }
}
errors::ConnectorError::MissingRequiredFields { field_names } => {
errors::ApiErrorResponse::MissingRequiredFields {
field_names: field_names.to_vec(),
}
}
errors::ConnectorError::NotSupported { message, connector } => {
errors::ApiErrorResponse::NotSupported {
message: format!("{message} by {connector}"),
}
}
errors::ConnectorError::NotImplemented(reason) => {
errors::ApiErrorResponse::NotImplemented {
message: errors::NotImplementedMessage::Reason(reason.to_string()),
}
}
errors::ConnectorError::InvalidConnectorConfig { config } => {
errors::ApiErrorResponse::InvalidConnectorConfiguration {
config: config.to_string(),
}
}
_ => errors::ApiErrorResponse::InternalServerError,
};
err.change_context(error)
})
}
fn to_vault_failed_response(self) -> error_stack::Result<T, errors::ApiErrorResponse> {
self.map_err(|err| {
let error = match err.current_context() {
errors::ConnectorError::ProcessingStepFailed(_) => {
errors::ApiErrorResponse::ExternalVaultFailed
}
errors::ConnectorError::MissingRequiredField { field_name } => {
errors::ApiErrorResponse::MissingRequiredField { field_name }
}
errors::ConnectorError::MissingRequiredFields { field_names } => {
errors::ApiErrorResponse::MissingRequiredFields {
field_names: field_names.to_vec(),
}
}
errors::ConnectorError::NotSupported { message, connector } => {
errors::ApiErrorResponse::NotSupported {
message: format!("{message} by {connector}"),
}
}
errors::ConnectorError::NotImplemented(reason) => {
errors::ApiErrorResponse::NotImplemented {
message: errors::NotImplementedMessage::Reason(reason.to_string()),
}
}
errors::ConnectorError::InvalidConnectorConfig { config } => {
errors::ApiErrorResponse::InvalidConnectorConfiguration {
config: config.to_string(),
}
}
_ => errors::ApiErrorResponse::InternalServerError,
};
err.change_context(error)
})
}
fn allow_webhook_event_type_not_found(
self,
enabled: bool,
) -> CustomResult<Option<T>, errors::ConnectorError> {
match self {
Ok(event_type) => Ok(Some(event_type)),
Err(error) => match error.current_context() {
errors::ConnectorError::WebhookEventTypeNotFound if enabled => Ok(None),
_ => Err(error),
},
}
}
}
pub trait RedisErrorExt {
#[track_caller]
fn to_redis_failed_response(self, key: &str) -> error_stack::Report<errors::StorageError>;
}
impl RedisErrorExt for error_stack::Report<errors::RedisError> {
fn to_redis_failed_response(self, key: &str) -> error_stack::Report<errors::StorageError> {
match self.current_context() {
errors::RedisError::NotFound => self.change_context(
errors::StorageError::ValueNotFound(format!("Data does not exist for key {key}")),
),
errors::RedisError::SetNxFailed => {
self.change_context(errors::StorageError::DuplicateValue {
entity: "redis",
key: Some(key.to_string()),
})
}
_ => self.change_context(errors::StorageError::KVError),
}
}
}
#[cfg(feature = "olap")]
impl<T> StorageErrorExt<T, errors::UserErrors> for error_stack::Result<T, errors::StorageError> {
#[track_caller]
fn to_not_found_response(
self,
not_found_response: errors::UserErrors,
) -> error_stack::Result<T, errors::UserErrors> {
self.map_err(|e| {
if e.current_context().is_db_not_found() {
e.change_context(not_found_response)
} else {
e.change_context(errors::UserErrors::InternalServerError)
}
})
}
#[track_caller]
fn to_duplicate_response(
self,
duplicate_response: errors::UserErrors,
) -> error_stack::Result<T, errors::UserErrors> {
self.map_err(|e| {
if e.current_context().is_db_unique_violation() {
e.change_context(duplicate_response)
} else {
e.change_context(errors::UserErrors::InternalServerError)
}
})
}
}
|
crates/router/src/core/errors/utils.rs
|
router::src::core::errors::utils
| 5,765
| true
|
// File: crates/router/src/core/errors/chat.rs
// Module: router::src::core::errors::chat
#[derive(Debug, thiserror::Error)]
pub enum ChatErrors {
#[error("User InternalServerError")]
InternalServerError,
#[error("Missing Config error")]
MissingConfigError,
#[error("Chat response deserialization failed")]
ChatResponseDeserializationFailed,
#[error("Unauthorized access")]
UnauthorizedAccess,
}
impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorResponse> for ChatErrors {
fn switch(&self) -> api_models::errors::types::ApiErrorResponse {
use api_models::errors::types::{ApiError, ApiErrorResponse as AER};
let sub_code = "AI";
match self {
Self::InternalServerError => {
AER::InternalServerError(ApiError::new("HE", 0, self.get_error_message(), None))
}
Self::MissingConfigError => {
AER::InternalServerError(ApiError::new(sub_code, 1, self.get_error_message(), None))
}
Self::ChatResponseDeserializationFailed => {
AER::BadRequest(ApiError::new(sub_code, 2, self.get_error_message(), None))
}
Self::UnauthorizedAccess => {
AER::Unauthorized(ApiError::new(sub_code, 3, self.get_error_message(), None))
}
}
}
}
impl ChatErrors {
pub fn get_error_message(&self) -> String {
match self {
Self::InternalServerError => "Something went wrong".to_string(),
Self::MissingConfigError => "Missing webhook url".to_string(),
Self::ChatResponseDeserializationFailed => "Failed to parse chat response".to_string(),
Self::UnauthorizedAccess => "Not authorized to access the resource".to_string(),
}
}
}
|
crates/router/src/core/errors/chat.rs
|
router::src::core::errors::chat
| 383
| true
|
// File: crates/router/src/core/errors/user/sample_data.rs
// Module: router::src::core::errors::user::sample_data
use api_models::errors::types::{ApiError, ApiErrorResponse};
use common_utils::errors::{CustomResult, ErrorSwitch, ErrorSwitchFrom};
use storage_impl::errors::StorageError;
pub type SampleDataResult<T> = CustomResult<T, SampleDataError>;
#[derive(Debug, Clone, serde::Serialize, thiserror::Error)]
pub enum SampleDataError {
#[error["Internal Server Error"]]
InternalServerError,
#[error("Data Does Not Exist")]
DataDoesNotExist,
#[error("Invalid Parameters")]
InvalidParameters,
#[error["Invalid Records"]]
InvalidRange,
}
impl ErrorSwitch<ApiErrorResponse> for SampleDataError {
fn switch(&self) -> ApiErrorResponse {
match self {
Self::InternalServerError => ApiErrorResponse::InternalServerError(ApiError::new(
"SD",
0,
"Something went wrong",
None,
)),
Self::DataDoesNotExist => ApiErrorResponse::NotFound(ApiError::new(
"SD",
1,
"Sample Data not present for given request",
None,
)),
Self::InvalidParameters => ApiErrorResponse::BadRequest(ApiError::new(
"SD",
2,
"Invalid parameters to generate Sample Data",
None,
)),
Self::InvalidRange => ApiErrorResponse::BadRequest(ApiError::new(
"SD",
3,
"Records to be generated should be between range 10 and 100",
None,
)),
}
}
}
impl ErrorSwitchFrom<StorageError> for SampleDataError {
fn switch_from(error: &StorageError) -> Self {
match matches!(error, StorageError::ValueNotFound(_)) {
true => Self::DataDoesNotExist,
false => Self::InternalServerError,
}
}
}
|
crates/router/src/core/errors/user/sample_data.rs
|
router::src::core::errors::user::sample_data
| 402
| true
|
// File: crates/router/src/core/relay/utils.rs
// Module: router::src::core::relay::utils
use std::str::FromStr;
use common_utils::{ext_traits::OptionExt, id_type};
use error_stack::ResultExt;
use hyperswitch_domain_models::{router_data::ErrorResponse, types};
use crate::{
core::payments,
db::{
domain,
errors::{self, RouterResult},
},
routes::SessionState,
};
const IRRELEVANT_PAYMENT_INTENT_ID: &str = "irrelevant_payment_intent_id";
const IRRELEVANT_PAYMENT_ATTEMPT_ID: &str = "irrelevant_payment_attempt_id";
pub async fn construct_relay_refund_router_data<F>(
state: &SessionState,
merchant_id: &id_type::MerchantId,
connector_account: &domain::MerchantConnectorAccount,
relay_record: &hyperswitch_domain_models::relay::Relay,
) -> RouterResult<types::RefundsRouterData<F>> {
let connector_auth_type = connector_account
.get_connector_account_details()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while parsing value for ConnectorAuthType")?;
#[cfg(feature = "v2")]
let connector_name = &connector_account.connector_name.to_string();
#[cfg(feature = "v1")]
let connector_name = &connector_account.connector_name;
let webhook_url = Some(payments::helpers::create_webhook_url(
&state.base_url.clone(),
merchant_id,
connector_account.get_id().get_string_repr(),
));
let supported_connector = &state
.conf
.multiple_api_version_supported_connectors
.supported_connectors;
let connector_enum = api_models::enums::Connector::from_str(connector_name)
.change_context(errors::ConnectorError::InvalidConnectorName)
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "connector",
})
.attach_printable_lazy(|| format!("unable to parse connector name {connector_name:?}"))?;
let connector_api_version = if supported_connector.contains(&connector_enum) {
state
.store
.find_config_by_key(&format!("connector_api_version_{connector_name}"))
.await
.map(|value| value.config)
.ok()
} else {
None
};
let hyperswitch_domain_models::relay::RelayData::Refund(relay_refund_data) = relay_record
.request_data
.clone()
.get_required_value("refund relay data")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to obtain relay data to construct relay refund data")?;
let relay_id_string = relay_record.id.get_string_repr().to_string();
let router_data = hyperswitch_domain_models::router_data::RouterData {
flow: std::marker::PhantomData,
merchant_id: merchant_id.clone(),
customer_id: None,
tenant_id: state.tenant.tenant_id.clone(),
connector: connector_name.to_string(),
payment_id: IRRELEVANT_PAYMENT_INTENT_ID.to_string(),
attempt_id: IRRELEVANT_PAYMENT_ATTEMPT_ID.to_string(),
status: common_enums::AttemptStatus::Charged,
payment_method: common_enums::PaymentMethod::default(),
payment_method_type: None,
connector_auth_type,
description: None,
address: hyperswitch_domain_models::payment_address::PaymentAddress::default(),
auth_type: common_enums::AuthenticationType::default(),
connector_meta_data: connector_account.metadata.clone(),
connector_wallets_details: None,
amount_captured: None,
payment_method_status: None,
minor_amount_captured: None,
request: hyperswitch_domain_models::router_request_types::RefundsData {
refund_id: relay_id_string.clone(),
connector_transaction_id: relay_record.connector_resource_id.clone(),
refund_amount: relay_refund_data.amount.get_amount_as_i64(),
minor_refund_amount: relay_refund_data.amount,
currency: relay_refund_data.currency,
payment_amount: relay_refund_data.amount.get_amount_as_i64(),
minor_payment_amount: relay_refund_data.amount,
webhook_url,
connector_metadata: None,
refund_connector_metadata: None,
reason: relay_refund_data.reason,
connector_refund_id: relay_record.connector_reference_id.clone(),
browser_info: None,
split_refunds: None,
integrity_object: None,
refund_status: common_enums::RefundStatus::from(relay_record.status),
merchant_account_id: None,
merchant_config_currency: None,
capture_method: None,
additional_payment_method_data: None,
},
response: Err(ErrorResponse::default()),
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: relay_id_string.clone(),
#[cfg(feature = "payouts")]
payout_method_data: None,
#[cfg(feature = "payouts")]
quote_id: None,
test_mode: connector_account.get_connector_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(relay_id_string),
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)
}
|
crates/router/src/core/relay/utils.rs
|
router::src::core::relay::utils
| 1,271
| true
|
// File: crates/router/src/core/webhooks/outgoing_v2.rs
// Module: router::src::core::webhooks::outgoing_v2
use std::collections::HashMap;
use api_models::{webhook_events, webhooks};
use common_utils::{ext_traits, request, type_name, types::keymanager};
use diesel_models::process_tracker::business_status;
use error_stack::{report, Report, ResultExt};
use hyperswitch_domain_models::type_encryption::{crypto_operation, CryptoOperation};
use hyperswitch_interfaces::consts;
use masking;
use router_env::{
instrument,
tracing::{self, Instrument},
};
use super::{
types,
utils::{self, increment_webhook_outgoing_received_count},
MERCHANT_ID,
};
use crate::{
core::{
errors::{self, CustomResult},
metrics,
},
events::outgoing_webhook_logs,
logger,
routes::{app::SessionStateInfo, SessionState},
services,
types::{
api, domain,
storage::{self, enums},
transformers::ForeignFrom,
},
};
#[allow(clippy::too_many_arguments)]
#[instrument(skip_all)]
pub(crate) async fn create_event_and_trigger_outgoing_webhook(
state: SessionState,
business_profile: domain::Profile,
merchant_key_store: &domain::MerchantKeyStore,
event_type: enums::EventType,
event_class: enums::EventClass,
primary_object_id: String,
primary_object_type: enums::EventObjectType,
content: api::OutgoingWebhookContent,
primary_object_created_at: time::PrimitiveDateTime,
) -> CustomResult<(), errors::ApiErrorResponse> {
let delivery_attempt = enums::WebhookDeliveryAttempt::InitialAttempt;
let idempotent_event_id =
utils::get_idempotent_event_id(&primary_object_id, event_type, delivery_attempt)
.change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
.attach_printable("Failed to generate idempotent event ID")?;
let webhook_url_result = business_profile
.get_webhook_url_from_profile()
.change_context(errors::WebhooksFlowError::MerchantWebhookUrlNotConfigured);
if utils::is_outgoing_webhook_disabled(
&state,
&webhook_url_result,
&business_profile,
&idempotent_event_id,
) {
return Ok(());
}
let event_id = utils::generate_event_id();
let merchant_id = business_profile.merchant_id.clone();
let now = common_utils::date_time::now();
let outgoing_webhook = api::OutgoingWebhook {
merchant_id: merchant_id.clone(),
event_id: event_id.clone(),
event_type,
content: content.clone(),
timestamp: now,
};
let request_content = get_outgoing_webhook_request(outgoing_webhook, &business_profile)
.change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
.attach_printable("Failed to construct outgoing webhook request content")?;
let event_metadata = storage::EventMetadata::foreign_from(&content);
let key_manager_state = &(&state).into();
let new_event = domain::Event {
event_id: event_id.clone(),
event_type,
event_class,
is_webhook_notified: false,
primary_object_id,
primary_object_type,
created_at: now,
merchant_id: Some(business_profile.merchant_id.clone()),
business_profile_id: Some(business_profile.get_id().to_owned()),
primary_object_created_at: Some(primary_object_created_at),
idempotent_event_id: Some(idempotent_event_id.clone()),
initial_attempt_id: Some(event_id.clone()),
request: Some(
crypto_operation(
key_manager_state,
type_name!(domain::Event),
CryptoOperation::Encrypt(
ext_traits::Encode::encode_to_string_of_json(&request_content)
.change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
.attach_printable("Failed to encode outgoing webhook request content")
.map(masking::Secret::new)?,
),
keymanager::Identifier::Merchant(merchant_key_store.merchant_id.clone()),
masking::PeekInterface::peek(merchant_key_store.key.get_inner()),
)
.await
.and_then(|val| val.try_into_operation())
.change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
.attach_printable("Failed to encrypt outgoing webhook request content")?,
),
response: None,
delivery_attempt: Some(delivery_attempt),
metadata: Some(event_metadata),
is_overall_delivery_successful: Some(false),
};
let event_insert_result = state
.store
.insert_event(key_manager_state, new_event, merchant_key_store)
.await;
let event = match event_insert_result {
Ok(event) => Ok(event),
Err(error) => {
if error.current_context().is_db_unique_violation() {
// If the event_id already exists in the database, it indicates that the event for the resource has already been sent, so we skip the flow
logger::debug!("Event with idempotent ID `{idempotent_event_id}` already exists in the database");
return Ok(());
} else {
logger::error!(event_insertion_failure=?error);
Err(error
.change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
.attach_printable("Failed to insert event in events table"))
}
}
}?;
let cloned_key_store = merchant_key_store.clone();
// Using a tokio spawn here and not arbiter because not all caller of this function
// may have an actix arbiter
tokio::spawn(
async move {
Box::pin(trigger_webhook_and_raise_event(
state,
business_profile,
&cloned_key_store,
event,
request_content,
delivery_attempt,
Some(content),
))
.await;
}
.in_current_span(),
);
Ok(())
}
#[allow(clippy::too_many_arguments)]
#[instrument(skip_all)]
pub(crate) async fn trigger_webhook_and_raise_event(
state: SessionState,
business_profile: domain::Profile,
merchant_key_store: &domain::MerchantKeyStore,
event: domain::Event,
request_content: webhook_events::OutgoingWebhookRequestContent,
delivery_attempt: enums::WebhookDeliveryAttempt,
content: Option<api::OutgoingWebhookContent>,
) {
logger::debug!(
event_id=%event.event_id,
idempotent_event_id=?event.idempotent_event_id,
initial_attempt_id=?event.initial_attempt_id,
"Attempting to send webhook"
);
let merchant_id = business_profile.merchant_id.clone();
let trigger_webhook_result = trigger_webhook_to_merchant(
state.clone(),
business_profile,
merchant_key_store,
event.clone(),
request_content,
delivery_attempt,
)
.await;
let _ =
raise_webhooks_analytics_event(state, trigger_webhook_result, content, merchant_id, event)
.await;
}
async fn trigger_webhook_to_merchant(
state: SessionState,
business_profile: domain::Profile,
merchant_key_store: &domain::MerchantKeyStore,
event: domain::Event,
request_content: webhook_events::OutgoingWebhookRequestContent,
delivery_attempt: enums::WebhookDeliveryAttempt,
) -> CustomResult<
(domain::Event, Option<Report<errors::WebhooksFlowError>>),
errors::WebhooksFlowError,
> {
let webhook_url = business_profile
.get_webhook_url_from_profile()
.change_context(errors::WebhooksFlowError::MerchantWebhookUrlNotConfigured)?;
let response = build_and_send_request(&state, request_content, webhook_url).await;
metrics::WEBHOOK_OUTGOING_COUNT.add(
1,
router_env::metric_attributes!((MERCHANT_ID, business_profile.merchant_id.clone())),
);
logger::debug!(outgoing_webhook_response=?response);
match response {
Ok(response) => {
delivery_attempt
.handle_success_response(
state,
merchant_key_store.clone(),
&business_profile.merchant_id,
&event.event_id,
None,
response,
)
.await
}
Err(client_error) => {
delivery_attempt
.handle_error_response(
state,
merchant_key_store.clone(),
&business_profile.merchant_id,
&event.event_id,
client_error,
)
.await
}
}
}
async fn raise_webhooks_analytics_event(
state: SessionState,
trigger_webhook_result: CustomResult<
(domain::Event, Option<Report<errors::WebhooksFlowError>>),
errors::WebhooksFlowError,
>,
content: Option<api::OutgoingWebhookContent>,
merchant_id: common_utils::id_type::MerchantId,
fallback_event: domain::Event,
) {
let (updated_event, optional_error) = match trigger_webhook_result {
Ok((updated_event, error)) => (updated_event, error),
Err(error) => (fallback_event, Some(error)),
};
let error = optional_error.and_then(|error| {
logger::error!(?error, "Failed to send webhook to merchant");
serde_json::to_value(error.current_context())
.change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
.inspect_err(|error| {
logger::error!(?error, "Failed to serialize outgoing webhook error as JSON");
})
.ok()
});
let outgoing_webhook_event_content = content
.as_ref()
.and_then(
outgoing_webhook_logs::OutgoingWebhookEventMetric::get_outgoing_webhook_event_content,
)
.or_else(|| {
updated_event
.metadata
.map(outgoing_webhook_logs::OutgoingWebhookEventContent::foreign_from)
});
// Get status_code from webhook response
let status_code = {
let webhook_response: Option<webhook_events::OutgoingWebhookResponseContent> =
updated_event.response.and_then(|res| {
ext_traits::StringExt::parse_struct(
masking::PeekInterface::peek(res.get_inner()),
"OutgoingWebhookResponseContent",
)
.map_err(|error| {
logger::error!(?error, "Error deserializing webhook response");
error
})
.ok()
});
webhook_response.and_then(|res| res.status_code)
};
let webhook_event = outgoing_webhook_logs::OutgoingWebhookEvent::new(
state.tenant.tenant_id.clone(),
merchant_id,
updated_event.event_id,
updated_event.event_type,
outgoing_webhook_event_content,
error,
updated_event.initial_attempt_id,
status_code,
updated_event.delivery_attempt,
);
state.event_handler().log_event(&webhook_event);
}
pub(crate) fn get_outgoing_webhook_request(
outgoing_webhook: api::OutgoingWebhook,
business_profile: &domain::Profile,
) -> CustomResult<webhook_events::OutgoingWebhookRequestContent, errors::WebhooksFlowError> {
#[inline]
fn get_outgoing_webhook_request_inner<WebhookType: types::OutgoingWebhookType>(
outgoing_webhook: api::OutgoingWebhook,
business_profile: &domain::Profile,
) -> CustomResult<webhook_events::OutgoingWebhookRequestContent, errors::WebhooksFlowError>
{
let mut headers = vec![
(
reqwest::header::CONTENT_TYPE.to_string(),
mime::APPLICATION_JSON.essence_str().into(),
),
(
reqwest::header::USER_AGENT.to_string(),
consts::USER_AGENT.to_string().into(),
),
];
let transformed_outgoing_webhook = WebhookType::from(outgoing_webhook);
let payment_response_hash_key = business_profile.payment_response_hash_key.clone();
let custom_headers = business_profile
.outgoing_webhook_custom_http_headers
.clone()
.map(|headers| {
ext_traits::ValueExt::parse_value::<HashMap<String, String>>(
masking::ExposeInterface::expose(headers.into_inner()),
"HashMap<String,String>",
)
.change_context(errors::WebhooksFlowError::OutgoingWebhookEncodingFailed)
.attach_printable("Failed to deserialize outgoing webhook custom HTTP headers")
})
.transpose()?;
if let Some(ref map) = custom_headers {
headers.extend(
map.iter()
.map(|(key, value)| (key.clone(), masking::Mask::into_masked(value.clone()))),
);
};
let outgoing_webhooks_signature = transformed_outgoing_webhook
.get_outgoing_webhooks_signature(payment_response_hash_key)?;
if let Some(signature) = outgoing_webhooks_signature.signature {
WebhookType::add_webhook_header(&mut headers, signature)
}
Ok(webhook_events::OutgoingWebhookRequestContent {
body: outgoing_webhooks_signature.payload,
headers: headers
.into_iter()
.map(|(name, value)| (name, masking::Secret::new(value.into_inner())))
.collect(),
})
}
get_outgoing_webhook_request_inner::<webhooks::OutgoingWebhook>(
outgoing_webhook,
business_profile,
)
}
async fn build_and_send_request(
state: &SessionState,
request_content: webhook_events::OutgoingWebhookRequestContent,
webhook_url: String,
) -> Result<reqwest::Response, Report<common_enums::ApiClientError>> {
let headers = request_content
.headers
.into_iter()
.map(|(name, value)| (name, masking::Mask::into_masked(value)))
.collect();
let request = services::RequestBuilder::new()
.method(services::Method::Post)
.url(&webhook_url)
.attach_default_headers()
.headers(headers)
.set_body(request::RequestContent::RawBytes(
masking::ExposeInterface::expose(request_content.body).into_bytes(),
))
.build();
state
.api_client
.send_request(state, request, None, false)
.await
}
async fn api_client_error_handler(
state: SessionState,
merchant_key_store: domain::MerchantKeyStore,
merchant_id: &common_utils::id_type::MerchantId,
event_id: &str,
client_error: Report<errors::ApiClientError>,
delivery_attempt: enums::WebhookDeliveryAttempt,
_schedule_webhook_retry: types::ScheduleWebhookRetry,
) -> CustomResult<
(domain::Event, Option<Report<errors::WebhooksFlowError>>),
errors::WebhooksFlowError,
> {
// Not including detailed error message in response information since it contains too
// much of diagnostic information to be exposed to the merchant.
let is_webhook_notified = false;
let response_to_store = webhook_events::OutgoingWebhookResponseContent {
body: None,
headers: None,
status_code: None,
error_message: Some("Unable to send request to merchant server".to_string()),
};
let updated_event = update_event_in_storage(
state,
is_webhook_notified,
response_to_store,
merchant_key_store,
merchant_id,
event_id,
)
.await?;
let error = client_error.change_context(errors::WebhooksFlowError::CallToMerchantFailed);
logger::error!(
?error,
?delivery_attempt,
"An error occurred when sending webhook to merchant"
);
//TODO: add outgoing webhook retries support
// if let ScheduleWebhookRetry::WithProcessTracker(process_tracker) = schedule_webhook_retry {
// // Schedule a retry attempt for webhook delivery
// outgoing_webhook_retry::retry_webhook_delivery_task(
// &*state.store,
// merchant_id,
// *process_tracker,
// )
// .await
// .change_context(errors::WebhooksFlowError::OutgoingWebhookRetrySchedulingFailed)?;
// }
Ok((updated_event, Some(error)))
}
async fn update_event_in_storage(
state: SessionState,
is_webhook_notified: bool,
outgoing_webhook_response: webhook_events::OutgoingWebhookResponseContent,
merchant_key_store: domain::MerchantKeyStore,
merchant_id: &common_utils::id_type::MerchantId,
event_id: &str,
) -> CustomResult<domain::Event, errors::WebhooksFlowError> {
let key_manager_state = &(&state).into();
let event_update = domain::EventUpdate::UpdateResponse {
is_webhook_notified,
response: Some(
crypto_operation(
key_manager_state,
type_name!(domain::Event),
CryptoOperation::Encrypt(
ext_traits::Encode::encode_to_string_of_json(&outgoing_webhook_response)
.change_context(
errors::WebhooksFlowError::OutgoingWebhookResponseEncodingFailed,
)
.map(masking::Secret::new)?,
),
keymanager::Identifier::Merchant(merchant_key_store.merchant_id.clone()),
masking::PeekInterface::peek(merchant_key_store.key.get_inner()),
)
.await
.and_then(|val| val.try_into_operation())
.change_context(errors::WebhooksFlowError::WebhookEventUpdationFailed)
.attach_printable("Failed to encrypt outgoing webhook response content")?,
),
};
state
.store
.update_event_by_merchant_id_event_id(
key_manager_state,
merchant_id,
event_id,
event_update,
&merchant_key_store,
)
.await
.change_context(errors::WebhooksFlowError::WebhookEventUpdationFailed)
}
async fn update_overall_delivery_status_in_storage(
state: SessionState,
merchant_key_store: domain::MerchantKeyStore,
merchant_id: &common_utils::id_type::MerchantId,
updated_event: &domain::Event,
) -> CustomResult<(), errors::WebhooksFlowError> {
let key_manager_state = &(&state).into();
let update_overall_delivery_status = domain::EventUpdate::OverallDeliveryStatusUpdate {
is_overall_delivery_successful: true,
};
let initial_attempt_id = updated_event.initial_attempt_id.as_ref();
let delivery_attempt = updated_event.delivery_attempt;
if let Some((
initial_attempt_id,
enums::WebhookDeliveryAttempt::InitialAttempt
| enums::WebhookDeliveryAttempt::AutomaticRetry,
)) = initial_attempt_id.zip(delivery_attempt)
{
state
.store
.update_event_by_merchant_id_event_id(
key_manager_state,
merchant_id,
initial_attempt_id.as_str(),
update_overall_delivery_status,
&merchant_key_store,
)
.await
.change_context(errors::WebhooksFlowError::WebhookEventUpdationFailed)
.attach_printable("Failed to update initial delivery attempt")?;
}
Ok(())
}
async fn handle_successful_delivery(
state: SessionState,
merchant_key_store: domain::MerchantKeyStore,
updated_event: &domain::Event,
merchant_id: &common_utils::id_type::MerchantId,
process_tracker: Option<storage::ProcessTracker>,
business_status: &'static str,
) -> CustomResult<(), errors::WebhooksFlowError> {
update_overall_delivery_status_in_storage(
state.clone(),
merchant_key_store.clone(),
merchant_id,
updated_event,
)
.await?;
increment_webhook_outgoing_received_count(merchant_id);
match process_tracker {
Some(process_tracker) => state
.store
.as_scheduler()
.finish_process_with_business_status(process_tracker, business_status)
.await
.change_context(
errors::WebhooksFlowError::OutgoingWebhookProcessTrackerTaskUpdateFailed,
),
None => Ok(()),
}
}
async fn handle_failed_delivery(
_state: SessionState,
merchant_id: &common_utils::id_type::MerchantId,
delivery_attempt: enums::WebhookDeliveryAttempt,
status_code: u16,
log_message: &'static str,
_schedule_webhook_retry: types::ScheduleWebhookRetry,
) -> CustomResult<(), errors::WebhooksFlowError> {
utils::increment_webhook_outgoing_not_received_count(merchant_id);
let error = report!(errors::WebhooksFlowError::NotReceivedByMerchant);
logger::warn!(?error, ?delivery_attempt, status_code, %log_message);
//TODO: add outgoing webhook retries support
// if let ScheduleWebhookRetry::WithProcessTracker(process_tracker) = schedule_webhook_retry {
// // Schedule a retry attempt for webhook delivery
// outgoing_webhook_retry::retry_webhook_delivery_task(
// &*state.store,
// merchant_id,
// *process_tracker,
// )
// .await
// .change_context(errors::WebhooksFlowError::OutgoingWebhookRetrySchedulingFailed)?;
// }
Err(error)
}
impl ForeignFrom<&api::OutgoingWebhookContent> for storage::EventMetadata {
fn foreign_from(content: &api::OutgoingWebhookContent) -> Self {
match content {
webhooks::OutgoingWebhookContent::PaymentDetails(payments_response) => Self::Payment {
payment_id: payments_response.id.clone(),
},
webhooks::OutgoingWebhookContent::RefundDetails(refund_response) => Self::Refund {
payment_id: refund_response.payment_id.clone(),
refund_id: refund_response.id.clone(),
},
webhooks::OutgoingWebhookContent::DisputeDetails(dispute_response) => {
//TODO: add support for dispute outgoing webhook
todo!()
}
webhooks::OutgoingWebhookContent::MandateDetails(mandate_response) => Self::Mandate {
payment_method_id: mandate_response.payment_method_id.clone(),
mandate_id: mandate_response.mandate_id.clone(),
},
#[cfg(feature = "payouts")]
webhooks::OutgoingWebhookContent::PayoutDetails(payout_response) => Self::Payout {
payout_id: payout_response.payout_id.clone(),
},
}
}
}
impl ForeignFrom<storage::EventMetadata> for outgoing_webhook_logs::OutgoingWebhookEventContent {
fn foreign_from(event_metadata: storage::EventMetadata) -> Self {
match event_metadata {
diesel_models::EventMetadata::Payment { payment_id } => Self::Payment {
payment_id,
content: serde_json::Value::Null,
},
diesel_models::EventMetadata::Payout { payout_id } => Self::Payout {
payout_id,
content: serde_json::Value::Null,
},
diesel_models::EventMetadata::Refund {
payment_id,
refund_id,
} => Self::Refund {
payment_id,
refund_id,
content: serde_json::Value::Null,
},
diesel_models::EventMetadata::Dispute {
payment_id,
attempt_id,
dispute_id,
} => Self::Dispute {
payment_id,
attempt_id,
dispute_id,
content: serde_json::Value::Null,
},
diesel_models::EventMetadata::Mandate {
payment_method_id,
mandate_id,
} => Self::Mandate {
payment_method_id,
mandate_id,
content: serde_json::Value::Null,
},
}
}
}
trait OutgoingWebhookResponseHandler {
async fn handle_error_response(
&self,
state: SessionState,
merchant_key_store: domain::MerchantKeyStore,
merchant_id: &common_utils::id_type::MerchantId,
event_id: &str,
client_error: Report<errors::ApiClientError>,
) -> CustomResult<
(domain::Event, Option<Report<errors::WebhooksFlowError>>),
errors::WebhooksFlowError,
>;
async fn handle_success_response(
&self,
state: SessionState,
merchant_key_store: domain::MerchantKeyStore,
merchant_id: &common_utils::id_type::MerchantId,
event_id: &str,
process_tracker: Option<storage::ProcessTracker>,
response: reqwest::Response,
) -> CustomResult<
(domain::Event, Option<Report<errors::WebhooksFlowError>>),
errors::WebhooksFlowError,
>;
}
impl OutgoingWebhookResponseHandler for enums::WebhookDeliveryAttempt {
async fn handle_error_response(
&self,
state: SessionState,
merchant_key_store: domain::MerchantKeyStore,
merchant_id: &common_utils::id_type::MerchantId,
event_id: &str,
client_error: Report<errors::ApiClientError>,
) -> CustomResult<
(domain::Event, Option<Report<errors::WebhooksFlowError>>),
errors::WebhooksFlowError,
> {
let schedule_webhook_retry = match self {
Self::InitialAttempt | Self::ManualRetry => types::ScheduleWebhookRetry::NoSchedule,
Self::AutomaticRetry => {
// ScheduleWebhookRetry::WithProcessTracker(Box::new(process_tracker))
todo!()
}
};
api_client_error_handler(
state,
merchant_key_store,
merchant_id,
event_id,
client_error,
*self,
schedule_webhook_retry,
)
.await
}
async fn handle_success_response(
&self,
state: SessionState,
merchant_key_store: domain::MerchantKeyStore,
merchant_id: &common_utils::id_type::MerchantId,
event_id: &str,
process_tracker: Option<storage::ProcessTracker>,
response: reqwest::Response,
) -> CustomResult<
(domain::Event, Option<Report<errors::WebhooksFlowError>>),
errors::WebhooksFlowError,
> {
let status_code = response.status();
let is_webhook_notified = status_code.is_success();
let response_struct = types::WebhookResponse { response };
let outgoing_webhook_response = response_struct
.get_outgoing_webhook_response_content()
.await;
let updated_event = update_event_in_storage(
state.clone(),
is_webhook_notified,
outgoing_webhook_response,
merchant_key_store.clone(),
merchant_id,
event_id,
)
.await?;
let webhook_action_handler = get_action_handler(*self);
let result = if is_webhook_notified {
webhook_action_handler
.notified_action(
state,
merchant_key_store,
&updated_event,
merchant_id,
process_tracker,
)
.await
} else {
webhook_action_handler
.not_notified_action(state, merchant_id, status_code.as_u16())
.await
};
Ok((updated_event, result))
}
}
#[async_trait::async_trait]
trait WebhookNotificationHandler: Send + Sync {
async fn notified_action(
&self,
state: SessionState,
merchant_key_store: domain::MerchantKeyStore,
updated_event: &domain::Event,
merchant_id: &common_utils::id_type::MerchantId,
process_tracker: Option<storage::ProcessTracker>,
) -> Option<Report<errors::WebhooksFlowError>>;
async fn not_notified_action(
&self,
state: SessionState,
merchant_id: &common_utils::id_type::MerchantId,
status_code: u16,
) -> Option<Report<errors::WebhooksFlowError>>;
}
struct InitialAttempt;
struct AutomaticRetry;
struct ManualRetry;
#[async_trait::async_trait]
impl WebhookNotificationHandler for InitialAttempt {
async fn notified_action(
&self,
state: SessionState,
merchant_key_store: domain::MerchantKeyStore,
updated_event: &domain::Event,
merchant_id: &common_utils::id_type::MerchantId,
process_tracker: Option<storage::ProcessTracker>,
) -> Option<Report<errors::WebhooksFlowError>> {
handle_successful_delivery(
state,
merchant_key_store,
updated_event,
merchant_id,
process_tracker,
business_status::INITIAL_DELIVERY_ATTEMPT_SUCCESSFUL,
)
.await
.err()
.map(|error: Report<errors::WebhooksFlowError>| report!(error))
}
async fn not_notified_action(
&self,
state: SessionState,
merchant_id: &common_utils::id_type::MerchantId,
status_code: u16,
) -> Option<Report<errors::WebhooksFlowError>> {
handle_failed_delivery(
state.clone(),
merchant_id,
enums::WebhookDeliveryAttempt::InitialAttempt,
status_code,
"Ignoring error when sending webhook to merchant",
types::ScheduleWebhookRetry::NoSchedule,
)
.await
.err()
.map(|error| report!(error))
}
}
#[async_trait::async_trait]
impl WebhookNotificationHandler for AutomaticRetry {
async fn notified_action(
&self,
_state: SessionState,
_merchant_key_store: domain::MerchantKeyStore,
_updated_event: &domain::Event,
_merchant_id: &common_utils::id_type::MerchantId,
_process_tracker: Option<storage::ProcessTracker>,
) -> Option<Report<errors::WebhooksFlowError>> {
todo!()
}
async fn not_notified_action(
&self,
_state: SessionState,
_merchant_id: &common_utils::id_type::MerchantId,
_status_code: u16,
) -> Option<Report<errors::WebhooksFlowError>> {
todo!()
}
}
#[async_trait::async_trait]
impl WebhookNotificationHandler for ManualRetry {
async fn notified_action(
&self,
_state: SessionState,
_merchant_key_store: domain::MerchantKeyStore,
_updated_event: &domain::Event,
merchant_id: &common_utils::id_type::MerchantId,
_process_tracker: Option<storage::ProcessTracker>,
) -> Option<Report<errors::WebhooksFlowError>> {
increment_webhook_outgoing_received_count(merchant_id);
None
}
async fn not_notified_action(
&self,
state: SessionState,
merchant_id: &common_utils::id_type::MerchantId,
status_code: u16,
) -> Option<Report<errors::WebhooksFlowError>> {
handle_failed_delivery(
state.clone(),
merchant_id,
enums::WebhookDeliveryAttempt::ManualRetry,
status_code,
"Ignoring error when sending webhook to merchant",
types::ScheduleWebhookRetry::NoSchedule,
)
.await
.err()
.map(|error| report!(error))
}
}
fn get_action_handler(
attempt: enums::WebhookDeliveryAttempt,
) -> Box<dyn WebhookNotificationHandler> {
match attempt {
enums::WebhookDeliveryAttempt::InitialAttempt => Box::new(InitialAttempt),
enums::WebhookDeliveryAttempt::AutomaticRetry => Box::new(AutomaticRetry),
enums::WebhookDeliveryAttempt::ManualRetry => Box::new(ManualRetry),
}
}
|
crates/router/src/core/webhooks/outgoing_v2.rs
|
router::src::core::webhooks::outgoing_v2
| 6,719
| true
|
// File: crates/router/src/core/webhooks/types.rs
// Module: router::src::core::webhooks::types
use api_models::{webhook_events, webhooks};
use common_utils::{crypto::SignMessage, ext_traits::Encode};
use error_stack::ResultExt;
use masking::Secret;
use serde::Serialize;
use crate::{
core::errors,
headers, logger,
services::request::Maskable,
types::storage::{self, enums},
};
#[derive(Debug)]
pub enum ScheduleWebhookRetry {
WithProcessTracker(Box<storage::ProcessTracker>),
NoSchedule,
}
pub struct OutgoingWebhookPayloadWithSignature {
pub payload: Secret<String>,
pub signature: Option<String>,
}
pub trait OutgoingWebhookType:
Serialize + From<webhooks::OutgoingWebhook> + Sync + Send + std::fmt::Debug + 'static
{
fn get_outgoing_webhooks_signature(
&self,
payment_response_hash_key: Option<impl AsRef<[u8]>>,
) -> errors::CustomResult<OutgoingWebhookPayloadWithSignature, errors::WebhooksFlowError>;
fn add_webhook_header(header: &mut Vec<(String, Maskable<String>)>, signature: String);
}
impl OutgoingWebhookType for webhooks::OutgoingWebhook {
fn get_outgoing_webhooks_signature(
&self,
payment_response_hash_key: Option<impl AsRef<[u8]>>,
) -> errors::CustomResult<OutgoingWebhookPayloadWithSignature, errors::WebhooksFlowError> {
let webhook_signature_payload = self
.encode_to_string_of_json()
.change_context(errors::WebhooksFlowError::OutgoingWebhookEncodingFailed)
.attach_printable("failed encoding outgoing webhook payload")?;
let signature = payment_response_hash_key
.map(|key| {
common_utils::crypto::HmacSha512::sign_message(
&common_utils::crypto::HmacSha512,
key.as_ref(),
webhook_signature_payload.as_bytes(),
)
})
.transpose()
.change_context(errors::WebhooksFlowError::OutgoingWebhookSigningFailed)
.attach_printable("Failed to sign the message")?
.map(hex::encode);
Ok(OutgoingWebhookPayloadWithSignature {
payload: webhook_signature_payload.into(),
signature,
})
}
fn add_webhook_header(header: &mut Vec<(String, Maskable<String>)>, signature: String) {
header.push((headers::X_WEBHOOK_SIGNATURE.to_string(), signature.into()))
}
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub(crate) struct OutgoingWebhookTrackingData {
pub(crate) merchant_id: common_utils::id_type::MerchantId,
pub(crate) business_profile_id: common_utils::id_type::ProfileId,
pub(crate) event_type: enums::EventType,
pub(crate) event_class: enums::EventClass,
pub(crate) primary_object_id: String,
pub(crate) primary_object_type: enums::EventObjectType,
pub(crate) initial_attempt_id: Option<String>,
}
pub struct WebhookResponse {
pub response: reqwest::Response,
}
impl WebhookResponse {
pub async fn get_outgoing_webhook_response_content(
self,
) -> webhook_events::OutgoingWebhookResponseContent {
let status_code = self.response.status();
let response_headers = self
.response
.headers()
.iter()
.map(|(name, value)| {
(
name.as_str().to_owned(),
value
.to_str()
.map(|s| Secret::from(String::from(s)))
.unwrap_or_else(|error| {
logger::warn!(
"Response header {} contains non-UTF-8 characters: {error:?}",
name.as_str()
);
Secret::from(String::from("Non-UTF-8 header value"))
}),
)
})
.collect::<Vec<_>>();
let response_body = self
.response
.text()
.await
.map(Secret::from)
.unwrap_or_else(|error| {
logger::warn!("Response contains non-UTF-8 characters: {error:?}");
Secret::from(String::from("Non-UTF-8 response body"))
});
webhook_events::OutgoingWebhookResponseContent {
body: Some(response_body),
headers: Some(response_headers),
status_code: Some(status_code.as_u16()),
error_message: None,
}
}
}
|
crates/router/src/core/webhooks/types.rs
|
router::src::core::webhooks::types
| 972
| true
|
// File: crates/router/src/core/webhooks/network_tokenization_incoming.rs
// Module: router::src::core::webhooks::network_tokenization_incoming
use std::str::FromStr;
use ::payment_methods::controller::PaymentMethodsController;
use api_models::webhooks::WebhookResponseTracker;
use async_trait::async_trait;
use common_utils::{
crypto::Encryptable,
ext_traits::{AsyncExt, ByteSliceExt, ValueExt},
id_type,
};
use error_stack::{report, ResultExt};
use http::HeaderValue;
use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
configs::settings,
core::{
errors::{self, CustomResult, RouterResult, StorageErrorExt},
payment_methods::cards,
},
logger,
routes::{app::SessionStateInfo, SessionState},
types::{
api, domain, payment_methods as pm_types,
storage::{self, enums},
},
utils::{self as helper_utils, ext_traits::OptionExt},
};
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(untagged)]
pub enum NetworkTokenWebhookResponse {
PanMetadataUpdate(pm_types::PanMetadataUpdateBody),
NetworkTokenMetadataUpdate(pm_types::NetworkTokenMetaDataUpdateBody),
}
impl NetworkTokenWebhookResponse {
fn get_network_token_requestor_ref_id(&self) -> String {
match self {
Self::PanMetadataUpdate(data) => data.card.card_reference.clone(),
Self::NetworkTokenMetadataUpdate(data) => data.token.card_reference.clone(),
}
}
pub fn get_response_data(self) -> Box<dyn NetworkTokenWebhookResponseExt> {
match self {
Self::PanMetadataUpdate(data) => Box::new(data),
Self::NetworkTokenMetadataUpdate(data) => Box::new(data),
}
}
pub async fn fetch_merchant_id_payment_method_id_customer_id_from_callback_mapper(
&self,
state: &SessionState,
) -> RouterResult<(id_type::MerchantId, String, id_type::CustomerId)> {
let network_token_requestor_ref_id = &self.get_network_token_requestor_ref_id();
let db = &*state.store;
let callback_mapper_data = db
.find_call_back_mapper_by_id(network_token_requestor_ref_id)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to fetch callback mapper data")?;
Ok(callback_mapper_data
.data
.get_network_token_webhook_details())
}
}
pub fn get_network_token_resource_object(
request_details: &api::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::NetworkTokenizationError> {
let response: NetworkTokenWebhookResponse = request_details
.body
.parse_struct("NetworkTokenWebhookResponse")
.change_context(errors::NetworkTokenizationError::ResponseDeserializationFailed)?;
Ok(Box::new(response))
}
#[async_trait]
pub trait NetworkTokenWebhookResponseExt {
fn decrypt_payment_method_data(
&self,
payment_method: &domain::PaymentMethod,
) -> CustomResult<api::payment_methods::CardDetailFromLocker, errors::ApiErrorResponse>;
async fn update_payment_method(
&self,
state: &SessionState,
payment_method: &domain::PaymentMethod,
merchant_context: &domain::MerchantContext,
) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse>;
}
#[async_trait]
impl NetworkTokenWebhookResponseExt for pm_types::PanMetadataUpdateBody {
fn decrypt_payment_method_data(
&self,
payment_method: &domain::PaymentMethod,
) -> CustomResult<api::payment_methods::CardDetailFromLocker, errors::ApiErrorResponse> {
let decrypted_data = payment_method
.payment_method_data
.clone()
.map(|payment_method_data| payment_method_data.into_inner().expose())
.and_then(|val| {
val.parse_value::<api::payment_methods::PaymentMethodsData>("PaymentMethodsData")
.map_err(|err| logger::error!(?err, "Failed to parse PaymentMethodsData"))
.ok()
})
.and_then(|pmd| match pmd {
api::payment_methods::PaymentMethodsData::Card(token) => {
Some(api::payment_methods::CardDetailFromLocker::from(token))
}
_ => None,
})
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to obtain decrypted token object from db")?;
Ok(decrypted_data)
}
async fn update_payment_method(
&self,
state: &SessionState,
payment_method: &domain::PaymentMethod,
merchant_context: &domain::MerchantContext,
) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> {
let decrypted_data = self.decrypt_payment_method_data(payment_method)?;
handle_metadata_update(
state,
&self.card,
payment_method
.locker_id
.clone()
.get_required_value("locker_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Locker id is not found for the payment method")?,
payment_method,
merchant_context,
decrypted_data,
true,
)
.await
}
}
#[async_trait]
impl NetworkTokenWebhookResponseExt for pm_types::NetworkTokenMetaDataUpdateBody {
fn decrypt_payment_method_data(
&self,
payment_method: &domain::PaymentMethod,
) -> CustomResult<api::payment_methods::CardDetailFromLocker, errors::ApiErrorResponse> {
let decrypted_data = payment_method
.network_token_payment_method_data
.clone()
.map(|x| x.into_inner().expose())
.and_then(|val| {
val.parse_value::<api::payment_methods::PaymentMethodsData>("PaymentMethodsData")
.map_err(|err| logger::error!(?err, "Failed to parse PaymentMethodsData"))
.ok()
})
.and_then(|pmd| match pmd {
api::payment_methods::PaymentMethodsData::Card(token) => {
Some(api::payment_methods::CardDetailFromLocker::from(token))
}
_ => None,
})
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to obtain decrypted token object from db")?;
Ok(decrypted_data)
}
async fn update_payment_method(
&self,
state: &SessionState,
payment_method: &domain::PaymentMethod,
merchant_context: &domain::MerchantContext,
) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> {
let decrypted_data = self.decrypt_payment_method_data(payment_method)?;
handle_metadata_update(
state,
&self.token,
payment_method
.network_token_locker_id
.clone()
.get_required_value("locker_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Locker id is not found for the payment method")?,
payment_method,
merchant_context,
decrypted_data,
true,
)
.await
}
}
pub struct Authorization {
header: Option<HeaderValue>,
}
impl Authorization {
pub fn new(header: Option<&HeaderValue>) -> Self {
Self {
header: header.cloned(),
}
}
pub async fn verify_webhook_source(
self,
nt_service: &settings::NetworkTokenizationService,
) -> CustomResult<(), errors::ApiErrorResponse> {
let secret = nt_service.webhook_source_verification_key.clone();
let source_verified = match self.header {
Some(authorization_header) => match authorization_header.to_str() {
Ok(header_value) => Ok(header_value == secret.expose()),
Err(err) => {
logger::error!(?err, "Failed to parse authorization header");
Err(errors::ApiErrorResponse::WebhookAuthenticationFailed)
}
},
None => Ok(false),
}?;
logger::info!(source_verified=?source_verified);
helper_utils::when(!source_verified, || {
Err(report!(
errors::ApiErrorResponse::WebhookAuthenticationFailed
))
})?;
Ok(())
}
}
#[allow(clippy::too_many_arguments)]
pub async fn handle_metadata_update(
state: &SessionState,
metadata: &pm_types::NetworkTokenRequestorData,
locker_id: String,
payment_method: &domain::PaymentMethod,
merchant_context: &domain::MerchantContext,
decrypted_data: api::payment_methods::CardDetailFromLocker,
is_pan_update: bool,
) -> RouterResult<WebhookResponseTracker> {
let merchant_id = merchant_context.get_merchant_account().get_id();
let customer_id = &payment_method.customer_id;
let payment_method_id = payment_method.get_id().clone();
let status = payment_method.status;
match metadata.is_update_required(decrypted_data) {
false => {
logger::info!(
"No update required for payment method {} for locker_id {}",
payment_method.get_id(),
locker_id
);
Ok(WebhookResponseTracker::PaymentMethod {
payment_method_id,
status,
})
}
true => {
let mut card = cards::get_card_from_locker(state, customer_id, merchant_id, &locker_id)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to fetch token information from the locker")?;
card.card_exp_year = metadata.expiry_year.clone();
card.card_exp_month = metadata.expiry_month.clone();
let card_network = card
.card_brand
.clone()
.map(|card_brand| enums::CardNetwork::from_str(&card_brand))
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "card network",
})
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Invalid Card Network stored in vault")?;
let card_data = api::payment_methods::CardDetail::from((card, card_network));
let payment_method_request: api::payment_methods::PaymentMethodCreate =
PaymentMethodCreateWrapper::from((&card_data, payment_method)).get_inner();
let pm_cards = cards::PmCards {
state,
merchant_context,
};
pm_cards
.delete_card_from_locker(customer_id, merchant_id, &locker_id)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to delete network token")?;
let (res, _) = pm_cards
.add_card_to_locker(payment_method_request, &card_data, customer_id, None)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to add network token")?;
let pm_details = res.card.as_ref().map(|card| {
api::payment_methods::PaymentMethodsData::Card(
api::payment_methods::CardDetailsPaymentMethod::from((card.clone(), None)),
)
});
let key_manager_state = state.into();
let pm_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>> = pm_details
.async_map(|pm_card| {
cards::create_encrypted_data(
&key_manager_state,
merchant_context.get_merchant_key_store(),
pm_card,
)
})
.await
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt payment method data")?;
let pm_update = if is_pan_update {
storage::PaymentMethodUpdate::AdditionalDataUpdate {
locker_id: Some(res.payment_method_id),
payment_method_data: pm_data_encrypted.map(Into::into),
status: None,
payment_method: None,
payment_method_type: None,
payment_method_issuer: None,
network_token_requestor_reference_id: None,
network_token_locker_id: None,
network_token_payment_method_data: None,
}
} else {
storage::PaymentMethodUpdate::AdditionalDataUpdate {
locker_id: None,
payment_method_data: None,
status: None,
payment_method: None,
payment_method_type: None,
payment_method_issuer: None,
network_token_requestor_reference_id: None,
network_token_locker_id: Some(res.payment_method_id),
network_token_payment_method_data: pm_data_encrypted.map(Into::into),
}
};
let db = &*state.store;
db.update_payment_method(
&key_manager_state,
merchant_context.get_merchant_key_store(),
payment_method.clone(),
pm_update,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update the payment method")?;
Ok(WebhookResponseTracker::PaymentMethod {
payment_method_id,
status,
})
}
}
}
pub struct PaymentMethodCreateWrapper(pub api::payment_methods::PaymentMethodCreate);
impl From<(&api::payment_methods::CardDetail, &domain::PaymentMethod)>
for PaymentMethodCreateWrapper
{
fn from(
(data, payment_method): (&api::payment_methods::CardDetail, &domain::PaymentMethod),
) -> Self {
Self(api::payment_methods::PaymentMethodCreate {
customer_id: Some(payment_method.customer_id.clone()),
payment_method: payment_method.payment_method,
payment_method_type: payment_method.payment_method_type,
payment_method_issuer: payment_method.payment_method_issuer.clone(),
payment_method_issuer_code: payment_method.payment_method_issuer_code,
metadata: payment_method.metadata.clone(),
payment_method_data: None,
connector_mandate_details: None,
client_secret: None,
billing: None,
card: Some(data.clone()),
card_network: data
.card_network
.clone()
.map(|card_network| card_network.to_string()),
bank_transfer: None,
wallet: None,
network_transaction_id: payment_method.network_transaction_id.clone(),
})
}
}
impl PaymentMethodCreateWrapper {
fn get_inner(self) -> api::payment_methods::PaymentMethodCreate {
self.0
}
}
pub async fn fetch_merchant_account_for_network_token_webhooks(
state: &SessionState,
merchant_id: &id_type::MerchantId,
) -> RouterResult<domain::MerchantContext> {
let db = &*state.store;
let key_manager_state = &(state).into();
let key_store = state
.store()
.get_merchant_key_store_by_merchant_id(
key_manager_state,
merchant_id,
&state.store().get_master_key().to_vec().into(),
)
.await
.change_context(errors::ApiErrorResponse::Unauthorized)
.attach_printable("Failed to fetch merchant key store for the merchant id")?;
let merchant_account = db
.find_merchant_account_by_merchant_id(key_manager_state, merchant_id, &key_store)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to fetch merchant account for the merchant id")?;
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(domain::Context(
merchant_account.clone(),
key_store,
)));
Ok(merchant_context)
}
pub async fn fetch_payment_method_for_network_token_webhooks(
state: &SessionState,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
payment_method_id: &str,
) -> RouterResult<domain::PaymentMethod> {
let db = &*state.store;
let key_manager_state = &(state).into();
let payment_method = db
.find_payment_method(
key_manager_state,
key_store,
payment_method_id,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::WebhookResourceNotFound)
.attach_printable("Failed to fetch the payment method")?;
Ok(payment_method)
}
|
crates/router/src/core/webhooks/network_tokenization_incoming.rs
|
router::src::core::webhooks::network_tokenization_incoming
| 3,434
| true
|
// File: crates/router/src/core/webhooks/outgoing.rs
// Module: router::src::core::webhooks::outgoing
use std::collections::HashMap;
use api_models::{
webhook_events::{OutgoingWebhookRequestContent, OutgoingWebhookResponseContent},
webhooks,
};
use common_utils::{
ext_traits::{Encode, StringExt},
request::RequestContent,
type_name,
types::keymanager::{Identifier, KeyManagerState},
};
use diesel_models::process_tracker::business_status;
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::type_encryption::{crypto_operation, CryptoOperation};
use hyperswitch_interfaces::consts;
use masking::{ExposeInterface, Mask, PeekInterface, Secret};
use router_env::{
instrument,
tracing::{self, Instrument},
};
use super::{types, utils, MERCHANT_ID};
#[cfg(feature = "stripe")]
use crate::compatibility::stripe::webhooks as stripe_webhooks;
use crate::{
core::{
errors::{self, CustomResult},
metrics,
},
db::StorageInterface,
events::outgoing_webhook_logs::{
OutgoingWebhookEvent, OutgoingWebhookEventContent, OutgoingWebhookEventMetric,
},
logger,
routes::{app::SessionStateInfo, SessionState},
services,
types::{
api,
domain::{self},
storage::{self, enums},
transformers::ForeignFrom,
},
utils::{OptionExt, ValueExt},
workflows::outgoing_webhook_retry,
};
#[allow(clippy::too_many_arguments)]
#[instrument(skip_all)]
pub(crate) async fn create_event_and_trigger_outgoing_webhook(
state: SessionState,
merchant_context: domain::MerchantContext,
business_profile: domain::Profile,
event_type: enums::EventType,
event_class: enums::EventClass,
primary_object_id: String,
primary_object_type: enums::EventObjectType,
content: api::OutgoingWebhookContent,
primary_object_created_at: Option<time::PrimitiveDateTime>,
) -> CustomResult<(), errors::ApiErrorResponse> {
let delivery_attempt = enums::WebhookDeliveryAttempt::InitialAttempt;
let idempotent_event_id =
utils::get_idempotent_event_id(&primary_object_id, event_type, delivery_attempt)
.change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
.attach_printable("Failed to generate idempotent event ID")?;
let webhook_url_result = get_webhook_url_from_business_profile(&business_profile);
if !state.conf.webhooks.outgoing_enabled
|| webhook_url_result.is_err()
|| webhook_url_result.as_ref().is_ok_and(String::is_empty)
{
logger::debug!(
business_profile_id=?business_profile.get_id(),
%idempotent_event_id,
"Outgoing webhooks are disabled in application configuration, or merchant webhook URL \
could not be obtained; skipping outgoing webhooks for event"
);
return Ok(());
}
let event_id = utils::generate_event_id();
let merchant_id = business_profile.merchant_id.clone();
let now = common_utils::date_time::now();
let outgoing_webhook = api::OutgoingWebhook {
merchant_id: merchant_id.clone(),
event_id: event_id.clone(),
event_type,
content: content.clone(),
timestamp: now,
};
let request_content =
get_outgoing_webhook_request(&merchant_context, outgoing_webhook, &business_profile)
.change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
.attach_printable("Failed to construct outgoing webhook request content")?;
let event_metadata = storage::EventMetadata::foreign_from(&content);
let key_manager_state = &(&state).into();
let new_event = domain::Event {
event_id: event_id.clone(),
event_type,
event_class,
is_webhook_notified: false,
primary_object_id,
primary_object_type,
created_at: now,
merchant_id: Some(business_profile.merchant_id.clone()),
business_profile_id: Some(business_profile.get_id().to_owned()),
primary_object_created_at,
idempotent_event_id: Some(idempotent_event_id.clone()),
initial_attempt_id: Some(event_id.clone()),
request: Some(
crypto_operation(
key_manager_state,
type_name!(domain::Event),
CryptoOperation::Encrypt(
request_content
.encode_to_string_of_json()
.change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
.attach_printable("Failed to encode outgoing webhook request content")
.map(Secret::new)?,
),
Identifier::Merchant(
merchant_context
.get_merchant_key_store()
.merchant_id
.clone(),
),
merchant_context
.get_merchant_key_store()
.key
.get_inner()
.peek(),
)
.await
.and_then(|val| val.try_into_operation())
.change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
.attach_printable("Failed to encrypt outgoing webhook request content")?,
),
response: None,
delivery_attempt: Some(delivery_attempt),
metadata: Some(event_metadata),
is_overall_delivery_successful: Some(false),
};
let lock_value = utils::perform_redis_lock(
&state,
&idempotent_event_id,
merchant_context.get_merchant_account().get_id().to_owned(),
)
.await?;
if lock_value.is_none() {
return Ok(());
}
if (state
.store
.find_event_by_merchant_id_idempotent_event_id(
key_manager_state,
&merchant_id,
&idempotent_event_id,
merchant_context.get_merchant_key_store(),
)
.await)
.is_ok()
{
logger::debug!(
"Event with idempotent ID `{idempotent_event_id}` already exists in the database"
);
utils::free_redis_lock(
&state,
&idempotent_event_id,
merchant_context.get_merchant_account().get_id().to_owned(),
lock_value,
)
.await?;
return Ok(());
}
let event_insert_result = state
.store
.insert_event(
key_manager_state,
new_event,
merchant_context.get_merchant_key_store(),
)
.await;
let event = match event_insert_result {
Ok(event) => Ok(event),
Err(error) => {
logger::error!(event_insertion_failure=?error);
Err(error
.change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
.attach_printable("Failed to insert event in events table"))
}
}?;
utils::free_redis_lock(
&state,
&idempotent_event_id,
merchant_context.get_merchant_account().get_id().to_owned(),
lock_value,
)
.await?;
let process_tracker = add_outgoing_webhook_retry_task_to_process_tracker(
&*state.store,
&business_profile,
&event,
)
.await
.inspect_err(|error| {
logger::error!(
?error,
"Failed to add outgoing webhook retry task to process tracker"
);
})
.ok();
let cloned_key_store = merchant_context.get_merchant_key_store().clone();
// Using a tokio spawn here and not arbiter because not all caller of this function
// may have an actix arbiter
tokio::spawn(
async move {
Box::pin(trigger_webhook_and_raise_event(
state,
business_profile,
&cloned_key_store,
event,
request_content,
delivery_attempt,
Some(content),
process_tracker,
))
.await;
}
.in_current_span(),
);
Ok(())
}
#[allow(clippy::too_many_arguments)]
#[instrument(skip_all)]
pub(crate) async fn trigger_webhook_and_raise_event(
state: SessionState,
business_profile: domain::Profile,
merchant_key_store: &domain::MerchantKeyStore,
event: domain::Event,
request_content: OutgoingWebhookRequestContent,
delivery_attempt: enums::WebhookDeliveryAttempt,
content: Option<api::OutgoingWebhookContent>,
process_tracker: Option<storage::ProcessTracker>,
) {
logger::debug!(
event_id=%event.event_id,
idempotent_event_id=?event.idempotent_event_id,
initial_attempt_id=?event.initial_attempt_id,
"Attempting to send webhook"
);
let merchant_id = business_profile.merchant_id.clone();
let trigger_webhook_result = trigger_webhook_to_merchant(
state.clone(),
business_profile,
merchant_key_store,
event.clone(),
request_content,
delivery_attempt,
process_tracker,
)
.await;
let _ = raise_webhooks_analytics_event(
state,
trigger_webhook_result,
content,
merchant_id,
event,
merchant_key_store,
)
.await;
}
async fn trigger_webhook_to_merchant(
state: SessionState,
business_profile: domain::Profile,
merchant_key_store: &domain::MerchantKeyStore,
event: domain::Event,
request_content: OutgoingWebhookRequestContent,
delivery_attempt: enums::WebhookDeliveryAttempt,
process_tracker: Option<storage::ProcessTracker>,
) -> CustomResult<(), errors::WebhooksFlowError> {
let webhook_url = match (
get_webhook_url_from_business_profile(&business_profile),
process_tracker.clone(),
) {
(Ok(webhook_url), _) => Ok(webhook_url),
(Err(error), Some(process_tracker)) => {
if !error
.current_context()
.is_webhook_delivery_retryable_error()
{
logger::debug!("Failed to obtain merchant webhook URL, aborting retries");
state
.store
.as_scheduler()
.finish_process_with_business_status(process_tracker, business_status::FAILURE)
.await
.change_context(
errors::WebhooksFlowError::OutgoingWebhookProcessTrackerTaskUpdateFailed,
)?;
}
Err(error)
}
(Err(error), None) => Err(error),
}?;
let event_id = event.event_id;
let headers = request_content
.headers
.into_iter()
.map(|(name, value)| (name, value.into_masked()))
.collect();
let request = services::RequestBuilder::new()
.method(services::Method::Post)
.url(&webhook_url)
.attach_default_headers()
.headers(headers)
.set_body(RequestContent::RawBytes(
request_content.body.expose().into_bytes(),
))
.build();
let response = state
.api_client
.send_request(&state, request, None, false)
.await;
metrics::WEBHOOK_OUTGOING_COUNT.add(
1,
router_env::metric_attributes!((MERCHANT_ID, business_profile.merchant_id.clone())),
);
logger::debug!(outgoing_webhook_response=?response);
match delivery_attempt {
enums::WebhookDeliveryAttempt::InitialAttempt => match response {
Err(client_error) => {
api_client_error_handler(
state.clone(),
merchant_key_store.clone(),
&business_profile.merchant_id,
&event_id,
client_error,
delivery_attempt,
ScheduleWebhookRetry::NoSchedule,
)
.await?
}
Ok(response) => {
let status_code = response.status();
let updated_event = update_event_in_storage(
state.clone(),
merchant_key_store.clone(),
&business_profile.merchant_id,
&event_id,
response,
)
.await?;
if status_code.is_success() {
update_overall_delivery_status_in_storage(
state.clone(),
merchant_key_store.clone(),
&business_profile.merchant_id,
updated_event,
)
.await?;
success_response_handler(
state.clone(),
&business_profile.merchant_id,
process_tracker,
business_status::INITIAL_DELIVERY_ATTEMPT_SUCCESSFUL,
)
.await?;
} else {
error_response_handler(
state.clone(),
&business_profile.merchant_id,
delivery_attempt,
status_code.as_u16(),
"Ignoring error when sending webhook to merchant",
ScheduleWebhookRetry::NoSchedule,
)
.await?;
}
}
},
enums::WebhookDeliveryAttempt::AutomaticRetry => {
let process_tracker = process_tracker
.get_required_value("process_tracker")
.change_context(errors::WebhooksFlowError::OutgoingWebhookRetrySchedulingFailed)
.attach_printable("`process_tracker` is unavailable in automatic retry flow")?;
match response {
Err(client_error) => {
api_client_error_handler(
state.clone(),
merchant_key_store.clone(),
&business_profile.merchant_id,
&event_id,
client_error,
delivery_attempt,
ScheduleWebhookRetry::WithProcessTracker(Box::new(process_tracker)),
)
.await?;
}
Ok(response) => {
let status_code = response.status();
let updated_event = update_event_in_storage(
state.clone(),
merchant_key_store.clone(),
&business_profile.merchant_id,
&event_id,
response,
)
.await?;
if status_code.is_success() {
update_overall_delivery_status_in_storage(
state.clone(),
merchant_key_store.clone(),
&business_profile.merchant_id,
updated_event,
)
.await?;
success_response_handler(
state.clone(),
&business_profile.merchant_id,
Some(process_tracker),
"COMPLETED_BY_PT",
)
.await?;
} else {
error_response_handler(
state.clone(),
&business_profile.merchant_id,
delivery_attempt,
status_code.as_u16(),
"An error occurred when sending webhook to merchant",
ScheduleWebhookRetry::WithProcessTracker(Box::new(process_tracker)),
)
.await?;
}
}
}
}
enums::WebhookDeliveryAttempt::ManualRetry => match response {
Err(client_error) => {
api_client_error_handler(
state.clone(),
merchant_key_store.clone(),
&business_profile.merchant_id,
&event_id,
client_error,
delivery_attempt,
ScheduleWebhookRetry::NoSchedule,
)
.await?
}
Ok(response) => {
let status_code = response.status();
let _updated_event = update_event_in_storage(
state.clone(),
merchant_key_store.clone(),
&business_profile.merchant_id,
&event_id,
response,
)
.await?;
if status_code.is_success() {
increment_webhook_outgoing_received_count(&business_profile.merchant_id);
} else {
error_response_handler(
state,
&business_profile.merchant_id,
delivery_attempt,
status_code.as_u16(),
"Ignoring error when sending webhook to merchant",
ScheduleWebhookRetry::NoSchedule,
)
.await?;
}
}
},
}
Ok(())
}
async fn raise_webhooks_analytics_event(
state: SessionState,
trigger_webhook_result: CustomResult<(), errors::WebhooksFlowError>,
content: Option<api::OutgoingWebhookContent>,
merchant_id: common_utils::id_type::MerchantId,
event: domain::Event,
merchant_key_store: &domain::MerchantKeyStore,
) {
let key_manager_state: &KeyManagerState = &(&state).into();
let event_id = event.event_id;
let error = if let Err(error) = trigger_webhook_result {
logger::error!(?error, "Failed to send webhook to merchant");
serde_json::to_value(error.current_context())
.change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
.inspect_err(|error| {
logger::error!(?error, "Failed to serialize outgoing webhook error as JSON");
})
.ok()
} else {
None
};
let outgoing_webhook_event_content = content
.as_ref()
.and_then(api::OutgoingWebhookContent::get_outgoing_webhook_event_content)
.or_else(|| get_outgoing_webhook_event_content_from_event_metadata(event.metadata));
// Fetch updated_event from db
let updated_event = state
.store
.find_event_by_merchant_id_event_id(
key_manager_state,
&merchant_id,
&event_id,
merchant_key_store,
)
.await
.attach_printable_lazy(|| format!("event not found for id: {}", &event_id))
.map_err(|error| {
logger::error!(?error);
error
})
.ok();
// Get status_code from webhook response
let status_code = updated_event.and_then(|updated_event| {
let webhook_response: Option<OutgoingWebhookResponseContent> =
updated_event.response.and_then(|res| {
res.peek()
.parse_struct("OutgoingWebhookResponseContent")
.map_err(|error| {
logger::error!(?error, "Error deserializing webhook response");
error
})
.ok()
});
webhook_response.and_then(|res| res.status_code)
});
let webhook_event = OutgoingWebhookEvent::new(
state.tenant.tenant_id.clone(),
merchant_id,
event_id,
event.event_type,
outgoing_webhook_event_content,
error,
event.initial_attempt_id,
status_code,
event.delivery_attempt,
);
state.event_handler().log_event(&webhook_event);
}
pub(crate) async fn add_outgoing_webhook_retry_task_to_process_tracker(
db: &dyn StorageInterface,
business_profile: &domain::Profile,
event: &domain::Event,
) -> CustomResult<storage::ProcessTracker, errors::StorageError> {
let schedule_time = outgoing_webhook_retry::get_webhook_delivery_retry_schedule_time(
db,
&business_profile.merchant_id,
0,
)
.await
.ok_or(errors::StorageError::ValueNotFound(
"Process tracker schedule time".into(), // Can raise a better error here
))
.attach_printable("Failed to obtain initial process tracker schedule time")?;
let tracking_data = types::OutgoingWebhookTrackingData {
merchant_id: business_profile.merchant_id.clone(),
business_profile_id: business_profile.get_id().to_owned(),
event_type: event.event_type,
event_class: event.event_class,
primary_object_id: event.primary_object_id.clone(),
primary_object_type: event.primary_object_type,
initial_attempt_id: event.initial_attempt_id.clone(),
};
let runner = storage::ProcessTrackerRunner::OutgoingWebhookRetryWorkflow;
let task = "OUTGOING_WEBHOOK_RETRY";
let tag = ["OUTGOING_WEBHOOKS"];
let process_tracker_id = scheduler::utils::get_process_tracker_id(
runner,
task,
&event.event_id,
&business_profile.merchant_id,
);
let process_tracker_entry = storage::ProcessTrackerNew::new(
process_tracker_id,
task,
runner,
tag,
tracking_data,
None,
schedule_time,
common_types::consts::API_VERSION,
)
.map_err(errors::StorageError::from)?;
let attributes = router_env::metric_attributes!(("flow", "OutgoingWebhookRetry"));
match db.insert_process(process_tracker_entry).await {
Ok(process_tracker) => {
crate::routes::metrics::TASKS_ADDED_COUNT.add(1, attributes);
Ok(process_tracker)
}
Err(error) => {
crate::routes::metrics::TASK_ADDITION_FAILURES_COUNT.add(1, attributes);
Err(error)
}
}
}
fn get_webhook_url_from_business_profile(
business_profile: &domain::Profile,
) -> CustomResult<String, errors::WebhooksFlowError> {
let webhook_details = business_profile
.webhook_details
.clone()
.get_required_value("webhook_details")
.change_context(errors::WebhooksFlowError::MerchantWebhookDetailsNotFound)?;
webhook_details
.webhook_url
.get_required_value("webhook_url")
.change_context(errors::WebhooksFlowError::MerchantWebhookUrlNotConfigured)
.map(ExposeInterface::expose)
}
pub(crate) fn get_outgoing_webhook_request(
merchant_context: &domain::MerchantContext,
outgoing_webhook: api::OutgoingWebhook,
business_profile: &domain::Profile,
) -> CustomResult<OutgoingWebhookRequestContent, errors::WebhooksFlowError> {
#[inline]
fn get_outgoing_webhook_request_inner<WebhookType: types::OutgoingWebhookType>(
outgoing_webhook: api::OutgoingWebhook,
business_profile: &domain::Profile,
) -> CustomResult<OutgoingWebhookRequestContent, errors::WebhooksFlowError> {
let mut headers = vec![
(
reqwest::header::CONTENT_TYPE.to_string(),
mime::APPLICATION_JSON.essence_str().into(),
),
(
reqwest::header::USER_AGENT.to_string(),
consts::USER_AGENT.to_string().into(),
),
];
let transformed_outgoing_webhook = WebhookType::from(outgoing_webhook);
let payment_response_hash_key = business_profile.payment_response_hash_key.clone();
let custom_headers = business_profile
.outgoing_webhook_custom_http_headers
.clone()
.map(|headers| {
headers
.into_inner()
.expose()
.parse_value::<HashMap<String, String>>("HashMap<String,String>")
.change_context(errors::WebhooksFlowError::OutgoingWebhookEncodingFailed)
.attach_printable("Failed to deserialize outgoing webhook custom HTTP headers")
})
.transpose()?;
if let Some(ref map) = custom_headers {
headers.extend(
map.iter()
.map(|(key, value)| (key.clone(), value.clone().into_masked())),
);
};
let outgoing_webhooks_signature = transformed_outgoing_webhook
.get_outgoing_webhooks_signature(payment_response_hash_key)?;
if let Some(signature) = outgoing_webhooks_signature.signature {
WebhookType::add_webhook_header(&mut headers, signature)
}
Ok(OutgoingWebhookRequestContent {
body: outgoing_webhooks_signature.payload,
headers: headers
.into_iter()
.map(|(name, value)| (name, Secret::new(value.into_inner())))
.collect(),
})
}
match merchant_context
.get_merchant_account()
.get_compatible_connector()
{
#[cfg(feature = "stripe")]
Some(api_models::enums::Connector::Stripe) => get_outgoing_webhook_request_inner::<
stripe_webhooks::StripeOutgoingWebhook,
>(outgoing_webhook, business_profile),
_ => get_outgoing_webhook_request_inner::<webhooks::OutgoingWebhook>(
outgoing_webhook,
business_profile,
),
}
}
#[derive(Debug)]
enum ScheduleWebhookRetry {
WithProcessTracker(Box<storage::ProcessTracker>),
NoSchedule,
}
async fn update_event_if_client_error(
state: SessionState,
merchant_key_store: domain::MerchantKeyStore,
merchant_id: &common_utils::id_type::MerchantId,
event_id: &str,
error_message: String,
) -> CustomResult<domain::Event, errors::WebhooksFlowError> {
let is_webhook_notified = false;
let key_manager_state = &(&state).into();
let response_to_store = OutgoingWebhookResponseContent {
body: None,
headers: None,
status_code: None,
error_message: Some(error_message),
};
let event_update = domain::EventUpdate::UpdateResponse {
is_webhook_notified,
response: Some(
crypto_operation(
key_manager_state,
type_name!(domain::Event),
CryptoOperation::Encrypt(
response_to_store
.encode_to_string_of_json()
.change_context(
errors::WebhooksFlowError::OutgoingWebhookResponseEncodingFailed,
)
.map(Secret::new)?,
),
Identifier::Merchant(merchant_key_store.merchant_id.clone()),
merchant_key_store.key.get_inner().peek(),
)
.await
.and_then(|val| val.try_into_operation())
.change_context(errors::WebhooksFlowError::WebhookEventUpdationFailed)
.attach_printable("Failed to encrypt outgoing webhook response content")?,
),
};
state
.store
.update_event_by_merchant_id_event_id(
key_manager_state,
merchant_id,
event_id,
event_update,
&merchant_key_store,
)
.await
.change_context(errors::WebhooksFlowError::WebhookEventUpdationFailed)
}
async fn api_client_error_handler(
state: SessionState,
merchant_key_store: domain::MerchantKeyStore,
merchant_id: &common_utils::id_type::MerchantId,
event_id: &str,
client_error: error_stack::Report<errors::ApiClientError>,
delivery_attempt: enums::WebhookDeliveryAttempt,
schedule_webhook_retry: ScheduleWebhookRetry,
) -> CustomResult<(), errors::WebhooksFlowError> {
// Not including detailed error message in response information since it contains too
// much of diagnostic information to be exposed to the merchant.
update_event_if_client_error(
state.clone(),
merchant_key_store,
merchant_id,
event_id,
"Unable to send request to merchant server".to_string(),
)
.await?;
let error = client_error.change_context(errors::WebhooksFlowError::CallToMerchantFailed);
logger::error!(
?error,
?delivery_attempt,
"An error occurred when sending webhook to merchant"
);
if let ScheduleWebhookRetry::WithProcessTracker(process_tracker) = schedule_webhook_retry {
// Schedule a retry attempt for webhook delivery
outgoing_webhook_retry::retry_webhook_delivery_task(
&*state.store,
merchant_id,
*process_tracker,
)
.await
.change_context(errors::WebhooksFlowError::OutgoingWebhookRetrySchedulingFailed)?;
}
Err(error)
}
async fn update_event_in_storage(
state: SessionState,
merchant_key_store: domain::MerchantKeyStore,
merchant_id: &common_utils::id_type::MerchantId,
event_id: &str,
response: reqwest::Response,
) -> CustomResult<domain::Event, errors::WebhooksFlowError> {
let status_code = response.status();
let is_webhook_notified = status_code.is_success();
let key_manager_state = &(&state).into();
let response_headers = response
.headers()
.iter()
.map(|(name, value)| {
(
name.as_str().to_owned(),
value
.to_str()
.map(|s| Secret::from(String::from(s)))
.unwrap_or_else(|error| {
logger::warn!(
"Response header {} contains non-UTF-8 characters: {error:?}",
name.as_str()
);
Secret::from(String::from("Non-UTF-8 header value"))
}),
)
})
.collect::<Vec<_>>();
let response_body = response
.text()
.await
.map(Secret::from)
.unwrap_or_else(|error| {
logger::warn!("Response contains non-UTF-8 characters: {error:?}");
Secret::from(String::from("Non-UTF-8 response body"))
});
let response_to_store = OutgoingWebhookResponseContent {
body: Some(response_body),
headers: Some(response_headers),
status_code: Some(status_code.as_u16()),
error_message: None,
};
let event_update = domain::EventUpdate::UpdateResponse {
is_webhook_notified,
response: Some(
crypto_operation(
key_manager_state,
type_name!(domain::Event),
CryptoOperation::Encrypt(
response_to_store
.encode_to_string_of_json()
.change_context(
errors::WebhooksFlowError::OutgoingWebhookResponseEncodingFailed,
)
.map(Secret::new)?,
),
Identifier::Merchant(merchant_key_store.merchant_id.clone()),
merchant_key_store.key.get_inner().peek(),
)
.await
.and_then(|val| val.try_into_operation())
.change_context(errors::WebhooksFlowError::WebhookEventUpdationFailed)
.attach_printable("Failed to encrypt outgoing webhook response content")?,
),
};
state
.store
.update_event_by_merchant_id_event_id(
key_manager_state,
merchant_id,
event_id,
event_update,
&merchant_key_store,
)
.await
.change_context(errors::WebhooksFlowError::WebhookEventUpdationFailed)
}
async fn update_overall_delivery_status_in_storage(
state: SessionState,
merchant_key_store: domain::MerchantKeyStore,
merchant_id: &common_utils::id_type::MerchantId,
updated_event: domain::Event,
) -> CustomResult<(), errors::WebhooksFlowError> {
let key_manager_state = &(&state).into();
let update_overall_delivery_status = domain::EventUpdate::OverallDeliveryStatusUpdate {
is_overall_delivery_successful: true,
};
let initial_attempt_id = updated_event.initial_attempt_id.as_ref();
let delivery_attempt = updated_event.delivery_attempt;
if let Some((
initial_attempt_id,
enums::WebhookDeliveryAttempt::InitialAttempt
| enums::WebhookDeliveryAttempt::AutomaticRetry,
)) = initial_attempt_id.zip(delivery_attempt)
{
state
.store
.update_event_by_merchant_id_event_id(
key_manager_state,
merchant_id,
initial_attempt_id.as_str(),
update_overall_delivery_status,
&merchant_key_store,
)
.await
.change_context(errors::WebhooksFlowError::WebhookEventUpdationFailed)
.attach_printable("Failed to update initial delivery attempt")?;
}
Ok(())
}
fn increment_webhook_outgoing_received_count(merchant_id: &common_utils::id_type::MerchantId) {
metrics::WEBHOOK_OUTGOING_RECEIVED_COUNT.add(
1,
router_env::metric_attributes!((MERCHANT_ID, merchant_id.clone())),
)
}
async fn success_response_handler(
state: SessionState,
merchant_id: &common_utils::id_type::MerchantId,
process_tracker: Option<storage::ProcessTracker>,
business_status: &'static str,
) -> CustomResult<(), errors::WebhooksFlowError> {
increment_webhook_outgoing_received_count(merchant_id);
match process_tracker {
Some(process_tracker) => state
.store
.as_scheduler()
.finish_process_with_business_status(process_tracker, business_status)
.await
.change_context(
errors::WebhooksFlowError::OutgoingWebhookProcessTrackerTaskUpdateFailed,
),
None => Ok(()),
}
}
async fn error_response_handler(
state: SessionState,
merchant_id: &common_utils::id_type::MerchantId,
delivery_attempt: enums::WebhookDeliveryAttempt,
status_code: u16,
log_message: &'static str,
schedule_webhook_retry: ScheduleWebhookRetry,
) -> CustomResult<(), errors::WebhooksFlowError> {
metrics::WEBHOOK_OUTGOING_NOT_RECEIVED_COUNT.add(
1,
router_env::metric_attributes!((MERCHANT_ID, merchant_id.clone())),
);
let error = report!(errors::WebhooksFlowError::NotReceivedByMerchant);
logger::warn!(?error, ?delivery_attempt, status_code, %log_message);
if let ScheduleWebhookRetry::WithProcessTracker(process_tracker) = schedule_webhook_retry {
// Schedule a retry attempt for webhook delivery
outgoing_webhook_retry::retry_webhook_delivery_task(
&*state.store,
merchant_id,
*process_tracker,
)
.await
.change_context(errors::WebhooksFlowError::OutgoingWebhookRetrySchedulingFailed)?;
}
Err(error)
}
impl ForeignFrom<&api::OutgoingWebhookContent> for storage::EventMetadata {
fn foreign_from(content: &api::OutgoingWebhookContent) -> Self {
match content {
webhooks::OutgoingWebhookContent::PaymentDetails(payments_response) => Self::Payment {
payment_id: payments_response.payment_id.clone(),
},
webhooks::OutgoingWebhookContent::RefundDetails(refund_response) => Self::Refund {
payment_id: refund_response.payment_id.clone(),
refund_id: refund_response.refund_id.clone(),
},
webhooks::OutgoingWebhookContent::DisputeDetails(dispute_response) => Self::Dispute {
payment_id: dispute_response.payment_id.clone(),
attempt_id: dispute_response.attempt_id.clone(),
dispute_id: dispute_response.dispute_id.clone(),
},
webhooks::OutgoingWebhookContent::MandateDetails(mandate_response) => Self::Mandate {
payment_method_id: mandate_response.payment_method_id.clone(),
mandate_id: mandate_response.mandate_id.clone(),
},
#[cfg(feature = "payouts")]
webhooks::OutgoingWebhookContent::PayoutDetails(payout_response) => Self::Payout {
payout_id: payout_response.payout_id.clone(),
},
}
}
}
fn get_outgoing_webhook_event_content_from_event_metadata(
event_metadata: Option<storage::EventMetadata>,
) -> Option<OutgoingWebhookEventContent> {
event_metadata.map(|metadata| match metadata {
diesel_models::EventMetadata::Payment { payment_id } => {
OutgoingWebhookEventContent::Payment {
payment_id,
content: serde_json::Value::Null,
}
}
diesel_models::EventMetadata::Payout { payout_id } => OutgoingWebhookEventContent::Payout {
payout_id,
content: serde_json::Value::Null,
},
diesel_models::EventMetadata::Refund {
payment_id,
refund_id,
} => OutgoingWebhookEventContent::Refund {
payment_id,
refund_id,
content: serde_json::Value::Null,
},
diesel_models::EventMetadata::Dispute {
payment_id,
attempt_id,
dispute_id,
} => OutgoingWebhookEventContent::Dispute {
payment_id,
attempt_id,
dispute_id,
content: serde_json::Value::Null,
},
diesel_models::EventMetadata::Mandate {
payment_method_id,
mandate_id,
} => OutgoingWebhookEventContent::Mandate {
payment_method_id,
mandate_id,
content: serde_json::Value::Null,
},
})
}
|
crates/router/src/core/webhooks/outgoing.rs
|
router::src::core::webhooks::outgoing
| 7,500
| true
|
// File: crates/router/src/core/webhooks/recovery_incoming.rs
// Module: router::src::core::webhooks::recovery_incoming
use std::{collections::HashMap, marker::PhantomData, str::FromStr};
use api_models::{enums as api_enums, payments as api_payments, webhooks};
use common_utils::{
ext_traits::{AsyncExt, ValueExt},
id_type,
};
use diesel_models::process_tracker as storage;
use error_stack::{report, ResultExt};
use futures::stream::SelectNextSome;
use hyperswitch_domain_models::{
payments as domain_payments,
revenue_recovery::{self, RecoveryPaymentIntent},
router_data_v2::flow_common_types,
router_flow_types,
router_request_types::revenue_recovery as revenue_recovery_request,
router_response_types::revenue_recovery as revenue_recovery_response,
types as router_types,
};
use hyperswitch_interfaces::webhooks as interface_webhooks;
use masking::{PeekInterface, Secret};
use router_env::{instrument, logger, tracing};
use services::kafka;
use storage::business_status;
use crate::{
core::{
self, admin,
errors::{self, CustomResult},
payments::{self, helpers},
},
db::{errors::RevenueRecoveryError, StorageInterface},
routes::{app::ReqState, metrics, SessionState},
services::{
self,
connector_integration_interface::{self, RouterDataConversion},
},
types::{
self, api, domain,
storage::{
revenue_recovery as storage_revenue_recovery,
revenue_recovery_redis_operation::{
PaymentProcessorTokenDetails, PaymentProcessorTokenStatus, RedisTokenManager,
},
},
transformers::ForeignFrom,
},
workflows::revenue_recovery as revenue_recovery_flow,
};
#[cfg(feature = "v2")]
pub const REVENUE_RECOVERY: &str = "revenue_recovery";
#[allow(clippy::too_many_arguments)]
#[instrument(skip_all)]
#[cfg(feature = "revenue_recovery")]
pub async fn recovery_incoming_webhook_flow(
state: SessionState,
merchant_context: domain::MerchantContext,
business_profile: domain::Profile,
source_verified: bool,
connector_enum: &connector_integration_interface::ConnectorEnum,
billing_connector_account: hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount,
connector_name: &str,
request_details: &hyperswitch_interfaces::webhooks::IncomingWebhookRequestDetails<'_>,
event_type: webhooks::IncomingWebhookEvent,
req_state: ReqState,
object_ref_id: &webhooks::ObjectReferenceId,
) -> CustomResult<webhooks::WebhookResponseTracker, errors::RevenueRecoveryError> {
// Source verification is necessary for revenue recovery webhooks flow since We don't have payment intent/attempt object created before in our system.
common_utils::fp_utils::when(!source_verified, || {
Err(report!(
errors::RevenueRecoveryError::WebhookAuthenticationFailed
))
})?;
let connector = api_enums::Connector::from_str(connector_name)
.change_context(errors::RevenueRecoveryError::InvoiceWebhookProcessingFailed)
.attach_printable_lazy(|| format!("unable to parse connector name {connector_name:?}"))?;
let billing_connectors_with_invoice_sync_call = &state.conf.billing_connectors_invoice_sync;
let should_billing_connector_invoice_api_called = billing_connectors_with_invoice_sync_call
.billing_connectors_which_requires_invoice_sync_call
.contains(&connector);
let billing_connectors_with_payment_sync_call = &state.conf.billing_connectors_payment_sync;
let should_billing_connector_payment_api_called = billing_connectors_with_payment_sync_call
.billing_connectors_which_require_payment_sync
.contains(&connector);
let billing_connector_payment_details =
BillingConnectorPaymentsSyncResponseData::get_billing_connector_payment_details(
should_billing_connector_payment_api_called,
&state,
&merchant_context,
&billing_connector_account,
connector_name,
object_ref_id,
)
.await?;
let invoice_id = billing_connector_payment_details
.clone()
.map(|data| data.merchant_reference_id);
let billing_connector_invoice_details =
BillingConnectorInvoiceSyncResponseData::get_billing_connector_invoice_details(
should_billing_connector_invoice_api_called,
&state,
&merchant_context,
&billing_connector_account,
connector_name,
invoice_id,
)
.await?;
// Checks whether we have data in billing_connector_invoice_details , if it is there then we construct revenue recovery invoice from it else it takes from webhook
let invoice_details = RevenueRecoveryInvoice::get_recovery_invoice_details(
connector_enum,
request_details,
billing_connector_invoice_details.as_ref(),
)?;
// Fetch the intent using merchant reference id, if not found create new intent.
let payment_intent = invoice_details
.get_payment_intent(&state, &req_state, &merchant_context, &business_profile)
.await
.transpose()
.async_unwrap_or_else(|| async {
invoice_details
.create_payment_intent(&state, &req_state, &merchant_context, &business_profile)
.await
})
.await?;
let is_event_recovery_transaction_event = event_type.is_recovery_transaction_event();
let (recovery_attempt_from_payment_attempt, recovery_intent_from_payment_attempt) =
RevenueRecoveryAttempt::get_recovery_payment_attempt(
is_event_recovery_transaction_event,
&billing_connector_account,
&state,
connector_enum,
&req_state,
billing_connector_payment_details.as_ref(),
request_details,
&merchant_context,
&business_profile,
&payment_intent,
&invoice_details.0,
)
.await?;
// Publish event to Kafka
if let Some(ref attempt) = recovery_attempt_from_payment_attempt {
// Passing `merchant_context` here
let recovery_payment_tuple =
&RecoveryPaymentTuple::new(&recovery_intent_from_payment_attempt, attempt);
if let Err(e) = RecoveryPaymentTuple::publish_revenue_recovery_event_to_kafka(
&state,
recovery_payment_tuple,
None,
)
.await
{
logger::error!(
"Failed to publish revenue recovery event to kafka : {:?}",
e
);
};
}
let attempt_triggered_by = recovery_attempt_from_payment_attempt
.as_ref()
.and_then(|attempt| attempt.get_attempt_triggered_by());
let recovery_action = RecoveryAction {
action: RecoveryAction::get_action(event_type, attempt_triggered_by),
};
let mca_retry_threshold = billing_connector_account
.get_retry_threshold()
.ok_or(report!(
errors::RevenueRecoveryError::BillingThresholdRetryCountFetchFailed
))?;
let intent_retry_count = recovery_intent_from_payment_attempt
.feature_metadata
.as_ref()
.and_then(|metadata| metadata.get_retry_count())
.ok_or(report!(errors::RevenueRecoveryError::RetryCountFetchFailed))?;
logger::info!("Intent retry count: {:?}", intent_retry_count);
recovery_action
.handle_action(
&state,
&business_profile,
&merchant_context,
&billing_connector_account,
mca_retry_threshold,
intent_retry_count,
&(
recovery_attempt_from_payment_attempt,
recovery_intent_from_payment_attempt,
),
)
.await
}
async fn handle_monitoring_threshold(
state: &SessionState,
business_profile: &domain::Profile,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<webhooks::WebhookResponseTracker, errors::RevenueRecoveryError> {
let db = &*state.store;
let key_manager_state = &(state).into();
let monitoring_threshold_config = state.conf.revenue_recovery.monitoring_threshold_in_seconds;
let retry_algorithm_type = state.conf.revenue_recovery.retry_algorithm_type;
let revenue_recovery_retry_algorithm = business_profile
.revenue_recovery_retry_algorithm_data
.clone()
.ok_or(report!(
errors::RevenueRecoveryError::RetryAlgorithmTypeNotFound
))?;
if revenue_recovery_retry_algorithm
.has_exceeded_monitoring_threshold(monitoring_threshold_config)
{
let profile_wrapper = admin::ProfileWrapper::new(business_profile.clone());
profile_wrapper
.update_revenue_recovery_algorithm_under_profile(
db,
key_manager_state,
key_store,
retry_algorithm_type,
)
.await
.change_context(errors::RevenueRecoveryError::RetryAlgorithmUpdationFailed)?;
}
Ok(webhooks::WebhookResponseTracker::NoEffect)
}
#[allow(clippy::too_many_arguments)]
async fn handle_schedule_failed_payment(
billing_connector_account: &domain::MerchantConnectorAccount,
intent_retry_count: u16,
mca_retry_threshold: u16,
state: &SessionState,
merchant_context: &domain::MerchantContext,
payment_attempt_with_recovery_intent: &(
Option<revenue_recovery::RecoveryPaymentAttempt>,
revenue_recovery::RecoveryPaymentIntent,
),
business_profile: &domain::Profile,
revenue_recovery_retry: api_enums::RevenueRecoveryAlgorithmType,
) -> CustomResult<webhooks::WebhookResponseTracker, errors::RevenueRecoveryError> {
let (recovery_attempt_from_payment_attempt, recovery_intent_from_payment_attempt) =
payment_attempt_with_recovery_intent;
// When intent_retry_count is less than or equal to threshold
(intent_retry_count <= mca_retry_threshold)
.then(|| {
logger::error!(
"Payment retry count {} is less than threshold {}",
intent_retry_count,
mca_retry_threshold
);
Ok(webhooks::WebhookResponseTracker::NoEffect)
})
.async_unwrap_or_else(|| async {
// Call calculate_job
core::revenue_recovery::upsert_calculate_pcr_task(
billing_connector_account,
state,
merchant_context,
recovery_intent_from_payment_attempt,
business_profile,
intent_retry_count,
recovery_attempt_from_payment_attempt
.as_ref()
.map(|attempt| attempt.attempt_id.clone()),
storage::ProcessTrackerRunner::PassiveRecoveryWorkflow,
revenue_recovery_retry,
)
.await
})
.await
}
#[derive(Debug)]
pub struct RevenueRecoveryInvoice(revenue_recovery::RevenueRecoveryInvoiceData);
#[derive(Debug)]
pub struct RevenueRecoveryAttempt(revenue_recovery::RevenueRecoveryAttemptData);
impl RevenueRecoveryInvoice {
pub async fn get_or_create_custom_recovery_intent(
data: api_models::payments::RecoveryPaymentsCreate,
state: &SessionState,
req_state: &ReqState,
merchant_context: &domain::MerchantContext,
profile: &domain::Profile,
) -> CustomResult<revenue_recovery::RecoveryPaymentIntent, errors::RevenueRecoveryError> {
let recovery_intent = Self(revenue_recovery::RevenueRecoveryInvoiceData::foreign_from(
data,
));
recovery_intent
.get_payment_intent(state, req_state, merchant_context, profile)
.await
.transpose()
.async_unwrap_or_else(|| async {
recovery_intent
.create_payment_intent(state, req_state, merchant_context, profile)
.await
})
.await
}
fn get_recovery_invoice_details(
connector_enum: &connector_integration_interface::ConnectorEnum,
request_details: &hyperswitch_interfaces::webhooks::IncomingWebhookRequestDetails<'_>,
billing_connector_invoice_details: Option<
&revenue_recovery_response::BillingConnectorInvoiceSyncResponse,
>,
) -> CustomResult<Self, errors::RevenueRecoveryError> {
billing_connector_invoice_details.map_or_else(
|| {
interface_webhooks::IncomingWebhook::get_revenue_recovery_invoice_details(
connector_enum,
request_details,
)
.change_context(errors::RevenueRecoveryError::InvoiceWebhookProcessingFailed)
.attach_printable("Failed while getting revenue recovery invoice details")
.map(RevenueRecoveryInvoice)
},
|data| {
Ok(Self(revenue_recovery::RevenueRecoveryInvoiceData::from(
data,
)))
},
)
}
async fn get_payment_intent(
&self,
state: &SessionState,
req_state: &ReqState,
merchant_context: &domain::MerchantContext,
profile: &domain::Profile,
) -> CustomResult<Option<revenue_recovery::RecoveryPaymentIntent>, errors::RevenueRecoveryError>
{
let payment_response = Box::pin(payments::payments_get_intent_using_merchant_reference(
state.clone(),
merchant_context.clone(),
profile.clone(),
req_state.clone(),
&self.0.merchant_reference_id,
hyperswitch_domain_models::payments::HeaderPayload::default(),
))
.await;
let response = match payment_response {
Ok(services::ApplicationResponse::JsonWithHeaders((payments_response, _))) => {
let payment_id = payments_response.id.clone();
let status = payments_response.status;
let feature_metadata = payments_response.feature_metadata;
let merchant_id = merchant_context.get_merchant_account().get_id().clone();
let revenue_recovery_invoice_data = &self.0;
Ok(Some(revenue_recovery::RecoveryPaymentIntent {
payment_id,
status,
feature_metadata,
merchant_id,
merchant_reference_id: Some(
revenue_recovery_invoice_data.merchant_reference_id.clone(),
),
invoice_amount: revenue_recovery_invoice_data.amount,
invoice_currency: revenue_recovery_invoice_data.currency,
created_at: revenue_recovery_invoice_data.billing_started_at,
billing_address: revenue_recovery_invoice_data.billing_address.clone(),
}))
}
Err(err)
if matches!(
err.current_context(),
&errors::ApiErrorResponse::PaymentNotFound
) =>
{
Ok(None)
}
Ok(_) => Err(errors::RevenueRecoveryError::PaymentIntentFetchFailed)
.attach_printable("Unexpected response from payment intent core"),
error @ Err(_) => {
logger::error!(?error);
Err(errors::RevenueRecoveryError::PaymentIntentFetchFailed)
.attach_printable("failed to fetch payment intent recovery webhook flow")
}
}?;
Ok(response)
}
async fn create_payment_intent(
&self,
state: &SessionState,
req_state: &ReqState,
merchant_context: &domain::MerchantContext,
profile: &domain::Profile,
) -> CustomResult<revenue_recovery::RecoveryPaymentIntent, errors::RevenueRecoveryError> {
let payload = api_payments::PaymentsCreateIntentRequest::from(&self.0);
let global_payment_id = id_type::GlobalPaymentId::generate(&state.conf.cell_information.id);
let create_intent_response = Box::pin(payments::payments_intent_core::<
router_flow_types::payments::PaymentCreateIntent,
api_payments::PaymentsIntentResponse,
_,
_,
hyperswitch_domain_models::payments::PaymentIntentData<
router_flow_types::payments::PaymentCreateIntent,
>,
>(
state.clone(),
req_state.clone(),
merchant_context.clone(),
profile.clone(),
payments::operations::PaymentIntentCreate,
payload,
global_payment_id,
hyperswitch_domain_models::payments::HeaderPayload::default(),
))
.await
.change_context(errors::RevenueRecoveryError::PaymentIntentCreateFailed)?;
let response = create_intent_response
.get_json_body()
.change_context(errors::RevenueRecoveryError::PaymentIntentCreateFailed)
.attach_printable("expected json response")?;
let merchant_id = merchant_context.get_merchant_account().get_id().clone();
let revenue_recovery_invoice_data = &self.0;
Ok(revenue_recovery::RecoveryPaymentIntent {
payment_id: response.id,
status: response.status,
feature_metadata: response.feature_metadata,
merchant_id,
merchant_reference_id: Some(
revenue_recovery_invoice_data.merchant_reference_id.clone(),
),
invoice_amount: revenue_recovery_invoice_data.amount,
invoice_currency: revenue_recovery_invoice_data.currency,
created_at: revenue_recovery_invoice_data.billing_started_at,
billing_address: revenue_recovery_invoice_data.billing_address.clone(),
})
}
}
impl RevenueRecoveryAttempt {
pub async fn load_recovery_attempt_from_api(
data: api_models::payments::RecoveryPaymentsCreate,
state: &SessionState,
req_state: &ReqState,
merchant_context: &domain::MerchantContext,
profile: &domain::Profile,
payment_intent: revenue_recovery::RecoveryPaymentIntent,
payment_merchant_connector_account: domain::MerchantConnectorAccount,
) -> CustomResult<
(
revenue_recovery::RecoveryPaymentAttempt,
revenue_recovery::RecoveryPaymentIntent,
),
errors::RevenueRecoveryError,
> {
let recovery_attempt = Self(revenue_recovery::RevenueRecoveryAttemptData::foreign_from(
&data,
));
recovery_attempt
.get_payment_attempt(state, req_state, merchant_context, profile, &payment_intent)
.await
.transpose()
.async_unwrap_or_else(|| async {
recovery_attempt
.record_payment_attempt(
state,
req_state,
merchant_context,
profile,
&payment_intent,
&data.billing_merchant_connector_id,
Some(payment_merchant_connector_account),
)
.await
})
.await
}
fn get_recovery_invoice_transaction_details(
connector_enum: &connector_integration_interface::ConnectorEnum,
request_details: &hyperswitch_interfaces::webhooks::IncomingWebhookRequestDetails<'_>,
billing_connector_payment_details: Option<
&revenue_recovery_response::BillingConnectorPaymentsSyncResponse,
>,
billing_connector_invoice_details: &revenue_recovery::RevenueRecoveryInvoiceData,
) -> CustomResult<Self, errors::RevenueRecoveryError> {
billing_connector_payment_details.map_or_else(
|| {
interface_webhooks::IncomingWebhook::get_revenue_recovery_attempt_details(
connector_enum,
request_details,
)
.change_context(errors::RevenueRecoveryError::TransactionWebhookProcessingFailed)
.attach_printable(
"Failed to get recovery attempt details from the billing connector",
)
.map(RevenueRecoveryAttempt)
},
|data| {
Ok(Self(revenue_recovery::RevenueRecoveryAttemptData::from((
data,
billing_connector_invoice_details,
))))
},
)
}
pub fn get_revenue_recovery_attempt(
payment_intent: &domain_payments::PaymentIntent,
revenue_recovery_metadata: &api_payments::PaymentRevenueRecoveryMetadata,
billing_connector_account: &domain::MerchantConnectorAccount,
card_info: api_payments::AdditionalCardInfo,
payment_processor_token: &str,
) -> CustomResult<Self, errors::RevenueRecoveryError> {
let revenue_recovery_data = payment_intent
.create_revenue_recovery_attempt_data(
revenue_recovery_metadata.clone(),
billing_connector_account,
card_info,
payment_processor_token,
)
.change_context(errors::RevenueRecoveryError::RevenueRecoveryAttemptDataCreateFailed)
.attach_printable("Failed to build recovery attempt data")?;
Ok(Self(revenue_recovery_data))
}
async fn get_payment_attempt(
&self,
state: &SessionState,
req_state: &ReqState,
merchant_context: &domain::MerchantContext,
profile: &domain::Profile,
payment_intent: &revenue_recovery::RecoveryPaymentIntent,
) -> CustomResult<
Option<(
revenue_recovery::RecoveryPaymentAttempt,
revenue_recovery::RecoveryPaymentIntent,
)>,
errors::RevenueRecoveryError,
> {
let attempt_response =
Box::pin(payments::payments_list_attempts_using_payment_intent_id::<
payments::operations::PaymentGetListAttempts,
api_payments::PaymentAttemptListResponse,
_,
payments::operations::payment_attempt_list::PaymentGetListAttempts,
hyperswitch_domain_models::payments::PaymentAttemptListData<
payments::operations::PaymentGetListAttempts,
>,
>(
state.clone(),
req_state.clone(),
merchant_context.clone(),
profile.clone(),
payments::operations::PaymentGetListAttempts,
api_payments::PaymentAttemptListRequest {
payment_intent_id: payment_intent.payment_id.clone(),
},
payment_intent.payment_id.clone(),
hyperswitch_domain_models::payments::HeaderPayload::default(),
))
.await;
let response = match attempt_response {
Ok(services::ApplicationResponse::JsonWithHeaders((payments_response, _))) => {
let final_attempt = self
.0
.charge_id
.as_ref()
.map(|charge_id| {
payments_response
.find_attempt_in_attempts_list_using_charge_id(charge_id.clone())
})
.unwrap_or_else(|| {
self.0
.connector_transaction_id
.as_ref()
.and_then(|transaction_id| {
payments_response
.find_attempt_in_attempts_list_using_connector_transaction_id(
transaction_id,
)
})
});
let payment_attempt =
final_attempt.map(|res| revenue_recovery::RecoveryPaymentAttempt {
attempt_id: res.id.to_owned(),
attempt_status: res.status.to_owned(),
feature_metadata: res.feature_metadata.to_owned(),
amount: res.amount.net_amount,
network_advice_code: res.error.clone().and_then(|e| e.network_advice_code), // Placeholder, to be populated if available
network_decline_code: res
.error
.clone()
.and_then(|e| e.network_decline_code), // Placeholder, to be populated if available
error_code: res.error.clone().map(|error| error.code),
created_at: res.created_at,
});
// If we have an attempt, combine it with payment_intent in a tuple.
let res_with_payment_intent_and_attempt =
payment_attempt.map(|attempt| (attempt, (*payment_intent).clone()));
Ok(res_with_payment_intent_and_attempt)
}
Ok(_) => Err(errors::RevenueRecoveryError::PaymentAttemptFetchFailed)
.attach_printable("Unexpected response from payment intent core"),
error @ Err(_) => {
logger::error!(?error);
Err(errors::RevenueRecoveryError::PaymentAttemptFetchFailed)
.attach_printable("failed to fetch payment attempt in recovery webhook flow")
}
}?;
Ok(response)
}
#[allow(clippy::too_many_arguments)]
async fn record_payment_attempt(
&self,
state: &SessionState,
req_state: &ReqState,
merchant_context: &domain::MerchantContext,
profile: &domain::Profile,
payment_intent: &revenue_recovery::RecoveryPaymentIntent,
billing_connector_account_id: &id_type::MerchantConnectorAccountId,
payment_connector_account: Option<domain::MerchantConnectorAccount>,
) -> CustomResult<
(
revenue_recovery::RecoveryPaymentAttempt,
revenue_recovery::RecoveryPaymentIntent,
),
errors::RevenueRecoveryError,
> {
let payment_connector_id = payment_connector_account.as_ref().map(|account: &hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount| account.id.clone());
let payment_connector_name = payment_connector_account
.as_ref()
.map(|account| account.connector_name);
let request_payload: api_payments::PaymentsAttemptRecordRequest = self
.create_payment_record_request(
state,
billing_connector_account_id,
payment_connector_id,
payment_connector_name,
common_enums::TriggeredBy::External,
)
.await?;
let attempt_response = Box::pin(payments::record_attempt_core(
state.clone(),
req_state.clone(),
merchant_context.clone(),
profile.clone(),
request_payload,
payment_intent.payment_id.clone(),
hyperswitch_domain_models::payments::HeaderPayload::default(),
))
.await;
let (recovery_attempt, updated_recovery_intent) = match attempt_response {
Ok(services::ApplicationResponse::JsonWithHeaders((attempt_response, _))) => {
Ok((
revenue_recovery::RecoveryPaymentAttempt {
attempt_id: attempt_response.id.clone(),
attempt_status: attempt_response.status,
feature_metadata: attempt_response.payment_attempt_feature_metadata,
amount: attempt_response.amount,
network_advice_code: attempt_response
.error_details
.clone()
.and_then(|error| error.network_decline_code), // Placeholder, to be populated if available
network_decline_code: attempt_response
.error_details
.clone()
.and_then(|error| error.network_decline_code), // Placeholder, to be populated if available
error_code: attempt_response
.error_details
.clone()
.map(|error| error.code),
created_at: attempt_response.created_at,
},
revenue_recovery::RecoveryPaymentIntent {
payment_id: payment_intent.payment_id.clone(),
status: attempt_response.status.into(), // Using status from attempt_response
feature_metadata: attempt_response.payment_intent_feature_metadata, // Using feature_metadata from attempt_response
merchant_id: payment_intent.merchant_id.clone(),
merchant_reference_id: payment_intent.merchant_reference_id.clone(),
invoice_amount: payment_intent.invoice_amount,
invoice_currency: payment_intent.invoice_currency,
created_at: payment_intent.created_at,
billing_address: payment_intent.billing_address.clone(),
},
))
}
Ok(_) => Err(errors::RevenueRecoveryError::PaymentAttemptFetchFailed)
.attach_printable("Unexpected response from record attempt core"),
error @ Err(_) => {
logger::error!(?error);
Err(errors::RevenueRecoveryError::PaymentAttemptFetchFailed)
.attach_printable("failed to record attempt in recovery webhook flow")
}
}?;
let response = (recovery_attempt, updated_recovery_intent);
self.store_payment_processor_tokens_in_redis(state, &response.0, payment_connector_name)
.await
.map_err(|e| {
router_env::logger::error!(
"Failed to store payment processor tokens in Redis: {:?}",
e
);
errors::RevenueRecoveryError::RevenueRecoveryRedisInsertFailed
})?;
Ok(response)
}
pub async fn create_payment_record_request(
&self,
state: &SessionState,
billing_merchant_connector_account_id: &id_type::MerchantConnectorAccountId,
payment_merchant_connector_account_id: Option<id_type::MerchantConnectorAccountId>,
payment_connector: Option<common_enums::connector_enums::Connector>,
triggered_by: common_enums::TriggeredBy,
) -> CustomResult<api_payments::PaymentsAttemptRecordRequest, errors::RevenueRecoveryError>
{
let revenue_recovery_attempt_data = &self.0;
let amount_details =
api_payments::PaymentAttemptAmountDetails::from(revenue_recovery_attempt_data);
let feature_metadata = api_payments::PaymentAttemptFeatureMetadata {
revenue_recovery: Some(api_payments::PaymentAttemptRevenueRecoveryData {
// Since we are recording the external paymenmt attempt, this is hardcoded to External
attempt_triggered_by: triggered_by,
charge_id: self.0.charge_id.clone(),
}),
};
let card_info = revenue_recovery_attempt_data
.card_info
.card_isin
.clone()
.async_and_then(|isin| async move {
let issuer_identifier_number = isin.clone();
state
.store
.get_card_info(issuer_identifier_number.as_str())
.await
.map_err(|error| services::logger::warn!(card_info_error=?error))
.ok()
})
.await
.flatten();
let payment_method_data = api_models::payments::RecordAttemptPaymentMethodDataRequest {
payment_method_data: api_models::payments::AdditionalPaymentData::Card(Box::new(
revenue_recovery_attempt_data.card_info.clone(),
)),
billing: None,
};
let card_issuer = revenue_recovery_attempt_data.card_info.card_issuer.clone();
let error =
Option::<api_payments::RecordAttemptErrorDetails>::from(revenue_recovery_attempt_data);
Ok(api_payments::PaymentsAttemptRecordRequest {
amount_details,
status: revenue_recovery_attempt_data.status,
billing: None,
shipping: None,
connector: payment_connector,
payment_merchant_connector_id: payment_merchant_connector_account_id,
error,
description: None,
connector_transaction_id: revenue_recovery_attempt_data
.connector_transaction_id
.clone(),
payment_method_type: revenue_recovery_attempt_data.payment_method_type,
billing_connector_id: billing_merchant_connector_account_id.clone(),
payment_method_subtype: revenue_recovery_attempt_data.payment_method_sub_type,
payment_method_data: Some(payment_method_data),
metadata: None,
feature_metadata: Some(feature_metadata),
transaction_created_at: revenue_recovery_attempt_data.transaction_created_at,
processor_payment_method_token: revenue_recovery_attempt_data
.processor_payment_method_token
.clone(),
connector_customer_id: revenue_recovery_attempt_data.connector_customer_id.clone(),
retry_count: revenue_recovery_attempt_data.retry_count,
invoice_next_billing_time: revenue_recovery_attempt_data.invoice_next_billing_time,
invoice_billing_started_at_time: revenue_recovery_attempt_data
.invoice_billing_started_at_time,
triggered_by,
card_network: revenue_recovery_attempt_data.card_info.card_network.clone(),
card_issuer,
})
}
pub async fn find_payment_merchant_connector_account(
&self,
state: &SessionState,
key_store: &domain::MerchantKeyStore,
billing_connector_account: &domain::MerchantConnectorAccount,
) -> CustomResult<Option<domain::MerchantConnectorAccount>, errors::RevenueRecoveryError> {
let payment_merchant_connector_account_id = billing_connector_account
.get_payment_merchant_connector_account_id_using_account_reference_id(
self.0.connector_account_reference_id.clone(),
);
let db = &*state.store;
let key_manager_state = &(state).into();
let payment_merchant_connector_account = payment_merchant_connector_account_id
.as_ref()
.async_map(|mca_id| async move {
db.find_merchant_connector_account_by_id(key_manager_state, mca_id, key_store)
.await
})
.await
.transpose()
.change_context(errors::RevenueRecoveryError::PaymentMerchantConnectorAccountNotFound)
.attach_printable(
"failed to fetch payment merchant connector id using account reference id",
)?;
Ok(payment_merchant_connector_account)
}
#[allow(clippy::too_many_arguments)]
async fn get_recovery_payment_attempt(
is_recovery_transaction_event: bool,
billing_connector_account: &domain::MerchantConnectorAccount,
state: &SessionState,
connector_enum: &connector_integration_interface::ConnectorEnum,
req_state: &ReqState,
billing_connector_payment_details: Option<
&revenue_recovery_response::BillingConnectorPaymentsSyncResponse,
>,
request_details: &hyperswitch_interfaces::webhooks::IncomingWebhookRequestDetails<'_>,
merchant_context: &domain::MerchantContext,
business_profile: &domain::Profile,
payment_intent: &revenue_recovery::RecoveryPaymentIntent,
invoice_details: &revenue_recovery::RevenueRecoveryInvoiceData,
) -> CustomResult<
(
Option<revenue_recovery::RecoveryPaymentAttempt>,
revenue_recovery::RecoveryPaymentIntent,
),
errors::RevenueRecoveryError,
> {
let payment_attempt_with_recovery_intent = match is_recovery_transaction_event {
true => {
let invoice_transaction_details = Self::get_recovery_invoice_transaction_details(
connector_enum,
request_details,
billing_connector_payment_details,
invoice_details,
)?;
// Find the payment merchant connector ID at the top level to avoid multiple DB calls.
let payment_merchant_connector_account = invoice_transaction_details
.find_payment_merchant_connector_account(
state,
merchant_context.get_merchant_key_store(),
billing_connector_account,
)
.await?;
let (payment_attempt, updated_payment_intent) = invoice_transaction_details
.get_payment_attempt(
state,
req_state,
merchant_context,
business_profile,
payment_intent,
)
.await
.transpose()
.async_unwrap_or_else(|| async {
invoice_transaction_details
.record_payment_attempt(
state,
req_state,
merchant_context,
business_profile,
payment_intent,
&billing_connector_account.get_id(),
payment_merchant_connector_account,
)
.await
})
.await?;
(Some(payment_attempt), updated_payment_intent)
}
false => (None, payment_intent.clone()),
};
Ok(payment_attempt_with_recovery_intent)
}
/// Store payment processor tokens in Redis for retry management
async fn store_payment_processor_tokens_in_redis(
&self,
state: &SessionState,
recovery_attempt: &revenue_recovery::RecoveryPaymentAttempt,
payment_connector_name: Option<common_enums::connector_enums::Connector>,
) -> CustomResult<(), errors::RevenueRecoveryError> {
let revenue_recovery_attempt_data = &self.0;
let error_code = revenue_recovery_attempt_data.error_code.clone();
let error_message = revenue_recovery_attempt_data.error_message.clone();
let connector_name = payment_connector_name
.ok_or(errors::RevenueRecoveryError::TransactionWebhookProcessingFailed)
.attach_printable("unable to derive payment connector")?
.to_string();
let gsm_record = helpers::get_gsm_record(
state,
error_code.clone(),
error_message,
connector_name,
REVENUE_RECOVERY.to_string(),
)
.await;
let is_hard_decline = gsm_record
.and_then(|record| record.error_category)
.map(|category| category == common_enums::ErrorCategory::HardDecline)
.unwrap_or(false);
// Extract required fields from the revenue recovery attempt data
let connector_customer_id = revenue_recovery_attempt_data.connector_customer_id.clone();
let attempt_id = recovery_attempt.attempt_id.clone();
let token_unit = PaymentProcessorTokenStatus {
error_code,
inserted_by_attempt_id: attempt_id.clone(),
daily_retry_history: HashMap::from([(recovery_attempt.created_at.date(), 1)]),
scheduled_at: None,
is_hard_decline: Some(is_hard_decline),
payment_processor_token_details: PaymentProcessorTokenDetails {
payment_processor_token: revenue_recovery_attempt_data
.processor_payment_method_token
.clone(),
expiry_month: revenue_recovery_attempt_data
.card_info
.card_exp_month
.clone(),
expiry_year: revenue_recovery_attempt_data
.card_info
.card_exp_year
.clone(),
card_issuer: revenue_recovery_attempt_data.card_info.card_issuer.clone(),
last_four_digits: revenue_recovery_attempt_data.card_info.last4.clone(),
card_network: revenue_recovery_attempt_data.card_info.card_network.clone(),
card_type: revenue_recovery_attempt_data.card_info.card_type.clone(),
},
};
// Make the Redis call to store tokens
RedisTokenManager::upsert_payment_processor_token(
state,
&connector_customer_id,
token_unit,
)
.await
.change_context(errors::RevenueRecoveryError::RevenueRecoveryRedisInsertFailed)
.attach_printable("Failed to store payment processor tokens in Redis")?;
Ok(())
}
}
pub struct BillingConnectorPaymentsSyncResponseData(
revenue_recovery_response::BillingConnectorPaymentsSyncResponse,
);
pub struct BillingConnectorPaymentsSyncFlowRouterData(
router_types::BillingConnectorPaymentsSyncRouterData,
);
impl BillingConnectorPaymentsSyncResponseData {
async fn handle_billing_connector_payment_sync_call(
state: &SessionState,
merchant_context: &domain::MerchantContext,
merchant_connector_account: &hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount,
connector_name: &str,
id: &str,
) -> CustomResult<Self, errors::RevenueRecoveryError> {
let connector_data = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
connector_name,
api::GetToken::Connector,
None,
)
.change_context(errors::RevenueRecoveryError::BillingConnectorPaymentsSyncFailed)
.attach_printable("invalid connector name received in payment attempt")?;
let connector_integration: services::BoxedBillingConnectorPaymentsSyncIntegrationInterface<
router_flow_types::BillingConnectorPaymentsSync,
revenue_recovery_request::BillingConnectorPaymentsSyncRequest,
revenue_recovery_response::BillingConnectorPaymentsSyncResponse,
> = connector_data.connector.get_connector_integration();
let router_data =
BillingConnectorPaymentsSyncFlowRouterData::construct_router_data_for_billing_connector_payment_sync_call(
state,
connector_name,
merchant_connector_account,
merchant_context,
id,
)
.await
.change_context(errors::RevenueRecoveryError::BillingConnectorPaymentsSyncFailed)
.attach_printable(
"Failed while constructing router data for billing connector psync call",
)?
.inner();
let response = services::execute_connector_processing_step(
state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.change_context(errors::RevenueRecoveryError::BillingConnectorPaymentsSyncFailed)
.attach_printable("Failed while fetching billing connector payment details")?;
let additional_recovery_details = match response.response {
Ok(response) => Ok(response),
error @ Err(_) => {
logger::error!(?error);
Err(errors::RevenueRecoveryError::BillingConnectorPaymentsSyncFailed)
.attach_printable("Failed while fetching billing connector payment details")
}
}?;
Ok(Self(additional_recovery_details))
}
async fn get_billing_connector_payment_details(
should_billing_connector_payment_api_called: bool,
state: &SessionState,
merchant_context: &domain::MerchantContext,
billing_connector_account: &hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount,
connector_name: &str,
object_ref_id: &webhooks::ObjectReferenceId,
) -> CustomResult<
Option<revenue_recovery_response::BillingConnectorPaymentsSyncResponse>,
errors::RevenueRecoveryError,
> {
let response_data = match should_billing_connector_payment_api_called {
true => {
let billing_connector_transaction_id = object_ref_id
.clone()
.get_connector_transaction_id_as_string()
.change_context(
errors::RevenueRecoveryError::BillingConnectorPaymentsSyncFailed,
)
.attach_printable("Billing connector Payments api call failed")?;
let billing_connector_payment_details =
Self::handle_billing_connector_payment_sync_call(
state,
merchant_context,
billing_connector_account,
connector_name,
&billing_connector_transaction_id,
)
.await?;
Some(billing_connector_payment_details.inner())
}
false => None,
};
Ok(response_data)
}
fn inner(self) -> revenue_recovery_response::BillingConnectorPaymentsSyncResponse {
self.0
}
}
impl BillingConnectorPaymentsSyncFlowRouterData {
async fn construct_router_data_for_billing_connector_payment_sync_call(
state: &SessionState,
connector_name: &str,
merchant_connector_account: &hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount,
merchant_context: &domain::MerchantContext,
billing_connector_psync_id: &str,
) -> CustomResult<Self, errors::RevenueRecoveryError> {
let auth_type: types::ConnectorAuthType = helpers::MerchantConnectorAccountType::DbVal(
Box::new(merchant_connector_account.clone()),
)
.get_connector_account_details()
.parse_value("ConnectorAuthType")
.change_context(errors::RevenueRecoveryError::BillingConnectorPaymentsSyncFailed)?;
let connector = common_enums::connector_enums::Connector::from_str(connector_name)
.change_context(errors::RevenueRecoveryError::BillingConnectorInvoiceSyncFailed)
.attach_printable("Cannot find connector from the connector_name")?;
let connector_params =
hyperswitch_domain_models::connector_endpoints::Connectors::get_connector_params(
&state.conf.connectors,
connector,
)
.change_context(errors::RevenueRecoveryError::BillingConnectorPaymentsSyncFailed)
.attach_printable(format!(
"cannot find connector params for this connector {connector} in this flow",
))?;
let router_data = types::RouterDataV2 {
flow: PhantomData::<router_flow_types::BillingConnectorPaymentsSync>,
tenant_id: state.tenant.tenant_id.clone(),
resource_common_data: flow_common_types::BillingConnectorPaymentsSyncFlowData,
connector_auth_type: auth_type,
request: revenue_recovery_request::BillingConnectorPaymentsSyncRequest {
connector_params,
billing_connector_psync_id: billing_connector_psync_id.to_string(),
},
response: Err(types::ErrorResponse::default()),
};
let old_router_data =
flow_common_types::BillingConnectorPaymentsSyncFlowData::to_old_router_data(
router_data,
)
.change_context(errors::RevenueRecoveryError::BillingConnectorPaymentsSyncFailed)
.attach_printable(
"Cannot construct router data for making the billing connector payments api call",
)?;
Ok(Self(old_router_data))
}
fn inner(self) -> router_types::BillingConnectorPaymentsSyncRouterData {
self.0
}
}
pub struct BillingConnectorInvoiceSyncResponseData(
revenue_recovery_response::BillingConnectorInvoiceSyncResponse,
);
pub struct BillingConnectorInvoiceSyncFlowRouterData(
router_types::BillingConnectorInvoiceSyncRouterData,
);
impl BillingConnectorInvoiceSyncResponseData {
async fn handle_billing_connector_invoice_sync_call(
state: &SessionState,
merchant_context: &domain::MerchantContext,
merchant_connector_account: &hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount,
connector_name: &str,
id: &str,
) -> CustomResult<Self, errors::RevenueRecoveryError> {
let connector_data = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
connector_name,
api::GetToken::Connector,
None,
)
.change_context(errors::RevenueRecoveryError::BillingConnectorInvoiceSyncFailed)
.attach_printable("invalid connector name received in payment attempt")?;
let connector_integration: services::BoxedBillingConnectorInvoiceSyncIntegrationInterface<
router_flow_types::BillingConnectorInvoiceSync,
revenue_recovery_request::BillingConnectorInvoiceSyncRequest,
revenue_recovery_response::BillingConnectorInvoiceSyncResponse,
> = connector_data.connector.get_connector_integration();
let router_data =
BillingConnectorInvoiceSyncFlowRouterData::construct_router_data_for_billing_connector_invoice_sync_call(
state,
connector_name,
merchant_connector_account,
merchant_context,
id,
)
.await
.change_context(errors::RevenueRecoveryError::BillingConnectorInvoiceSyncFailed)
.attach_printable(
"Failed while constructing router data for billing connector psync call",
)?
.inner();
let response = services::execute_connector_processing_step(
state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.change_context(errors::RevenueRecoveryError::BillingConnectorInvoiceSyncFailed)
.attach_printable("Failed while fetching billing connector Invoice details")?;
let additional_recovery_details = match response.response {
Ok(response) => Ok(response),
error @ Err(_) => {
logger::error!(?error);
Err(errors::RevenueRecoveryError::BillingConnectorPaymentsSyncFailed)
.attach_printable("Failed while fetching billing connector Invoice details")
}
}?;
Ok(Self(additional_recovery_details))
}
async fn get_billing_connector_invoice_details(
should_billing_connector_invoice_api_called: bool,
state: &SessionState,
merchant_context: &domain::MerchantContext,
billing_connector_account: &hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount,
connector_name: &str,
merchant_reference_id: Option<id_type::PaymentReferenceId>,
) -> CustomResult<
Option<revenue_recovery_response::BillingConnectorInvoiceSyncResponse>,
errors::RevenueRecoveryError,
> {
let response_data = match should_billing_connector_invoice_api_called {
true => {
let billing_connector_invoice_id = merchant_reference_id
.as_ref()
.map(|id| id.get_string_repr())
.ok_or(errors::RevenueRecoveryError::BillingConnectorInvoiceSyncFailed)?;
let billing_connector_invoice_details =
Self::handle_billing_connector_invoice_sync_call(
state,
merchant_context,
billing_connector_account,
connector_name,
billing_connector_invoice_id,
)
.await?;
Some(billing_connector_invoice_details.inner())
}
false => None,
};
Ok(response_data)
}
fn inner(self) -> revenue_recovery_response::BillingConnectorInvoiceSyncResponse {
self.0
}
}
impl BillingConnectorInvoiceSyncFlowRouterData {
async fn construct_router_data_for_billing_connector_invoice_sync_call(
state: &SessionState,
connector_name: &str,
merchant_connector_account: &hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount,
merchant_context: &domain::MerchantContext,
billing_connector_invoice_id: &str,
) -> CustomResult<Self, errors::RevenueRecoveryError> {
let auth_type: types::ConnectorAuthType = helpers::MerchantConnectorAccountType::DbVal(
Box::new(merchant_connector_account.clone()),
)
.get_connector_account_details()
.parse_value("ConnectorAuthType")
.change_context(errors::RevenueRecoveryError::BillingConnectorInvoiceSyncFailed)?;
let connector = common_enums::connector_enums::Connector::from_str(connector_name)
.change_context(errors::RevenueRecoveryError::BillingConnectorInvoiceSyncFailed)
.attach_printable("Cannot find connector from the connector_name")?;
let connector_params =
hyperswitch_domain_models::connector_endpoints::Connectors::get_connector_params(
&state.conf.connectors,
connector,
)
.change_context(errors::RevenueRecoveryError::BillingConnectorPaymentsSyncFailed)
.attach_printable(format!(
"cannot find connector params for this connector {connector} in this flow",
))?;
let router_data = types::RouterDataV2 {
flow: PhantomData::<router_flow_types::BillingConnectorInvoiceSync>,
tenant_id: state.tenant.tenant_id.clone(),
resource_common_data: flow_common_types::BillingConnectorInvoiceSyncFlowData,
connector_auth_type: auth_type,
request: revenue_recovery_request::BillingConnectorInvoiceSyncRequest {
billing_connector_invoice_id: billing_connector_invoice_id.to_string(),
connector_params,
},
response: Err(types::ErrorResponse::default()),
};
let old_router_data =
flow_common_types::BillingConnectorInvoiceSyncFlowData::to_old_router_data(
router_data,
)
.change_context(errors::RevenueRecoveryError::BillingConnectorInvoiceSyncFailed)
.attach_printable(
"Cannot construct router data for making the billing connector invoice api call",
)?;
Ok(Self(old_router_data))
}
fn inner(self) -> router_types::BillingConnectorInvoiceSyncRouterData {
self.0
}
}
#[derive(Clone, Debug)]
pub struct RecoveryPaymentTuple(
revenue_recovery::RecoveryPaymentIntent,
revenue_recovery::RecoveryPaymentAttempt,
);
impl RecoveryPaymentTuple {
pub fn new(
payment_intent: &revenue_recovery::RecoveryPaymentIntent,
payment_attempt: &revenue_recovery::RecoveryPaymentAttempt,
) -> Self {
Self(payment_intent.clone(), payment_attempt.clone())
}
pub async fn publish_revenue_recovery_event_to_kafka(
state: &SessionState,
recovery_payment_tuple: &Self,
retry_count: Option<i32>,
) -> CustomResult<(), errors::RevenueRecoveryError> {
let recovery_payment_intent = &recovery_payment_tuple.0;
let recovery_payment_attempt = &recovery_payment_tuple.1;
let revenue_recovery_feature_metadata = recovery_payment_intent
.feature_metadata
.as_ref()
.and_then(|metadata| metadata.revenue_recovery.as_ref());
let billing_city = recovery_payment_intent
.billing_address
.as_ref()
.and_then(|billing_address| billing_address.address.as_ref())
.and_then(|address| address.city.clone())
.map(Secret::new);
let billing_state = recovery_payment_intent
.billing_address
.as_ref()
.and_then(|billing_address| billing_address.address.as_ref())
.and_then(|address| address.state.clone());
let billing_country = recovery_payment_intent
.billing_address
.as_ref()
.and_then(|billing_address| billing_address.address.as_ref())
.and_then(|address| address.country);
let card_info = revenue_recovery_feature_metadata.and_then(|metadata| {
metadata
.billing_connector_payment_method_details
.as_ref()
.and_then(|details| details.get_billing_connector_card_info())
});
#[allow(clippy::as_conversions)]
let retry_count = Some(retry_count.unwrap_or_else(|| {
revenue_recovery_feature_metadata
.map(|data| data.total_retry_count as i32)
.unwrap_or(0)
}));
let event = kafka::revenue_recovery::RevenueRecovery {
merchant_id: &recovery_payment_intent.merchant_id,
invoice_amount: recovery_payment_intent.invoice_amount,
invoice_currency: &recovery_payment_intent.invoice_currency,
invoice_date: revenue_recovery_feature_metadata.and_then(|data| {
data.invoice_billing_started_at_time
.map(|time| time.assume_utc())
}),
invoice_due_date: revenue_recovery_feature_metadata
.and_then(|data| data.invoice_next_billing_time.map(|time| time.assume_utc())),
billing_city,
billing_country: billing_country.as_ref(),
billing_state,
attempt_amount: recovery_payment_attempt.amount,
attempt_currency: &recovery_payment_intent.invoice_currency.clone(),
attempt_status: &recovery_payment_attempt.attempt_status.clone(),
pg_error_code: recovery_payment_attempt.error_code.clone(),
network_advice_code: recovery_payment_attempt.network_advice_code.clone(),
network_error_code: recovery_payment_attempt.network_decline_code.clone(),
first_pg_error_code: revenue_recovery_feature_metadata
.and_then(|data| data.first_payment_attempt_pg_error_code.clone()),
first_network_advice_code: revenue_recovery_feature_metadata
.and_then(|data| data.first_payment_attempt_network_advice_code.clone()),
first_network_error_code: revenue_recovery_feature_metadata
.and_then(|data| data.first_payment_attempt_network_decline_code.clone()),
attempt_created_at: recovery_payment_attempt.created_at.assume_utc(),
payment_method_type: revenue_recovery_feature_metadata
.map(|data| &data.payment_method_type),
payment_method_subtype: revenue_recovery_feature_metadata
.map(|data| &data.payment_method_subtype),
card_network: card_info
.as_ref()
.and_then(|info| info.card_network.as_ref()),
card_issuer: card_info.and_then(|data| data.card_issuer.clone()),
retry_count,
payment_gateway: revenue_recovery_feature_metadata.map(|data| data.connector),
};
state.event_handler.log_event(&event);
Ok(())
}
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug)]
pub struct RecoveryAction {
pub action: common_types::payments::RecoveryAction,
}
impl RecoveryAction {
pub fn get_action(
event_type: webhooks::IncomingWebhookEvent,
attempt_triggered_by: Option<common_enums::TriggeredBy>,
) -> common_types::payments::RecoveryAction {
match event_type {
webhooks::IncomingWebhookEvent::PaymentIntentFailure
| webhooks::IncomingWebhookEvent::PaymentIntentSuccess
| webhooks::IncomingWebhookEvent::PaymentIntentProcessing
| webhooks::IncomingWebhookEvent::PaymentIntentPartiallyFunded
| webhooks::IncomingWebhookEvent::PaymentIntentCancelled
| webhooks::IncomingWebhookEvent::PaymentIntentCancelFailure
| webhooks::IncomingWebhookEvent::PaymentIntentAuthorizationSuccess
| webhooks::IncomingWebhookEvent::PaymentIntentAuthorizationFailure
| webhooks::IncomingWebhookEvent::PaymentIntentCaptureSuccess
| webhooks::IncomingWebhookEvent::PaymentIntentCaptureFailure
| webhooks::IncomingWebhookEvent::PaymentIntentExpired
| webhooks::IncomingWebhookEvent::PaymentActionRequired
| webhooks::IncomingWebhookEvent::EventNotSupported
| webhooks::IncomingWebhookEvent::SourceChargeable
| webhooks::IncomingWebhookEvent::SourceTransactionCreated
| webhooks::IncomingWebhookEvent::RefundFailure
| webhooks::IncomingWebhookEvent::RefundSuccess
| webhooks::IncomingWebhookEvent::DisputeOpened
| webhooks::IncomingWebhookEvent::DisputeExpired
| webhooks::IncomingWebhookEvent::DisputeAccepted
| webhooks::IncomingWebhookEvent::DisputeCancelled
| webhooks::IncomingWebhookEvent::DisputeChallenged
| webhooks::IncomingWebhookEvent::DisputeWon
| webhooks::IncomingWebhookEvent::DisputeLost
| webhooks::IncomingWebhookEvent::MandateActive
| webhooks::IncomingWebhookEvent::MandateRevoked
| webhooks::IncomingWebhookEvent::EndpointVerification
| webhooks::IncomingWebhookEvent::PaymentIntentExtendAuthorizationSuccess
| webhooks::IncomingWebhookEvent::PaymentIntentExtendAuthorizationFailure
| webhooks::IncomingWebhookEvent::ExternalAuthenticationARes
| webhooks::IncomingWebhookEvent::FrmApproved
| webhooks::IncomingWebhookEvent::FrmRejected
| webhooks::IncomingWebhookEvent::PayoutSuccess
| webhooks::IncomingWebhookEvent::PayoutFailure
| webhooks::IncomingWebhookEvent::PayoutProcessing
| webhooks::IncomingWebhookEvent::PayoutCancelled
| webhooks::IncomingWebhookEvent::PayoutCreated
| webhooks::IncomingWebhookEvent::PayoutExpired
| webhooks::IncomingWebhookEvent::PayoutReversed
| webhooks::IncomingWebhookEvent::InvoiceGenerated
| webhooks::IncomingWebhookEvent::SetupWebhook => {
common_types::payments::RecoveryAction::InvalidAction
}
webhooks::IncomingWebhookEvent::RecoveryPaymentFailure => match attempt_triggered_by {
Some(common_enums::TriggeredBy::Internal) => {
common_types::payments::RecoveryAction::NoAction
}
Some(common_enums::TriggeredBy::External) | None => {
common_types::payments::RecoveryAction::ScheduleFailedPayment
}
},
webhooks::IncomingWebhookEvent::RecoveryPaymentSuccess => match attempt_triggered_by {
Some(common_enums::TriggeredBy::Internal) => {
common_types::payments::RecoveryAction::NoAction
}
Some(common_enums::TriggeredBy::External) | None => {
common_types::payments::RecoveryAction::SuccessPaymentExternal
}
},
webhooks::IncomingWebhookEvent::RecoveryPaymentPending => {
common_types::payments::RecoveryAction::PendingPayment
}
webhooks::IncomingWebhookEvent::RecoveryInvoiceCancel => {
common_types::payments::RecoveryAction::CancelInvoice
}
}
}
#[allow(clippy::too_many_arguments)]
pub async fn handle_action(
&self,
state: &SessionState,
business_profile: &domain::Profile,
merchant_context: &domain::MerchantContext,
billing_connector_account: &hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount,
mca_retry_threshold: u16,
intent_retry_count: u16,
recovery_tuple: &(
Option<revenue_recovery::RecoveryPaymentAttempt>,
revenue_recovery::RecoveryPaymentIntent,
),
) -> CustomResult<webhooks::WebhookResponseTracker, errors::RevenueRecoveryError> {
match self.action {
common_types::payments::RecoveryAction::CancelInvoice => todo!(),
common_types::payments::RecoveryAction::ScheduleFailedPayment => {
let recovery_algorithm_type = business_profile
.revenue_recovery_retry_algorithm_type
.ok_or(report!(
errors::RevenueRecoveryError::RetryAlgorithmTypeNotFound
))?;
match recovery_algorithm_type {
api_enums::RevenueRecoveryAlgorithmType::Monitoring => {
handle_monitoring_threshold(
state,
business_profile,
merchant_context.get_merchant_key_store(),
)
.await
}
revenue_recovery_retry_type => {
handle_schedule_failed_payment(
billing_connector_account,
intent_retry_count,
mca_retry_threshold,
state,
merchant_context,
recovery_tuple,
business_profile,
revenue_recovery_retry_type,
)
.await
}
}
}
common_types::payments::RecoveryAction::SuccessPaymentExternal => {
logger::info!("Payment has been succeeded via external system");
Ok(webhooks::WebhookResponseTracker::NoEffect)
}
common_types::payments::RecoveryAction::PendingPayment => {
logger::info!(
"Pending transactions are not consumed by the revenue recovery webhooks"
);
Ok(webhooks::WebhookResponseTracker::NoEffect)
}
common_types::payments::RecoveryAction::NoAction => {
logger::info!(
"No Recovery action is taken place for recovery event and attempt triggered_by"
);
Ok(webhooks::WebhookResponseTracker::NoEffect)
}
common_types::payments::RecoveryAction::InvalidAction => {
logger::error!("Invalid Revenue recovery action state has been received");
Ok(webhooks::WebhookResponseTracker::NoEffect)
}
}
}
}
|
crates/router/src/core/webhooks/recovery_incoming.rs
|
router::src::core::webhooks::recovery_incoming
| 12,367
| true
|
// File: crates/router/src/core/webhooks/incoming_v2.rs
// Module: router::src::core::webhooks::incoming_v2
use std::{marker::PhantomData, str::FromStr, time::Instant};
use actix_web::FromRequest;
use api_models::webhooks::{self, WebhookResponseTracker};
use common_utils::{
errors::ReportSwitchExt, events::ApiEventsType, types::keymanager::KeyManagerState,
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payments::{HeaderPayload, PaymentStatusData},
router_request_types::VerifyWebhookSourceRequestData,
router_response_types::{VerifyWebhookSourceResponseData, VerifyWebhookStatus},
};
use hyperswitch_interfaces::webhooks::IncomingWebhookRequestDetails;
use router_env::{instrument, tracing, tracing_actix_web::RequestId};
use super::{types, utils, MERCHANT_ID};
#[cfg(feature = "revenue_recovery")]
use crate::core::webhooks::recovery_incoming;
use crate::{
core::{
api_locking,
errors::{self, ConnectorErrorExt, CustomResult, RouterResponse, StorageErrorExt},
metrics,
payments::{
self,
transformers::{GenerateResponse, ToResponse},
},
webhooks::{
create_event_and_trigger_outgoing_webhook, utils::construct_webhook_router_data,
},
},
db::StorageInterface,
events::api_logs::ApiEvent,
logger,
routes::{
app::{ReqState, SessionStateInfo},
lock_utils, SessionState,
},
services::{
self, authentication as auth, connector_integration_interface::ConnectorEnum,
ConnectorValidation,
},
types::{
api::{self, ConnectorData, GetToken, IncomingWebhook},
domain,
storage::enums,
transformers::ForeignInto,
},
};
#[allow(clippy::too_many_arguments)]
pub async fn incoming_webhooks_wrapper<W: types::OutgoingWebhookType>(
flow: &impl router_env::types::FlowMetric,
state: SessionState,
req_state: ReqState,
req: &actix_web::HttpRequest,
merchant_context: domain::MerchantContext,
profile: domain::Profile,
connector_id: &common_utils::id_type::MerchantConnectorAccountId,
body: actix_web::web::Bytes,
is_relay_webhook: bool,
) -> RouterResponse<serde_json::Value> {
let start_instant = Instant::now();
let (application_response, webhooks_response_tracker, serialized_req) =
Box::pin(incoming_webhooks_core::<W>(
state.clone(),
req_state,
req,
merchant_context.clone(),
profile,
connector_id,
body.clone(),
is_relay_webhook,
))
.await?;
logger::info!(incoming_webhook_payload = ?serialized_req);
let request_duration = Instant::now()
.saturating_duration_since(start_instant)
.as_millis();
let request_id = RequestId::extract(req)
.await
.attach_printable("Unable to extract request id from request")
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let auth_type = auth::AuthenticationType::WebhookAuth {
merchant_id: merchant_context.get_merchant_account().get_id().clone(),
};
let status_code = 200;
let api_event = ApiEventsType::Webhooks {
connector: connector_id.clone(),
payment_id: webhooks_response_tracker.get_payment_id(),
};
let response_value = serde_json::to_value(&webhooks_response_tracker)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Could not convert webhook effect to string")?;
let infra = state.infra_components.clone();
let api_event = ApiEvent::new(
state.tenant.tenant_id.clone(),
Some(merchant_context.get_merchant_account().get_id().clone()),
flow,
&request_id,
request_duration,
status_code,
serialized_req,
Some(response_value),
None,
auth_type,
None,
api_event,
req,
req.method(),
infra,
);
state.event_handler().log_event(&api_event);
Ok(application_response)
}
#[instrument(skip_all)]
#[allow(clippy::too_many_arguments)]
async fn incoming_webhooks_core<W: types::OutgoingWebhookType>(
state: SessionState,
req_state: ReqState,
req: &actix_web::HttpRequest,
merchant_context: domain::MerchantContext,
profile: domain::Profile,
connector_id: &common_utils::id_type::MerchantConnectorAccountId,
body: actix_web::web::Bytes,
_is_relay_webhook: bool,
) -> errors::RouterResult<(
services::ApplicationResponse<serde_json::Value>,
WebhookResponseTracker,
serde_json::Value,
)> {
metrics::WEBHOOK_INCOMING_COUNT.add(
1,
router_env::metric_attributes!((
MERCHANT_ID,
merchant_context.get_merchant_account().get_id().clone()
)),
);
let mut request_details = IncomingWebhookRequestDetails {
method: req.method().clone(),
uri: req.uri().clone(),
headers: req.headers(),
query_params: req.query_string().to_string(),
body: &body,
};
// Fetch the merchant connector account to get the webhooks source secret
// `webhooks source secret` is a secret shared between the merchant and connector
// This is used for source verification and webhooks integrity
let (merchant_connector_account, connector, connector_name) = fetch_mca_and_connector(
&state,
connector_id,
merchant_context.get_merchant_key_store(),
)
.await?;
let decoded_body = connector
.decode_webhook_body(
&request_details,
merchant_context.get_merchant_account().get_id(),
merchant_connector_account.connector_webhook_details.clone(),
connector_name.as_str(),
)
.await
.switch()
.attach_printable("There was an error in incoming webhook body decoding")?;
request_details.body = &decoded_body;
let event_type = match connector
.get_webhook_event_type(&request_details)
.allow_webhook_event_type_not_found(
state
.clone()
.conf
.webhooks
.ignore_error
.event_type
.unwrap_or(true),
)
.switch()
.attach_printable("Could not find event type in incoming webhook body")?
{
Some(event_type) => event_type,
// Early return allows us to acknowledge the webhooks that we do not support
None => {
logger::error!(
webhook_payload =? request_details.body,
"Failed while identifying the event type",
);
metrics::WEBHOOK_EVENT_TYPE_IDENTIFICATION_FAILURE_COUNT.add(
1,
router_env::metric_attributes!(
(
MERCHANT_ID,
merchant_context.get_merchant_account().get_id().clone()
),
("connector", connector_name)
),
);
let response = connector
.get_webhook_api_response(&request_details, None)
.switch()
.attach_printable("Failed while early return in case of event type parsing")?;
return Ok((
response,
WebhookResponseTracker::NoEffect,
serde_json::Value::Null,
));
}
};
logger::info!(event_type=?event_type);
// if it is a setup webhook event, return ok status
if event_type == webhooks::IncomingWebhookEvent::SetupWebhook {
return Ok((
services::ApplicationResponse::StatusOk,
WebhookResponseTracker::NoEffect,
serde_json::Value::default(),
));
}
let is_webhook_event_supported = !matches!(
event_type,
webhooks::IncomingWebhookEvent::EventNotSupported
);
let is_webhook_event_enabled = !utils::is_webhook_event_disabled(
&*state.clone().store,
connector_name.as_str(),
merchant_context.get_merchant_account().get_id(),
&event_type,
)
.await;
//process webhook further only if webhook event is enabled and is not event_not_supported
let process_webhook_further = is_webhook_event_enabled && is_webhook_event_supported;
logger::info!(process_webhook=?process_webhook_further);
let flow_type: api::WebhookFlow = event_type.into();
let mut event_object: Box<dyn masking::ErasedMaskSerialize> = Box::new(serde_json::Value::Null);
let webhook_effect = if process_webhook_further
&& !matches!(flow_type, api::WebhookFlow::ReturnResponse)
{
let object_ref_id = connector
.get_webhook_object_reference_id(&request_details)
.switch()
.attach_printable("Could not find object reference id in incoming webhook body")?;
let connector_enum = api_models::enums::Connector::from_str(&connector_name)
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "connector",
})
.attach_printable_lazy(|| {
format!("unable to parse connector name {connector_name:?}")
})?;
let connectors_with_source_verification_call = &state.conf.webhook_source_verification_call;
let source_verified = if connectors_with_source_verification_call
.connectors_with_webhook_source_verification_call
.contains(&connector_enum)
{
verify_webhook_source_verification_call(
connector.clone(),
&state,
&merchant_context,
merchant_connector_account.clone(),
&connector_name,
&request_details,
)
.await
.or_else(|error| match error.current_context() {
errors::ConnectorError::WebhookSourceVerificationFailed => {
logger::error!(?error, "Source Verification Failed");
Ok(false)
}
_ => Err(error),
})
.switch()
.attach_printable("There was an issue in incoming webhook source verification")?
} else {
connector
.clone()
.verify_webhook_source(
&request_details,
merchant_context.get_merchant_account().get_id(),
merchant_connector_account.connector_webhook_details.clone(),
merchant_connector_account.connector_account_details.clone(),
connector_name.as_str(),
)
.await
.or_else(|error| match error.current_context() {
errors::ConnectorError::WebhookSourceVerificationFailed => {
logger::error!(?error, "Source Verification Failed");
Ok(false)
}
_ => Err(error),
})
.switch()
.attach_printable("There was an issue in incoming webhook source verification")?
};
logger::info!(source_verified=?source_verified);
if source_verified {
metrics::WEBHOOK_SOURCE_VERIFIED_COUNT.add(
1,
router_env::metric_attributes!((
MERCHANT_ID,
merchant_context.get_merchant_account().get_id().clone()
)),
);
}
// If source verification is mandatory and source is not verified, fail with webhook authentication error
// else continue the flow
match (
connector.is_webhook_source_verification_mandatory(),
source_verified,
) {
(true, false) => Err(errors::ApiErrorResponse::WebhookAuthenticationFailed)?,
_ => {
event_object = connector
.get_webhook_resource_object(&request_details)
.switch()
.attach_printable("Could not find resource object in incoming webhook body")?;
let webhook_details = api::IncomingWebhookDetails {
object_reference_id: object_ref_id.clone(),
resource_object: serde_json::to_vec(&event_object)
.change_context(errors::ParsingError::EncodeError("byte-vec"))
.attach_printable("Unable to convert webhook payload to a value")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"There was an issue when encoding the incoming webhook body to bytes",
)?,
};
match flow_type {
api::WebhookFlow::Payment => Box::pin(payments_incoming_webhook_flow(
state.clone(),
req_state,
merchant_context,
profile,
webhook_details,
source_verified,
))
.await
.attach_printable("Incoming webhook flow for payments failed")?,
api::WebhookFlow::Refund => todo!(),
api::WebhookFlow::Dispute => todo!(),
api::WebhookFlow::BankTransfer => todo!(),
api::WebhookFlow::ReturnResponse => WebhookResponseTracker::NoEffect,
api::WebhookFlow::Mandate => todo!(),
api::WebhookFlow::ExternalAuthentication => todo!(),
api::WebhookFlow::FraudCheck => todo!(),
api::WebhookFlow::Setup => WebhookResponseTracker::NoEffect,
#[cfg(feature = "payouts")]
api::WebhookFlow::Payout => todo!(),
api::WebhookFlow::Subscription => todo!(),
#[cfg(all(feature = "revenue_recovery", feature = "v2"))]
api::WebhookFlow::Recovery => {
Box::pin(recovery_incoming::recovery_incoming_webhook_flow(
state.clone(),
merchant_context,
profile,
source_verified,
&connector,
merchant_connector_account,
&connector_name,
&request_details,
event_type,
req_state,
&object_ref_id,
))
.await
.change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
.attach_printable("Failed to process recovery incoming webhook")?
}
}
}
}
} else {
metrics::WEBHOOK_INCOMING_FILTERED_COUNT.add(
1,
router_env::metric_attributes!((
MERCHANT_ID,
merchant_context.get_merchant_account().get_id().clone()
)),
);
WebhookResponseTracker::NoEffect
};
let response = connector
.get_webhook_api_response(&request_details, None)
.switch()
.attach_printable("Could not get incoming webhook api response from connector")?;
let serialized_request = event_object
.masked_serialize()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Could not convert webhook effect to string")?;
Ok((response, webhook_effect, serialized_request))
}
#[instrument(skip_all)]
async fn payments_incoming_webhook_flow(
state: SessionState,
req_state: ReqState,
merchant_context: domain::MerchantContext,
profile: domain::Profile,
webhook_details: api::IncomingWebhookDetails,
source_verified: bool,
) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> {
let consume_or_trigger_flow = if source_verified {
payments::CallConnectorAction::HandleResponse(webhook_details.resource_object)
} else {
payments::CallConnectorAction::Trigger
};
let key_manager_state = &(&state).into();
let payments_response = match webhook_details.object_reference_id {
webhooks::ObjectReferenceId::PaymentId(id) => {
let get_trackers_response = get_trackers_response_for_payment_get_operation(
state.store.as_ref(),
&id,
profile.get_id(),
key_manager_state,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let payment_id = get_trackers_response.payment_data.get_payment_id();
let lock_action = api_locking::LockAction::Hold {
input: api_locking::LockingInput {
unique_locking_key: payment_id.get_string_repr().to_owned(),
api_identifier: lock_utils::ApiIdentifier::Payments,
override_lock_retries: None,
},
};
lock_action
.clone()
.perform_locking_action(
&state,
merchant_context.get_merchant_account().get_id().to_owned(),
)
.await?;
let (
payment_data,
_req,
customer,
connector_http_status_code,
external_latency,
connector_response_data,
) = Box::pin(payments::payments_operation_core::<
api::PSync,
_,
_,
_,
PaymentStatusData<api::PSync>,
>(
&state,
req_state,
merchant_context.clone(),
&profile,
payments::operations::PaymentGet,
api::PaymentsRetrieveRequest {
force_sync: true,
expand_attempts: false,
param: None,
return_raw_connector_response: None,
merchant_connector_details: None,
},
get_trackers_response,
consume_or_trigger_flow,
HeaderPayload::default(),
))
.await?;
let response = payment_data.generate_response(
&state,
connector_http_status_code,
external_latency,
None,
&merchant_context,
&profile,
Some(connector_response_data),
);
lock_action
.free_lock_action(
&state,
merchant_context.get_merchant_account().get_id().to_owned(),
)
.await?;
match response {
Ok(value) => value,
Err(err)
if matches!(
err.current_context(),
&errors::ApiErrorResponse::PaymentNotFound
) && state
.clone()
.conf
.webhooks
.ignore_error
.payment_not_found
.unwrap_or(true) =>
{
metrics::WEBHOOK_PAYMENT_NOT_FOUND.add(
1,
router_env::metric_attributes!((
"merchant_id",
merchant_context.get_merchant_account().get_id().clone()
)),
);
return Ok(WebhookResponseTracker::NoEffect);
}
error @ Err(_) => error?,
}
}
_ => Err(errors::ApiErrorResponse::WebhookProcessingFailure).attach_printable(
"Did not get payment id as object reference id in webhook payments flow",
)?,
};
match payments_response {
services::ApplicationResponse::JsonWithHeaders((payments_response, _)) => {
let payment_id = payments_response.id.clone();
let status = payments_response.status;
let event_type: Option<enums::EventType> = payments_response.status.into();
// If event is NOT an UnsupportedEvent, trigger Outgoing Webhook
if let Some(outgoing_event_type) = event_type {
let primary_object_created_at = payments_response.created;
// TODO: trigger an outgoing webhook to merchant
Box::pin(create_event_and_trigger_outgoing_webhook(
state,
profile,
merchant_context.get_merchant_key_store(),
outgoing_event_type,
enums::EventClass::Payments,
payment_id.get_string_repr().to_owned(),
enums::EventObjectType::PaymentDetails,
api::OutgoingWebhookContent::PaymentDetails(Box::new(payments_response)),
primary_object_created_at,
))
.await?;
};
let response = WebhookResponseTracker::Payment { payment_id, status };
Ok(response)
}
_ => Err(errors::ApiErrorResponse::WebhookProcessingFailure)
.attach_printable("received non-json response from payments core")?,
}
}
async fn get_trackers_response_for_payment_get_operation<F>(
db: &dyn StorageInterface,
payment_id: &api::PaymentIdType,
profile_id: &common_utils::id_type::ProfileId,
key_manager_state: &KeyManagerState,
merchant_key_store: &domain::MerchantKeyStore,
storage_scheme: enums::MerchantStorageScheme,
) -> errors::RouterResult<payments::operations::GetTrackerResponse<PaymentStatusData<F>>>
where
F: Clone,
{
let (payment_intent, payment_attempt) = match payment_id {
api_models::payments::PaymentIdType::PaymentIntentId(ref id) => {
let payment_intent = db
.find_payment_intent_by_id(
key_manager_state,
id,
merchant_key_store,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
let payment_attempt = db
.find_payment_attempt_by_id(
key_manager_state,
merchant_key_store,
&payment_intent
.active_attempt_id
.clone()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("active_attempt_id not present in payment_attempt")?,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
(payment_intent, payment_attempt)
}
api_models::payments::PaymentIdType::ConnectorTransactionId(ref id) => {
let payment_attempt = db
.find_payment_attempt_by_profile_id_connector_transaction_id(
key_manager_state,
merchant_key_store,
profile_id,
id,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
let payment_intent = db
.find_payment_intent_by_id(
key_manager_state,
&payment_attempt.payment_id,
merchant_key_store,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
(payment_intent, payment_attempt)
}
api_models::payments::PaymentIdType::PaymentAttemptId(ref id) => {
let global_attempt_id = common_utils::id_type::GlobalAttemptId::try_from(
std::borrow::Cow::Owned(id.to_owned()),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error while getting GlobalAttemptId")?;
let payment_attempt = db
.find_payment_attempt_by_id(
key_manager_state,
merchant_key_store,
&global_attempt_id,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
let payment_intent = db
.find_payment_intent_by_id(
key_manager_state,
&payment_attempt.payment_id,
merchant_key_store,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
(payment_intent, payment_attempt)
}
api_models::payments::PaymentIdType::PreprocessingId(ref _id) => todo!(),
};
// We need the address here to send it in the response
// In case we need to send an outgoing webhook, we might have to send the billing address and shipping address
let payment_address = hyperswitch_domain_models::payment_address::PaymentAddress::new(
payment_intent
.shipping_address
.clone()
.map(|address| address.into_inner()),
payment_intent
.billing_address
.clone()
.map(|address| address.into_inner()),
payment_attempt
.payment_method_billing_address
.clone()
.map(|address| address.into_inner()),
Some(true),
);
Ok(payments::operations::GetTrackerResponse {
payment_data: PaymentStatusData {
flow: PhantomData,
payment_intent,
payment_attempt,
attempts: None,
should_sync_with_connector: true,
payment_address,
merchant_connector_details: None,
},
})
}
#[inline]
async fn verify_webhook_source_verification_call(
connector: ConnectorEnum,
state: &SessionState,
merchant_context: &domain::MerchantContext,
merchant_connector_account: domain::MerchantConnectorAccount,
connector_name: &str,
request_details: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<bool, errors::ConnectorError> {
let connector_data = ConnectorData::get_connector_by_name(
&state.conf.connectors,
connector_name,
GetToken::Connector,
None,
)
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)
.attach_printable("invalid connector name received in payment attempt")?;
let connector_integration: services::BoxedWebhookSourceVerificationConnectorIntegrationInterface<
hyperswitch_domain_models::router_flow_types::VerifyWebhookSource,
VerifyWebhookSourceRequestData,
VerifyWebhookSourceResponseData,
> = connector_data.connector.get_connector_integration();
let connector_webhook_secrets = connector
.get_webhook_source_verification_merchant_secret(
merchant_context.get_merchant_account().get_id(),
connector_name,
merchant_connector_account.connector_webhook_details.clone(),
)
.await
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;
let router_data = construct_webhook_router_data(
state,
connector_name,
merchant_connector_account,
merchant_context,
&connector_webhook_secrets,
request_details,
)
.await
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)
.attach_printable("Failed while constructing webhook router data")?;
let response = services::execute_connector_processing_step(
state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await?;
let verification_result = response
.response
.map(|response| response.verify_webhook_status);
match verification_result {
Ok(VerifyWebhookStatus::SourceVerified) => Ok(true),
_ => Ok(false),
}
}
fn get_connector_by_connector_name(
state: &SessionState,
connector_name: &str,
merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
) -> CustomResult<(ConnectorEnum, String), errors::ApiErrorResponse> {
let authentication_connector =
api_models::enums::convert_authentication_connector(connector_name);
#[cfg(feature = "frm")]
{
let frm_connector = api_models::enums::convert_frm_connector(connector_name);
if frm_connector.is_some() {
let frm_connector_data =
api::FraudCheckConnectorData::get_connector_by_name(connector_name)?;
return Ok((
frm_connector_data.connector,
frm_connector_data.connector_name.to_string(),
));
}
}
let (connector, connector_name) = if authentication_connector.is_some() {
let authentication_connector_data =
api::AuthenticationConnectorData::get_connector_by_name(connector_name)?;
(
authentication_connector_data.connector,
authentication_connector_data.connector_name.to_string(),
)
} else {
let connector_data = ConnectorData::get_connector_by_name(
&state.conf.connectors,
connector_name,
GetToken::Connector,
merchant_connector_id,
)
.change_context(errors::ApiErrorResponse::InvalidRequestData {
message: "invalid connector name received".to_string(),
})
.attach_printable("Failed construction of ConnectorData")?;
(
connector_data.connector,
connector_data.connector_name.to_string(),
)
};
Ok((connector, connector_name))
}
/// This function fetches the merchant connector account and connector details
async fn fetch_mca_and_connector(
state: &SessionState,
connector_id: &common_utils::id_type::MerchantConnectorAccountId,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<(domain::MerchantConnectorAccount, ConnectorEnum, String), errors::ApiErrorResponse>
{
let db = &state.store;
let mca = db
.find_merchant_connector_account_by_id(&state.into(), connector_id, key_store)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: connector_id.get_string_repr().to_owned(),
})
.attach_printable("error while fetching merchant_connector_account from connector_id")?;
let (connector, connector_name) = get_connector_by_connector_name(
state,
&mca.connector_name.to_string(),
Some(mca.get_id()),
)?;
Ok((mca, connector, connector_name))
}
|
crates/router/src/core/webhooks/incoming_v2.rs
|
router::src::core::webhooks::incoming_v2
| 5,882
| true
|
// File: crates/router/src/core/webhooks/incoming.rs
// Module: router::src::core::webhooks::incoming
use std::{str::FromStr, time::Instant};
use actix_web::FromRequest;
#[cfg(feature = "payouts")]
use api_models::payouts as payout_models;
use api_models::{
enums::Connector,
webhooks::{self, WebhookResponseTracker},
};
pub use common_enums::{connector_enums::InvoiceStatus, enums::ProcessTrackerRunner};
use common_utils::{
errors::ReportSwitchExt,
events::ApiEventsType,
ext_traits::{AsyncExt, ByteSliceExt},
types::{AmountConvertor, StringMinorUnitForConnector},
};
use diesel_models::{refund as diesel_refund, ConnectorMandateReferenceId};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
mandates::CommonMandateReference,
payments::{payment_attempt::PaymentAttempt, HeaderPayload},
router_request_types::VerifyWebhookSourceRequestData,
router_response_types::{VerifyWebhookSourceResponseData, VerifyWebhookStatus},
};
use hyperswitch_interfaces::webhooks::{IncomingWebhookFlowError, IncomingWebhookRequestDetails};
use masking::{ExposeInterface, PeekInterface};
use router_env::{instrument, tracing, tracing_actix_web::RequestId};
use super::{types, utils, MERCHANT_ID};
use crate::{
consts,
core::{
api_locking,
errors::{self, ConnectorErrorExt, CustomResult, RouterResponse, StorageErrorExt},
metrics, payment_methods,
payments::{self, tokenization},
refunds, relay, unified_connector_service, utils as core_utils,
webhooks::{network_tokenization_incoming, utils::construct_webhook_router_data},
},
db::StorageInterface,
events::api_logs::ApiEvent,
logger,
routes::{
app::{ReqState, SessionStateInfo},
lock_utils, SessionState,
},
services::{
self, authentication as auth, connector_integration_interface::ConnectorEnum,
ConnectorValidation,
},
types::{
api::{
self, mandates::MandateResponseExt, ConnectorCommon, ConnectorData, GetToken,
IncomingWebhook,
},
domain,
storage::{self, enums},
transformers::{ForeignFrom, ForeignInto, ForeignTryFrom},
},
utils::{self as helper_utils, ext_traits::OptionExt, generate_id},
};
#[cfg(feature = "payouts")]
use crate::{core::payouts, types::storage::PayoutAttemptUpdate};
#[allow(clippy::too_many_arguments)]
pub async fn incoming_webhooks_wrapper<W: types::OutgoingWebhookType>(
flow: &impl router_env::types::FlowMetric,
state: SessionState,
req_state: ReqState,
req: &actix_web::HttpRequest,
merchant_context: domain::MerchantContext,
connector_name_or_mca_id: &str,
body: actix_web::web::Bytes,
is_relay_webhook: bool,
) -> RouterResponse<serde_json::Value> {
let start_instant = Instant::now();
let (application_response, webhooks_response_tracker, serialized_req) =
Box::pin(incoming_webhooks_core::<W>(
state.clone(),
req_state,
req,
merchant_context.clone(),
connector_name_or_mca_id,
body.clone(),
is_relay_webhook,
))
.await?;
logger::info!(incoming_webhook_payload = ?serialized_req);
let request_duration = Instant::now()
.saturating_duration_since(start_instant)
.as_millis();
let request_id = RequestId::extract(req)
.await
.attach_printable("Unable to extract request id from request")
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let auth_type = auth::AuthenticationType::WebhookAuth {
merchant_id: merchant_context.get_merchant_account().get_id().clone(),
};
let status_code = 200;
let api_event = ApiEventsType::Webhooks {
connector: connector_name_or_mca_id.to_string(),
payment_id: webhooks_response_tracker.get_payment_id(),
};
let response_value = serde_json::to_value(&webhooks_response_tracker)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Could not convert webhook effect to string")?;
let infra = state.infra_components.clone();
let api_event = ApiEvent::new(
state.tenant.tenant_id.clone(),
Some(merchant_context.get_merchant_account().get_id().clone()),
flow,
&request_id,
request_duration,
status_code,
serialized_req,
Some(response_value),
None,
auth_type,
None,
api_event,
req,
req.method(),
infra,
);
state.event_handler().log_event(&api_event);
Ok(application_response)
}
#[cfg(feature = "v1")]
pub async fn network_token_incoming_webhooks_wrapper<W: types::OutgoingWebhookType>(
flow: &impl router_env::types::FlowMetric,
state: SessionState,
req: &actix_web::HttpRequest,
body: actix_web::web::Bytes,
) -> RouterResponse<serde_json::Value> {
let start_instant = Instant::now();
let request_details: IncomingWebhookRequestDetails<'_> = IncomingWebhookRequestDetails {
method: req.method().clone(),
uri: req.uri().clone(),
headers: req.headers(),
query_params: req.query_string().to_string(),
body: &body,
};
let (application_response, webhooks_response_tracker, serialized_req, merchant_id) = Box::pin(
network_token_incoming_webhooks_core::<W>(&state, request_details),
)
.await?;
logger::info!(incoming_webhook_payload = ?serialized_req);
let request_duration = Instant::now()
.saturating_duration_since(start_instant)
.as_millis();
let request_id = RequestId::extract(req)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to extract request id from request")?;
let auth_type = auth::AuthenticationType::NoAuth;
let status_code = 200;
let api_event = ApiEventsType::NetworkTokenWebhook {
payment_method_id: webhooks_response_tracker.get_payment_method_id(),
};
let response_value = serde_json::to_value(&webhooks_response_tracker)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Could not convert webhook effect to string")?;
let infra = state.infra_components.clone();
let api_event = ApiEvent::new(
state.tenant.tenant_id.clone(),
Some(merchant_id),
flow,
&request_id,
request_duration,
status_code,
serialized_req,
Some(response_value),
None,
auth_type,
None,
api_event,
req,
req.method(),
infra,
);
state.event_handler().log_event(&api_event);
Ok(application_response)
}
#[allow(clippy::too_many_arguments)]
#[instrument(skip_all)]
async fn incoming_webhooks_core<W: types::OutgoingWebhookType>(
state: SessionState,
req_state: ReqState,
req: &actix_web::HttpRequest,
merchant_context: domain::MerchantContext,
connector_name_or_mca_id: &str,
body: actix_web::web::Bytes,
is_relay_webhook: bool,
) -> errors::RouterResult<(
services::ApplicationResponse<serde_json::Value>,
WebhookResponseTracker,
serde_json::Value,
)> {
// Initial setup and metrics
metrics::WEBHOOK_INCOMING_COUNT.add(
1,
router_env::metric_attributes!((
MERCHANT_ID,
merchant_context.get_merchant_account().get_id().clone()
)),
);
let request_details = IncomingWebhookRequestDetails {
method: req.method().clone(),
uri: req.uri().clone(),
headers: req.headers(),
query_params: req.query_string().to_string(),
body: &body,
};
// Fetch the merchant connector account to get the webhooks source secret
let (merchant_connector_account, connector, connector_name) =
fetch_optional_mca_and_connector(&state, &merchant_context, connector_name_or_mca_id)
.await?;
// Determine webhook processing path (UCS vs non-UCS) and handle event type extraction
let webhook_processing_result =
match if unified_connector_service::should_call_unified_connector_service_for_webhooks(
&state,
&merchant_context,
&connector_name,
)
.await?
{
logger::info!(
connector = connector_name,
"Using Unified Connector Service for webhook processing",
);
process_ucs_webhook_transform(
&state,
&merchant_context,
&connector_name,
&body,
&request_details,
merchant_connector_account.as_ref(),
)
.await
} else {
// NON-UCS PATH: Need to decode body first
let decoded_body = connector
.decode_webhook_body(
&request_details,
merchant_context.get_merchant_account().get_id(),
merchant_connector_account
.clone()
.and_then(|mca| mca.connector_webhook_details.clone()),
&connector_name,
)
.await
.switch()
.attach_printable("There was an error in incoming webhook body decoding")?;
process_non_ucs_webhook(
&state,
&merchant_context,
&connector,
&connector_name,
decoded_body.into(),
&request_details,
)
.await
} {
Ok(result) => result,
Err(error) => {
let error_result = handle_incoming_webhook_error(
error,
&connector,
connector_name.as_str(),
&request_details,
merchant_context.get_merchant_account().get_id(),
);
match error_result {
Ok((response, webhook_tracker, serialized_request)) => {
return Ok((response, webhook_tracker, serialized_request));
}
Err(e) => return Err(e),
}
}
};
// if it is a setup webhook event, return ok status
if webhook_processing_result.event_type == webhooks::IncomingWebhookEvent::SetupWebhook {
return Ok((
services::ApplicationResponse::StatusOk,
WebhookResponseTracker::NoEffect,
serde_json::Value::default(),
));
}
// Update request_details with the appropriate body (decoded for non-UCS, raw for UCS)
let final_request_details = match &webhook_processing_result.decoded_body {
Some(decoded_body) => IncomingWebhookRequestDetails {
method: request_details.method.clone(),
uri: request_details.uri.clone(),
headers: request_details.headers,
query_params: request_details.query_params.clone(),
body: decoded_body,
},
None => request_details, // Use original request details for UCS
};
logger::info!(event_type=?webhook_processing_result.event_type);
// Check if webhook should be processed further
let is_webhook_event_supported = !matches!(
webhook_processing_result.event_type,
webhooks::IncomingWebhookEvent::EventNotSupported
);
let is_webhook_event_enabled = !utils::is_webhook_event_disabled(
&*state.clone().store,
connector_name.as_str(),
merchant_context.get_merchant_account().get_id(),
&webhook_processing_result.event_type,
)
.await;
let flow_type: api::WebhookFlow = webhook_processing_result.event_type.into();
let process_webhook_further = is_webhook_event_enabled
&& is_webhook_event_supported
&& !matches!(flow_type, api::WebhookFlow::ReturnResponse);
logger::info!(process_webhook=?process_webhook_further);
let mut event_object: Box<dyn masking::ErasedMaskSerialize> = Box::new(serde_json::Value::Null);
let webhook_effect = match process_webhook_further {
true => {
let business_logic_result = process_webhook_business_logic(
&state,
req_state,
&merchant_context,
&connector,
&connector_name,
webhook_processing_result.event_type,
webhook_processing_result.source_verified,
&webhook_processing_result.transform_data,
&final_request_details,
is_relay_webhook,
)
.await;
match business_logic_result {
Ok(response) => {
// Extract event object for serialization
event_object = extract_webhook_event_object(
&webhook_processing_result.transform_data,
&connector,
&final_request_details,
)?;
response
}
Err(error) => {
let error_result = handle_incoming_webhook_error(
error,
&connector,
connector_name.as_str(),
&final_request_details,
merchant_context.get_merchant_account().get_id(),
);
match error_result {
Ok((_, webhook_tracker, _)) => webhook_tracker,
Err(e) => return Err(e),
}
}
}
}
false => {
metrics::WEBHOOK_INCOMING_FILTERED_COUNT.add(
1,
router_env::metric_attributes!((
MERCHANT_ID,
merchant_context.get_merchant_account().get_id().clone()
)),
);
WebhookResponseTracker::NoEffect
}
};
// Generate response
let response = connector
.get_webhook_api_response(&final_request_details, None)
.switch()
.attach_printable("Could not get incoming webhook api response from connector")?;
let serialized_request = event_object
.masked_serialize()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Could not convert webhook effect to string")?;
Ok((response, webhook_effect, serialized_request))
}
/// Process UCS webhook transformation using the high-level UCS abstraction
async fn process_ucs_webhook_transform(
state: &SessionState,
merchant_context: &domain::MerchantContext,
connector_name: &str,
body: &actix_web::web::Bytes,
request_details: &IncomingWebhookRequestDetails<'_>,
merchant_connector_account: Option<&domain::MerchantConnectorAccount>,
) -> errors::RouterResult<WebhookProcessingResult> {
// Use the new UCS abstraction which provides clean separation
let (event_type, source_verified, transform_data) =
unified_connector_service::call_unified_connector_service_for_webhook(
state,
merchant_context,
connector_name,
body,
request_details,
merchant_connector_account,
)
.await?;
Ok(WebhookProcessingResult {
event_type,
source_verified,
transform_data: Some(Box::new(transform_data)),
decoded_body: None, // UCS path uses raw body
})
}
/// Result type for webhook processing path determination
pub struct WebhookProcessingResult {
event_type: webhooks::IncomingWebhookEvent,
source_verified: bool,
transform_data: Option<Box<unified_connector_service::WebhookTransformData>>,
decoded_body: Option<actix_web::web::Bytes>,
}
/// Process non-UCS webhook using traditional connector processing
async fn process_non_ucs_webhook(
state: &SessionState,
merchant_context: &domain::MerchantContext,
connector: &ConnectorEnum,
connector_name: &str,
decoded_body: actix_web::web::Bytes,
request_details: &IncomingWebhookRequestDetails<'_>,
) -> errors::RouterResult<WebhookProcessingResult> {
// Create request_details with decoded body for connector processing
let updated_request_details = IncomingWebhookRequestDetails {
method: request_details.method.clone(),
uri: request_details.uri.clone(),
headers: request_details.headers,
query_params: request_details.query_params.clone(),
body: &decoded_body,
};
match connector
.get_webhook_event_type(&updated_request_details)
.allow_webhook_event_type_not_found(
state
.clone()
.conf
.webhooks
.ignore_error
.event_type
.unwrap_or(true),
)
.switch()
.attach_printable("Could not find event type in incoming webhook body")?
{
Some(event_type) => Ok(WebhookProcessingResult {
event_type,
source_verified: false,
transform_data: None,
decoded_body: Some(decoded_body),
}),
None => {
metrics::WEBHOOK_EVENT_TYPE_IDENTIFICATION_FAILURE_COUNT.add(
1,
router_env::metric_attributes!(
(
MERCHANT_ID,
merchant_context.get_merchant_account().get_id().clone()
),
("connector", connector_name.to_string())
),
);
Err(errors::ApiErrorResponse::WebhookProcessingFailure)
.attach_printable("Failed to identify event type in incoming webhook body")
}
}
}
/// Extract webhook event object based on transform data availability
fn extract_webhook_event_object(
transform_data: &Option<Box<unified_connector_service::WebhookTransformData>>,
connector: &ConnectorEnum,
request_details: &IncomingWebhookRequestDetails<'_>,
) -> errors::RouterResult<Box<dyn masking::ErasedMaskSerialize>> {
match transform_data {
Some(transform_data) => match &transform_data.webhook_content {
Some(webhook_content) => {
let serialized_value = serde_json::to_value(webhook_content)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to serialize UCS webhook content")?;
Ok(Box::new(serialized_value))
}
None => connector
.get_webhook_resource_object(request_details)
.switch()
.attach_printable("Could not find resource object in incoming webhook body"),
},
None => connector
.get_webhook_resource_object(request_details)
.switch()
.attach_printable("Could not find resource object in incoming webhook body"),
}
}
/// Process the main webhook business logic after event type determination
#[allow(clippy::too_many_arguments)]
async fn process_webhook_business_logic(
state: &SessionState,
req_state: ReqState,
merchant_context: &domain::MerchantContext,
connector: &ConnectorEnum,
connector_name: &str,
event_type: webhooks::IncomingWebhookEvent,
source_verified_via_ucs: bool,
webhook_transform_data: &Option<Box<unified_connector_service::WebhookTransformData>>,
request_details: &IncomingWebhookRequestDetails<'_>,
is_relay_webhook: bool,
) -> errors::RouterResult<WebhookResponseTracker> {
let object_ref_id = connector
.get_webhook_object_reference_id(request_details)
.switch()
.attach_printable("Could not find object reference id in incoming webhook body")?;
let connector_enum = Connector::from_str(connector_name)
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "connector",
})
.attach_printable_lazy(|| format!("unable to parse connector name {connector_name:?}"))?;
let connectors_with_source_verification_call = &state.conf.webhook_source_verification_call;
let merchant_connector_account = match Box::pin(helper_utils::get_mca_from_object_reference_id(
state,
object_ref_id.clone(),
merchant_context,
connector_name,
))
.await
{
Ok(mca) => mca,
Err(error) => {
let result = handle_incoming_webhook_error(
error,
connector,
connector_name,
request_details,
merchant_context.get_merchant_account().get_id(),
);
match result {
Ok((_, webhook_tracker, _)) => return Ok(webhook_tracker),
Err(e) => return Err(e),
}
}
};
let source_verified = if source_verified_via_ucs {
// If UCS handled verification, use that result
source_verified_via_ucs
} else {
// Fall back to traditional source verification
if connectors_with_source_verification_call
.connectors_with_webhook_source_verification_call
.contains(&connector_enum)
{
verify_webhook_source_verification_call(
connector.clone(),
state,
merchant_context,
merchant_connector_account.clone(),
connector_name,
request_details,
)
.await
.or_else(|error| match error.current_context() {
errors::ConnectorError::WebhookSourceVerificationFailed => {
logger::error!(?error, "Source Verification Failed");
Ok(false)
}
_ => Err(error),
})
.switch()
.attach_printable("There was an issue in incoming webhook source verification")?
} else {
connector
.clone()
.verify_webhook_source(
request_details,
merchant_context.get_merchant_account().get_id(),
merchant_connector_account.connector_webhook_details.clone(),
merchant_connector_account.connector_account_details.clone(),
connector_name,
)
.await
.or_else(|error| match error.current_context() {
errors::ConnectorError::WebhookSourceVerificationFailed => {
logger::error!(?error, "Source Verification Failed");
Ok(false)
}
_ => Err(error),
})
.switch()
.attach_printable("There was an issue in incoming webhook source verification")?
}
};
if source_verified {
metrics::WEBHOOK_SOURCE_VERIFIED_COUNT.add(
1,
router_env::metric_attributes!((
MERCHANT_ID,
merchant_context.get_merchant_account().get_id().clone()
)),
);
} else if connector.is_webhook_source_verification_mandatory() {
// if webhook consumption is mandatory for connector, fail webhook
// so that merchant can retrigger it after updating merchant_secret
return Err(errors::ApiErrorResponse::WebhookAuthenticationFailed.into());
}
logger::info!(source_verified=?source_verified);
let event_object: Box<dyn masking::ErasedMaskSerialize> =
if let Some(transform_data) = webhook_transform_data {
// Use UCS transform data if available
if let Some(webhook_content) = &transform_data.webhook_content {
// Convert UCS webhook content to appropriate format
Box::new(
serde_json::to_value(webhook_content)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to serialize UCS webhook content")?,
)
} else {
// Fall back to connector extraction
connector
.get_webhook_resource_object(request_details)
.switch()
.attach_printable("Could not find resource object in incoming webhook body")?
}
} else {
// Use traditional connector extraction
connector
.get_webhook_resource_object(request_details)
.switch()
.attach_printable("Could not find resource object in incoming webhook body")?
};
let webhook_details = api::IncomingWebhookDetails {
object_reference_id: object_ref_id.clone(),
resource_object: serde_json::to_vec(&event_object)
.change_context(errors::ParsingError::EncodeError("byte-vec"))
.attach_printable("Unable to convert webhook payload to a value")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"There was an issue when encoding the incoming webhook body to bytes",
)?,
};
let profile_id = &merchant_connector_account.profile_id;
let key_manager_state = &(state).into();
let business_profile = state
.store
.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(),
})?;
// If the incoming webhook is a relay webhook, then we need to trigger the relay webhook flow
let result_response = if is_relay_webhook {
let relay_webhook_response = Box::pin(relay_incoming_webhook_flow(
state.clone(),
merchant_context.clone(),
business_profile,
webhook_details,
event_type,
source_verified,
))
.await
.attach_printable("Incoming webhook flow for relay failed");
// Using early return ensures unsupported webhooks are acknowledged to the connector
if let Some(errors::ApiErrorResponse::NotSupported { .. }) = relay_webhook_response
.as_ref()
.err()
.map(|a| a.current_context())
{
logger::error!(
webhook_payload =? request_details.body,
"Failed while identifying the event type",
);
let _response = connector
.get_webhook_api_response(request_details, None)
.switch()
.attach_printable(
"Failed while early return in case of not supported event type in relay webhooks",
)?;
return Ok(WebhookResponseTracker::NoEffect);
};
relay_webhook_response
} else {
let flow_type: api::WebhookFlow = event_type.into();
match flow_type {
api::WebhookFlow::Payment => Box::pin(payments_incoming_webhook_flow(
state.clone(),
req_state,
merchant_context.clone(),
business_profile,
webhook_details,
source_verified,
connector,
request_details,
event_type,
webhook_transform_data,
))
.await
.attach_printable("Incoming webhook flow for payments failed"),
api::WebhookFlow::Refund => Box::pin(refunds_incoming_webhook_flow(
state.clone(),
merchant_context.clone(),
business_profile,
webhook_details,
connector_name,
source_verified,
event_type,
))
.await
.attach_printable("Incoming webhook flow for refunds failed"),
api::WebhookFlow::Dispute => Box::pin(disputes_incoming_webhook_flow(
state.clone(),
merchant_context.clone(),
business_profile,
webhook_details,
source_verified,
connector,
request_details,
event_type,
))
.await
.attach_printable("Incoming webhook flow for disputes failed"),
api::WebhookFlow::BankTransfer => Box::pin(bank_transfer_webhook_flow(
state.clone(),
req_state,
merchant_context.clone(),
business_profile,
webhook_details,
source_verified,
))
.await
.attach_printable("Incoming bank-transfer webhook flow failed"),
api::WebhookFlow::ReturnResponse => Ok(WebhookResponseTracker::NoEffect),
api::WebhookFlow::Mandate => Box::pin(mandates_incoming_webhook_flow(
state.clone(),
merchant_context.clone(),
business_profile,
webhook_details,
source_verified,
event_type,
))
.await
.attach_printable("Incoming webhook flow for mandates failed"),
api::WebhookFlow::ExternalAuthentication => {
Box::pin(external_authentication_incoming_webhook_flow(
state.clone(),
req_state,
merchant_context.clone(),
source_verified,
event_type,
request_details,
connector,
object_ref_id,
business_profile,
merchant_connector_account,
))
.await
.attach_printable("Incoming webhook flow for external authentication failed")
}
api::WebhookFlow::FraudCheck => Box::pin(frm_incoming_webhook_flow(
state.clone(),
req_state,
merchant_context.clone(),
source_verified,
event_type,
object_ref_id,
business_profile,
))
.await
.attach_printable("Incoming webhook flow for fraud check failed"),
#[cfg(feature = "payouts")]
api::WebhookFlow::Payout => Box::pin(payouts_incoming_webhook_flow(
state.clone(),
merchant_context.clone(),
business_profile,
webhook_details,
event_type,
source_verified,
))
.await
.attach_printable("Incoming webhook flow for payouts failed"),
api::WebhookFlow::Subscription => {
Box::pin(subscriptions::webhooks::incoming_webhook_flow(
state.clone().into(),
merchant_context.clone(),
business_profile,
webhook_details,
source_verified,
connector,
request_details,
event_type,
merchant_connector_account,
))
.await
.attach_printable("Incoming webhook flow for subscription failed")
}
_ => Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unsupported Flow Type received in incoming webhooks"),
}
};
match result_response {
Ok(response) => Ok(response),
Err(error) => {
let result = handle_incoming_webhook_error(
error,
connector,
connector_name,
request_details,
merchant_context.get_merchant_account().get_id(),
);
match result {
Ok((_, webhook_tracker, _)) => Ok(webhook_tracker),
Err(e) => Err(e),
}
}
}
}
fn handle_incoming_webhook_error(
error: error_stack::Report<errors::ApiErrorResponse>,
connector: &ConnectorEnum,
connector_name: &str,
request_details: &IncomingWebhookRequestDetails<'_>,
merchant_id: &common_utils::id_type::MerchantId,
) -> errors::RouterResult<(
services::ApplicationResponse<serde_json::Value>,
WebhookResponseTracker,
serde_json::Value,
)> {
logger::error!(?error, "Incoming webhook flow failed");
// fetch the connector enum from the connector name
let connector_enum = Connector::from_str(connector_name)
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "connector",
})
.attach_printable_lazy(|| format!("unable to parse connector name {connector_name:?}"))?;
// get the error response from the connector
if connector_enum.should_acknowledge_webhook_for_resource_not_found_errors() {
metrics::WEBHOOK_FLOW_FAILED_BUT_ACKNOWLEDGED.add(
1,
router_env::metric_attributes!(
("connector", connector_name.to_string()),
("merchant_id", merchant_id.get_string_repr().to_string())
),
);
let response = connector
.get_webhook_api_response(
request_details,
Some(IncomingWebhookFlowError::from(error.current_context())),
)
.switch()
.attach_printable("Failed to get incoming webhook api response from connector")?;
Ok((
response,
WebhookResponseTracker::NoEffect,
serde_json::Value::Null,
))
} else {
Err(error)
}
}
#[instrument(skip_all)]
#[cfg(feature = "v1")]
async fn network_token_incoming_webhooks_core<W: types::OutgoingWebhookType>(
state: &SessionState,
request_details: IncomingWebhookRequestDetails<'_>,
) -> errors::RouterResult<(
services::ApplicationResponse<serde_json::Value>,
WebhookResponseTracker,
serde_json::Value,
common_utils::id_type::MerchantId,
)> {
let serialized_request =
network_tokenization_incoming::get_network_token_resource_object(&request_details)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Network Token Requestor Webhook deserialization failed")?
.masked_serialize()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Could not convert webhook effect to string")?;
let network_tokenization_service = &state
.conf
.network_tokenization_service
.as_ref()
.ok_or(errors::NetworkTokenizationError::NetworkTokenizationServiceNotConfigured)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Network Tokenization Service not configured")?;
//source verification
network_tokenization_incoming::Authorization::new(request_details.headers.get("Authorization"))
.verify_webhook_source(network_tokenization_service.get_inner())
.await?;
let response: network_tokenization_incoming::NetworkTokenWebhookResponse = request_details
.body
.parse_struct("NetworkTokenWebhookResponse")
.change_context(errors::ApiErrorResponse::WebhookUnprocessableEntity)?;
let (merchant_id, payment_method_id, _customer_id) = response
.fetch_merchant_id_payment_method_id_customer_id_from_callback_mapper(state)
.await?;
metrics::WEBHOOK_SOURCE_VERIFIED_COUNT.add(
1,
router_env::metric_attributes!((MERCHANT_ID, merchant_id.clone())),
);
let merchant_context =
network_tokenization_incoming::fetch_merchant_account_for_network_token_webhooks(
state,
&merchant_id,
)
.await?;
let payment_method =
network_tokenization_incoming::fetch_payment_method_for_network_token_webhooks(
state,
merchant_context.get_merchant_account(),
merchant_context.get_merchant_key_store(),
&payment_method_id,
)
.await?;
let response_data = response.get_response_data();
let webhook_resp_tracker = response_data
.update_payment_method(state, &payment_method, &merchant_context)
.await?;
Ok((
services::ApplicationResponse::StatusOk,
webhook_resp_tracker,
serialized_request,
merchant_id.clone(),
))
}
#[allow(clippy::too_many_arguments)]
#[instrument(skip_all)]
async fn payments_incoming_webhook_flow(
state: SessionState,
req_state: ReqState,
merchant_context: domain::MerchantContext,
business_profile: domain::Profile,
webhook_details: api::IncomingWebhookDetails,
source_verified: bool,
connector: &ConnectorEnum,
request_details: &IncomingWebhookRequestDetails<'_>,
event_type: webhooks::IncomingWebhookEvent,
webhook_transform_data: &Option<Box<unified_connector_service::WebhookTransformData>>,
) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> {
let consume_or_trigger_flow = if source_verified {
// Determine the appropriate action based on UCS availability
let resource_object = webhook_details.resource_object;
match webhook_transform_data.as_ref() {
Some(transform_data) => {
// Serialize the transform data to pass to UCS handler
let transform_data_bytes = serde_json::to_vec(transform_data.as_ref())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to serialize UCS webhook transform data")?;
payments::CallConnectorAction::UCSHandleResponse(transform_data_bytes)
}
None => payments::CallConnectorAction::HandleResponse(resource_object),
}
} else {
payments::CallConnectorAction::Trigger
};
let payments_response = match webhook_details.object_reference_id {
webhooks::ObjectReferenceId::PaymentId(ref id) => {
let payment_id = get_payment_id(
state.store.as_ref(),
id,
merchant_context.get_merchant_account().get_id(),
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let lock_action = api_locking::LockAction::Hold {
input: api_locking::LockingInput {
unique_locking_key: payment_id.get_string_repr().to_owned(),
api_identifier: lock_utils::ApiIdentifier::Payments,
override_lock_retries: None,
},
};
lock_action
.clone()
.perform_locking_action(
&state,
merchant_context.get_merchant_account().get_id().to_owned(),
)
.await?;
let response = Box::pin(payments::payments_core::<
api::PSync,
api::PaymentsResponse,
_,
_,
_,
payments::PaymentData<api::PSync>,
>(
state.clone(),
req_state,
merchant_context.clone(),
None,
payments::operations::PaymentStatus,
api::PaymentsRetrieveRequest {
resource_id: id.clone(),
merchant_id: Some(merchant_context.get_merchant_account().get_id().clone()),
force_sync: true,
connector: None,
param: None,
merchant_connector_details: None,
client_secret: None,
expand_attempts: None,
expand_captures: None,
all_keys_required: None,
},
services::AuthFlow::Merchant,
consume_or_trigger_flow.clone(),
None,
HeaderPayload::default(),
))
.await;
// When mandate details are present in successful webhooks, and consuming webhooks are skipped during payment sync if the payment status is already updated to charged, this function is used to update the connector mandate details.
if should_update_connector_mandate_details(source_verified, event_type) {
update_connector_mandate_details(
&state,
&merchant_context,
webhook_details.object_reference_id.clone(),
connector,
request_details,
)
.await?
};
lock_action
.free_lock_action(
&state,
merchant_context.get_merchant_account().get_id().to_owned(),
)
.await?;
match response {
Ok(value) => value,
Err(err)
if matches!(
err.current_context(),
&errors::ApiErrorResponse::PaymentNotFound
) && state
.conf
.webhooks
.ignore_error
.payment_not_found
.unwrap_or(true) =>
{
metrics::WEBHOOK_PAYMENT_NOT_FOUND.add(
1,
router_env::metric_attributes!((
"merchant_id",
merchant_context.get_merchant_account().get_id().clone()
)),
);
return Ok(WebhookResponseTracker::NoEffect);
}
error @ Err(_) => error?,
}
}
_ => Err(errors::ApiErrorResponse::WebhookProcessingFailure).attach_printable(
"Did not get payment id as object reference id in webhook payments flow",
)?,
};
match payments_response {
services::ApplicationResponse::JsonWithHeaders((payments_response, _)) => {
let payment_id = payments_response.payment_id.clone();
let status = payments_response.status;
let event_type: Option<enums::EventType> = payments_response.status.into();
// If event is NOT an UnsupportedEvent, trigger Outgoing Webhook
if let Some(outgoing_event_type) = event_type {
let primary_object_created_at = payments_response.created;
Box::pin(super::create_event_and_trigger_outgoing_webhook(
state,
merchant_context,
business_profile,
outgoing_event_type,
enums::EventClass::Payments,
payment_id.get_string_repr().to_owned(),
enums::EventObjectType::PaymentDetails,
api::OutgoingWebhookContent::PaymentDetails(Box::new(payments_response)),
primary_object_created_at,
))
.await?;
};
let response = WebhookResponseTracker::Payment { payment_id, status };
Ok(response)
}
_ => Err(errors::ApiErrorResponse::WebhookProcessingFailure)
.attach_printable("received non-json response from payments core")?,
}
}
#[cfg(feature = "payouts")]
#[instrument(skip_all)]
async fn payouts_incoming_webhook_flow(
state: SessionState,
merchant_context: domain::MerchantContext,
business_profile: domain::Profile,
webhook_details: api::IncomingWebhookDetails,
event_type: webhooks::IncomingWebhookEvent,
source_verified: bool,
) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> {
metrics::INCOMING_PAYOUT_WEBHOOK_METRIC.add(1, &[]);
if source_verified {
let db = &*state.store;
//find payout_attempt by object_reference_id
let payout_attempt = match webhook_details.object_reference_id {
webhooks::ObjectReferenceId::PayoutId(payout_id_type) => match payout_id_type {
webhooks::PayoutIdType::PayoutAttemptId(id) => db
.find_payout_attempt_by_merchant_id_payout_attempt_id(
merchant_context.get_merchant_account().get_id(),
&id,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::WebhookResourceNotFound)
.attach_printable("Failed to fetch the payout attempt")?,
webhooks::PayoutIdType::ConnectorPayoutId(id) => db
.find_payout_attempt_by_merchant_id_connector_payout_id(
merchant_context.get_merchant_account().get_id(),
&id,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::WebhookResourceNotFound)
.attach_printable("Failed to fetch the payout attempt")?,
},
_ => Err(errors::ApiErrorResponse::WebhookProcessingFailure)
.attach_printable("received a non-payout id when processing payout webhooks")?,
};
let payouts = db
.find_payout_by_merchant_id_payout_id(
merchant_context.get_merchant_account().get_id(),
&payout_attempt.payout_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::WebhookResourceNotFound)
.attach_printable("Failed to fetch the payout")?;
let payout_attempt_update = PayoutAttemptUpdate::StatusUpdate {
connector_payout_id: payout_attempt.connector_payout_id.clone(),
status: common_enums::PayoutStatus::foreign_try_from(event_type)
.change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
.attach_printable("failed payout status mapping from event type")?,
error_message: None,
error_code: None,
is_eligible: payout_attempt.is_eligible,
unified_code: None,
unified_message: None,
payout_connector_metadata: payout_attempt.payout_connector_metadata.clone(),
};
let action_req =
payout_models::PayoutRequest::PayoutActionRequest(payout_models::PayoutActionRequest {
payout_id: payouts.payout_id.clone(),
});
let mut payout_data = Box::pin(payouts::make_payout_data(
&state,
&merchant_context,
None,
&action_req,
common_utils::consts::DEFAULT_LOCALE,
))
.await?;
let updated_payout_attempt = db
.update_payout_attempt(
&payout_attempt,
payout_attempt_update,
&payout_data.payouts,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::WebhookResourceNotFound)
.attach_printable_lazy(|| {
format!(
"Failed while updating payout attempt: payout_attempt_id: {}",
payout_attempt.payout_attempt_id
)
})?;
payout_data.payout_attempt = updated_payout_attempt;
let event_type: Option<enums::EventType> = payout_data.payout_attempt.status.into();
// If event is NOT an UnsupportedEvent, trigger Outgoing Webhook
if let Some(outgoing_event_type) = event_type {
let payout_create_response =
payouts::response_handler(&state, &merchant_context, &payout_data).await?;
Box::pin(super::create_event_and_trigger_outgoing_webhook(
state,
merchant_context,
business_profile,
outgoing_event_type,
enums::EventClass::Payouts,
payout_data
.payout_attempt
.payout_id
.get_string_repr()
.to_string(),
enums::EventObjectType::PayoutDetails,
api::OutgoingWebhookContent::PayoutDetails(Box::new(payout_create_response)),
Some(payout_data.payout_attempt.created_at),
))
.await?;
}
Ok(WebhookResponseTracker::Payout {
payout_id: payout_data.payout_attempt.payout_id,
status: payout_data.payout_attempt.status,
})
} else {
metrics::INCOMING_PAYOUT_WEBHOOK_SIGNATURE_FAILURE_METRIC.add(1, &[]);
Err(report!(
errors::ApiErrorResponse::WebhookAuthenticationFailed
))
}
}
async fn relay_refunds_incoming_webhook_flow(
state: SessionState,
merchant_context: domain::MerchantContext,
business_profile: domain::Profile,
webhook_details: api::IncomingWebhookDetails,
event_type: webhooks::IncomingWebhookEvent,
source_verified: bool,
) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> {
let db = &*state.store;
let key_manager_state = &(&state).into();
let relay_record = match webhook_details.object_reference_id {
webhooks::ObjectReferenceId::RefundId(refund_id_type) => match refund_id_type {
webhooks::RefundIdType::RefundId(refund_id) => {
let relay_id = common_utils::id_type::RelayId::from_str(&refund_id)
.change_context(errors::ValidationError::IncorrectValueProvided {
field_name: "relay_id",
})
.change_context(errors::ApiErrorResponse::InternalServerError)?;
db.find_relay_by_id(
key_manager_state,
merchant_context.get_merchant_key_store(),
&relay_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::WebhookResourceNotFound)
.attach_printable("Failed to fetch the relay record")?
}
webhooks::RefundIdType::ConnectorRefundId(connector_refund_id) => db
.find_relay_by_profile_id_connector_reference_id(
key_manager_state,
merchant_context.get_merchant_key_store(),
business_profile.get_id(),
&connector_refund_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::WebhookResourceNotFound)
.attach_printable("Failed to fetch the relay record")?,
},
_ => Err(errors::ApiErrorResponse::WebhookProcessingFailure)
.attach_printable("received a non-refund id when processing relay refund webhooks")?,
};
// if source_verified then update relay status else trigger relay force sync
let relay_response = if source_verified {
let relay_update = hyperswitch_domain_models::relay::RelayUpdate::StatusUpdate {
connector_reference_id: None,
status: common_enums::RelayStatus::foreign_try_from(event_type)
.change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
.attach_printable("failed relay refund status mapping from event type")?,
};
db.update_relay(
key_manager_state,
merchant_context.get_merchant_key_store(),
relay_record,
relay_update,
)
.await
.map(api_models::relay::RelayResponse::from)
.to_not_found_response(errors::ApiErrorResponse::WebhookResourceNotFound)
.attach_printable("Failed to update relay")?
} else {
let relay_retrieve_request = api_models::relay::RelayRetrieveRequest {
force_sync: true,
id: relay_record.id,
};
let relay_force_sync_response = Box::pin(relay::relay_retrieve(
state,
merchant_context,
Some(business_profile.get_id().clone()),
relay_retrieve_request,
))
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to force sync relay")?;
if let hyperswitch_domain_models::api::ApplicationResponse::Json(response) =
relay_force_sync_response
{
response
} else {
Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unexpected response from force sync relay")?
}
};
Ok(WebhookResponseTracker::Relay {
relay_id: relay_response.id,
status: relay_response.status,
})
}
#[allow(clippy::too_many_arguments)]
#[instrument(skip_all)]
async fn refunds_incoming_webhook_flow(
state: SessionState,
merchant_context: domain::MerchantContext,
business_profile: domain::Profile,
webhook_details: api::IncomingWebhookDetails,
connector_name: &str,
source_verified: bool,
event_type: webhooks::IncomingWebhookEvent,
) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> {
let db = &*state.store;
//find refund by connector refund id
let refund = match webhook_details.object_reference_id {
webhooks::ObjectReferenceId::RefundId(refund_id_type) => match refund_id_type {
webhooks::RefundIdType::RefundId(id) => db
.find_refund_by_merchant_id_refund_id(
merchant_context.get_merchant_account().get_id(),
&id,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::WebhookResourceNotFound)
.attach_printable("Failed to fetch the refund")?,
webhooks::RefundIdType::ConnectorRefundId(id) => db
.find_refund_by_merchant_id_connector_refund_id_connector(
merchant_context.get_merchant_account().get_id(),
&id,
connector_name,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::WebhookResourceNotFound)
.attach_printable("Failed to fetch the refund")?,
},
_ => Err(errors::ApiErrorResponse::WebhookProcessingFailure)
.attach_printable("received a non-refund id when processing refund webhooks")?,
};
let refund_id = refund.refund_id.to_owned();
//if source verified then update refund status else trigger refund sync
let updated_refund = if source_verified {
let refund_update = diesel_refund::RefundUpdate::StatusUpdate {
connector_refund_id: None,
sent_to_gateway: true,
refund_status: common_enums::RefundStatus::foreign_try_from(event_type)
.change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
.attach_printable("failed refund status mapping from event type")?,
updated_by: merchant_context
.get_merchant_account()
.storage_scheme
.to_string(),
processor_refund_data: None,
};
db.update_refund(
refund.to_owned(),
refund_update,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::WebhookResourceNotFound)
.attach_printable_lazy(|| format!("Failed while updating refund: refund_id: {refund_id}"))?
} else {
Box::pin(refunds::refund_retrieve_core_with_refund_id(
state.clone(),
merchant_context.clone(),
None,
api_models::refunds::RefundsRetrieveRequest {
refund_id: refund_id.to_owned(),
force_sync: Some(true),
merchant_connector_details: None,
},
))
.await
.attach_printable_lazy(|| format!("Failed while updating refund: refund_id: {refund_id}"))?
};
let event_type: Option<enums::EventType> = updated_refund.refund_status.into();
// If event is NOT an UnsupportedEvent, trigger Outgoing Webhook
if let Some(outgoing_event_type) = event_type {
let refund_response: api_models::refunds::RefundResponse =
updated_refund.clone().foreign_into();
Box::pin(super::create_event_and_trigger_outgoing_webhook(
state,
merchant_context,
business_profile,
outgoing_event_type,
enums::EventClass::Refunds,
refund_id,
enums::EventObjectType::RefundDetails,
api::OutgoingWebhookContent::RefundDetails(Box::new(refund_response)),
Some(updated_refund.created_at),
))
.await?;
}
Ok(WebhookResponseTracker::Refund {
payment_id: updated_refund.payment_id,
refund_id: updated_refund.refund_id,
status: updated_refund.refund_status,
})
}
async fn relay_incoming_webhook_flow(
state: SessionState,
merchant_context: domain::MerchantContext,
business_profile: domain::Profile,
webhook_details: api::IncomingWebhookDetails,
event_type: webhooks::IncomingWebhookEvent,
source_verified: bool,
) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> {
let flow_type: api::WebhookFlow = event_type.into();
let result_response = match flow_type {
webhooks::WebhookFlow::Refund => Box::pin(relay_refunds_incoming_webhook_flow(
state,
merchant_context,
business_profile,
webhook_details,
event_type,
source_verified,
))
.await
.attach_printable("Incoming webhook flow for relay refund failed")?,
webhooks::WebhookFlow::Payment
| webhooks::WebhookFlow::Payout
| webhooks::WebhookFlow::Dispute
| webhooks::WebhookFlow::Subscription
| webhooks::WebhookFlow::ReturnResponse
| webhooks::WebhookFlow::BankTransfer
| webhooks::WebhookFlow::Mandate
| webhooks::WebhookFlow::Setup
| webhooks::WebhookFlow::ExternalAuthentication
| webhooks::WebhookFlow::FraudCheck => Err(errors::ApiErrorResponse::NotSupported {
message: "Relay webhook flow types not supported".to_string(),
})?,
};
Ok(result_response)
}
pub async fn get_payment_attempt_from_object_reference_id(
state: &SessionState,
object_reference_id: webhooks::ObjectReferenceId,
merchant_context: &domain::MerchantContext,
) -> CustomResult<PaymentAttempt, errors::ApiErrorResponse> {
let db = &*state.store;
match object_reference_id {
api::ObjectReferenceId::PaymentId(api::PaymentIdType::ConnectorTransactionId(ref id)) => db
.find_payment_attempt_by_merchant_id_connector_txn_id(
merchant_context.get_merchant_account().get_id(),
id,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::WebhookResourceNotFound),
api::ObjectReferenceId::PaymentId(api::PaymentIdType::PaymentAttemptId(ref id)) => db
.find_payment_attempt_by_attempt_id_merchant_id(
id,
merchant_context.get_merchant_account().get_id(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::WebhookResourceNotFound),
api::ObjectReferenceId::PaymentId(api::PaymentIdType::PreprocessingId(ref id)) => db
.find_payment_attempt_by_preprocessing_id_merchant_id(
id,
merchant_context.get_merchant_account().get_id(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::WebhookResourceNotFound),
_ => Err(errors::ApiErrorResponse::WebhookProcessingFailure)
.attach_printable("received a non-payment id for retrieving payment")?,
}
}
#[allow(clippy::too_many_arguments)]
pub async fn get_or_update_dispute_object(
state: SessionState,
option_dispute: Option<diesel_models::dispute::Dispute>,
dispute_details: api::disputes::DisputePayload,
merchant_id: &common_utils::id_type::MerchantId,
organization_id: &common_utils::id_type::OrganizationId,
payment_attempt: &PaymentAttempt,
dispute_status: common_enums::enums::DisputeStatus,
business_profile: &domain::Profile,
connector_name: &str,
) -> CustomResult<diesel_models::dispute::Dispute, errors::ApiErrorResponse> {
let db = &*state.store;
match option_dispute {
None => {
metrics::INCOMING_DISPUTE_WEBHOOK_NEW_RECORD_METRIC.add(1, &[]);
let dispute_id = generate_id(consts::ID_LENGTH, "dp");
let new_dispute = diesel_models::dispute::DisputeNew {
dispute_id,
amount: dispute_details.amount.clone(),
currency: dispute_details.currency.to_string(),
dispute_stage: dispute_details.dispute_stage,
dispute_status,
payment_id: payment_attempt.payment_id.to_owned(),
connector: connector_name.to_owned(),
attempt_id: payment_attempt.attempt_id.to_owned(),
merchant_id: merchant_id.to_owned(),
connector_status: dispute_details.connector_status,
connector_dispute_id: dispute_details.connector_dispute_id,
connector_reason: dispute_details.connector_reason,
connector_reason_code: dispute_details.connector_reason_code,
challenge_required_by: dispute_details.challenge_required_by,
connector_created_at: dispute_details.created_at,
connector_updated_at: dispute_details.updated_at,
profile_id: Some(business_profile.get_id().to_owned()),
evidence: None,
merchant_connector_id: payment_attempt.merchant_connector_id.clone(),
dispute_amount: StringMinorUnitForConnector::convert_back(
&StringMinorUnitForConnector,
dispute_details.amount,
dispute_details.currency,
)
.change_context(
errors::ApiErrorResponse::AmountConversionFailed {
amount_type: "MinorUnit",
},
)?,
organization_id: organization_id.clone(),
dispute_currency: Some(dispute_details.currency),
};
state
.store
.insert_dispute(new_dispute.clone())
.await
.to_not_found_response(errors::ApiErrorResponse::WebhookResourceNotFound)
}
Some(dispute) => {
logger::info!("Dispute Already exists, Updating the dispute details");
metrics::INCOMING_DISPUTE_WEBHOOK_UPDATE_RECORD_METRIC.add(1, &[]);
core_utils::validate_dispute_stage_and_dispute_status(
dispute.dispute_stage,
dispute.dispute_status,
dispute_details.dispute_stage,
dispute_status,
)
.change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
.attach_printable("dispute stage and status validation failed")?;
let update_dispute = diesel_models::dispute::DisputeUpdate::Update {
dispute_stage: dispute_details.dispute_stage,
dispute_status,
connector_status: dispute_details.connector_status,
connector_reason: dispute_details.connector_reason,
connector_reason_code: dispute_details.connector_reason_code,
challenge_required_by: dispute_details.challenge_required_by,
connector_updated_at: dispute_details.updated_at,
};
db.update_dispute(dispute, update_dispute)
.await
.to_not_found_response(errors::ApiErrorResponse::WebhookResourceNotFound)
}
}
}
#[allow(clippy::too_many_arguments)]
#[instrument(skip_all)]
async fn external_authentication_incoming_webhook_flow(
state: SessionState,
req_state: ReqState,
merchant_context: domain::MerchantContext,
source_verified: bool,
event_type: webhooks::IncomingWebhookEvent,
request_details: &IncomingWebhookRequestDetails<'_>,
connector: &ConnectorEnum,
object_ref_id: api::ObjectReferenceId,
business_profile: domain::Profile,
merchant_connector_account: domain::MerchantConnectorAccount,
) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> {
if source_verified {
let authentication_details = connector
.get_external_authentication_details(request_details)
.switch()?;
let trans_status = authentication_details.trans_status;
let authentication_update = storage::AuthenticationUpdate::PostAuthenticationUpdate {
authentication_status: common_enums::AuthenticationStatus::foreign_from(
trans_status.clone(),
),
trans_status,
eci: authentication_details.eci,
challenge_cancel: authentication_details.challenge_cancel,
challenge_code_reason: authentication_details.challenge_code_reason,
};
let authentication =
if let webhooks::ObjectReferenceId::ExternalAuthenticationID(authentication_id_type) =
object_ref_id
{
match authentication_id_type {
webhooks::AuthenticationIdType::AuthenticationId(authentication_id) => state
.store
.find_authentication_by_merchant_id_authentication_id(
merchant_context.get_merchant_account().get_id(),
&authentication_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::AuthenticationNotFound {
id: authentication_id.get_string_repr().to_string(),
})
.attach_printable("Error while fetching authentication record"),
webhooks::AuthenticationIdType::ConnectorAuthenticationId(
connector_authentication_id,
) => state
.store
.find_authentication_by_merchant_id_connector_authentication_id(
merchant_context.get_merchant_account().get_id().clone(),
connector_authentication_id.clone(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::AuthenticationNotFound {
id: connector_authentication_id,
})
.attach_printable("Error while fetching authentication record"),
}
} else {
Err(errors::ApiErrorResponse::WebhookProcessingFailure).attach_printable(
"received a non-external-authentication id for retrieving authentication",
)
}?;
let updated_authentication = state
.store
.update_authentication_by_merchant_id_authentication_id(
authentication,
authentication_update,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error while updating authentication")?;
authentication_details
.authentication_value
.async_map(|auth_val| {
payment_methods::vault::create_tokenize(
&state,
auth_val.expose(),
None,
updated_authentication
.authentication_id
.clone()
.get_string_repr()
.to_string(),
merchant_context.get_merchant_key_store().key.get_inner(),
)
})
.await
.transpose()?;
// Check if it's a payment authentication flow, payment_id would be there only for payment authentication flows
if let Some(payment_id) = updated_authentication.payment_id {
let is_pull_mechanism_enabled = helper_utils::check_if_pull_mechanism_for_external_3ds_enabled_from_connector_metadata(merchant_connector_account.metadata.map(|metadata| metadata.expose()));
// Merchant doesn't have pull mechanism enabled and if it's challenge flow, we have to authorize whenever we receive a ARes webhook
if !is_pull_mechanism_enabled
&& updated_authentication.authentication_type
== Some(common_enums::DecoupledAuthenticationType::Challenge)
&& event_type == webhooks::IncomingWebhookEvent::ExternalAuthenticationARes
{
let payment_confirm_req = api::PaymentsRequest {
payment_id: Some(api_models::payments::PaymentIdType::PaymentIntentId(
payment_id,
)),
merchant_id: Some(merchant_context.get_merchant_account().get_id().clone()),
..Default::default()
};
let payments_response = Box::pin(payments::payments_core::<
api::Authorize,
api::PaymentsResponse,
_,
_,
_,
payments::PaymentData<api::Authorize>,
>(
state.clone(),
req_state,
merchant_context.clone(),
None,
payments::PaymentConfirm,
payment_confirm_req,
services::api::AuthFlow::Merchant,
payments::CallConnectorAction::Trigger,
None,
HeaderPayload::with_source(enums::PaymentSource::ExternalAuthenticator),
))
.await?;
match payments_response {
services::ApplicationResponse::JsonWithHeaders((payments_response, _)) => {
let payment_id = payments_response.payment_id.clone();
let status = payments_response.status;
let event_type: Option<enums::EventType> = payments_response.status.into();
// Set poll_id as completed in redis to allow the fetch status of poll through retrieve_poll_status api from client
let poll_id = core_utils::get_poll_id(
merchant_context.get_merchant_account().get_id(),
core_utils::get_external_authentication_request_poll_id(&payment_id),
);
let redis_conn = state
.store
.get_redis_conn()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get redis connection")?;
redis_conn
.set_key_without_modifying_ttl(
&poll_id.into(),
api_models::poll::PollStatus::Completed.to_string(),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to add poll_id in redis")?;
// If event is NOT an UnsupportedEvent, trigger Outgoing Webhook
if let Some(outgoing_event_type) = event_type {
let primary_object_created_at = payments_response.created;
Box::pin(super::create_event_and_trigger_outgoing_webhook(
state,
merchant_context,
business_profile,
outgoing_event_type,
enums::EventClass::Payments,
payment_id.get_string_repr().to_owned(),
enums::EventObjectType::PaymentDetails,
api::OutgoingWebhookContent::PaymentDetails(Box::new(
payments_response,
)),
primary_object_created_at,
))
.await?;
};
let response = WebhookResponseTracker::Payment { payment_id, status };
Ok(response)
}
_ => Err(errors::ApiErrorResponse::WebhookProcessingFailure).attach_printable(
"Did not get payment id as object reference id in webhook payments flow",
)?,
}
} else {
Ok(WebhookResponseTracker::NoEffect)
}
} else {
Ok(WebhookResponseTracker::NoEffect)
}
} else {
logger::error!(
"Webhook source verification failed for external authentication webhook flow"
);
Err(report!(
errors::ApiErrorResponse::WebhookAuthenticationFailed
))
}
}
#[instrument(skip_all)]
async fn mandates_incoming_webhook_flow(
state: SessionState,
merchant_context: domain::MerchantContext,
business_profile: domain::Profile,
webhook_details: api::IncomingWebhookDetails,
source_verified: bool,
event_type: webhooks::IncomingWebhookEvent,
) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> {
if source_verified {
let db = &*state.store;
let mandate = match webhook_details.object_reference_id {
webhooks::ObjectReferenceId::MandateId(webhooks::MandateIdType::MandateId(
mandate_id,
)) => db
.find_mandate_by_merchant_id_mandate_id(
merchant_context.get_merchant_account().get_id(),
mandate_id.as_str(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?,
webhooks::ObjectReferenceId::MandateId(
webhooks::MandateIdType::ConnectorMandateId(connector_mandate_id),
) => db
.find_mandate_by_merchant_id_connector_mandate_id(
merchant_context.get_merchant_account().get_id(),
connector_mandate_id.as_str(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?,
_ => Err(errors::ApiErrorResponse::WebhookProcessingFailure)
.attach_printable("received a non-mandate id for retrieving mandate")?,
};
let mandate_status = common_enums::MandateStatus::foreign_try_from(event_type)
.change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
.attach_printable("event type to mandate status mapping failed")?;
let mandate_id = mandate.mandate_id.clone();
let updated_mandate = db
.update_mandate_by_merchant_id_mandate_id(
merchant_context.get_merchant_account().get_id(),
&mandate_id,
storage::MandateUpdate::StatusUpdate { mandate_status },
mandate,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?;
let mandates_response = Box::new(
api::mandates::MandateResponse::from_db_mandate(
&state,
merchant_context.get_merchant_key_store().clone(),
updated_mandate.clone(),
merchant_context.get_merchant_account(),
)
.await?,
);
let event_type: Option<enums::EventType> = updated_mandate.mandate_status.into();
if let Some(outgoing_event_type) = event_type {
Box::pin(super::create_event_and_trigger_outgoing_webhook(
state,
merchant_context,
business_profile,
outgoing_event_type,
enums::EventClass::Mandates,
updated_mandate.mandate_id.clone(),
enums::EventObjectType::MandateDetails,
api::OutgoingWebhookContent::MandateDetails(mandates_response),
Some(updated_mandate.created_at),
))
.await?;
}
Ok(WebhookResponseTracker::Mandate {
mandate_id: updated_mandate.mandate_id,
status: updated_mandate.mandate_status,
})
} else {
logger::error!("Webhook source verification failed for mandates webhook flow");
Err(report!(
errors::ApiErrorResponse::WebhookAuthenticationFailed
))
}
}
#[allow(clippy::too_many_arguments)]
#[instrument(skip_all)]
async fn frm_incoming_webhook_flow(
state: SessionState,
req_state: ReqState,
merchant_context: domain::MerchantContext,
source_verified: bool,
event_type: webhooks::IncomingWebhookEvent,
object_ref_id: api::ObjectReferenceId,
business_profile: domain::Profile,
) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> {
if source_verified {
let payment_attempt =
get_payment_attempt_from_object_reference_id(&state, object_ref_id, &merchant_context)
.await?;
let payment_response = match event_type {
webhooks::IncomingWebhookEvent::FrmApproved => {
Box::pin(payments::payments_core::<
api::Capture,
api::PaymentsResponse,
_,
_,
_,
payments::PaymentData<api::Capture>,
>(
state.clone(),
req_state,
merchant_context.clone(),
None,
payments::PaymentApprove,
api::PaymentsCaptureRequest {
payment_id: payment_attempt.payment_id,
amount_to_capture: payment_attempt.amount_to_capture,
..Default::default()
},
services::api::AuthFlow::Merchant,
payments::CallConnectorAction::Trigger,
None,
HeaderPayload::default(),
))
.await?
}
webhooks::IncomingWebhookEvent::FrmRejected => {
Box::pin(payments::payments_core::<
api::Void,
api::PaymentsResponse,
_,
_,
_,
payments::PaymentData<api::Void>,
>(
state.clone(),
req_state,
merchant_context.clone(),
None,
payments::PaymentReject,
api::PaymentsCancelRequest {
payment_id: payment_attempt.payment_id.clone(),
cancellation_reason: Some(
"Rejected by merchant based on FRM decision".to_string(),
),
..Default::default()
},
services::api::AuthFlow::Merchant,
payments::CallConnectorAction::Trigger,
None,
HeaderPayload::default(),
))
.await?
}
_ => Err(errors::ApiErrorResponse::EventNotFound)?,
};
match payment_response {
services::ApplicationResponse::JsonWithHeaders((payments_response, _)) => {
let payment_id = payments_response.payment_id.clone();
let status = payments_response.status;
let event_type: Option<enums::EventType> = payments_response.status.into();
if let Some(outgoing_event_type) = event_type {
let primary_object_created_at = payments_response.created;
Box::pin(super::create_event_and_trigger_outgoing_webhook(
state,
merchant_context,
business_profile,
outgoing_event_type,
enums::EventClass::Payments,
payment_id.get_string_repr().to_owned(),
enums::EventObjectType::PaymentDetails,
api::OutgoingWebhookContent::PaymentDetails(Box::new(payments_response)),
primary_object_created_at,
))
.await?;
};
let response = WebhookResponseTracker::Payment { payment_id, status };
Ok(response)
}
_ => Err(errors::ApiErrorResponse::WebhookProcessingFailure).attach_printable(
"Did not get payment id as object reference id in webhook payments flow",
)?,
}
} else {
logger::error!("Webhook source verification failed for frm webhooks flow");
Err(report!(
errors::ApiErrorResponse::WebhookAuthenticationFailed
))
}
}
#[allow(clippy::too_many_arguments)]
#[instrument(skip_all)]
async fn disputes_incoming_webhook_flow(
state: SessionState,
merchant_context: domain::MerchantContext,
business_profile: domain::Profile,
webhook_details: api::IncomingWebhookDetails,
source_verified: bool,
connector: &ConnectorEnum,
request_details: &IncomingWebhookRequestDetails<'_>,
event_type: webhooks::IncomingWebhookEvent,
) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> {
metrics::INCOMING_DISPUTE_WEBHOOK_METRIC.add(1, &[]);
if source_verified {
let db = &*state.store;
let dispute_details = connector.get_dispute_details(request_details).switch()?;
let payment_attempt = get_payment_attempt_from_object_reference_id(
&state,
webhook_details.object_reference_id,
&merchant_context,
)
.await?;
let option_dispute = db
.find_by_merchant_id_payment_id_connector_dispute_id(
merchant_context.get_merchant_account().get_id(),
&payment_attempt.payment_id,
&dispute_details.connector_dispute_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::WebhookResourceNotFound)?;
let dispute_status = common_enums::DisputeStatus::foreign_try_from(event_type)
.change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
.attach_printable("event type to dispute status mapping failed")?;
let dispute_object = get_or_update_dispute_object(
state.clone(),
option_dispute,
dispute_details,
merchant_context.get_merchant_account().get_id(),
&merchant_context.get_merchant_account().organization_id,
&payment_attempt,
dispute_status,
&business_profile,
connector.id(),
)
.await?;
let disputes_response = Box::new(dispute_object.clone().foreign_into());
let event_type: enums::EventType = dispute_object.dispute_status.into();
Box::pin(super::create_event_and_trigger_outgoing_webhook(
state,
merchant_context,
business_profile,
event_type,
enums::EventClass::Disputes,
dispute_object.dispute_id.clone(),
enums::EventObjectType::DisputeDetails,
api::OutgoingWebhookContent::DisputeDetails(disputes_response),
Some(dispute_object.created_at),
))
.await?;
metrics::INCOMING_DISPUTE_WEBHOOK_MERCHANT_NOTIFIED_METRIC.add(1, &[]);
Ok(WebhookResponseTracker::Dispute {
dispute_id: dispute_object.dispute_id,
payment_id: dispute_object.payment_id,
status: dispute_object.dispute_status,
})
} else {
metrics::INCOMING_DISPUTE_WEBHOOK_SIGNATURE_FAILURE_METRIC.add(1, &[]);
Err(report!(
errors::ApiErrorResponse::WebhookAuthenticationFailed
))
}
}
#[instrument(skip_all)]
async fn bank_transfer_webhook_flow(
state: SessionState,
req_state: ReqState,
merchant_context: domain::MerchantContext,
business_profile: domain::Profile,
webhook_details: api::IncomingWebhookDetails,
source_verified: bool,
) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> {
let response = if source_verified {
let payment_attempt = get_payment_attempt_from_object_reference_id(
&state,
webhook_details.object_reference_id,
&merchant_context,
)
.await?;
let payment_id = payment_attempt.payment_id;
let request = api::PaymentsRequest {
payment_id: Some(api_models::payments::PaymentIdType::PaymentIntentId(
payment_id,
)),
payment_token: payment_attempt.payment_token,
..Default::default()
};
Box::pin(payments::payments_core::<
api::Authorize,
api::PaymentsResponse,
_,
_,
_,
payments::PaymentData<api::Authorize>,
>(
state.clone(),
req_state,
merchant_context.to_owned(),
None,
payments::PaymentConfirm,
request,
services::api::AuthFlow::Merchant,
payments::CallConnectorAction::Trigger,
None,
HeaderPayload::with_source(common_enums::PaymentSource::Webhook),
))
.await
} else {
Err(report!(
errors::ApiErrorResponse::WebhookAuthenticationFailed
))
};
match response? {
services::ApplicationResponse::JsonWithHeaders((payments_response, _)) => {
let payment_id = payments_response.payment_id.clone();
let event_type: Option<enums::EventType> = payments_response.status.into();
let status = payments_response.status;
// If event is NOT an UnsupportedEvent, trigger Outgoing Webhook
if let Some(outgoing_event_type) = event_type {
let primary_object_created_at = payments_response.created;
Box::pin(super::create_event_and_trigger_outgoing_webhook(
state,
merchant_context,
business_profile,
outgoing_event_type,
enums::EventClass::Payments,
payment_id.get_string_repr().to_owned(),
enums::EventObjectType::PaymentDetails,
api::OutgoingWebhookContent::PaymentDetails(Box::new(payments_response)),
primary_object_created_at,
))
.await?;
}
Ok(WebhookResponseTracker::Payment { payment_id, status })
}
_ => Err(errors::ApiErrorResponse::WebhookProcessingFailure)
.attach_printable("received non-json response from payments core")?,
}
}
async fn get_payment_id(
db: &dyn StorageInterface,
payment_id: &api::PaymentIdType,
merchant_id: &common_utils::id_type::MerchantId,
storage_scheme: enums::MerchantStorageScheme,
) -> errors::RouterResult<common_utils::id_type::PaymentId> {
let pay_id = || async {
match payment_id {
api_models::payments::PaymentIdType::PaymentIntentId(ref id) => Ok(id.to_owned()),
api_models::payments::PaymentIdType::ConnectorTransactionId(ref id) => db
.find_payment_attempt_by_merchant_id_connector_txn_id(
merchant_id,
id,
storage_scheme,
)
.await
.map(|p| p.payment_id),
api_models::payments::PaymentIdType::PaymentAttemptId(ref id) => db
.find_payment_attempt_by_attempt_id_merchant_id(id, merchant_id, storage_scheme)
.await
.map(|p| p.payment_id),
api_models::payments::PaymentIdType::PreprocessingId(ref id) => db
.find_payment_attempt_by_preprocessing_id_merchant_id(
id,
merchant_id,
storage_scheme,
)
.await
.map(|p| p.payment_id),
}
};
pay_id()
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)
}
#[inline]
async fn verify_webhook_source_verification_call(
connector: ConnectorEnum,
state: &SessionState,
merchant_context: &domain::MerchantContext,
merchant_connector_account: domain::MerchantConnectorAccount,
connector_name: &str,
request_details: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<bool, errors::ConnectorError> {
let connector_data = ConnectorData::get_connector_by_name(
&state.conf.connectors,
connector_name,
GetToken::Connector,
None,
)
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)
.attach_printable("invalid connector name received in payment attempt")?;
let connector_integration: services::BoxedWebhookSourceVerificationConnectorIntegrationInterface<
hyperswitch_domain_models::router_flow_types::VerifyWebhookSource,
VerifyWebhookSourceRequestData,
VerifyWebhookSourceResponseData,
> = connector_data.connector.get_connector_integration();
let connector_webhook_secrets = connector
.get_webhook_source_verification_merchant_secret(
merchant_context.get_merchant_account().get_id(),
connector_name,
merchant_connector_account.connector_webhook_details.clone(),
)
.await
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;
let router_data = construct_webhook_router_data(
state,
connector_name,
merchant_connector_account,
merchant_context,
&connector_webhook_secrets,
request_details,
)
.await
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)
.attach_printable("Failed while constructing webhook router data")?;
let response = services::execute_connector_processing_step(
state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await?;
let verification_result = response
.response
.map(|response| response.verify_webhook_status);
match verification_result {
Ok(VerifyWebhookStatus::SourceVerified) => Ok(true),
_ => Ok(false),
}
}
pub fn get_connector_by_connector_name(
state: &SessionState,
connector_name: &str,
merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
) -> CustomResult<(ConnectorEnum, String), errors::ApiErrorResponse> {
let authentication_connector =
api_models::enums::convert_authentication_connector(connector_name);
#[cfg(feature = "frm")]
{
let frm_connector = api_models::enums::convert_frm_connector(connector_name);
if frm_connector.is_some() {
let frm_connector_data =
api::FraudCheckConnectorData::get_connector_by_name(connector_name)?;
return Ok((
frm_connector_data.connector,
frm_connector_data.connector_name.to_string(),
));
}
}
let (connector, connector_name) = if authentication_connector.is_some() {
let authentication_connector_data =
api::AuthenticationConnectorData::get_connector_by_name(connector_name)?;
(
authentication_connector_data.connector,
authentication_connector_data.connector_name.to_string(),
)
} else {
let connector_data = ConnectorData::get_connector_by_name(
&state.conf.connectors,
connector_name,
GetToken::Connector,
merchant_connector_id,
)
.change_context(errors::ApiErrorResponse::InvalidRequestData {
message: "invalid connector name received".to_string(),
})
.attach_printable("Failed construction of ConnectorData")?;
(
connector_data.connector,
connector_data.connector_name.to_string(),
)
};
Ok((connector, connector_name))
}
/// This function fetches the merchant connector account ( if the url used is /{merchant_connector_id})
/// if merchant connector id is not passed in the request, then this will return None for mca
async fn fetch_optional_mca_and_connector(
state: &SessionState,
merchant_context: &domain::MerchantContext,
connector_name_or_mca_id: &str,
) -> CustomResult<
(
Option<domain::MerchantConnectorAccount>,
ConnectorEnum,
String,
),
errors::ApiErrorResponse,
> {
let db = &state.store;
if connector_name_or_mca_id.starts_with("mca_") {
#[cfg(feature = "v1")]
let mca = db
.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
&state.into(),
merchant_context.get_merchant_account().get_id(),
&common_utils::id_type::MerchantConnectorAccountId::wrap(
connector_name_or_mca_id.to_owned(),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Error while converting MerchanConnectorAccountId from string
",
)?,
merchant_context.get_merchant_key_store(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: connector_name_or_mca_id.to_string(),
})
.attach_printable(
"error while fetching merchant_connector_account from connector_id",
)?;
#[cfg(feature = "v2")]
let mca: domain::MerchantConnectorAccount = {
let _ = merchant_account;
let _ = key_store;
let _ = db;
todo!()
};
let (connector, connector_name) =
get_connector_by_connector_name(state, &mca.connector_name, Some(mca.get_id()))?;
Ok((Some(mca), connector, connector_name))
} else {
// Merchant connector account is already being queried, it is safe to set connector id as None
let (connector, connector_name) =
get_connector_by_connector_name(state, connector_name_or_mca_id, None)?;
Ok((None, connector, connector_name))
}
}
fn should_update_connector_mandate_details(
source_verified: bool,
event_type: webhooks::IncomingWebhookEvent,
) -> bool {
source_verified && event_type == webhooks::IncomingWebhookEvent::PaymentIntentSuccess
}
async fn update_connector_mandate_details(
state: &SessionState,
merchant_context: &domain::MerchantContext,
object_ref_id: api::ObjectReferenceId,
connector: &ConnectorEnum,
request_details: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<(), errors::ApiErrorResponse> {
let webhook_connector_mandate_details = connector
.get_mandate_details(request_details)
.switch()
.attach_printable("Could not find connector mandate details in incoming webhook body")?;
let webhook_connector_network_transaction_id = connector
.get_network_txn_id(request_details)
.switch()
.attach_printable(
"Could not find connector network transaction id in incoming webhook body",
)?;
// Either one OR both of the fields are present
if webhook_connector_mandate_details.is_some()
|| webhook_connector_network_transaction_id.is_some()
{
let payment_attempt =
get_payment_attempt_from_object_reference_id(state, object_ref_id, merchant_context)
.await?;
if let Some(ref payment_method_id) = payment_attempt.payment_method_id {
let key_manager_state = &state.into();
let payment_method_info = state
.store
.find_payment_method(
key_manager_state,
merchant_context.get_merchant_key_store(),
payment_method_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
// Update connector's mandate details
let updated_connector_mandate_details =
if let Some(webhook_mandate_details) = webhook_connector_mandate_details {
let mandate_details = payment_method_info
.get_common_mandate_reference()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to deserialize to Payment Mandate Reference")?;
let merchant_connector_account_id = payment_attempt
.merchant_connector_id
.clone()
.get_required_value("merchant_connector_id")?;
if mandate_details.payments.as_ref().is_none_or(|payments| {
!payments.0.contains_key(&merchant_connector_account_id)
}) {
// Update the payment attempt to maintain consistency across tables.
let (mandate_metadata, connector_mandate_request_reference_id) =
payment_attempt
.connector_mandate_detail
.as_ref()
.map(|details| {
(
details.mandate_metadata.clone(),
details.connector_mandate_request_reference_id.clone(),
)
})
.unwrap_or((None, None));
let connector_mandate_reference_id = ConnectorMandateReferenceId {
connector_mandate_id: Some(
webhook_mandate_details
.connector_mandate_id
.peek()
.to_string(),
),
payment_method_id: Some(payment_method_id.to_string()),
mandate_metadata,
connector_mandate_request_reference_id,
};
let attempt_update =
storage::PaymentAttemptUpdate::ConnectorMandateDetailUpdate {
connector_mandate_detail: Some(connector_mandate_reference_id),
updated_by: merchant_context
.get_merchant_account()
.storage_scheme
.to_string(),
};
state
.store
.update_payment_attempt_with_attempt_id(
payment_attempt.clone(),
attempt_update,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
insert_mandate_details(
&payment_attempt,
&webhook_mandate_details,
Some(mandate_details),
)?
} else {
logger::info!(
"Skipping connector mandate details update since they are already present."
);
None
}
} else {
None
};
let connector_mandate_details_value = updated_connector_mandate_details
.map(|common_mandate| {
common_mandate.get_mandate_details_value().map_err(|err| {
router_env::logger::error!(
"Failed to get get_mandate_details_value : {:?}",
err
);
errors::ApiErrorResponse::MandateUpdateFailed
})
})
.transpose()?;
let pm_update = diesel_models::PaymentMethodUpdate::ConnectorNetworkTransactionIdAndMandateDetailsUpdate {
connector_mandate_details: connector_mandate_details_value.map(masking::Secret::new),
network_transaction_id: webhook_connector_network_transaction_id
.map(|webhook_network_transaction_id| webhook_network_transaction_id.get_id().clone()),
};
state
.store
.update_payment_method(
key_manager_state,
merchant_context.get_merchant_key_store(),
payment_method_info,
pm_update,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update payment method in db")?;
}
}
Ok(())
}
fn insert_mandate_details(
payment_attempt: &PaymentAttempt,
webhook_mandate_details: &hyperswitch_domain_models::router_flow_types::ConnectorMandateDetails,
payment_method_mandate_details: Option<CommonMandateReference>,
) -> CustomResult<Option<CommonMandateReference>, errors::ApiErrorResponse> {
let (mandate_metadata, connector_mandate_request_reference_id) = payment_attempt
.connector_mandate_detail
.clone()
.map(|mandate_reference| {
(
mandate_reference.mandate_metadata,
mandate_reference.connector_mandate_request_reference_id,
)
})
.unwrap_or((None, None));
let connector_mandate_details = tokenization::update_connector_mandate_details(
payment_method_mandate_details,
payment_attempt.payment_method_type,
Some(
payment_attempt
.net_amount
.get_total_amount()
.get_amount_as_i64(),
),
payment_attempt.currency,
payment_attempt.merchant_connector_id.clone(),
Some(
webhook_mandate_details
.connector_mandate_id
.peek()
.to_string(),
),
mandate_metadata,
connector_mandate_request_reference_id,
)?;
Ok(connector_mandate_details)
}
|
crates/router/src/core/webhooks/incoming.rs
|
router::src::core::webhooks::incoming
| 19,504
| true
|
// File: crates/router/src/core/webhooks/webhook_events.rs
// Module: router::src::core::webhooks::webhook_events
use std::collections::HashSet;
use common_utils::{self, errors::CustomResult, fp_utils};
use error_stack::ResultExt;
use masking::PeekInterface;
use router_env::{instrument, tracing};
use crate::{
core::errors::{self, RouterResponse, StorageErrorExt},
routes::SessionState,
services::ApplicationResponse,
types::{api, domain, storage, transformers::ForeignTryFrom},
utils::{OptionExt, StringExt},
};
const INITIAL_DELIVERY_ATTEMPTS_LIST_MAX_LIMIT: i64 = 100;
const INITIAL_DELIVERY_ATTEMPTS_LIST_MAX_DAYS: i64 = 90;
#[derive(Debug)]
enum MerchantAccountOrProfile {
MerchantAccount(Box<domain::MerchantAccount>),
Profile(Box<domain::Profile>),
}
#[instrument(skip(state))]
pub async fn list_initial_delivery_attempts(
state: SessionState,
merchant_id: common_utils::id_type::MerchantId,
api_constraints: api::webhook_events::EventListConstraints,
) -> RouterResponse<api::webhook_events::TotalEventsResponse> {
let profile_id = api_constraints.profile_id.clone();
let constraints = api::webhook_events::EventListConstraintsInternal::foreign_try_from(
api_constraints.clone(),
)?;
let store = state.store.as_ref();
let key_manager_state = &(&state).into();
let (account, key_store) =
get_account_and_key_store(state.clone(), merchant_id.clone(), profile_id.clone()).await?;
let now = common_utils::date_time::now();
let events_list_begin_time =
(now.date() - time::Duration::days(INITIAL_DELIVERY_ATTEMPTS_LIST_MAX_DAYS)).midnight();
let (events, total_count) = match constraints {
api_models::webhook_events::EventListConstraintsInternal::ObjectIdFilter { object_id } => {
let events = match account {
MerchantAccountOrProfile::MerchantAccount(merchant_account) => {
store
.list_initial_events_by_merchant_id_primary_object_id(
key_manager_state,
merchant_account.get_id(),
&object_id,
&key_store,
)
.await
}
MerchantAccountOrProfile::Profile(business_profile) => {
store
.list_initial_events_by_profile_id_primary_object_id(
key_manager_state,
business_profile.get_id(),
&object_id,
&key_store,
)
.await
}
}
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to list events with specified constraints")?;
let total_count = i64::try_from(events.len())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error while converting from usize to i64")?;
(events, total_count)
}
api_models::webhook_events::EventListConstraintsInternal::GenericFilter {
created_after,
created_before,
limit,
offset,
event_classes,
event_types,
is_delivered,
} => {
let limit = match limit {
Some(limit) if limit <= INITIAL_DELIVERY_ATTEMPTS_LIST_MAX_LIMIT => Ok(Some(limit)),
Some(limit) if limit > INITIAL_DELIVERY_ATTEMPTS_LIST_MAX_LIMIT => Err(
errors::ApiErrorResponse::InvalidRequestData{
message: format!("`limit` must be a number less than {INITIAL_DELIVERY_ATTEMPTS_LIST_MAX_LIMIT}")
}
),
_ => Ok(Some(INITIAL_DELIVERY_ATTEMPTS_LIST_MAX_LIMIT)),
}?;
let offset = match offset {
Some(offset) if offset > 0 => Some(offset),
_ => None,
};
let event_classes = event_classes.unwrap_or(HashSet::new());
let mut event_types = event_types.unwrap_or(HashSet::new());
if !event_classes.is_empty() {
event_types = finalize_event_types(event_classes, event_types).await?;
}
fp_utils::when(
!created_after
.zip(created_before)
.map(|(created_after, created_before)| created_after <= created_before)
.unwrap_or(true),
|| {
Err(errors::ApiErrorResponse::InvalidRequestData { message: "The `created_after` timestamp must be an earlier timestamp compared to the `created_before` timestamp".to_string() })
},
)?;
let created_after = match created_after {
Some(created_after) => {
if created_after < events_list_begin_time {
Err(errors::ApiErrorResponse::InvalidRequestData { message: format!("`created_after` must be a timestamp within the past {INITIAL_DELIVERY_ATTEMPTS_LIST_MAX_DAYS} days.") })
} else {
Ok(created_after)
}
}
None => Ok(events_list_begin_time),
}?;
let created_before = match created_before {
Some(created_before) => {
if created_before < events_list_begin_time {
Err(errors::ApiErrorResponse::InvalidRequestData { message: format!("`created_before` must be a timestamp within the past {INITIAL_DELIVERY_ATTEMPTS_LIST_MAX_DAYS} days.") })
} else {
Ok(created_before)
}
}
None => Ok(now),
}?;
let events = match account {
MerchantAccountOrProfile::MerchantAccount(merchant_account) => {
store
.list_initial_events_by_merchant_id_constraints(
key_manager_state,
merchant_account.get_id(),
created_after,
created_before,
limit,
offset,
event_types.clone(),
is_delivered,
&key_store,
)
.await
}
MerchantAccountOrProfile::Profile(business_profile) => {
store
.list_initial_events_by_profile_id_constraints(
key_manager_state,
business_profile.get_id(),
created_after,
created_before,
limit,
offset,
event_types.clone(),
is_delivered,
&key_store,
)
.await
}
}
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to list events with specified constraints")?;
let total_count = store
.count_initial_events_by_constraints(
&merchant_id,
profile_id,
created_after,
created_before,
event_types,
is_delivered,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get total events count")?;
(events, total_count)
}
};
let events = events
.into_iter()
.map(api::webhook_events::EventListItemResponse::try_from)
.collect::<Result<Vec<_>, _>>()?;
Ok(ApplicationResponse::Json(
api::webhook_events::TotalEventsResponse::new(total_count, events),
))
}
#[instrument(skip(state))]
pub async fn list_delivery_attempts(
state: SessionState,
merchant_id: common_utils::id_type::MerchantId,
initial_attempt_id: String,
) -> RouterResponse<Vec<api::webhook_events::EventRetrieveResponse>> {
let store = state.store.as_ref();
let key_manager_state = &(&state).into();
let key_store = store
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&merchant_id,
&store.get_master_key().to_vec().into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
let events = store
.list_events_by_merchant_id_initial_attempt_id(
key_manager_state,
&merchant_id,
&initial_attempt_id,
&key_store,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to list delivery attempts for initial event")?;
if events.is_empty() {
Err(error_stack::report!(
errors::ApiErrorResponse::EventNotFound
))
.attach_printable("No delivery attempts found with the specified `initial_attempt_id`")
} else {
Ok(ApplicationResponse::Json(
events
.into_iter()
.map(api::webhook_events::EventRetrieveResponse::try_from)
.collect::<Result<Vec<_>, _>>()?,
))
}
}
#[instrument(skip(state))]
#[cfg(feature = "v1")]
pub async fn retry_delivery_attempt(
state: SessionState,
merchant_id: common_utils::id_type::MerchantId,
event_id: String,
) -> RouterResponse<api::webhook_events::EventRetrieveResponse> {
let store = state.store.as_ref();
let key_manager_state = &(&state).into();
let key_store = store
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&merchant_id,
&store.get_master_key().to_vec().into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
let event_to_retry = store
.find_event_by_merchant_id_event_id(
key_manager_state,
&key_store.merchant_id,
&event_id,
&key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::EventNotFound)?;
let business_profile_id = event_to_retry
.business_profile_id
.get_required_value("business_profile_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to read business profile ID from event to retry")?;
let business_profile = store
.find_business_profile_by_profile_id(key_manager_state, &key_store, &business_profile_id)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to find business profile")?;
let delivery_attempt = storage::enums::WebhookDeliveryAttempt::ManualRetry;
let new_event_id = super::utils::generate_event_id();
let idempotent_event_id = super::utils::get_idempotent_event_id(
&event_to_retry.primary_object_id,
event_to_retry.event_type,
delivery_attempt,
)
.change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
.attach_printable("Failed to generate idempotent event ID")?;
let now = common_utils::date_time::now();
let new_event = domain::Event {
event_id: new_event_id.clone(),
event_type: event_to_retry.event_type,
event_class: event_to_retry.event_class,
is_webhook_notified: false,
primary_object_id: event_to_retry.primary_object_id,
primary_object_type: event_to_retry.primary_object_type,
created_at: now,
merchant_id: Some(business_profile.merchant_id.clone()),
business_profile_id: Some(business_profile.get_id().to_owned()),
primary_object_created_at: event_to_retry.primary_object_created_at,
idempotent_event_id: Some(idempotent_event_id),
initial_attempt_id: event_to_retry.initial_attempt_id,
request: event_to_retry.request,
response: None,
delivery_attempt: Some(delivery_attempt),
metadata: event_to_retry.metadata,
is_overall_delivery_successful: Some(false),
};
let event = store
.insert_event(key_manager_state, new_event, &key_store)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to insert event")?;
// We only allow retrying deliveries for events with `request` populated.
let request_content = event
.request
.as_ref()
.get_required_value("request")
.change_context(errors::ApiErrorResponse::InternalServerError)?
.peek()
.parse_struct("OutgoingWebhookRequestContent")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to parse webhook event request information")?;
Box::pin(super::outgoing::trigger_webhook_and_raise_event(
state.clone(),
business_profile,
&key_store,
event,
request_content,
delivery_attempt,
None,
None,
))
.await;
let updated_event = store
.find_event_by_merchant_id_event_id(
key_manager_state,
&key_store.merchant_id,
&new_event_id,
&key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::EventNotFound)?;
Ok(ApplicationResponse::Json(
api::webhook_events::EventRetrieveResponse::try_from(updated_event)?,
))
}
async fn get_account_and_key_store(
state: SessionState,
merchant_id: common_utils::id_type::MerchantId,
profile_id: Option<common_utils::id_type::ProfileId>,
) -> errors::RouterResult<(MerchantAccountOrProfile, domain::MerchantKeyStore)> {
let store = state.store.as_ref();
let key_manager_state = &(&state).into();
let merchant_key_store = store
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&merchant_id,
&store.get_master_key().to_vec().into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
match profile_id {
// If profile ID is specified, return business profile, since a business profile is more
// specific than a merchant account.
Some(profile_id) => {
let business_profile = store
.find_business_profile_by_merchant_id_profile_id(
key_manager_state,
&merchant_key_store,
&merchant_id,
&profile_id,
)
.await
.attach_printable_lazy(|| {
format!(
"Failed to find business profile by merchant_id `{merchant_id:?}` and profile_id `{profile_id:?}`. \
The merchant_id associated with the business profile `{profile_id:?}` may be \
different than the merchant_id specified (`{merchant_id:?}`)."
)
})
.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
Ok((
MerchantAccountOrProfile::Profile(Box::new(business_profile)),
merchant_key_store,
))
}
None => {
let merchant_account = store
.find_merchant_account_by_merchant_id(
key_manager_state,
&merchant_id,
&merchant_key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
Ok((
MerchantAccountOrProfile::MerchantAccount(Box::new(merchant_account)),
merchant_key_store,
))
}
}
}
async fn finalize_event_types(
event_classes: HashSet<common_enums::EventClass>,
mut event_types: HashSet<common_enums::EventType>,
) -> CustomResult<HashSet<common_enums::EventType>, errors::ApiErrorResponse> {
// Examples:
// 1. event_classes = ["payments", "refunds"], event_types = ["payment_succeeded"]
// 2. event_classes = ["refunds"], event_types = ["payment_succeeded"]
// Create possible_event_types based on event_classes
// Example 1: possible_event_types = ["payment_*", "refund_*"]
// Example 2: possible_event_types = ["refund_*"]
let possible_event_types = event_classes
.clone()
.into_iter()
.flat_map(common_enums::EventClass::event_types)
.collect::<HashSet<_>>();
if event_types.is_empty() {
return Ok(possible_event_types);
}
// Extend event_types if disjoint with event_classes
// Example 1: event_types = ["payment_succeeded", "refund_*"], is_disjoint is used to extend "refund_*" and ignore "payment_*".
// Example 2: event_types = ["payment_succeeded", "refund_*"], is_disjoint is only used to extend "refund_*".
event_classes.into_iter().for_each(|class| {
let valid_event_types = class.event_types();
if event_types.is_disjoint(&valid_event_types) {
event_types.extend(valid_event_types);
}
});
// Validate event_types is a subset of possible_event_types
// Example 1: event_types is a subset of possible_event_types (valid)
// Example 2: event_types is not a subset of possible_event_types (error due to "payment_succeeded")
if !event_types.is_subset(&possible_event_types) {
return Err(error_stack::report!(
errors::ApiErrorResponse::InvalidRequestData {
message: "`event_types` must be a subset of `event_classes`".to_string(),
}
));
}
Ok(event_types.clone())
}
|
crates/router/src/core/webhooks/webhook_events.rs
|
router::src::core::webhooks::webhook_events
| 3,555
| true
|
// File: crates/router/src/core/webhooks/utils.rs
// Module: router::src::core::webhooks::utils
use std::marker::PhantomData;
use base64::Engine;
use common_utils::{
consts,
crypto::{self, GenerateDigest},
errors::CustomResult,
ext_traits::ValueExt,
};
use error_stack::{Report, ResultExt};
use redis_interface as redis;
use router_env::tracing;
use super::MERCHANT_ID;
use crate::{
core::{
errors::{self},
metrics,
payments::helpers,
},
db::{get_and_deserialize_key, StorageInterface},
errors::RouterResult,
routes::app::SessionStateInfo,
services::logger,
types::{self, api, domain, PaymentAddress},
SessionState,
};
const IRRELEVANT_ATTEMPT_ID_IN_SOURCE_VERIFICATION_FLOW: &str =
"irrelevant_attempt_id_in_source_verification_flow";
const IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_SOURCE_VERIFICATION_FLOW: &str =
"irrelevant_connector_request_reference_id_in_source_verification_flow";
/// Check whether the merchant has configured to disable the webhook `event` for the `connector`
/// First check for the key "whconf_{merchant_id}_{connector_id}" in redis,
/// if not found, fetch from configs table in database
pub async fn is_webhook_event_disabled(
db: &dyn StorageInterface,
connector_id: &str,
merchant_id: &common_utils::id_type::MerchantId,
event: &api::IncomingWebhookEvent,
) -> bool {
let redis_key = merchant_id.get_webhook_config_disabled_events_key(connector_id);
let merchant_webhook_disable_config_result: CustomResult<
api::MerchantWebhookConfig,
redis_interface::errors::RedisError,
> = get_and_deserialize_key(db, &redis_key, "MerchantWebhookConfig").await;
match merchant_webhook_disable_config_result {
Ok(merchant_webhook_config) => merchant_webhook_config.contains(event),
Err(..) => {
//if failed to fetch from redis. fetch from db and populate redis
db.find_config_by_key(&redis_key)
.await
.map(|config| {
match serde_json::from_str::<api::MerchantWebhookConfig>(&config.config) {
Ok(set) => set.contains(event),
Err(err) => {
logger::warn!(?err, "error while parsing merchant webhook config");
false
}
}
})
.unwrap_or_else(|err| {
logger::warn!(?err, "error while fetching merchant webhook config");
false
})
}
}
}
pub async fn construct_webhook_router_data(
state: &SessionState,
connector_name: &str,
merchant_connector_account: domain::MerchantConnectorAccount,
merchant_context: &domain::MerchantContext,
connector_wh_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
request_details: &api::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<types::VerifyWebhookSourceRouterData, errors::ApiErrorResponse> {
let auth_type: types::ConnectorAuthType =
helpers::MerchantConnectorAccountType::DbVal(Box::new(merchant_connector_account.clone()))
.get_connector_account_details()
.parse_value("ConnectorAuthType")
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let router_data = types::RouterData {
flow: PhantomData,
merchant_id: merchant_context.get_merchant_account().get_id().clone(),
connector: connector_name.to_string(),
customer_id: None,
tenant_id: state.tenant.tenant_id.clone(),
payment_id: common_utils::id_type::PaymentId::get_irrelevant_id("source_verification_flow")
.get_string_repr()
.to_owned(),
attempt_id: IRRELEVANT_ATTEMPT_ID_IN_SOURCE_VERIFICATION_FLOW.to_string(),
status: diesel_models::enums::AttemptStatus::default(),
payment_method: diesel_models::enums::PaymentMethod::default(),
payment_method_type: None,
connector_auth_type: auth_type,
description: None,
address: PaymentAddress::default(),
auth_type: diesel_models::enums::AuthenticationType::default(),
connector_meta_data: None,
connector_wallets_details: None,
amount_captured: None,
minor_amount_captured: None,
request: types::VerifyWebhookSourceRequestData {
webhook_headers: request_details.headers.clone(),
webhook_body: request_details.body.to_vec().clone(),
merchant_secret: connector_wh_secrets.to_owned(),
},
response: Err(types::ErrorResponse::default()),
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:
IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_SOURCE_VERIFICATION_FLOW.to_string(),
#[cfg(feature = "payouts")]
payout_method_data: None,
#[cfg(feature = "payouts")]
quote_id: None,
test_mode: None,
payment_method_balance: None,
payment_method_status: 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)
}
#[inline]
pub(crate) fn get_idempotent_event_id(
primary_object_id: &str,
event_type: types::storage::enums::EventType,
delivery_attempt: types::storage::enums::WebhookDeliveryAttempt,
) -> Result<String, Report<errors::WebhooksFlowError>> {
use crate::types::storage::enums::WebhookDeliveryAttempt;
const EVENT_ID_SUFFIX_LENGTH: usize = 8;
let common_prefix = format!("{primary_object_id}_{event_type}");
// Hash the common prefix with SHA256 and encode with URL-safe base64 without padding
let digest = crypto::Sha256
.generate_digest(common_prefix.as_bytes())
.change_context(errors::WebhooksFlowError::IdGenerationFailed)
.attach_printable("Failed to generate idempotent event ID")?;
let base_encoded = consts::BASE64_ENGINE_URL_SAFE_NO_PAD.encode(digest);
let result = match delivery_attempt {
WebhookDeliveryAttempt::InitialAttempt => base_encoded,
WebhookDeliveryAttempt::AutomaticRetry | WebhookDeliveryAttempt::ManualRetry => {
common_utils::generate_id(EVENT_ID_SUFFIX_LENGTH, &base_encoded)
}
};
Ok(result)
}
#[inline]
pub(crate) fn generate_event_id() -> String {
common_utils::generate_time_ordered_id("evt")
}
pub fn increment_webhook_outgoing_received_count(merchant_id: &common_utils::id_type::MerchantId) {
metrics::WEBHOOK_OUTGOING_RECEIVED_COUNT.add(
1,
router_env::metric_attributes!((MERCHANT_ID, merchant_id.clone())),
)
}
pub fn increment_webhook_outgoing_not_received_count(
merchant_id: &common_utils::id_type::MerchantId,
) {
metrics::WEBHOOK_OUTGOING_NOT_RECEIVED_COUNT.add(
1,
router_env::metric_attributes!((MERCHANT_ID, merchant_id.clone())),
);
}
pub fn is_outgoing_webhook_disabled(
state: &SessionState,
webhook_url_result: &Result<String, Report<errors::WebhooksFlowError>>,
business_profile: &domain::Profile,
idempotent_event_id: &str,
) -> bool {
if !state.conf.webhooks.outgoing_enabled
|| webhook_url_result.is_err()
|| webhook_url_result.as_ref().is_ok_and(String::is_empty)
{
logger::debug!(
business_profile_id=?business_profile.get_id(),
%idempotent_event_id,
"Outgoing webhooks are disabled in application configuration, or merchant webhook URL \
could not be obtained; skipping outgoing webhooks for event"
);
return true;
}
false
}
const WEBHOOK_LOCK_PREFIX: &str = "WEBHOOK_LOCK";
pub(super) async fn perform_redis_lock<A>(
state: &A,
unique_locking_key: &str,
merchant_id: common_utils::id_type::MerchantId,
) -> RouterResult<Option<String>>
where
A: SessionStateInfo,
{
let lock_value: String = uuid::Uuid::new_v4().to_string();
let redis_conn = state
.store()
.get_redis_conn()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error connecting to redis")?;
let redis_locking_key = format!(
"{}_{}_{}",
WEBHOOK_LOCK_PREFIX,
merchant_id.get_string_repr(),
unique_locking_key
);
let redis_lock_expiry_seconds = state.conf().webhooks.redis_lock_expiry_seconds;
let redis_lock_result = redis_conn
.set_key_if_not_exists_with_expiry(
&redis_locking_key.as_str().into(),
lock_value.clone(),
Some(i64::from(redis_lock_expiry_seconds)),
)
.await;
match redis_lock_result {
Ok(redis::SetnxReply::KeySet) => {
logger::info!("Lock acquired for for {redis_locking_key}");
Ok(Some(lock_value))
}
Ok(redis::SetnxReply::KeyNotSet) => {
logger::info!("Lock already held for {redis_locking_key}");
Ok(None)
}
Err(err) => Err(err
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error acquiring redis lock")),
}
}
pub(super) async fn free_redis_lock<A>(
state: &A,
unique_locking_key: &str,
merchant_id: common_utils::id_type::MerchantId,
lock_value: Option<String>,
) -> RouterResult<()>
where
A: SessionStateInfo,
{
let redis_conn = state
.store()
.get_redis_conn()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error connecting to redis")?;
let redis_locking_key = format!(
"{}_{}_{}",
WEBHOOK_LOCK_PREFIX,
merchant_id.get_string_repr(),
unique_locking_key
);
match redis_conn
.get_key::<Option<String>>(&redis_locking_key.as_str().into())
.await
{
Ok(val) => {
if val == lock_value {
match redis_conn
.delete_key(&redis_locking_key.as_str().into())
.await
{
Ok(redis::types::DelReply::KeyDeleted) => {
logger::info!("Lock freed {redis_locking_key}");
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)
.attach_printable("Error while deleting redis key"),
}
} else {
Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable("The redis value which acquired the lock is not equal to the redis value requesting for releasing the lock")
}
}
Err(error) => Err(error)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error while deleting redis key"),
}
}
|
crates/router/src/core/webhooks/utils.rs
|
router::src::core::webhooks::utils
| 2,579
| true
|
// File: crates/router/src/core/payment_methods/cards.rs
// Module: router::src::core::payment_methods::cards
use std::{
collections::{HashMap, HashSet},
fmt::Debug,
str::FromStr,
};
use ::payment_methods::{
configs::payment_connector_required_fields::{
get_billing_required_fields, get_shipping_required_fields,
},
controller::PaymentMethodsController,
};
#[cfg(feature = "v1")]
use api_models::admin::PaymentMethodsEnabled;
use api_models::{
enums as api_enums,
payment_methods::{
BankAccountTokenData, Card, CardDetailUpdate, CardDetailsPaymentMethod, CardNetworkTypes,
CountryCodeWithName, ListCountriesCurrenciesRequest, ListCountriesCurrenciesResponse,
MaskedBankDetails, PaymentExperienceTypes, PaymentMethodsData, RequestPaymentMethodTypes,
RequiredFieldInfo, ResponsePaymentMethodIntermediate, ResponsePaymentMethodTypes,
ResponsePaymentMethodsEnabled,
},
payments::BankCodeResponse,
pm_auth::PaymentMethodAuthConfig,
surcharge_decision_configs as api_surcharge_decision_configs,
};
use common_enums::{enums::MerchantStorageScheme, ConnectorType};
use common_utils::{
consts,
crypto::{self, Encryptable},
encryption::Encryption,
ext_traits::{AsyncExt, BytesExt, Encode, StringExt, ValueExt},
generate_id, id_type,
request::Request,
type_name,
types::{
keymanager::{Identifier, KeyManagerState},
MinorUnit,
},
};
use diesel_models::payment_method;
use error_stack::{report, ResultExt};
use euclid::{
dssa::graph::{AnalysisContext, CgraphExt},
frontend::dir,
};
use hyperswitch_constraint_graph as cgraph;
#[cfg(feature = "v1")]
use hyperswitch_domain_models::customer::CustomerUpdate;
use hyperswitch_domain_models::mandates::CommonMandateReference;
use hyperswitch_interfaces::secrets_interface::secret_state::RawSecret;
#[cfg(feature = "v1")]
use kgraph_utils::transformers::IntoDirValue;
use masking::Secret;
use router_env::{instrument, tracing};
use scheduler::errors as sch_errors;
use strum::IntoEnumIterator;
#[cfg(feature = "v1")]
use super::surcharge_decision_configs::{
perform_surcharge_decision_management_for_payment_method_list,
perform_surcharge_decision_management_for_saved_cards,
};
#[cfg(feature = "v1")]
use super::tokenize::NetworkTokenizationProcess;
#[cfg(feature = "v1")]
use crate::core::payment_methods::{
add_payment_method_status_update_task, tokenize,
utils::{get_merchant_pm_filter_graph, make_pm_graph, refresh_pm_filters_cache},
};
#[cfg(feature = "v1")]
use crate::routes::app::SessionStateInfo;
#[cfg(feature = "payouts")]
use crate::types::domain::types::AsyncLift;
use crate::{
configs::settings,
consts as router_consts,
core::{
configs,
errors::{self, StorageErrorExt},
payment_methods::{network_tokenization, transformers as payment_methods, vault},
payments::{
helpers,
routing::{self, SessionFlowRoutingInput},
},
utils as core_utils,
},
db, logger,
pii::prelude::*,
routes::{self, metrics, payment_methods::ParentPaymentMethodToken},
services,
types::{
api::{self, routing as routing_types, PaymentMethodCreateExt},
domain::{self, Profile},
storage::{self, enums, PaymentMethodListContext, PaymentTokenData},
transformers::{ForeignFrom, ForeignTryFrom},
},
utils,
utils::OptionExt,
};
#[cfg(feature = "v2")]
use crate::{
core::payment_methods as pm_core, headers, types::payment_methods as pm_types,
utils::ConnectorResponseExt,
};
pub struct PmCards<'a> {
pub state: &'a routes::SessionState,
pub merchant_context: &'a domain::MerchantContext,
}
#[async_trait::async_trait]
impl PaymentMethodsController for PmCards<'_> {
#[cfg(feature = "v1")]
#[instrument(skip_all)]
#[allow(clippy::too_many_arguments)]
async fn create_payment_method(
&self,
req: &api::PaymentMethodCreate,
customer_id: &id_type::CustomerId,
payment_method_id: &str,
locker_id: Option<String>,
merchant_id: &id_type::MerchantId,
pm_metadata: Option<serde_json::Value>,
customer_acceptance: Option<serde_json::Value>,
payment_method_data: crypto::OptionalEncryptableValue,
connector_mandate_details: Option<serde_json::Value>,
status: Option<enums::PaymentMethodStatus>,
network_transaction_id: Option<String>,
payment_method_billing_address: crypto::OptionalEncryptableValue,
card_scheme: Option<String>,
network_token_requestor_reference_id: Option<String>,
network_token_locker_id: Option<String>,
network_token_payment_method_data: crypto::OptionalEncryptableValue,
vault_source_details: Option<domain::PaymentMethodVaultSourceDetails>,
) -> errors::CustomResult<domain::PaymentMethod, errors::ApiErrorResponse> {
let db = &*self.state.store;
let customer = db
.find_customer_by_customer_id_merchant_id(
&self.state.into(),
customer_id,
merchant_id,
self.merchant_context.get_merchant_key_store(),
self.merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?;
let client_secret = generate_id(
consts::ID_LENGTH,
format!("{payment_method_id}_secret").as_str(),
);
let current_time = common_utils::date_time::now();
let response = db
.insert_payment_method(
&self.state.into(),
self.merchant_context.get_merchant_key_store(),
domain::PaymentMethod {
customer_id: customer_id.to_owned(),
merchant_id: merchant_id.to_owned(),
payment_method_id: payment_method_id.to_string(),
locker_id,
payment_method: req.payment_method,
payment_method_type: req.payment_method_type,
payment_method_issuer: req.payment_method_issuer.clone(),
scheme: req.card_network.clone().or(card_scheme),
metadata: pm_metadata.map(Secret::new),
payment_method_data,
connector_mandate_details,
customer_acceptance: customer_acceptance.map(Secret::new),
client_secret: Some(client_secret),
status: status.unwrap_or(enums::PaymentMethodStatus::Active),
network_transaction_id: network_transaction_id.to_owned(),
payment_method_issuer_code: None,
accepted_currency: None,
token: None,
cardholder_name: None,
issuer_name: None,
issuer_country: None,
payer_country: None,
is_stored: None,
swift_code: None,
direct_debit_token: None,
created_at: current_time,
last_modified: current_time,
last_used_at: current_time,
payment_method_billing_address,
updated_by: None,
version: common_types::consts::API_VERSION,
network_token_requestor_reference_id,
network_token_locker_id,
network_token_payment_method_data,
vault_source_details: vault_source_details
.unwrap_or(domain::PaymentMethodVaultSourceDetails::InternalVault),
},
self.merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to add payment method in db")?;
if customer.default_payment_method_id.is_none() && req.payment_method.is_some() {
let _ = self
.set_default_payment_method(merchant_id, customer_id, payment_method_id.to_owned())
.await
.map_err(|error| {
logger::error!(?error, "Failed to set the payment method as default")
});
}
Ok(response)
}
#[cfg(feature = "v1")]
fn store_default_payment_method(
&self,
req: &api::PaymentMethodCreate,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
) -> (
api::PaymentMethodResponse,
Option<payment_methods::DataDuplicationCheck>,
) {
let pm_id = generate_id(consts::ID_LENGTH, "pm");
let payment_method_response = api::PaymentMethodResponse {
merchant_id: merchant_id.to_owned(),
customer_id: Some(customer_id.to_owned()),
payment_method_id: pm_id,
payment_method: req.payment_method,
payment_method_type: req.payment_method_type,
#[cfg(feature = "payouts")]
bank_transfer: None,
card: None,
metadata: req.metadata.clone(),
created: Some(common_utils::date_time::now()),
recurring_enabled: Some(false), //[#219]
installment_payment_enabled: Some(false), //[#219]
payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]),
last_used_at: Some(common_utils::date_time::now()),
client_secret: None,
};
(payment_method_response, None)
}
#[cfg(feature = "v2")]
fn store_default_payment_method(
&self,
_req: &api::PaymentMethodCreate,
_customer_id: &id_type::CustomerId,
_merchant_id: &id_type::MerchantId,
) -> (
api::PaymentMethodResponse,
Option<payment_methods::DataDuplicationCheck>,
) {
todo!()
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn get_or_insert_payment_method(
&self,
req: api::PaymentMethodCreate,
resp: &mut api::PaymentMethodResponse,
customer_id: &id_type::CustomerId,
key_store: &domain::MerchantKeyStore,
) -> errors::RouterResult<domain::PaymentMethod> {
let mut payment_method_id = resp.payment_method_id.clone();
let mut locker_id = None;
let db = &*self.state.store;
let key_manager_state = &(self.state.into());
let payment_method = {
let existing_pm_by_pmid = db
.find_payment_method(
key_manager_state,
key_store,
&payment_method_id,
self.merchant_context.get_merchant_account().storage_scheme,
)
.await;
if let Err(err) = existing_pm_by_pmid {
if err.current_context().is_db_not_found() {
locker_id = Some(payment_method_id.clone());
let existing_pm_by_locker_id = db
.find_payment_method_by_locker_id(
key_manager_state,
key_store,
&payment_method_id,
self.merchant_context.get_merchant_account().storage_scheme,
)
.await;
match &existing_pm_by_locker_id {
Ok(pm) => payment_method_id.clone_from(pm.get_id()),
Err(_) => payment_method_id = generate_id(consts::ID_LENGTH, "pm"),
};
existing_pm_by_locker_id
} else {
Err(err)
}
} else {
existing_pm_by_pmid
}
};
payment_method_id.clone_into(&mut resp.payment_method_id);
match payment_method {
Ok(pm) => Ok(pm),
Err(err) => {
if err.current_context().is_db_not_found() {
self.insert_payment_method(
resp,
&req,
key_store,
self.merchant_context.get_merchant_account().get_id(),
customer_id,
resp.metadata.clone().map(|val| val.expose()),
None,
locker_id,
None,
req.network_transaction_id.clone(),
None,
None,
None,
None,
Default::default(),
)
.await
} else {
Err(err)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error while finding payment method")
}
}
}
}
#[cfg(feature = "v2")]
async fn get_or_insert_payment_method(
&self,
_req: api::PaymentMethodCreate,
_resp: &mut api::PaymentMethodResponse,
_customer_id: &id_type::CustomerId,
_key_store: &domain::MerchantKeyStore,
) -> errors::RouterResult<domain::PaymentMethod> {
todo!()
}
#[cfg(feature = "v1")]
#[allow(clippy::too_many_arguments)]
async fn save_network_token_and_update_payment_method(
&self,
req: &api::PaymentMethodMigrate,
key_store: &domain::MerchantKeyStore,
network_token_data: &api_models::payment_methods::MigrateNetworkTokenData,
network_token_requestor_ref_id: String,
pm_id: String,
) -> errors::RouterResult<bool> {
let payment_method_create_request =
api::PaymentMethodCreate::get_payment_method_create_from_payment_method_migrate(
network_token_data.network_token_number.clone(),
req,
);
let customer_id = req.customer_id.clone().get_required_value("customer_id")?;
let network_token_details = api::CardDetail {
card_number: network_token_data.network_token_number.clone(),
card_exp_month: network_token_data.network_token_exp_month.clone(),
card_exp_year: network_token_data.network_token_exp_year.clone(),
card_holder_name: network_token_data.card_holder_name.clone(),
nick_name: network_token_data.nick_name.clone(),
card_issuing_country: network_token_data.card_issuing_country.clone(),
card_network: network_token_data.card_network.clone(),
card_issuer: network_token_data.card_issuer.clone(),
card_type: network_token_data.card_type.clone(),
};
logger::debug!(
"Adding network token to locker for customer_id: {:?}",
customer_id
);
let token_resp = Box::pin(self.add_card_to_locker(
payment_method_create_request.clone(),
&network_token_details,
&customer_id,
None,
))
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Add Network Token failed");
let key_manager_state = &self.state.into();
match token_resp {
Ok(resp) => {
logger::debug!("Network token added to locker");
let (token_pm_resp, _duplication_check) = resp;
let pm_token_details = token_pm_resp.card.as_ref().map(|card| {
PaymentMethodsData::Card(CardDetailsPaymentMethod::from((card.clone(), None)))
});
let pm_network_token_data_encrypted = pm_token_details
.async_map(|pm_card| {
create_encrypted_data(key_manager_state, key_store, pm_card)
})
.await
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt payment method data")?;
let pm_update = storage::PaymentMethodUpdate::NetworkTokenDataUpdate {
network_token_requestor_reference_id: Some(network_token_requestor_ref_id),
network_token_locker_id: Some(token_pm_resp.payment_method_id),
network_token_payment_method_data: pm_network_token_data_encrypted
.map(Into::into),
};
let db = &*self.state.store;
let existing_pm = db
.find_payment_method(
&self.state.into(),
key_store,
&pm_id,
self.merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(format!(
"Failed to fetch payment method for existing pm_id: {pm_id:?} in db",
))?;
db.update_payment_method(
&self.state.into(),
key_store,
existing_pm,
pm_update,
self.merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(format!(
"Failed to update payment method for existing pm_id: {pm_id:?} in db",
))?;
logger::debug!("Network token added to locker and payment method updated");
Ok(true)
}
Err(err) => {
logger::debug!("Network token added to locker failed {:?}", err);
Ok(false)
}
}
}
#[cfg(feature = "v1")]
#[allow(clippy::too_many_arguments)]
async fn insert_payment_method(
&self,
resp: &api::PaymentMethodResponse,
req: &api::PaymentMethodCreate,
key_store: &domain::MerchantKeyStore,
merchant_id: &id_type::MerchantId,
customer_id: &id_type::CustomerId,
pm_metadata: Option<serde_json::Value>,
customer_acceptance: Option<serde_json::Value>,
locker_id: Option<String>,
connector_mandate_details: Option<serde_json::Value>,
network_transaction_id: Option<String>,
payment_method_billing_address: crypto::OptionalEncryptableValue,
network_token_requestor_reference_id: Option<String>,
network_token_locker_id: Option<String>,
network_token_payment_method_data: crypto::OptionalEncryptableValue,
vault_source_details: Option<domain::PaymentMethodVaultSourceDetails>,
) -> errors::RouterResult<domain::PaymentMethod> {
let pm_card_details = resp.card.clone().map(|card| {
PaymentMethodsData::Card(CardDetailsPaymentMethod::from((card.clone(), None)))
});
let key_manager_state = self.state.into();
let pm_data_encrypted: crypto::OptionalEncryptableValue = pm_card_details
.clone()
.async_map(|pm_card| create_encrypted_data(&key_manager_state, key_store, pm_card))
.await
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt payment method data")?;
self.create_payment_method(
req,
customer_id,
&resp.payment_method_id,
locker_id,
merchant_id,
pm_metadata,
customer_acceptance,
pm_data_encrypted,
connector_mandate_details,
None,
network_transaction_id,
payment_method_billing_address,
resp.card.clone().and_then(|card| {
card.card_network
.map(|card_network| card_network.to_string())
}),
network_token_requestor_reference_id,
network_token_locker_id,
network_token_payment_method_data,
vault_source_details,
)
.await
}
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments)]
async fn insert_payment_method(
&self,
resp: &api::PaymentMethodResponse,
req: &api::PaymentMethodCreate,
key_store: &domain::MerchantKeyStore,
merchant_id: &id_type::MerchantId,
customer_id: &id_type::CustomerId,
pm_metadata: Option<serde_json::Value>,
customer_acceptance: Option<serde_json::Value>,
locker_id: Option<String>,
connector_mandate_details: Option<serde_json::Value>,
network_transaction_id: Option<String>,
payment_method_billing_address: Option<Encryption>,
) -> errors::RouterResult<domain::PaymentMethod> {
todo!()
}
#[cfg(feature = "payouts")]
async fn add_bank_to_locker(
&self,
req: api::PaymentMethodCreate,
key_store: &domain::MerchantKeyStore,
bank: &api::BankPayout,
customer_id: &id_type::CustomerId,
) -> errors::CustomResult<
(
api::PaymentMethodResponse,
Option<payment_methods::DataDuplicationCheck>,
),
errors::VaultError,
> {
let key = key_store.key.get_inner().peek();
let payout_method_data = api::PayoutMethodData::Bank(bank.clone());
let key_manager_state: KeyManagerState = self.state.into();
let enc_data = async {
serde_json::to_value(payout_method_data.to_owned())
.map_err(|err| {
logger::error!("Error while encoding payout method data: {err:?}");
errors::VaultError::SavePaymentMethodFailed
})
.change_context(errors::VaultError::SavePaymentMethodFailed)
.attach_printable("Unable to encode payout method data")
.ok()
.map(|v| {
let secret: Secret<String> = Secret::new(v.to_string());
secret
})
.async_lift(|inner| async {
domain::types::crypto_operation(
&key_manager_state,
type_name!(payment_method::PaymentMethod),
domain::types::CryptoOperation::EncryptOptional(inner),
Identifier::Merchant(key_store.merchant_id.clone()),
key,
)
.await
.and_then(|val| val.try_into_optionaloperation())
})
.await
}
.await
.change_context(errors::VaultError::SavePaymentMethodFailed)
.attach_printable("Failed to encrypt payout method data")?
.map(Encryption::from)
.map(|e| e.into_inner())
.map_or(Err(errors::VaultError::SavePaymentMethodFailed), |e| {
Ok(hex::encode(e.peek()))
})?;
let payload =
payment_methods::StoreLockerReq::LockerGeneric(payment_methods::StoreGenericReq {
merchant_id: self
.merchant_context
.get_merchant_account()
.get_id()
.to_owned(),
merchant_customer_id: customer_id.to_owned(),
enc_data,
ttl: self.state.conf.locker.ttl_for_storage_in_secs,
});
let store_resp = add_card_to_hs_locker(
self.state,
&payload,
customer_id,
api_enums::LockerChoice::HyperswitchCardVault,
)
.await?;
let payment_method_resp = payment_methods::mk_add_bank_response_hs(
bank.clone(),
store_resp.card_reference,
req,
self.merchant_context.get_merchant_account().get_id(),
);
Ok((payment_method_resp, store_resp.duplication_check))
}
/// The response will be the tuple of PaymentMethodResponse and the duplication check of payment_method
async fn add_card_to_locker(
&self,
req: api::PaymentMethodCreate,
card: &api::CardDetail,
customer_id: &id_type::CustomerId,
card_reference: Option<&str>,
) -> errors::CustomResult<
(
api::PaymentMethodResponse,
Option<payment_methods::DataDuplicationCheck>,
),
errors::VaultError,
> {
metrics::STORED_TO_LOCKER.add(1, &[]);
let add_card_to_hs_resp = Box::pin(common_utils::metrics::utils::record_operation_time(
async {
self.add_card_hs(
req.clone(),
card,
customer_id,
api_enums::LockerChoice::HyperswitchCardVault,
card_reference,
)
.await
.inspect_err(|_| {
metrics::CARD_LOCKER_FAILURES.add(
1,
router_env::metric_attributes!(("locker", "rust"), ("operation", "add")),
);
})
},
&metrics::CARD_ADD_TIME,
router_env::metric_attributes!(("locker", "rust")),
))
.await?;
logger::debug!("card added to hyperswitch-card-vault");
Ok(add_card_to_hs_resp)
}
async fn delete_card_from_locker(
&self,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
card_reference: &str,
) -> errors::RouterResult<payment_methods::DeleteCardResp> {
metrics::DELETE_FROM_LOCKER.add(1, &[]);
common_utils::metrics::utils::record_operation_time(
async move {
delete_card_from_hs_locker(self.state, customer_id, merchant_id, card_reference)
.await
.inspect_err(|_| {
metrics::CARD_LOCKER_FAILURES.add(
1,
router_env::metric_attributes!(
("locker", "rust"),
("operation", "delete")
),
);
})
},
&metrics::CARD_DELETE_TIME,
&[],
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while deleting card from locker")
}
#[instrument(skip_all)]
async fn add_card_hs(
&self,
req: api::PaymentMethodCreate,
card: &api::CardDetail,
customer_id: &id_type::CustomerId,
locker_choice: api_enums::LockerChoice,
card_reference: Option<&str>,
) -> errors::CustomResult<
(
api::PaymentMethodResponse,
Option<payment_methods::DataDuplicationCheck>,
),
errors::VaultError,
> {
let payload = payment_methods::StoreLockerReq::LockerCard(payment_methods::StoreCardReq {
merchant_id: self
.merchant_context
.get_merchant_account()
.get_id()
.to_owned(),
merchant_customer_id: customer_id.to_owned(),
requestor_card_reference: card_reference.map(str::to_string),
card: Card {
card_number: card.card_number.to_owned(),
name_on_card: card.card_holder_name.to_owned(),
card_exp_month: card.card_exp_month.to_owned(),
card_exp_year: card.card_exp_year.to_owned(),
card_brand: card.card_network.as_ref().map(ToString::to_string),
card_isin: None,
nick_name: card.nick_name.as_ref().map(Secret::peek).cloned(),
},
ttl: self.state.conf.locker.ttl_for_storage_in_secs,
});
let store_card_payload =
add_card_to_hs_locker(self.state, &payload, customer_id, locker_choice).await?;
let payment_method_resp = payment_methods::mk_add_card_response_hs(
card.clone(),
store_card_payload.card_reference,
req,
self.merchant_context.get_merchant_account().get_id(),
);
Ok((payment_method_resp, store_card_payload.duplication_check))
}
#[cfg(feature = "v1")]
async fn get_card_details_with_locker_fallback(
&self,
pm: &domain::PaymentMethod,
) -> errors::RouterResult<Option<api::CardDetailFromLocker>> {
let card_decrypted = pm
.payment_method_data
.clone()
.map(|x| x.into_inner().expose())
.and_then(|v| serde_json::from_value::<PaymentMethodsData>(v).ok())
.and_then(|pmd| match pmd {
PaymentMethodsData::Card(crd) => Some(api::CardDetailFromLocker::from(crd)),
_ => None,
});
Ok(if let Some(mut crd) = card_decrypted {
crd.scheme.clone_from(&pm.scheme);
Some(crd)
} else {
logger::debug!(
"Getting card details from locker as it is not found in payment methods table"
);
Some(get_card_details_from_locker(self.state, pm).await?)
})
}
#[cfg(feature = "v1")]
async fn get_card_details_without_locker_fallback(
&self,
pm: &domain::PaymentMethod,
) -> errors::RouterResult<api::CardDetailFromLocker> {
let card_decrypted = pm
.payment_method_data
.clone()
.map(|x| x.into_inner().expose())
.and_then(|v| serde_json::from_value::<PaymentMethodsData>(v).ok())
.and_then(|pmd| match pmd {
PaymentMethodsData::Card(crd) => Some(api::CardDetailFromLocker::from(crd)),
_ => None,
});
Ok(if let Some(mut crd) = card_decrypted {
crd.scheme.clone_from(&pm.scheme);
crd
} else {
logger::debug!(
"Getting card details from locker as it is not found in payment methods table"
);
get_card_details_from_locker(self.state, pm).await?
})
}
#[cfg(feature = "v1")]
async fn set_default_payment_method(
&self,
merchant_id: &id_type::MerchantId,
customer_id: &id_type::CustomerId,
payment_method_id: String,
) -> errors::RouterResponse<api_models::payment_methods::CustomerDefaultPaymentMethodResponse>
{
let db = &*self.state.store;
let key_manager_state = &self.state.into();
// check for the customer
// TODO: customer need not be checked again here, this function can take an optional customer and check for existence of customer based on the optional value
let customer = db
.find_customer_by_customer_id_merchant_id(
key_manager_state,
customer_id,
merchant_id,
self.merchant_context.get_merchant_key_store(),
self.merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?;
// check for the presence of payment_method
let payment_method = db
.find_payment_method(
&(self.state.into()),
self.merchant_context.get_merchant_key_store(),
&payment_method_id,
self.merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
let pm = payment_method
.get_payment_method_type()
.get_required_value("payment_method")?;
utils::when(
&payment_method.customer_id != customer_id
|| payment_method.merchant_id != *merchant_id,
|| {
Err(errors::ApiErrorResponse::PreconditionFailed {
message: "The payment_method_id is not valid".to_string(),
})
},
)?;
utils::when(
Some(payment_method_id.clone()) == customer.default_payment_method_id,
|| {
Err(errors::ApiErrorResponse::PreconditionFailed {
message: "Payment Method is already set as default".to_string(),
})
},
)?;
let customer_id = customer.customer_id.clone();
let customer_update = CustomerUpdate::UpdateDefaultPaymentMethod {
default_payment_method_id: Some(Some(payment_method_id.to_owned())),
};
// update the db with the default payment method id
let updated_customer_details = db
.update_customer_by_customer_id_merchant_id(
key_manager_state,
customer_id.to_owned(),
merchant_id.to_owned(),
customer,
customer_update,
self.merchant_context.get_merchant_key_store(),
self.merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update the default payment method id for the customer")?;
let resp = api_models::payment_methods::CustomerDefaultPaymentMethodResponse {
default_payment_method_id: updated_customer_details.default_payment_method_id,
customer_id,
payment_method_type: payment_method.get_payment_method_subtype(),
payment_method: pm,
};
Ok(services::ApplicationResponse::Json(resp))
}
#[cfg(feature = "v1")]
async fn add_payment_method_status_update_task(
&self,
payment_method: &domain::PaymentMethod,
prev_status: common_enums::PaymentMethodStatus,
curr_status: common_enums::PaymentMethodStatus,
merchant_id: &id_type::MerchantId,
) -> Result<(), sch_errors::ProcessTrackerError> {
add_payment_method_status_update_task(
&*self.state.store,
payment_method,
prev_status,
curr_status,
merchant_id,
)
.await
}
#[cfg(feature = "v1")]
async fn validate_merchant_connector_ids_in_connector_mandate_details(
&self,
key_store: &domain::MerchantKeyStore,
connector_mandate_details: &api_models::payment_methods::CommonMandateReference,
merchant_id: &id_type::MerchantId,
card_network: Option<common_enums::CardNetwork>,
) -> errors::RouterResult<()> {
helpers::validate_merchant_connector_ids_in_connector_mandate_details(
self.state,
key_store,
connector_mandate_details,
merchant_id,
card_network,
)
.await
}
#[cfg(feature = "v1")]
async fn get_card_details_from_locker(
&self,
pm: &domain::PaymentMethod,
) -> errors::RouterResult<api::CardDetailFromLocker> {
get_card_details_from_locker(self.state, pm).await
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn retrieve_payment_method(
&self,
pm: api::PaymentMethodId,
) -> errors::RouterResponse<api::PaymentMethodResponse> {
let db = self.state.store.as_ref();
let pm = db
.find_payment_method(
&self.state.into(),
self.merchant_context.get_merchant_key_store(),
&pm.payment_method_id,
self.merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
let card = if pm.get_payment_method_type() == Some(enums::PaymentMethod::Card) {
let card_detail = if self.state.conf.locker.locker_enabled {
let card = get_card_from_locker(
self.state,
&pm.customer_id,
&pm.merchant_id,
pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error getting card from card vault")?;
payment_methods::get_card_detail(&pm, card)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while getting card details from locker")?
} else {
self.get_card_details_without_locker_fallback(&pm).await?
};
Some(card_detail)
} else {
None
};
Ok(services::ApplicationResponse::Json(
api::PaymentMethodResponse {
merchant_id: pm.merchant_id.clone(),
customer_id: Some(pm.customer_id.clone()),
payment_method_id: pm.payment_method_id.clone(),
payment_method: pm.get_payment_method_type(),
payment_method_type: pm.get_payment_method_subtype(),
#[cfg(feature = "payouts")]
bank_transfer: None,
card,
metadata: pm.metadata,
created: Some(pm.created_at),
recurring_enabled: Some(false),
installment_payment_enabled: Some(false),
payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]),
last_used_at: Some(pm.last_used_at),
client_secret: pm.client_secret,
},
))
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn delete_payment_method(
&self,
pm_id: api::PaymentMethodId,
) -> errors::RouterResponse<api::PaymentMethodDeleteResponse> {
let db = self.state.store.as_ref();
let key_manager_state = &(self.state.into());
let key = db
.find_payment_method(
key_manager_state,
self.merchant_context.get_merchant_key_store(),
pm_id.payment_method_id.as_str(),
self.merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
let customer = db
.find_customer_by_customer_id_merchant_id(
key_manager_state,
&key.customer_id,
self.merchant_context.get_merchant_account().get_id(),
self.merchant_context.get_merchant_key_store(),
self.merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Customer not found for the payment method")?;
if key.get_payment_method_type() == Some(enums::PaymentMethod::Card) {
let response = self
.delete_card_from_locker(
&key.customer_id,
&key.merchant_id,
key.locker_id.as_ref().unwrap_or(&key.payment_method_id),
)
.await?;
if let Some(network_token_ref_id) = key.network_token_requestor_reference_id {
let resp =
network_tokenization::delete_network_token_from_locker_and_token_service(
self.state,
&key.customer_id,
&key.merchant_id,
key.payment_method_id.clone(),
key.network_token_locker_id,
network_token_ref_id,
self.merchant_context,
)
.await?;
if resp.status == "Ok" {
logger::info!("Token From locker deleted Successfully!");
} else {
logger::error!("Error: Deleting Token From Locker!\n{:#?}", resp);
}
}
if response.status == "Ok" {
logger::info!("Card From locker deleted Successfully!");
} else {
logger::error!("Error: Deleting Card From Locker!\n{:#?}", response);
Err(errors::ApiErrorResponse::InternalServerError)?
}
}
db.delete_payment_method_by_merchant_id_payment_method_id(
&(self.state.into()),
self.merchant_context.get_merchant_key_store(),
self.merchant_context.get_merchant_account().get_id(),
pm_id.payment_method_id.as_str(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
if customer.default_payment_method_id.as_ref() == Some(&pm_id.payment_method_id) {
let customer_update = CustomerUpdate::UpdateDefaultPaymentMethod {
default_payment_method_id: Some(None),
};
db.update_customer_by_customer_id_merchant_id(
key_manager_state,
key.customer_id,
key.merchant_id,
customer,
customer_update,
self.merchant_context.get_merchant_key_store(),
self.merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update the default payment method id for the customer")?;
};
Ok(services::ApplicationResponse::Json(
api::PaymentMethodDeleteResponse {
payment_method_id: key.payment_method_id.clone(),
deleted: true,
},
))
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn add_payment_method(
&self,
req: &api::PaymentMethodCreate,
) -> errors::RouterResponse<api::PaymentMethodResponse> {
req.validate()?;
let db = &*self.state.store;
let merchant_id = self.merchant_context.get_merchant_account().get_id();
let customer_id = req.customer_id.clone().get_required_value("customer_id")?;
let payment_method = req.payment_method.get_required_value("payment_method")?;
let key_manager_state = self.state.into();
let payment_method_billing_address: Option<Encryptable<Secret<serde_json::Value>>> = req
.billing
.clone()
.async_map(|billing| {
create_encrypted_data(
&key_manager_state,
self.merchant_context.get_merchant_key_store(),
billing,
)
})
.await
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt Payment method billing address")?;
let connector_mandate_details = req
.connector_mandate_details
.clone()
.map(serde_json::to_value)
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let response = match payment_method {
#[cfg(feature = "payouts")]
api_enums::PaymentMethod::BankTransfer => match req.bank_transfer.clone() {
Some(bank) => self
.add_bank_to_locker(
req.clone(),
self.merchant_context.get_merchant_key_store(),
&bank,
&customer_id,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Add PaymentMethod Failed"),
_ => Ok(self.store_default_payment_method(req, &customer_id, merchant_id)),
},
api_enums::PaymentMethod::Card => match req.card.clone() {
Some(card) => {
let mut card_details = card;
card_details = helpers::populate_bin_details_for_payment_method_create(
card_details.clone(),
db.get_payment_methods_store(),
)
.await;
helpers::validate_card_expiry(
&card_details.card_exp_month,
&card_details.card_exp_year,
)?;
Box::pin(self.add_card_to_locker(
req.clone(),
&card_details,
&customer_id,
None,
))
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Add Card Failed")
}
_ => Ok(self.store_default_payment_method(req, &customer_id, merchant_id)),
},
_ => Ok(self.store_default_payment_method(req, &customer_id, merchant_id)),
};
let (mut resp, duplication_check) = response?;
match duplication_check {
Some(duplication_check) => match duplication_check {
payment_methods::DataDuplicationCheck::Duplicated => {
let existing_pm = self
.get_or_insert_payment_method(
req.clone(),
&mut resp,
&customer_id,
self.merchant_context.get_merchant_key_store(),
)
.await?;
resp.client_secret = existing_pm.client_secret;
}
payment_methods::DataDuplicationCheck::MetaDataChanged => {
if let Some(card) = req.card.clone() {
let existing_pm = self
.get_or_insert_payment_method(
req.clone(),
&mut resp,
&customer_id,
self.merchant_context.get_merchant_key_store(),
)
.await?;
let client_secret = existing_pm.client_secret.clone();
self.delete_card_from_locker(
&customer_id,
merchant_id,
existing_pm
.locker_id
.as_ref()
.unwrap_or(&existing_pm.payment_method_id),
)
.await?;
let add_card_resp = self
.add_card_hs(
req.clone(),
&card,
&customer_id,
api::enums::LockerChoice::HyperswitchCardVault,
Some(
existing_pm
.locker_id
.as_ref()
.unwrap_or(&existing_pm.payment_method_id),
),
)
.await;
if let Err(err) = add_card_resp {
logger::error!(vault_err=?err);
db.delete_payment_method_by_merchant_id_payment_method_id(
&(self.state.into()),
self.merchant_context.get_merchant_key_store(),
merchant_id,
&resp.payment_method_id,
)
.await
.to_not_found_response(
errors::ApiErrorResponse::PaymentMethodNotFound,
)?;
Err(report!(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while updating card metadata changes"))?
};
let existing_pm_data = self
.get_card_details_without_locker_fallback(&existing_pm)
.await?;
let updated_card = Some(api::CardDetailFromLocker {
scheme: existing_pm.scheme.clone(),
last4_digits: Some(card.card_number.get_last4()),
issuer_country: card
.card_issuing_country
.or(existing_pm_data.issuer_country),
card_isin: Some(card.card_number.get_card_isin()),
card_number: Some(card.card_number),
expiry_month: Some(card.card_exp_month),
expiry_year: Some(card.card_exp_year),
card_token: None,
card_fingerprint: None,
card_holder_name: card
.card_holder_name
.or(existing_pm_data.card_holder_name),
nick_name: card.nick_name.or(existing_pm_data.nick_name),
card_network: card.card_network.or(existing_pm_data.card_network),
card_issuer: card.card_issuer.or(existing_pm_data.card_issuer),
card_type: card.card_type.or(existing_pm_data.card_type),
saved_to_locker: true,
});
let updated_pmd = updated_card.as_ref().map(|card| {
PaymentMethodsData::Card(CardDetailsPaymentMethod::from((
card.clone(),
None,
)))
});
let pm_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>> =
updated_pmd
.async_map(|updated_pmd| {
create_encrypted_data(
&key_manager_state,
self.merchant_context.get_merchant_key_store(),
updated_pmd,
)
})
.await
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt payment method data")?;
let pm_update = storage::PaymentMethodUpdate::PaymentMethodDataUpdate {
payment_method_data: pm_data_encrypted.map(Into::into),
};
db.update_payment_method(
&(self.state.into()),
self.merchant_context.get_merchant_key_store(),
existing_pm,
pm_update,
self.merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to add payment method in db")?;
resp.client_secret = client_secret;
}
}
},
None => {
let pm_metadata = resp.metadata.as_ref().map(|data| data.peek());
let locker_id = if resp.payment_method == Some(api_enums::PaymentMethod::Card)
|| resp.payment_method == Some(api_enums::PaymentMethod::BankTransfer)
{
Some(resp.payment_method_id)
} else {
None
};
resp.payment_method_id = generate_id(consts::ID_LENGTH, "pm");
let pm = self
.insert_payment_method(
&resp,
req,
self.merchant_context.get_merchant_key_store(),
merchant_id,
&customer_id,
pm_metadata.cloned(),
None,
locker_id,
connector_mandate_details,
req.network_transaction_id.clone(),
payment_method_billing_address,
None,
None,
None,
Default::default(), //Currently this method is used for adding payment method via PaymentMethodCreate API which doesn't support external vault. hence Default i.e. InternalVault is passed for vault source and type
)
.await?;
resp.client_secret = pm.client_secret;
}
}
Ok(services::ApplicationResponse::Json(resp))
}
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
pub async fn get_client_secret_or_add_payment_method(
state: &routes::SessionState,
req: api::PaymentMethodCreate,
merchant_context: &domain::MerchantContext,
) -> errors::RouterResponse<api::PaymentMethodResponse> {
let merchant_id = merchant_context.get_merchant_account().get_id();
let customer_id = req.customer_id.clone().get_required_value("customer_id")?;
let cards = PmCards {
state,
merchant_context,
};
#[cfg(not(feature = "payouts"))]
let condition = req.card.is_some();
#[cfg(feature = "payouts")]
let condition = req.card.is_some() || req.bank_transfer.is_some() || req.wallet.is_some();
let key_manager_state = state.into();
let payment_method_billing_address: Option<Encryptable<Secret<serde_json::Value>>> = req
.billing
.clone()
.async_map(|billing| {
create_encrypted_data(
&key_manager_state,
merchant_context.get_merchant_key_store(),
billing,
)
})
.await
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt Payment method billing address")?;
let connector_mandate_details = req
.connector_mandate_details
.clone()
.map(serde_json::to_value)
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)?;
if condition {
Box::pin(cards.add_payment_method(&req)).await
} else {
let payment_method_id = generate_id(consts::ID_LENGTH, "pm");
let res = cards
.create_payment_method(
&req,
&customer_id,
payment_method_id.as_str(),
None,
merchant_id,
None,
None,
None,
connector_mandate_details,
Some(enums::PaymentMethodStatus::AwaitingData),
None,
payment_method_billing_address,
None,
None,
None,
None,
Default::default(), //Currently this method is used for adding payment method via PaymentMethodCreate API which doesn't support external vault. hence Default i.e. InternalVault is passed for vault type
)
.await?;
if res.status == enums::PaymentMethodStatus::AwaitingData {
add_payment_method_status_update_task(
&*state.store,
&res,
enums::PaymentMethodStatus::AwaitingData,
enums::PaymentMethodStatus::Inactive,
merchant_id,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Failed to add payment method status update task in process tracker",
)?;
}
Ok(services::api::ApplicationResponse::Json(
api::PaymentMethodResponse::foreign_from((None, res)),
))
}
}
#[instrument(skip_all)]
pub fn authenticate_pm_client_secret_and_check_expiry(
req_client_secret: &String,
payment_method: &domain::PaymentMethod,
) -> errors::CustomResult<bool, errors::ApiErrorResponse> {
let stored_client_secret = payment_method
.client_secret
.clone()
.get_required_value("client_secret")
.change_context(errors::ApiErrorResponse::MissingRequiredField {
field_name: "client_secret",
})
.attach_printable("client secret not found in db")?;
if req_client_secret != &stored_client_secret {
Err((errors::ApiErrorResponse::ClientSecretInvalid).into())
} else {
let current_timestamp = common_utils::date_time::now();
let session_expiry = payment_method
.created_at
.saturating_add(time::Duration::seconds(consts::DEFAULT_SESSION_EXPIRY));
let expired = current_timestamp > session_expiry;
Ok(expired)
}
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
pub async fn add_payment_method_data(
state: routes::SessionState,
req: api::PaymentMethodCreate,
merchant_context: domain::MerchantContext,
pm_id: String,
) -> errors::RouterResponse<api::PaymentMethodResponse> {
let db = &*state.store;
let cards = PmCards {
state: &state,
merchant_context: &merchant_context,
};
let pmd = req
.payment_method_data
.clone()
.get_required_value("payment_method_data")?;
req.payment_method.get_required_value("payment_method")?;
let client_secret = req
.client_secret
.clone()
.get_required_value("client_secret")?;
let payment_method = db
.find_payment_method(
&((&state).into()),
merchant_context.get_merchant_key_store(),
pm_id.as_str(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::PaymentMethodNotFound)
.attach_printable("Unable to find payment method")?;
if payment_method.status != enums::PaymentMethodStatus::AwaitingData {
return Err((errors::ApiErrorResponse::ClientSecretExpired).into());
}
let customer_id = payment_method.customer_id.clone();
let customer = db
.find_customer_by_customer_id_merchant_id(
&(&state).into(),
&customer_id,
merchant_context.get_merchant_account().get_id(),
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?;
let client_secret_expired =
authenticate_pm_client_secret_and_check_expiry(&client_secret, &payment_method)?;
if client_secret_expired {
return Err((errors::ApiErrorResponse::ClientSecretExpired).into());
};
let key_manager_state = (&state).into();
match pmd {
api_models::payment_methods::PaymentMethodCreateData::Card(card) => {
helpers::validate_card_expiry(&card.card_exp_month, &card.card_exp_year)?;
let resp = Box::pin(cards.add_card_to_locker(req.clone(), &card, &customer_id, None))
.await
.change_context(errors::ApiErrorResponse::InternalServerError);
match resp {
Ok((mut pm_resp, duplication_check)) => {
if duplication_check.is_some() {
let pm_update = storage::PaymentMethodUpdate::StatusUpdate {
status: Some(enums::PaymentMethodStatus::Inactive),
};
db.update_payment_method(
&((&state).into()),
merchant_context.get_merchant_key_store(),
payment_method,
pm_update,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to add payment method in db")?;
cards
.get_or_insert_payment_method(
req.clone(),
&mut pm_resp,
&customer_id,
merchant_context.get_merchant_key_store(),
)
.await?;
return Ok(services::ApplicationResponse::Json(pm_resp));
} else {
let locker_id = pm_resp.payment_method_id.clone();
pm_resp.payment_method_id.clone_from(&pm_id);
pm_resp.client_secret = Some(client_secret.clone());
let card_isin = card.card_number.get_card_isin();
let card_info = db
.get_card_info(card_isin.as_str())
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get card info")?;
let updated_card = CardDetailsPaymentMethod {
issuer_country: card_info
.as_ref()
.and_then(|ci| ci.card_issuing_country.clone()),
last4_digits: Some(card.card_number.get_last4()),
expiry_month: Some(card.card_exp_month),
expiry_year: Some(card.card_exp_year),
nick_name: card.nick_name,
card_holder_name: card.card_holder_name,
card_network: card_info.as_ref().and_then(|ci| ci.card_network.clone()),
card_isin: Some(card_isin),
card_issuer: card_info.as_ref().and_then(|ci| ci.card_issuer.clone()),
card_type: card_info.as_ref().and_then(|ci| ci.card_type.clone()),
saved_to_locker: true,
co_badged_card_data: None,
};
let pm_data_encrypted: Encryptable<Secret<serde_json::Value>> =
create_encrypted_data(
&key_manager_state,
merchant_context.get_merchant_key_store(),
PaymentMethodsData::Card(updated_card),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt payment method data")?;
let pm_update = storage::PaymentMethodUpdate::AdditionalDataUpdate {
payment_method_data: Some(pm_data_encrypted.into()),
status: Some(enums::PaymentMethodStatus::Active),
locker_id: Some(locker_id),
network_token_requestor_reference_id: None,
payment_method: req.payment_method,
payment_method_issuer: req.payment_method_issuer,
payment_method_type: req.payment_method_type,
network_token_locker_id: None,
network_token_payment_method_data: None,
};
db.update_payment_method(
&((&state).into()),
merchant_context.get_merchant_key_store(),
payment_method,
pm_update,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to add payment method in db")?;
if customer.default_payment_method_id.is_none() {
let _ = cards
.set_default_payment_method(
merchant_context.get_merchant_account().get_id(),
&customer_id,
pm_id,
)
.await
.map_err(|error| {
logger::error!(
?error,
"Failed to set the payment method as default"
)
});
}
return Ok(services::ApplicationResponse::Json(pm_resp));
}
}
Err(e) => {
let pm_update = storage::PaymentMethodUpdate::StatusUpdate {
status: Some(enums::PaymentMethodStatus::Inactive),
};
db.update_payment_method(
&((&state).into()),
merchant_context.get_merchant_key_store(),
payment_method,
pm_update,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update payment method in db")?;
return Err(e.attach_printable("Failed to add card to locker"));
}
}
}
}
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
pub async fn update_customer_payment_method(
state: routes::SessionState,
merchant_context: domain::MerchantContext,
req: api::PaymentMethodUpdate,
payment_method_id: &str,
) -> errors::RouterResponse<api::PaymentMethodResponse> {
// Currently update is supported only for cards
if let Some(card_update) = req.card.clone() {
let db = state.store.as_ref();
let pm = db
.find_payment_method(
&((&state).into()),
merchant_context.get_merchant_key_store(),
payment_method_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
if let Some(cs) = &req.client_secret {
let is_client_secret_expired = authenticate_pm_client_secret_and_check_expiry(cs, &pm)?;
if is_client_secret_expired {
return Err((errors::ApiErrorResponse::ClientSecretExpired).into());
};
};
if pm.status == enums::PaymentMethodStatus::AwaitingData {
return Err(report!(errors::ApiErrorResponse::NotSupported {
message: "Payment method is awaiting data so it cannot be updated".into()
}));
}
if pm.payment_method_data.is_none() {
return Err(report!(errors::ApiErrorResponse::GenericNotFoundError {
message: "payment_method_data not found".to_string()
}));
}
// Fetch the existing payment method data from db
let existing_card_data =
pm.payment_method_data
.clone()
.map(|x| x.into_inner().expose())
.map(
|value| -> Result<
PaymentMethodsData,
error_stack::Report<errors::ApiErrorResponse>,
> {
value
.parse_value::<PaymentMethodsData>("PaymentMethodsData")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to deserialize payment methods data")
},
)
.transpose()?
.and_then(|pmd| match pmd {
PaymentMethodsData::Card(crd) => Some(api::CardDetailFromLocker::from(crd)),
_ => None,
})
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to obtain decrypted card object from db")?;
let is_card_updation_required =
validate_payment_method_update(card_update.clone(), existing_card_data.clone());
let response = if is_card_updation_required {
// Fetch the existing card data from locker for getting card number
let card_data_from_locker = get_card_from_locker(
&state,
&pm.customer_id,
&pm.merchant_id,
pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id),
)
.await
.attach_printable("Error getting card from locker")?;
if card_update.card_exp_month.is_some() || card_update.card_exp_year.is_some() {
helpers::validate_card_expiry(
card_update
.card_exp_month
.as_ref()
.unwrap_or(&card_data_from_locker.card_exp_month),
card_update
.card_exp_year
.as_ref()
.unwrap_or(&card_data_from_locker.card_exp_year),
)?;
}
let updated_card_details = card_update.apply(card_data_from_locker.clone());
// Construct new payment method object from request
let new_pm = api::PaymentMethodCreate {
payment_method: pm.get_payment_method_type(),
payment_method_type: pm.get_payment_method_subtype(),
payment_method_issuer: pm.payment_method_issuer.clone(),
payment_method_issuer_code: pm.payment_method_issuer_code,
#[cfg(feature = "payouts")]
bank_transfer: None,
card: Some(updated_card_details.clone()),
#[cfg(feature = "payouts")]
wallet: None,
metadata: None,
customer_id: Some(pm.customer_id.clone()),
client_secret: pm.client_secret.clone(),
payment_method_data: None,
card_network: None,
billing: None,
connector_mandate_details: None,
network_transaction_id: None,
};
new_pm.validate()?;
let cards = PmCards {
state: &state,
merchant_context: &merchant_context,
};
// Delete old payment method from locker
cards
.delete_card_from_locker(
&pm.customer_id,
&pm.merchant_id,
pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id),
)
.await?;
// Add the updated payment method data to locker
let (mut add_card_resp, _) = Box::pin(cards.add_card_to_locker(
new_pm.clone(),
&updated_card_details,
&pm.customer_id,
Some(pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id)),
))
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to add updated payment method to locker")?;
// Construct new updated card object. Consider a field if passed in request or else populate it with the existing value from existing_card_data
let updated_card = Some(api::CardDetailFromLocker {
scheme: existing_card_data.scheme,
last4_digits: Some(card_data_from_locker.card_number.get_last4()),
issuer_country: existing_card_data.issuer_country,
card_number: existing_card_data.card_number,
expiry_month: card_update
.card_exp_month
.or(existing_card_data.expiry_month),
expiry_year: card_update.card_exp_year.or(existing_card_data.expiry_year),
card_token: existing_card_data.card_token,
card_fingerprint: existing_card_data.card_fingerprint,
card_holder_name: card_update
.card_holder_name
.or(existing_card_data.card_holder_name),
nick_name: card_update.nick_name.or(existing_card_data.nick_name),
card_network: existing_card_data.card_network,
card_isin: existing_card_data.card_isin,
card_issuer: existing_card_data.card_issuer,
card_type: existing_card_data.card_type,
saved_to_locker: true,
});
let updated_pmd = updated_card.as_ref().map(|card| {
PaymentMethodsData::Card(CardDetailsPaymentMethod::from((card.clone(), None)))
});
let key_manager_state = (&state).into();
let pm_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>> = updated_pmd
.async_map(|updated_pmd| {
create_encrypted_data(
&key_manager_state,
merchant_context.get_merchant_key_store(),
updated_pmd,
)
})
.await
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt payment method data")?;
let pm_update = storage::PaymentMethodUpdate::PaymentMethodDataUpdate {
payment_method_data: pm_data_encrypted.map(Into::into),
};
add_card_resp
.payment_method_id
.clone_from(&pm.payment_method_id);
db.update_payment_method(
&((&state).into()),
merchant_context.get_merchant_key_store(),
pm,
pm_update,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update payment method in db")?;
add_card_resp
} else {
// Return existing payment method data as response without any changes
api::PaymentMethodResponse {
merchant_id: pm.merchant_id.to_owned(),
customer_id: Some(pm.customer_id.clone()),
payment_method_id: pm.payment_method_id.clone(),
payment_method: pm.get_payment_method_type(),
payment_method_type: pm.get_payment_method_subtype(),
#[cfg(feature = "payouts")]
bank_transfer: None,
card: Some(existing_card_data),
metadata: pm.metadata,
created: Some(pm.created_at),
recurring_enabled: Some(false),
installment_payment_enabled: Some(false),
payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]),
last_used_at: Some(common_utils::date_time::now()),
client_secret: pm.client_secret.clone(),
}
};
Ok(services::ApplicationResponse::Json(response))
} else {
Err(report!(errors::ApiErrorResponse::NotSupported {
message: "Payment method update for the given payment method is not supported".into()
}))
}
}
#[cfg(feature = "v1")]
pub fn validate_payment_method_update(
card_updation_obj: CardDetailUpdate,
existing_card_data: api::CardDetailFromLocker,
) -> bool {
// Return true If any one of the below condition returns true,
// If a field is not passed in the update request, return false.
// If the field is present, it depends on the existing field data:
// - If existing field data is not present, or if it is present and doesn't match
// the update request data, then return true.
// - Or else return false
card_updation_obj
.card_exp_month
.map(|exp_month| exp_month.expose())
.is_some_and(|new_exp_month| {
existing_card_data
.expiry_month
.map(|exp_month| exp_month.expose())
!= Some(new_exp_month)
})
|| card_updation_obj
.card_exp_year
.map(|exp_year| exp_year.expose())
.is_some_and(|new_exp_year| {
existing_card_data
.expiry_year
.map(|exp_year| exp_year.expose())
!= Some(new_exp_year)
})
|| card_updation_obj
.card_holder_name
.map(|name| name.expose())
.is_some_and(|new_card_holder_name| {
existing_card_data
.card_holder_name
.map(|name| name.expose())
!= Some(new_card_holder_name)
})
|| card_updation_obj
.nick_name
.map(|nick_name| nick_name.expose())
.is_some_and(|new_nick_name| {
existing_card_data
.nick_name
.map(|nick_name| nick_name.expose())
!= Some(new_nick_name)
})
}
#[cfg(feature = "v2")]
pub fn validate_payment_method_update(
_card_updation_obj: CardDetailUpdate,
_existing_card_data: api::CardDetailFromLocker,
) -> bool {
todo!()
}
// Wrapper function to switch lockers
pub async fn get_card_from_locker(
state: &routes::SessionState,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
card_reference: &str,
) -> errors::RouterResult<Card> {
metrics::GET_FROM_LOCKER.add(1, &[]);
let get_card_from_rs_locker_resp = common_utils::metrics::utils::record_operation_time(
async {
get_card_from_hs_locker(
state,
customer_id,
merchant_id,
card_reference,
api_enums::LockerChoice::HyperswitchCardVault,
)
.await
.map_err(|err| match err.current_context() {
errors::VaultError::FetchCardFailed => {
err.change_context(errors::ApiErrorResponse::GenericNotFoundError {
message: "Card not found in vault".to_string(),
})
}
_ => err
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error getting card from card vault"),
})
.inspect_err(|_| {
metrics::CARD_LOCKER_FAILURES.add(
1,
router_env::metric_attributes!(("locker", "rust"), ("operation", "get")),
);
})
},
&metrics::CARD_GET_TIME,
router_env::metric_attributes!(("locker", "rust")),
)
.await?;
logger::debug!("card retrieved from rust locker");
Ok(get_card_from_rs_locker_resp)
}
#[cfg(feature = "v2")]
pub async fn delete_card_by_locker_id(
state: &routes::SessionState,
id: &id_type::GlobalCustomerId,
merchant_id: &id_type::MerchantId,
) -> errors::RouterResult<payment_methods::DeleteCardResp> {
todo!()
}
#[instrument(skip_all)]
pub async fn decode_and_decrypt_locker_data(
state: &routes::SessionState,
key_store: &domain::MerchantKeyStore,
enc_card_data: String,
) -> errors::CustomResult<Secret<String>, errors::VaultError> {
let key = key_store.key.get_inner().peek();
let decoded_bytes = hex::decode(&enc_card_data)
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Failed to decode hex string into bytes")?;
// Decrypt
domain::types::crypto_operation(
&state.into(),
type_name!(payment_method::PaymentMethod),
domain::types::CryptoOperation::DecryptOptional(Some(Encryption::new(
decoded_bytes.into(),
))),
Identifier::Merchant(key_store.merchant_id.clone()),
key,
)
.await
.and_then(|val| val.try_into_optionaloperation())
.change_context(errors::VaultError::FetchPaymentMethodFailed)?
.map_or(
Err(report!(errors::VaultError::FetchPaymentMethodFailed)),
|d| Ok(d.into_inner()),
)
}
#[instrument(skip_all)]
pub async fn get_payment_method_from_hs_locker<'a>(
state: &'a routes::SessionState,
key_store: &domain::MerchantKeyStore,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
payment_method_reference: &'a str,
locker_choice: Option<api_enums::LockerChoice>,
) -> errors::CustomResult<Secret<String>, errors::VaultError> {
let locker = &state.conf.locker;
let jwekey = state.conf.jwekey.get_inner();
let payment_method_data = if !locker.mock_locker {
let request = payment_methods::mk_get_card_request_hs(
jwekey,
locker,
customer_id,
merchant_id,
payment_method_reference,
locker_choice,
state.tenant.tenant_id.clone(),
state.request_id,
)
.await
.change_context(errors::VaultError::FetchPaymentMethodFailed)
.attach_printable("Making get payment method request failed")?;
let get_card_resp = call_locker_api::<payment_methods::RetrieveCardResp>(
state,
request,
"get_pm_from_locker",
locker_choice,
)
.await
.change_context(errors::VaultError::FetchPaymentMethodFailed)?;
let retrieve_card_resp = get_card_resp
.payload
.get_required_value("RetrieveCardRespPayload")
.change_context(errors::VaultError::FetchPaymentMethodFailed)
.attach_printable("Failed to retrieve field - payload from RetrieveCardResp")?;
let enc_card_data = retrieve_card_resp
.enc_card_data
.get_required_value("enc_card_data")
.change_context(errors::VaultError::FetchPaymentMethodFailed)
.attach_printable(
"Failed to retrieve field - enc_card_data from RetrieveCardRespPayload",
)?;
decode_and_decrypt_locker_data(state, key_store, enc_card_data.peek().to_string()).await?
} else {
mock_get_payment_method(state, key_store, payment_method_reference)
.await?
.payment_method
.payment_method_data
};
Ok(payment_method_data)
}
#[instrument(skip_all)]
pub async fn add_card_to_hs_locker(
state: &routes::SessionState,
payload: &payment_methods::StoreLockerReq,
customer_id: &id_type::CustomerId,
locker_choice: api_enums::LockerChoice,
) -> errors::CustomResult<payment_methods::StoreCardRespPayload, errors::VaultError> {
let locker = &state.conf.locker;
let jwekey = state.conf.jwekey.get_inner();
let db = &*state.store;
let stored_card_response = if !locker.mock_locker {
let request = payment_methods::mk_add_locker_request_hs(
jwekey,
locker,
payload,
locker_choice,
state.tenant.tenant_id.clone(),
state.request_id,
)
.await?;
call_locker_api::<payment_methods::StoreCardResp>(
state,
request,
"add_card_to_hs_locker",
Some(locker_choice),
)
.await
.change_context(errors::VaultError::SaveCardFailed)?
} else {
let card_id = generate_id(consts::ID_LENGTH, "card");
mock_call_to_locker_hs(db, &card_id, payload, None, None, Some(customer_id)).await?
};
let stored_card = stored_card_response
.payload
.get_required_value("StoreCardRespPayload")
.change_context(errors::VaultError::SaveCardFailed)?;
Ok(stored_card)
}
#[instrument(skip_all)]
pub async fn call_locker_api<T>(
state: &routes::SessionState,
request: Request,
flow_name: &str,
locker_choice: Option<api_enums::LockerChoice>,
) -> errors::CustomResult<T, errors::VaultError>
where
T: serde::de::DeserializeOwned,
{
let locker = &state.conf.locker;
let jwekey = state.conf.jwekey.get_inner();
let response_type_name = type_name!(T);
let response = services::call_connector_api(state, request, flow_name)
.await
.change_context(errors::VaultError::ApiError)?;
let is_locker_call_succeeded = response.is_ok();
let jwe_body = response
.unwrap_or_else(|err| err)
.response
.parse_struct::<services::JweBody>("JweBody")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Failed while parsing locker response into JweBody")?;
let decrypted_payload = payment_methods::get_decrypted_response_payload(
jwekey,
jwe_body,
locker_choice,
locker.decryption_scheme.clone(),
)
.await
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Failed while decrypting locker payload response")?;
// Irrespective of locker's response status, payload is JWE + JWS decrypted. But based on locker's status,
// if Ok, deserialize the decrypted payload into given type T
// if Err, raise an error including locker error message too
if is_locker_call_succeeded {
let stored_card_resp: Result<T, error_stack::Report<errors::VaultError>> =
decrypted_payload
.parse_struct(response_type_name)
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable_lazy(|| {
format!("Failed while parsing locker response into {response_type_name}")
});
stored_card_resp
} else {
Err::<T, error_stack::Report<errors::VaultError>>((errors::VaultError::ApiError).into())
.attach_printable_lazy(|| format!("Locker error response: {decrypted_payload:?}"))
}
}
#[cfg(feature = "v1")]
pub async fn update_payment_method_metadata_and_last_used(
state: &routes::SessionState,
key_store: &domain::MerchantKeyStore,
db: &dyn db::StorageInterface,
pm: domain::PaymentMethod,
pm_metadata: Option<serde_json::Value>,
storage_scheme: MerchantStorageScheme,
) -> errors::CustomResult<(), errors::VaultError> {
let pm_update = payment_method::PaymentMethodUpdate::MetadataUpdateAndLastUsed {
metadata: pm_metadata,
last_used_at: common_utils::date_time::now(),
};
db.update_payment_method(&(state.into()), key_store, pm, pm_update, storage_scheme)
.await
.change_context(errors::VaultError::UpdateInPaymentMethodDataTableFailed)?;
Ok(())
}
pub async fn update_payment_method_and_last_used(
state: &routes::SessionState,
key_store: &domain::MerchantKeyStore,
db: &dyn db::StorageInterface,
pm: domain::PaymentMethod,
payment_method_update: Option<Encryption>,
storage_scheme: MerchantStorageScheme,
card_scheme: Option<String>,
) -> errors::CustomResult<(), errors::VaultError> {
let pm_update = payment_method::PaymentMethodUpdate::UpdatePaymentMethodDataAndLastUsed {
payment_method_data: payment_method_update,
scheme: card_scheme,
last_used_at: common_utils::date_time::now(),
};
db.update_payment_method(&(state.into()), key_store, pm, pm_update, storage_scheme)
.await
.change_context(errors::VaultError::UpdateInPaymentMethodDataTableFailed)?;
Ok(())
}
#[cfg(feature = "v2")]
pub async fn update_payment_method_connector_mandate_details(
state: &routes::SessionState,
key_store: &domain::MerchantKeyStore,
db: &dyn db::StorageInterface,
pm: domain::PaymentMethod,
connector_mandate_details: Option<CommonMandateReference>,
storage_scheme: MerchantStorageScheme,
) -> errors::CustomResult<(), errors::VaultError> {
let pm_update = payment_method::PaymentMethodUpdate::ConnectorMandateDetailsUpdate {
connector_mandate_details: connector_mandate_details.map(|cmd| cmd.into()),
};
db.update_payment_method(&(state.into()), key_store, pm, pm_update, storage_scheme)
.await
.change_context(errors::VaultError::UpdateInPaymentMethodDataTableFailed)?;
Ok(())
}
#[cfg(feature = "v1")]
pub async fn update_payment_method_connector_mandate_details(
state: &routes::SessionState,
key_store: &domain::MerchantKeyStore,
db: &dyn db::StorageInterface,
pm: domain::PaymentMethod,
connector_mandate_details: Option<CommonMandateReference>,
storage_scheme: MerchantStorageScheme,
) -> errors::CustomResult<(), errors::VaultError> {
let connector_mandate_details_value = connector_mandate_details
.map(|common_mandate| {
common_mandate.get_mandate_details_value().map_err(|err| {
router_env::logger::error!("Failed to get get_mandate_details_value : {:?}", err);
errors::VaultError::UpdateInPaymentMethodDataTableFailed
})
})
.transpose()?;
let pm_update = payment_method::PaymentMethodUpdate::ConnectorMandateDetailsUpdate {
connector_mandate_details: connector_mandate_details_value,
};
db.update_payment_method(&(state.into()), key_store, pm, pm_update, storage_scheme)
.await
.change_context(errors::VaultError::UpdateInPaymentMethodDataTableFailed)?;
Ok(())
}
#[instrument(skip_all)]
pub async fn get_card_from_hs_locker<'a>(
state: &'a routes::SessionState,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
card_reference: &'a str,
locker_choice: api_enums::LockerChoice,
) -> errors::CustomResult<Card, errors::VaultError> {
let locker = &state.conf.locker;
let jwekey = &state.conf.jwekey.get_inner();
if !locker.mock_locker {
let request = payment_methods::mk_get_card_request_hs(
jwekey,
locker,
customer_id,
merchant_id,
card_reference,
Some(locker_choice),
state.tenant.tenant_id.clone(),
state.request_id,
)
.await
.change_context(errors::VaultError::FetchCardFailed)
.attach_printable("Making get card request failed")?;
let get_card_resp = call_locker_api::<payment_methods::RetrieveCardResp>(
state,
request,
"get_card_from_locker",
Some(locker_choice),
)
.await
.change_context(errors::VaultError::FetchCardFailed)?;
let retrieve_card_resp = get_card_resp
.payload
.get_required_value("RetrieveCardRespPayload")
.change_context(errors::VaultError::FetchCardFailed)?;
retrieve_card_resp
.card
.get_required_value("Card")
.change_context(errors::VaultError::FetchCardFailed)
} else {
let (get_card_resp, _) = mock_get_card(&*state.store, card_reference).await?;
payment_methods::mk_get_card_response(get_card_resp)
.change_context(errors::VaultError::ResponseDeserializationFailed)
}
}
#[instrument(skip_all)]
pub async fn delete_card_from_hs_locker<'a>(
state: &routes::SessionState,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
card_reference: &'a str,
) -> errors::CustomResult<payment_methods::DeleteCardResp, errors::VaultError> {
let locker = &state.conf.locker;
let jwekey = &state.conf.jwekey.get_inner();
let request = payment_methods::mk_delete_card_request_hs(
jwekey,
locker,
customer_id,
merchant_id,
card_reference,
state.tenant.tenant_id.clone(),
state.request_id,
)
.await
.change_context(errors::VaultError::DeleteCardFailed)
.attach_printable("Making delete card request failed")?;
if !locker.mock_locker {
call_locker_api::<payment_methods::DeleteCardResp>(
state,
request,
"delete_card_from_locker",
Some(api_enums::LockerChoice::HyperswitchCardVault),
)
.await
.change_context(errors::VaultError::DeleteCardFailed)
} else {
Ok(mock_delete_card_hs(&*state.store, card_reference)
.await
.change_context(errors::VaultError::DeleteCardFailed)?)
}
}
// Need to fix this function while completing v2
#[cfg(feature = "v2")]
#[instrument(skip_all)]
pub async fn delete_card_from_hs_locker_by_global_id<'a>(
state: &routes::SessionState,
id: &str,
merchant_id: &id_type::MerchantId,
card_reference: &'a str,
) -> errors::RouterResult<payment_methods::DeleteCardResp> {
todo!()
}
///Mock api for local testing
pub async fn mock_call_to_locker_hs(
db: &dyn db::StorageInterface,
card_id: &str,
payload: &payment_methods::StoreLockerReq,
card_cvc: Option<String>,
payment_method_id: Option<String>,
customer_id: Option<&id_type::CustomerId>,
) -> errors::CustomResult<payment_methods::StoreCardResp, errors::VaultError> {
let mut locker_mock_up = storage::LockerMockUpNew {
card_id: card_id.to_string(),
external_id: uuid::Uuid::new_v4().to_string(),
card_fingerprint: uuid::Uuid::new_v4().to_string(),
card_global_fingerprint: uuid::Uuid::new_v4().to_string(),
merchant_id: id_type::MerchantId::default(),
card_number: "4111111111111111".to_string(),
card_exp_year: "2099".to_string(),
card_exp_month: "12".to_string(),
card_cvc,
payment_method_id,
customer_id: customer_id.map(ToOwned::to_owned),
name_on_card: None,
nickname: None,
enc_card_data: None,
};
locker_mock_up = match payload {
payment_methods::StoreLockerReq::LockerCard(store_card_req) => storage::LockerMockUpNew {
merchant_id: store_card_req.merchant_id.to_owned(),
card_number: store_card_req.card.card_number.peek().to_string(),
card_exp_year: store_card_req.card.card_exp_year.peek().to_string(),
card_exp_month: store_card_req.card.card_exp_month.peek().to_string(),
name_on_card: store_card_req.card.name_on_card.to_owned().expose_option(),
nickname: store_card_req.card.nick_name.to_owned(),
..locker_mock_up
},
payment_methods::StoreLockerReq::LockerGeneric(store_generic_req) => {
storage::LockerMockUpNew {
merchant_id: store_generic_req.merchant_id.to_owned(),
enc_card_data: Some(store_generic_req.enc_data.to_owned()),
..locker_mock_up
}
}
};
let response = db
.insert_locker_mock_up(locker_mock_up)
.await
.change_context(errors::VaultError::SaveCardFailed)?;
let payload = payment_methods::StoreCardRespPayload {
card_reference: response.card_id,
duplication_check: None,
};
Ok(payment_methods::StoreCardResp {
status: "Ok".to_string(),
error_code: None,
error_message: None,
payload: Some(payload),
})
}
#[instrument(skip_all)]
pub async fn mock_get_card<'a>(
db: &dyn db::StorageInterface,
card_id: &'a str,
) -> errors::CustomResult<(payment_methods::GetCardResponse, Option<String>), errors::VaultError> {
let locker_mock_up = db
.find_locker_by_card_id(card_id)
.await
.change_context(errors::VaultError::FetchCardFailed)?;
let add_card_response = payment_methods::AddCardResponse {
card_id: locker_mock_up
.payment_method_id
.unwrap_or(locker_mock_up.card_id),
external_id: locker_mock_up.external_id,
card_fingerprint: locker_mock_up.card_fingerprint.into(),
card_global_fingerprint: locker_mock_up.card_global_fingerprint.into(),
merchant_id: Some(locker_mock_up.merchant_id),
card_number: cards::CardNumber::try_from(locker_mock_up.card_number)
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Invalid card number format from the mock locker")
.map(Some)?,
card_exp_year: Some(locker_mock_up.card_exp_year.into()),
card_exp_month: Some(locker_mock_up.card_exp_month.into()),
name_on_card: locker_mock_up.name_on_card.map(|card| card.into()),
nickname: locker_mock_up.nickname,
customer_id: locker_mock_up.customer_id,
duplicate: locker_mock_up.duplicate,
};
Ok((
payment_methods::GetCardResponse {
card: add_card_response,
},
locker_mock_up.card_cvc,
))
}
#[instrument(skip_all)]
pub async fn mock_get_payment_method<'a>(
state: &routes::SessionState,
key_store: &domain::MerchantKeyStore,
card_id: &'a str,
) -> errors::CustomResult<payment_methods::GetPaymentMethodResponse, errors::VaultError> {
let db = &*state.store;
let locker_mock_up = db
.find_locker_by_card_id(card_id)
.await
.change_context(errors::VaultError::FetchPaymentMethodFailed)?;
let dec_data = if let Some(e) = locker_mock_up.enc_card_data {
decode_and_decrypt_locker_data(state, key_store, e).await
} else {
Err(report!(errors::VaultError::FetchPaymentMethodFailed))
}?;
let payment_method_response = payment_methods::AddPaymentMethodResponse {
payment_method_id: locker_mock_up
.payment_method_id
.unwrap_or(locker_mock_up.card_id),
external_id: locker_mock_up.external_id,
merchant_id: Some(locker_mock_up.merchant_id.to_owned()),
nickname: locker_mock_up.nickname,
customer_id: locker_mock_up.customer_id,
duplicate: locker_mock_up.duplicate,
payment_method_data: dec_data,
};
Ok(payment_methods::GetPaymentMethodResponse {
payment_method: payment_method_response,
})
}
#[instrument(skip_all)]
pub async fn mock_delete_card_hs<'a>(
db: &dyn db::StorageInterface,
card_id: &'a str,
) -> errors::CustomResult<payment_methods::DeleteCardResp, errors::VaultError> {
db.delete_locker_mock_up(card_id)
.await
.change_context(errors::VaultError::FetchCardFailed)?;
Ok(payment_methods::DeleteCardResp {
status: "Ok".to_string(),
error_code: None,
error_message: None,
})
}
#[instrument(skip_all)]
pub async fn mock_delete_card<'a>(
db: &dyn db::StorageInterface,
card_id: &'a str,
) -> errors::CustomResult<payment_methods::DeleteCardResponse, errors::VaultError> {
let locker_mock_up = db
.delete_locker_mock_up(card_id)
.await
.change_context(errors::VaultError::FetchCardFailed)?;
Ok(payment_methods::DeleteCardResponse {
card_id: Some(locker_mock_up.card_id),
external_id: Some(locker_mock_up.external_id),
card_isin: None,
status: "Ok".to_string(),
})
}
//------------------------------------------------------------------------------
pub fn get_banks(
state: &routes::SessionState,
pm_type: common_enums::enums::PaymentMethodType,
connectors: Vec<String>,
) -> Result<Vec<BankCodeResponse>, errors::ApiErrorResponse> {
let mut bank_names_hm: HashMap<String, HashSet<common_enums::enums::BankNames>> =
HashMap::new();
if matches!(
pm_type,
api_enums::PaymentMethodType::Giropay | api_enums::PaymentMethodType::Sofort
) {
Ok(vec![BankCodeResponse {
bank_name: vec![],
eligible_connectors: connectors,
}])
} else {
let mut bank_code_responses = vec![];
for connector in &connectors {
if let Some(connector_bank_names) = state.conf.bank_config.0.get(&pm_type) {
if let Some(connector_hash_set) = connector_bank_names.0.get(connector) {
bank_names_hm.insert(connector.clone(), connector_hash_set.banks.clone());
} else {
logger::error!("Could not find any configured connectors for payment_method -> {pm_type} for connector -> {connector}");
}
} else {
logger::error!("Could not find any configured banks for payment_method -> {pm_type} for connector -> {connector}");
}
}
let vector_of_hashsets = bank_names_hm
.values()
.map(|bank_names_hashset| bank_names_hashset.to_owned())
.collect::<Vec<_>>();
let mut common_bank_names = HashSet::new();
if let Some(first_element) = vector_of_hashsets.first() {
common_bank_names = vector_of_hashsets
.iter()
.skip(1)
.fold(first_element.to_owned(), |acc, hs| {
acc.intersection(hs).copied().collect()
});
}
if !common_bank_names.is_empty() {
bank_code_responses.push(BankCodeResponse {
bank_name: common_bank_names.clone().into_iter().collect(),
eligible_connectors: connectors.clone(),
});
}
for connector in connectors {
if let Some(all_bank_codes_for_connector) = bank_names_hm.get(&connector) {
let remaining_bank_codes: HashSet<_> = all_bank_codes_for_connector
.difference(&common_bank_names)
.collect();
if !remaining_bank_codes.is_empty() {
bank_code_responses.push(BankCodeResponse {
bank_name: remaining_bank_codes
.into_iter()
.map(|ele| ele.to_owned())
.collect(),
eligible_connectors: vec![connector],
})
}
} else {
logger::error!("Could not find any configured banks for payment_method -> {pm_type} for connector -> {connector}");
}
}
Ok(bank_code_responses)
}
}
fn get_val(str: String, val: &serde_json::Value) -> Option<String> {
str.split('.')
.try_fold(val, |acc, x| acc.get(x))
.and_then(|v| v.as_str())
.map(|s| s.to_string())
}
#[cfg(feature = "v1")]
pub async fn list_payment_methods(
state: routes::SessionState,
merchant_context: domain::MerchantContext,
mut req: api::PaymentMethodListRequest,
) -> errors::RouterResponse<api::PaymentMethodListResponse> {
let db = &*state.store;
let pm_config_mapping = &state.conf.pm_filters;
let key_manager_state = &(&state).into();
let payment_intent = if let Some(cs) = &req.client_secret {
if cs.starts_with("pm_") {
validate_payment_method_and_client_secret(&state, cs, db, &merchant_context).await?;
None
} else {
helpers::verify_payment_intent_time_and_client_secret(
&state,
&merchant_context,
req.client_secret.clone(),
)
.await?
}
} else {
None
};
let shipping_address = payment_intent
.as_ref()
.async_map(|pi| async {
helpers::get_address_by_id(
&state,
pi.shipping_address_id.clone(),
merchant_context.get_merchant_key_store(),
&pi.payment_id,
merchant_context.get_merchant_account().get_id(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
})
.await
.transpose()?
.flatten();
let billing_address = payment_intent
.as_ref()
.async_map(|pi| async {
helpers::get_address_by_id(
&state,
pi.billing_address_id.clone(),
merchant_context.get_merchant_key_store(),
&pi.payment_id,
merchant_context.get_merchant_account().get_id(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
})
.await
.transpose()?
.flatten();
let customer = payment_intent
.as_ref()
.async_and_then(|pi| async {
pi.customer_id
.as_ref()
.async_and_then(|cust| async {
db.find_customer_by_customer_id_merchant_id(
key_manager_state,
cust,
&pi.merchant_id,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)
.ok()
})
.await
})
.await;
let payment_attempt = payment_intent
.as_ref()
.async_map(|pi| async {
db.find_payment_attempt_by_payment_id_merchant_id_attempt_id(
&pi.payment_id,
&pi.merchant_id,
&pi.active_attempt.get_id(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::PaymentNotFound)
})
.await
.transpose()?;
let setup_future_usage = payment_intent.as_ref().and_then(|pi| pi.setup_future_usage);
let is_cit_transaction = payment_attempt
.as_ref()
.map(|pa| pa.mandate_details.is_some())
.unwrap_or(false)
|| setup_future_usage
.map(|future_usage| future_usage == common_enums::FutureUsage::OffSession)
.unwrap_or(false);
let payment_type = payment_attempt.as_ref().map(|pa| {
let amount = api::Amount::from(pa.net_amount.get_order_amount());
let mandate_type = if pa.mandate_id.is_some() {
Some(api::MandateTransactionType::RecurringMandateTransaction)
} else if is_cit_transaction {
Some(api::MandateTransactionType::NewMandateTransaction)
} else {
None
};
helpers::infer_payment_type(amount, mandate_type.as_ref())
});
let all_mcas = db
.find_merchant_connector_account_by_merchant_id_and_disabled_list(
key_manager_state,
merchant_context.get_merchant_account().get_id(),
false,
merchant_context.get_merchant_key_store(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
let profile_id = payment_intent
.as_ref()
.and_then(|payment_intent| payment_intent.profile_id.as_ref())
.get_required_value("profile_id")
.change_context(errors::ApiErrorResponse::GenericNotFoundError {
message: "Profile id not found".to_string(),
})?;
let business_profile = db
.find_business_profile_by_profile_id(
key_manager_state,
merchant_context.get_merchant_key_store(),
profile_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
// filter out payment connectors based on profile_id
let filtered_mcas = all_mcas
.clone()
.filter_based_on_profile_and_connector_type(profile_id, ConnectorType::PaymentProcessor);
logger::debug!(mca_before_filtering=?filtered_mcas);
let mut response: Vec<ResponsePaymentMethodIntermediate> = vec![];
// Key creation for storing PM_FILTER_CGRAPH
let key = {
format!(
"pm_filters_cgraph_{}_{}",
merchant_context
.get_merchant_account()
.get_id()
.get_string_repr(),
profile_id.get_string_repr()
)
};
if let Some(graph) = get_merchant_pm_filter_graph(&state, &key).await {
// Derivation of PM_FILTER_CGRAPH from MokaCache successful
for mca in &filtered_mcas {
let payment_methods = match &mca.payment_methods_enabled {
Some(pm) => pm,
None => continue,
};
filter_payment_methods(
&graph,
mca.get_id(),
payment_methods,
&mut req,
&mut response,
payment_intent.as_ref(),
payment_attempt.as_ref(),
billing_address.as_ref(),
mca.connector_name.clone(),
&state.conf,
)
.await?;
}
} else {
// No PM_FILTER_CGRAPH Cache present in MokaCache
let mut builder = cgraph::ConstraintGraphBuilder::new();
for mca in &filtered_mcas {
let domain_id = builder.make_domain(
mca.get_id().get_string_repr().to_string(),
mca.connector_name.as_str(),
);
let Ok(domain_id) = domain_id else {
logger::error!("Failed to construct domain for list payment methods");
return Err(errors::ApiErrorResponse::InternalServerError.into());
};
let payment_methods = match &mca.payment_methods_enabled {
Some(pm) => pm,
None => continue,
};
if let Err(e) = make_pm_graph(
&mut builder,
domain_id,
payment_methods,
mca.connector_name.clone(),
pm_config_mapping,
&state.conf.mandates.supported_payment_methods,
&state.conf.mandates.update_mandate_supported,
) {
logger::error!(
"Failed to construct constraint graph for list payment methods {e:?}"
);
}
}
// Refreshing our CGraph cache
let graph = refresh_pm_filters_cache(&state, &key, builder.build()).await;
for mca in &filtered_mcas {
let payment_methods = match &mca.payment_methods_enabled {
Some(pm) => pm,
None => continue,
};
filter_payment_methods(
&graph,
mca.get_id().clone(),
payment_methods,
&mut req,
&mut response,
payment_intent.as_ref(),
payment_attempt.as_ref(),
billing_address.as_ref(),
mca.connector_name.clone(),
&state.conf,
)
.await?;
}
}
logger::info!(
"The Payment Methods available after Constraint Graph filtering are {:?}",
response
);
let mut pmt_to_auth_connector: HashMap<
enums::PaymentMethod,
HashMap<enums::PaymentMethodType, String>,
> = HashMap::new();
if let Some((payment_attempt, payment_intent)) =
payment_attempt.as_ref().zip(payment_intent.as_ref())
{
let routing_enabled_pms = &router_consts::ROUTING_ENABLED_PAYMENT_METHODS;
let routing_enabled_pm_types = &router_consts::ROUTING_ENABLED_PAYMENT_METHOD_TYPES;
let mut chosen = api::SessionConnectorDatas::new(Vec::new());
for intermediate in &response {
if routing_enabled_pm_types.contains(&intermediate.payment_method_type)
|| routing_enabled_pms.contains(&intermediate.payment_method)
{
let connector_data = helpers::get_connector_data_with_token(
&state,
intermediate.connector.to_string(),
None,
intermediate.payment_method_type,
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("invalid connector name received")?;
chosen.push(api::SessionConnectorData {
payment_method_sub_type: intermediate.payment_method_type,
payment_method_type: intermediate.payment_method,
connector: connector_data,
business_sub_label: None,
});
}
}
let sfr = SessionFlowRoutingInput {
state: &state,
country: billing_address.clone().and_then(|ad| ad.country),
key_store: merchant_context.get_merchant_key_store(),
merchant_account: merchant_context.get_merchant_account(),
payment_attempt,
payment_intent,
chosen,
};
let (result, routing_approach) = routing::perform_session_flow_routing(
sfr,
&business_profile,
&enums::TransactionType::Payment,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("error performing session flow routing")?;
response.retain(|intermediate| {
if !routing_enabled_pm_types.contains(&intermediate.payment_method_type)
&& !routing_enabled_pms.contains(&intermediate.payment_method)
{
return true;
}
if let Some(choice) = result.get(&intermediate.payment_method_type) {
if let Some(first_routable_connector) = choice.first() {
intermediate.connector
== first_routable_connector
.connector
.connector_name
.to_string()
&& first_routable_connector
.connector
.merchant_connector_id
.as_ref()
.map(|merchant_connector_id| {
*merchant_connector_id.get_string_repr()
== intermediate.merchant_connector_id
})
.unwrap_or_default()
} else {
false
}
} else {
false
}
});
let mut routing_info: storage::PaymentRoutingInfo = payment_attempt
.straight_through_algorithm
.clone()
.map(|val| val.parse_value("PaymentRoutingInfo"))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Invalid PaymentRoutingInfo format found in payment attempt")?
.unwrap_or(storage::PaymentRoutingInfo {
algorithm: None,
pre_routing_results: None,
});
let mut pre_routing_results: HashMap<
api_enums::PaymentMethodType,
storage::PreRoutingConnectorChoice,
> = HashMap::new();
for (pm_type, routing_choice) in result {
let mut routable_choice_list = vec![];
for choice in routing_choice {
let routable_choice = routing_types::RoutableConnectorChoice {
choice_kind: routing_types::RoutableChoiceKind::FullStruct,
connector: choice
.connector
.connector_name
.to_string()
.parse::<api_enums::RoutableConnectors>()
.change_context(errors::ApiErrorResponse::InternalServerError)?,
merchant_connector_id: choice.connector.merchant_connector_id.clone(),
};
routable_choice_list.push(routable_choice);
}
pre_routing_results.insert(
pm_type,
storage::PreRoutingConnectorChoice::Multiple(routable_choice_list),
);
}
let redis_conn = db
.get_redis_conn()
.map_err(|redis_error| logger::error!(?redis_error))
.ok();
let mut val = Vec::new();
for (payment_method_type, routable_connector_choice) in &pre_routing_results {
let routable_connector_list = match routable_connector_choice {
storage::PreRoutingConnectorChoice::Single(routable_connector) => {
vec![routable_connector.clone()]
}
storage::PreRoutingConnectorChoice::Multiple(routable_connector_list) => {
routable_connector_list.clone()
}
};
let first_routable_connector = routable_connector_list
.first()
.ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)?;
let matched_mca = filtered_mcas.iter().find(|m| {
first_routable_connector.merchant_connector_id.as_ref() == Some(&m.get_id())
});
if let Some(m) = matched_mca {
let pm_auth_config = m
.pm_auth_config
.as_ref()
.map(|config| {
serde_json::from_value::<PaymentMethodAuthConfig>(config.clone().expose())
.change_context(errors::StorageError::DeserializationFailed)
.attach_printable("Failed to deserialize Payment Method Auth config")
})
.transpose()
.unwrap_or_else(|error| {
logger::error!(?error);
None
});
if let Some(config) = pm_auth_config {
for inner_config in config.enabled_payment_methods.iter() {
let is_active_mca = all_mcas
.iter()
.any(|mca| mca.get_id() == inner_config.mca_id);
if inner_config.payment_method_type == *payment_method_type && is_active_mca
{
let pm = pmt_to_auth_connector
.get(&inner_config.payment_method)
.cloned();
let inner_map = if let Some(mut inner_map) = pm {
inner_map.insert(
*payment_method_type,
inner_config.connector_name.clone(),
);
inner_map
} else {
HashMap::from([(
*payment_method_type,
inner_config.connector_name.clone(),
)])
};
pmt_to_auth_connector.insert(inner_config.payment_method, inner_map);
val.push(inner_config.clone());
}
}
};
}
}
let pm_auth_key = payment_intent.payment_id.get_pm_auth_key();
let redis_expiry = state.conf.payment_method_auth.get_inner().redis_expiry;
if let Some(rc) = redis_conn {
rc.serialize_and_set_key_with_expiry(&pm_auth_key.as_str().into(), val, redis_expiry)
.await
.attach_printable("Failed to store pm auth data in redis")
.unwrap_or_else(|error| {
logger::error!(?error);
})
};
routing_info.pre_routing_results = Some(pre_routing_results);
let encoded = routing_info
.encode_to_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to serialize payment routing info to value")?;
let attempt_update = storage::PaymentAttemptUpdate::UpdateTrackers {
payment_token: None,
connector: None,
straight_through_algorithm: Some(encoded),
amount_capturable: None,
updated_by: merchant_context
.get_merchant_account()
.storage_scheme
.to_string(),
merchant_connector_id: None,
surcharge_amount: None,
tax_amount: None,
routing_approach,
is_stored_credential: None,
};
state
.store
.update_payment_attempt_with_attempt_id(
payment_attempt.clone(),
attempt_update,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
}
// Check for `use_billing_as_payment_method_billing` config under business_profile
// If this is disabled, then the billing details in required fields will be empty and have to be collected by the customer
let billing_address_for_calculating_required_fields = business_profile
.use_billing_as_payment_method_billing
.unwrap_or(true)
.then_some(billing_address.as_ref())
.flatten();
let req = api_models::payments::PaymentsRequest::foreign_try_from((
payment_attempt.as_ref(),
payment_intent.as_ref(),
shipping_address.as_ref(),
billing_address_for_calculating_required_fields,
customer.as_ref(),
))?;
let req_val = serde_json::to_value(req).ok();
logger::debug!(filtered_payment_methods=?response);
let mut payment_experiences_consolidated_hm: HashMap<
api_enums::PaymentMethod,
HashMap<api_enums::PaymentMethodType, HashMap<api_enums::PaymentExperience, Vec<String>>>,
> = HashMap::new();
let mut card_networks_consolidated_hm: HashMap<
api_enums::PaymentMethod,
HashMap<api_enums::PaymentMethodType, HashMap<api_enums::CardNetwork, Vec<String>>>,
> = HashMap::new();
let mut banks_consolidated_hm: HashMap<api_enums::PaymentMethodType, Vec<String>> =
HashMap::new();
let mut bank_debits_consolidated_hm =
HashMap::<api_enums::PaymentMethodType, Vec<String>>::new();
let mut bank_transfer_consolidated_hm =
HashMap::<api_enums::PaymentMethodType, Vec<String>>::new();
// All the required fields will be stored here and later filtered out based on business profile config
let mut required_fields_hm = HashMap::<
api_enums::PaymentMethod,
HashMap<api_enums::PaymentMethodType, HashMap<String, RequiredFieldInfo>>,
>::new();
for element in response.clone() {
let payment_method = element.payment_method;
let payment_method_type = element.payment_method_type;
let connector = element.connector.clone();
let connector_variant = api_enums::Connector::from_str(connector.as_str())
.change_context(errors::ConnectorError::InvalidConnectorName)
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "connector",
})
.attach_printable_lazy(|| format!("unable to parse connector name {connector:?}"))?;
state.conf.required_fields.0.get(&payment_method).map(
|required_fields_hm_for_each_payment_method_type| {
required_fields_hm_for_each_payment_method_type
.0
.get(&payment_method_type)
.map(|required_fields_hm_for_each_connector| {
required_fields_hm.entry(payment_method).or_default();
required_fields_hm_for_each_connector
.fields
.get(&connector_variant)
.map(|required_fields_final| {
let mut required_fields_hs = required_fields_final.common.clone();
if is_cit_transaction {
required_fields_hs
.extend(required_fields_final.mandate.clone());
} else {
required_fields_hs
.extend(required_fields_final.non_mandate.clone());
}
required_fields_hs = should_collect_shipping_or_billing_details_from_wallet_connector(
payment_method,
element.payment_experience.as_ref(),
&business_profile,
required_fields_hs.clone(),
);
// get the config, check the enums while adding
{
for (key, val) in &mut required_fields_hs {
let temp = req_val
.as_ref()
.and_then(|r| get_val(key.to_owned(), r));
if let Some(s) = temp {
val.value = Some(s.into())
};
}
}
let existing_req_fields_hs = required_fields_hm
.get_mut(&payment_method)
.and_then(|inner_hm| inner_hm.get_mut(&payment_method_type));
// If payment_method_type already exist in required_fields_hm, extend the required_fields hs to existing hs.
if let Some(inner_hs) = existing_req_fields_hs {
inner_hs.extend(required_fields_hs);
} else {
required_fields_hm.get_mut(&payment_method).map(|inner_hm| {
inner_hm.insert(payment_method_type, required_fields_hs)
});
}
})
})
},
);
if let Some(payment_experience) = element.payment_experience {
if let Some(payment_method_hm) =
payment_experiences_consolidated_hm.get_mut(&payment_method)
{
if let Some(payment_method_type_hm) =
payment_method_hm.get_mut(&payment_method_type)
{
if let Some(vector_of_connectors) =
payment_method_type_hm.get_mut(&payment_experience)
{
vector_of_connectors.push(connector);
} else {
payment_method_type_hm.insert(payment_experience, vec![connector]);
}
} else {
payment_method_hm.insert(
payment_method_type,
HashMap::from([(payment_experience, vec![connector])]),
);
}
} else {
let inner_hm = HashMap::from([(payment_experience, vec![connector])]);
let payment_method_type_hm = HashMap::from([(payment_method_type, inner_hm)]);
payment_experiences_consolidated_hm.insert(payment_method, payment_method_type_hm);
}
}
if let Some(card_networks) = element.card_networks {
if let Some(payment_method_hm) = card_networks_consolidated_hm.get_mut(&payment_method)
{
if let Some(payment_method_type_hm) =
payment_method_hm.get_mut(&payment_method_type)
{
for card_network in card_networks {
if let Some(vector_of_connectors) =
payment_method_type_hm.get_mut(&card_network)
{
let connector = element.connector.clone();
vector_of_connectors.push(connector);
} else {
let connector = element.connector.clone();
payment_method_type_hm.insert(card_network, vec![connector]);
}
}
} else {
let mut inner_hashmap: HashMap<api_enums::CardNetwork, Vec<String>> =
HashMap::new();
for card_network in card_networks {
if let Some(vector_of_connectors) = inner_hashmap.get_mut(&card_network) {
let connector = element.connector.clone();
vector_of_connectors.push(connector);
} else {
let connector = element.connector.clone();
inner_hashmap.insert(card_network, vec![connector]);
}
}
payment_method_hm.insert(payment_method_type, inner_hashmap);
}
} else {
let mut inner_hashmap: HashMap<api_enums::CardNetwork, Vec<String>> =
HashMap::new();
for card_network in card_networks {
if let Some(vector_of_connectors) = inner_hashmap.get_mut(&card_network) {
let connector = element.connector.clone();
vector_of_connectors.push(connector);
} else {
let connector = element.connector.clone();
inner_hashmap.insert(card_network, vec![connector]);
}
}
let payment_method_type_hm = HashMap::from([(payment_method_type, inner_hashmap)]);
card_networks_consolidated_hm.insert(payment_method, payment_method_type_hm);
}
}
if element.payment_method == api_enums::PaymentMethod::BankRedirect {
let connector = element.connector.clone();
if let Some(vector_of_connectors) =
banks_consolidated_hm.get_mut(&element.payment_method_type)
{
vector_of_connectors.push(connector);
} else {
banks_consolidated_hm.insert(element.payment_method_type, vec![connector]);
}
}
if element.payment_method == api_enums::PaymentMethod::BankDebit {
let connector = element.connector.clone();
if let Some(vector_of_connectors) =
bank_debits_consolidated_hm.get_mut(&element.payment_method_type)
{
vector_of_connectors.push(connector);
} else {
bank_debits_consolidated_hm.insert(element.payment_method_type, vec![connector]);
}
}
if element.payment_method == api_enums::PaymentMethod::BankTransfer {
let connector = element.connector.clone();
if let Some(vector_of_connectors) =
bank_transfer_consolidated_hm.get_mut(&element.payment_method_type)
{
vector_of_connectors.push(connector);
} else {
bank_transfer_consolidated_hm.insert(element.payment_method_type, vec![connector]);
}
}
}
let mut payment_method_responses: Vec<ResponsePaymentMethodsEnabled> = vec![];
for key in payment_experiences_consolidated_hm.iter() {
let mut payment_method_types = vec![];
for payment_method_types_hm in key.1 {
let mut payment_experience_types = vec![];
for payment_experience_type in payment_method_types_hm.1 {
payment_experience_types.push(PaymentExperienceTypes {
payment_experience_type: *payment_experience_type.0,
eligible_connectors: payment_experience_type.1.clone(),
})
}
payment_method_types.push(ResponsePaymentMethodTypes {
payment_method_type: *payment_method_types_hm.0,
payment_experience: Some(payment_experience_types),
card_networks: None,
bank_names: None,
bank_debits: None,
bank_transfers: None,
// Required fields for PayLater payment method
required_fields: required_fields_hm
.get(key.0)
.and_then(|inner_hm| inner_hm.get(payment_method_types_hm.0))
.cloned(),
surcharge_details: None,
pm_auth_connector: pmt_to_auth_connector
.get(key.0)
.and_then(|pm_map| pm_map.get(payment_method_types_hm.0))
.cloned(),
})
}
payment_method_responses.push(ResponsePaymentMethodsEnabled {
payment_method: *key.0,
payment_method_types,
})
}
for key in card_networks_consolidated_hm.iter() {
let mut payment_method_types = vec![];
for payment_method_types_hm in key.1 {
let mut card_network_types = vec![];
for card_network_type in payment_method_types_hm.1 {
card_network_types.push(CardNetworkTypes {
card_network: card_network_type.0.clone(),
eligible_connectors: card_network_type.1.clone(),
surcharge_details: None,
})
}
payment_method_types.push(ResponsePaymentMethodTypes {
payment_method_type: *payment_method_types_hm.0,
card_networks: Some(card_network_types),
payment_experience: None,
bank_names: None,
bank_debits: None,
bank_transfers: None,
// Required fields for Card payment method
required_fields: required_fields_hm
.get(key.0)
.and_then(|inner_hm| inner_hm.get(payment_method_types_hm.0))
.cloned(),
surcharge_details: None,
pm_auth_connector: pmt_to_auth_connector
.get(key.0)
.and_then(|pm_map| pm_map.get(payment_method_types_hm.0))
.cloned(),
})
}
payment_method_responses.push(ResponsePaymentMethodsEnabled {
payment_method: *key.0,
payment_method_types,
})
}
let mut bank_redirect_payment_method_types = vec![];
for key in banks_consolidated_hm.iter() {
let payment_method_type = *key.0;
let connectors = key.1.clone();
let bank_names = get_banks(&state, payment_method_type, connectors)?;
bank_redirect_payment_method_types.push({
ResponsePaymentMethodTypes {
payment_method_type,
bank_names: Some(bank_names),
payment_experience: None,
card_networks: None,
bank_debits: None,
bank_transfers: None,
// Required fields for BankRedirect payment method
required_fields: required_fields_hm
.get(&api_enums::PaymentMethod::BankRedirect)
.and_then(|inner_hm| inner_hm.get(key.0))
.cloned(),
surcharge_details: None,
pm_auth_connector: pmt_to_auth_connector
.get(&enums::PaymentMethod::BankRedirect)
.and_then(|pm_map| pm_map.get(key.0))
.cloned(),
}
})
}
if !bank_redirect_payment_method_types.is_empty() {
payment_method_responses.push(ResponsePaymentMethodsEnabled {
payment_method: api_enums::PaymentMethod::BankRedirect,
payment_method_types: bank_redirect_payment_method_types,
});
}
let mut bank_debit_payment_method_types = vec![];
for key in bank_debits_consolidated_hm.iter() {
let payment_method_type = *key.0;
let connectors = key.1.clone();
bank_debit_payment_method_types.push({
ResponsePaymentMethodTypes {
payment_method_type,
bank_names: None,
payment_experience: None,
card_networks: None,
bank_debits: Some(api_models::payment_methods::BankDebitTypes {
eligible_connectors: connectors.clone(),
}),
bank_transfers: None,
// Required fields for BankDebit payment method
required_fields: required_fields_hm
.get(&api_enums::PaymentMethod::BankDebit)
.and_then(|inner_hm| inner_hm.get(key.0))
.cloned(),
surcharge_details: None,
pm_auth_connector: pmt_to_auth_connector
.get(&enums::PaymentMethod::BankDebit)
.and_then(|pm_map| pm_map.get(key.0))
.cloned(),
}
})
}
if !bank_debit_payment_method_types.is_empty() {
payment_method_responses.push(ResponsePaymentMethodsEnabled {
payment_method: api_enums::PaymentMethod::BankDebit,
payment_method_types: bank_debit_payment_method_types,
});
}
let mut bank_transfer_payment_method_types = vec![];
for key in bank_transfer_consolidated_hm.iter() {
let payment_method_type = *key.0;
let connectors = key.1.clone();
bank_transfer_payment_method_types.push({
ResponsePaymentMethodTypes {
payment_method_type,
bank_names: None,
payment_experience: None,
card_networks: None,
bank_debits: None,
bank_transfers: Some(api_models::payment_methods::BankTransferTypes {
eligible_connectors: connectors,
}),
// Required fields for BankTransfer payment method
required_fields: required_fields_hm
.get(&api_enums::PaymentMethod::BankTransfer)
.and_then(|inner_hm| inner_hm.get(key.0))
.cloned(),
surcharge_details: None,
pm_auth_connector: pmt_to_auth_connector
.get(&enums::PaymentMethod::BankTransfer)
.and_then(|pm_map| pm_map.get(key.0))
.cloned(),
}
})
}
if !bank_transfer_payment_method_types.is_empty() {
payment_method_responses.push(ResponsePaymentMethodsEnabled {
payment_method: api_enums::PaymentMethod::BankTransfer,
payment_method_types: bank_transfer_payment_method_types,
});
}
let currency = payment_intent.as_ref().and_then(|pi| pi.currency);
let skip_external_tax_calculation = payment_intent
.as_ref()
.and_then(|intent| intent.skip_external_tax_calculation)
.unwrap_or(false);
let request_external_three_ds_authentication = payment_intent
.as_ref()
.and_then(|intent| intent.request_external_three_ds_authentication)
.unwrap_or(false);
let merchant_surcharge_configs = if let Some((payment_attempt, payment_intent)) =
payment_attempt.as_ref().zip(payment_intent)
{
Box::pin(call_surcharge_decision_management(
state,
&merchant_context,
&business_profile,
payment_attempt,
payment_intent,
billing_address,
&mut payment_method_responses,
))
.await?
} else {
api_surcharge_decision_configs::MerchantSurchargeConfigs::default()
};
let collect_shipping_details_from_wallets = if business_profile
.always_collect_shipping_details_from_wallet_connector
.unwrap_or(false)
{
business_profile.always_collect_shipping_details_from_wallet_connector
} else {
business_profile.collect_shipping_details_from_wallet_connector
};
let collect_billing_details_from_wallets = if business_profile
.always_collect_billing_details_from_wallet_connector
.unwrap_or(false)
{
business_profile.always_collect_billing_details_from_wallet_connector
} else {
business_profile.collect_billing_details_from_wallet_connector
};
let is_tax_connector_enabled = business_profile.get_is_tax_connector_enabled();
Ok(services::ApplicationResponse::Json(
api::PaymentMethodListResponse {
redirect_url: business_profile.return_url.clone(),
merchant_name: merchant_context
.get_merchant_account()
.merchant_name
.to_owned(),
payment_type,
payment_methods: payment_method_responses,
mandate_payment: payment_attempt.and_then(|inner| inner.mandate_details).map(
|d| match d {
hyperswitch_domain_models::mandates::MandateDataType::SingleUse(i) => {
api::MandateType::SingleUse(api::MandateAmountData {
amount: i.amount,
currency: i.currency,
start_date: i.start_date,
end_date: i.end_date,
metadata: i.metadata,
})
}
hyperswitch_domain_models::mandates::MandateDataType::MultiUse(Some(i)) => {
api::MandateType::MultiUse(Some(api::MandateAmountData {
amount: i.amount,
currency: i.currency,
start_date: i.start_date,
end_date: i.end_date,
metadata: i.metadata,
}))
}
hyperswitch_domain_models::mandates::MandateDataType::MultiUse(None) => {
api::MandateType::MultiUse(None)
}
},
),
show_surcharge_breakup_screen: merchant_surcharge_configs
.show_surcharge_breakup_screen
.unwrap_or_default(),
currency,
request_external_three_ds_authentication,
collect_shipping_details_from_wallets,
collect_billing_details_from_wallets,
is_tax_calculation_enabled: is_tax_connector_enabled && !skip_external_tax_calculation,
},
))
}
#[cfg(feature = "v1")]
fn should_collect_shipping_or_billing_details_from_wallet_connector(
payment_method: api_enums::PaymentMethod,
payment_experience_optional: Option<&api_enums::PaymentExperience>,
business_profile: &Profile,
mut required_fields_hs: HashMap<String, RequiredFieldInfo>,
) -> HashMap<String, RequiredFieldInfo> {
match (payment_method, payment_experience_optional) {
(api_enums::PaymentMethod::Wallet, Some(api_enums::PaymentExperience::InvokeSdkClient))
| (
api_enums::PaymentMethod::PayLater,
Some(api_enums::PaymentExperience::InvokeSdkClient),
) => {
let always_send_billing_details =
business_profile.always_collect_billing_details_from_wallet_connector;
let always_send_shipping_details =
business_profile.always_collect_shipping_details_from_wallet_connector;
if always_send_billing_details == Some(true) {
let billing_details = get_billing_required_fields();
required_fields_hs.extend(billing_details)
};
if always_send_shipping_details == Some(true) {
let shipping_details = get_shipping_required_fields();
required_fields_hs.extend(shipping_details)
};
required_fields_hs
}
_ => required_fields_hs,
}
}
#[cfg(feature = "v1")]
async fn validate_payment_method_and_client_secret(
state: &routes::SessionState,
cs: &String,
db: &dyn db::StorageInterface,
merchant_context: &domain::MerchantContext,
) -> Result<(), error_stack::Report<errors::ApiErrorResponse>> {
let pm_vec = cs.split("_secret").collect::<Vec<&str>>();
let pm_id = pm_vec
.first()
.ok_or(errors::ApiErrorResponse::MissingRequiredField {
field_name: "client_secret",
})?;
let payment_method = db
.find_payment_method(
&(state.into()),
merchant_context.get_merchant_key_store(),
pm_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::PaymentMethodNotFound)
.attach_printable("Unable to find payment method")?;
let client_secret_expired =
authenticate_pm_client_secret_and_check_expiry(cs, &payment_method)?;
if client_secret_expired {
return Err::<(), error_stack::Report<errors::ApiErrorResponse>>(
(errors::ApiErrorResponse::ClientSecretExpired).into(),
);
}
Ok(())
}
#[cfg(feature = "v1")]
#[allow(clippy::too_many_arguments)]
pub async fn call_surcharge_decision_management(
state: routes::SessionState,
merchant_context: &domain::MerchantContext,
business_profile: &Profile,
payment_attempt: &storage::PaymentAttempt,
payment_intent: storage::PaymentIntent,
billing_address: Option<domain::Address>,
response_payment_method_types: &mut [ResponsePaymentMethodsEnabled],
) -> errors::RouterResult<api_surcharge_decision_configs::MerchantSurchargeConfigs> {
#[cfg(feature = "v1")]
let algorithm_ref: routing_types::RoutingAlgorithmRef = merchant_context
.get_merchant_account()
.routing_algorithm
.clone()
.map(|val| val.parse_value("routing algorithm"))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Could not decode the routing algorithm")?
.unwrap_or_default();
// TODO: Move to business profile surcharge decision column
#[cfg(feature = "v2")]
let algorithm_ref: routing_types::RoutingAlgorithmRef = todo!();
let (surcharge_results, merchant_sucharge_configs) =
perform_surcharge_decision_management_for_payment_method_list(
&state,
algorithm_ref,
payment_attempt,
&payment_intent,
billing_address.as_ref().map(Into::into),
response_payment_method_types,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("error performing surcharge decision operation")?;
if !surcharge_results.is_empty_result() {
surcharge_results
.persist_individual_surcharge_details_in_redis(&state, business_profile)
.await?;
let _ = state
.store
.update_payment_intent(
&(&state).into(),
payment_intent,
storage::PaymentIntentUpdate::SurchargeApplicableUpdate {
surcharge_applicable: true,
updated_by: merchant_context
.get_merchant_account()
.storage_scheme
.to_string(),
},
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)
.attach_printable("Failed to update surcharge_applicable in Payment Intent");
}
Ok(merchant_sucharge_configs)
}
#[cfg(feature = "v1")]
pub async fn call_surcharge_decision_management_for_saved_card(
state: &routes::SessionState,
merchant_context: &domain::MerchantContext,
business_profile: &Profile,
payment_attempt: &storage::PaymentAttempt,
payment_intent: storage::PaymentIntent,
customer_payment_method_response: &mut api::CustomerPaymentMethodsListResponse,
) -> errors::RouterResult<()> {
#[cfg(feature = "v1")]
let algorithm_ref: routing_types::RoutingAlgorithmRef = merchant_context
.get_merchant_account()
.routing_algorithm
.clone()
.map(|val| val.parse_value("routing algorithm"))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Could not decode the routing algorithm")?
.unwrap_or_default();
#[cfg(feature = "v2")]
let algorithm_ref: routing_types::RoutingAlgorithmRef = todo!();
// TODO: Move to business profile surcharge column
let surcharge_results = perform_surcharge_decision_management_for_saved_cards(
state,
algorithm_ref,
payment_attempt,
&payment_intent,
&mut customer_payment_method_response.customer_payment_methods,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("error performing surcharge decision operation")?;
if !surcharge_results.is_empty_result() {
surcharge_results
.persist_individual_surcharge_details_in_redis(state, business_profile)
.await?;
let _ = state
.store
.update_payment_intent(
&state.into(),
payment_intent,
storage::PaymentIntentUpdate::SurchargeApplicableUpdate {
surcharge_applicable: true,
updated_by: merchant_context
.get_merchant_account()
.storage_scheme
.to_string(),
},
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)
.attach_printable("Failed to update surcharge_applicable in Payment Intent");
}
Ok(())
}
#[cfg(feature = "v1")]
#[allow(clippy::too_many_arguments)]
pub async fn filter_payment_methods(
graph: &cgraph::ConstraintGraph<dir::DirValue>,
mca_id: id_type::MerchantConnectorAccountId,
payment_methods: &[Secret<serde_json::Value>],
req: &mut api::PaymentMethodListRequest,
resp: &mut Vec<ResponsePaymentMethodIntermediate>,
payment_intent: Option<&storage::PaymentIntent>,
payment_attempt: Option<&storage::PaymentAttempt>,
address: Option<&domain::Address>,
connector: String,
configs: &settings::Settings<RawSecret>,
) -> errors::CustomResult<(), errors::ApiErrorResponse> {
for payment_method in payment_methods.iter() {
let parse_result = serde_json::from_value::<PaymentMethodsEnabled>(
payment_method.clone().expose().clone(),
);
if let Ok(payment_methods_enabled) = parse_result {
let payment_method = payment_methods_enabled.payment_method;
let allowed_payment_method_types = payment_intent.and_then(|payment_intent| {
payment_intent
.allowed_payment_method_types
.clone()
.map(|val| val.parse_value("Vec<PaymentMethodType>"))
.transpose()
.unwrap_or_else(|error| {
logger::error!(
?error,
"Failed to deserialize PaymentIntent allowed_payment_method_types"
);
None
})
});
for payment_method_type_info in payment_methods_enabled
.payment_method_types
.unwrap_or_default()
{
if filter_recurring_based(&payment_method_type_info, req.recurring_enabled)
&& filter_installment_based(
&payment_method_type_info,
req.installment_payment_enabled,
)
&& filter_amount_based(&payment_method_type_info, req.amount)
{
let payment_method_object = payment_method_type_info.clone();
let pm_dir_value: dir::DirValue =
(payment_method_type_info.payment_method_type, payment_method)
.into_dir_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("pm_value_node not created")?;
let connector_variant = api_enums::Connector::from_str(connector.as_str())
.change_context(errors::ConnectorError::InvalidConnectorName)
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "connector",
})
.attach_printable_lazy(|| {
format!("unable to parse connector name {connector:?}")
})?;
let mut context_values: Vec<dir::DirValue> = Vec::new();
context_values.push(pm_dir_value.clone());
payment_intent.map(|intent| {
intent.currency.map(|currency| {
context_values.push(dir::DirValue::PaymentCurrency(currency))
})
});
address.map(|address| {
address.country.map(|country| {
context_values.push(dir::DirValue::BillingCountry(
common_enums::Country::from_alpha2(country),
))
})
});
// Addition of Connector to context
if let Ok(connector) = api_enums::RoutableConnectors::from_str(
connector_variant.to_string().as_str(),
) {
context_values.push(dir::DirValue::Connector(Box::new(
api_models::routing::ast::ConnectorChoice { connector },
)));
};
let filter_pm_based_on_allowed_types = filter_pm_based_on_allowed_types(
allowed_payment_method_types.as_ref(),
payment_method_object.payment_method_type,
);
// Filter logic for payment method types based on the below conditions
// Case 1: If the payment method type support Zero Mandate flow, filter only payment method type that support it
// Case 2: Whether the payment method type support Mandates or not, list all the payment method types
if payment_attempt
.and_then(|attempt| attempt.mandate_details.as_ref())
.is_some()
|| payment_intent
.and_then(|intent| intent.setup_future_usage)
.map(|future_usage| {
future_usage == common_enums::FutureUsage::OffSession
})
.unwrap_or(false)
{
payment_intent.map(|intent| intent.amount).map(|amount| {
if amount == MinorUnit::zero() {
if configs
.zero_mandates
.supported_payment_methods
.0
.get(&payment_method)
.and_then(|supported_pm_for_mandates| {
supported_pm_for_mandates
.0
.get(&payment_method_type_info.payment_method_type)
.map(|supported_connector_for_mandates| {
supported_connector_for_mandates
.connector_list
.contains(&connector_variant)
})
})
.unwrap_or(false)
{
context_values.push(dir::DirValue::PaymentType(
euclid::enums::PaymentType::SetupMandate,
));
}
} else if configs
.mandates
.supported_payment_methods
.0
.get(&payment_method)
.and_then(|supported_pm_for_mandates| {
supported_pm_for_mandates
.0
.get(&payment_method_type_info.payment_method_type)
.map(|supported_connector_for_mandates| {
supported_connector_for_mandates
.connector_list
.contains(&connector_variant)
})
})
.unwrap_or(false)
{
context_values.push(dir::DirValue::PaymentType(
euclid::enums::PaymentType::NewMandate,
));
} else {
context_values.push(dir::DirValue::PaymentType(
euclid::enums::PaymentType::NonMandate,
));
}
});
} else {
context_values.push(dir::DirValue::PaymentType(
euclid::enums::PaymentType::NonMandate,
));
}
payment_attempt
.and_then(|attempt| attempt.mandate_data.as_ref())
.map(|mandate_detail| {
if mandate_detail.update_mandate_id.is_some() {
context_values.push(dir::DirValue::PaymentType(
euclid::enums::PaymentType::UpdateMandate,
));
}
});
payment_attempt
.and_then(|inner| inner.capture_method)
.map(|capture_method| {
context_values.push(dir::DirValue::CaptureMethod(capture_method));
});
let filter_pm_card_network_based = filter_pm_card_network_based(
payment_method_object.card_networks.as_ref(),
req.card_networks.as_ref(),
payment_method_object.payment_method_type,
);
let saved_payment_methods_filter = req
.client_secret
.as_ref()
.map(|cs| {
if cs.starts_with("pm_") {
configs
.saved_payment_methods
.sdk_eligible_payment_methods
.contains(payment_method.to_string().as_str())
} else {
true
}
})
.unwrap_or(true);
let context = AnalysisContext::from_dir_values(context_values.clone());
logger::info!("Context created for List Payment method is {:?}", context);
let domain_ident: &[String] = &[mca_id.clone().get_string_repr().to_string()];
let result = graph.key_value_analysis(
pm_dir_value.clone(),
&context,
&mut cgraph::Memoization::new(),
&mut cgraph::CycleCheck::new(),
Some(domain_ident),
);
if let Err(ref e) = result {
logger::error!(
"Error while performing Constraint graph's key value analysis
for list payment methods {:?}",
e
);
} else if filter_pm_based_on_allowed_types
&& filter_pm_card_network_based
&& saved_payment_methods_filter
&& matches!(result, Ok(()))
{
let response_pm_type = ResponsePaymentMethodIntermediate::new(
payment_method_object,
connector.clone(),
mca_id.get_string_repr().to_string(),
payment_method,
);
resp.push(response_pm_type);
} else {
logger::error!("Filtering Payment Methods Failed");
}
}
}
}
}
Ok(())
}
fn filter_amount_based(
payment_method: &RequestPaymentMethodTypes,
amount: Option<MinorUnit>,
) -> bool {
let min_check = amount
.and_then(|amt| payment_method.minimum_amount.map(|min_amt| amt >= min_amt))
.unwrap_or(true);
let max_check = amount
.and_then(|amt| payment_method.maximum_amount.map(|max_amt| amt <= max_amt))
.unwrap_or(true);
(min_check && max_check) || amount == Some(MinorUnit::zero())
}
fn filter_installment_based(
payment_method: &RequestPaymentMethodTypes,
installment_payment_enabled: Option<bool>,
) -> bool {
installment_payment_enabled
.is_none_or(|enabled| payment_method.installment_payment_enabled == Some(enabled))
}
fn filter_pm_card_network_based(
pm_card_networks: Option<&Vec<api_enums::CardNetwork>>,
request_card_networks: Option<&Vec<api_enums::CardNetwork>>,
pm_type: api_enums::PaymentMethodType,
) -> bool {
match pm_type {
api_enums::PaymentMethodType::Credit | api_enums::PaymentMethodType::Debit => {
match (pm_card_networks, request_card_networks) {
(Some(pm_card_networks), Some(request_card_networks)) => request_card_networks
.iter()
.all(|card_network| pm_card_networks.contains(card_network)),
(None, Some(_)) => false,
_ => true,
}
}
_ => true,
}
}
fn filter_pm_based_on_allowed_types(
allowed_types: Option<&Vec<api_enums::PaymentMethodType>>,
payment_method_type: api_enums::PaymentMethodType,
) -> bool {
allowed_types.is_none_or(|pm| pm.contains(&payment_method_type))
}
fn filter_recurring_based(
payment_method: &RequestPaymentMethodTypes,
recurring_enabled: Option<bool>,
) -> bool {
recurring_enabled.is_none_or(|enabled| payment_method.recurring_enabled == Some(enabled))
}
#[cfg(feature = "v1")]
pub async fn do_list_customer_pm_fetch_customer_if_not_passed(
state: routes::SessionState,
merchant_context: domain::MerchantContext,
req: Option<api::PaymentMethodListRequest>,
customer_id: Option<&id_type::CustomerId>,
ephemeral_api_key: Option<&str>,
) -> errors::RouterResponse<api::CustomerPaymentMethodsListResponse> {
let limit = req.clone().and_then(|pml_req| pml_req.limit);
let auth_cust = if let Some(key) = ephemeral_api_key {
let key = state
.store()
.get_ephemeral_key(key)
.await
.change_context(errors::ApiErrorResponse::Unauthorized)?;
Some(key.customer_id.clone())
} else {
None
};
let customer_id = customer_id.or(auth_cust.as_ref());
if let Some(customer_id) = customer_id {
Box::pin(list_customer_payment_method(
&state,
merchant_context.clone(),
None,
customer_id,
limit,
))
.await
} else {
let cloned_secret = req.and_then(|r| r.client_secret.as_ref().cloned());
let payment_intent: Option<hyperswitch_domain_models::payments::PaymentIntent> =
helpers::verify_payment_intent_time_and_client_secret(
&state,
&merchant_context,
cloned_secret,
)
.await?;
match payment_intent
.as_ref()
.and_then(|intent| intent.customer_id.to_owned())
{
Some(customer_id) => {
Box::pin(list_customer_payment_method(
&state,
merchant_context,
payment_intent,
&customer_id,
limit,
))
.await
}
None => {
let response = api::CustomerPaymentMethodsListResponse {
customer_payment_methods: Vec::new(),
is_guest_customer: Some(true),
};
Ok(services::ApplicationResponse::Json(response))
}
}
}
}
#[cfg(feature = "v1")]
pub async fn list_customer_payment_method(
state: &routes::SessionState,
merchant_context: domain::MerchantContext,
payment_intent: Option<storage::PaymentIntent>,
customer_id: &id_type::CustomerId,
limit: Option<i64>,
) -> errors::RouterResponse<api::CustomerPaymentMethodsListResponse> {
let db = &*state.store;
let key_manager_state = &state.into();
let off_session_payment_flag = payment_intent
.as_ref()
.map(|pi| {
matches!(
pi.setup_future_usage,
Some(common_enums::FutureUsage::OffSession)
)
})
.unwrap_or(false);
let customer = db
.find_customer_by_customer_id_merchant_id(
&state.into(),
customer_id,
merchant_context.get_merchant_account().get_id(),
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?;
let requires_cvv = configs::get_config_bool(
state,
router_consts::superposition::REQUIRES_CVV, // superposition key
&merchant_context
.get_merchant_account()
.get_id()
.get_requires_cvv_key(), // database key
Some(
external_services::superposition::ConfigContext::new().with(
"merchant_id",
merchant_context
.get_merchant_account()
.get_id()
.get_string_repr(),
),
), // context
true, // default value
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to fetch requires_cvv config")?;
let resp = db
.find_payment_method_by_customer_id_merchant_id_status(
&(state.into()),
merchant_context.get_merchant_key_store(),
customer_id,
merchant_context.get_merchant_account().get_id(),
common_enums::PaymentMethodStatus::Active,
limit,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
let mut customer_pms = Vec::new();
let profile_id = payment_intent
.as_ref()
.map(|payment_intent| {
payment_intent
.profile_id
.clone()
.get_required_value("profile_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("profile_id is not set in payment_intent")
})
.transpose()?;
let business_profile = core_utils::validate_and_get_business_profile(
db,
key_manager_state,
merchant_context.get_merchant_key_store(),
profile_id.as_ref(),
merchant_context.get_merchant_account().get_id(),
)
.await?;
let is_connector_agnostic_mit_enabled = business_profile
.as_ref()
.and_then(|business_profile| business_profile.is_connector_agnostic_mit_enabled)
.unwrap_or(false);
for pm in resp.into_iter() {
let parent_payment_method_token = generate_id(consts::ID_LENGTH, "token");
let payment_method = pm
.get_payment_method_type()
.get_required_value("payment_method")?;
let pm_list_context = get_pm_list_context(
state,
&payment_method,
merchant_context.get_merchant_key_store(),
&pm,
Some(parent_payment_method_token.clone()),
true,
false,
&merchant_context,
)
.await?;
if pm_list_context.is_none() {
continue;
}
let pm_list_context = pm_list_context.get_required_value("PaymentMethodListContext")?;
// Retrieve the masked bank details to be sent as a response
let bank_details = if payment_method == enums::PaymentMethod::BankDebit {
get_masked_bank_details(&pm).await.unwrap_or_else(|error| {
logger::error!(?error);
None
})
} else {
None
};
let payment_method_billing = pm
.payment_method_billing_address
.clone()
.map(|decrypted_data| decrypted_data.into_inner().expose())
.map(|decrypted_value| decrypted_value.parse_value("payment method billing address"))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to decrypt payment method billing address details")?;
let connector_mandate_details = pm
.get_common_mandate_reference()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to deserialize to Payment Mandate Reference ")?;
let mca_enabled = get_mca_status(
state,
merchant_context.get_merchant_key_store(),
profile_id.clone(),
merchant_context.get_merchant_account().get_id(),
is_connector_agnostic_mit_enabled,
Some(connector_mandate_details),
pm.network_transaction_id.as_ref(),
)
.await?;
let requires_cvv = if is_connector_agnostic_mit_enabled {
requires_cvv
&& !(off_session_payment_flag
&& (pm.connector_mandate_details.is_some()
|| pm.network_transaction_id.is_some()))
} else {
requires_cvv && !(off_session_payment_flag && pm.connector_mandate_details.is_some())
};
// Need validation for enabled payment method ,querying MCA
let pma = api::CustomerPaymentMethod {
payment_token: parent_payment_method_token.to_owned(),
payment_method_id: pm.payment_method_id.clone(),
customer_id: pm.customer_id.clone(),
payment_method,
payment_method_type: pm.get_payment_method_subtype(),
payment_method_issuer: pm.payment_method_issuer,
card: pm_list_context.card_details,
metadata: pm.metadata,
payment_method_issuer_code: pm.payment_method_issuer_code,
recurring_enabled: mca_enabled,
installment_payment_enabled: Some(false),
payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]),
created: Some(pm.created_at),
#[cfg(feature = "payouts")]
bank_transfer: pm_list_context.bank_transfer_details,
bank: bank_details,
surcharge_details: None,
requires_cvv,
last_used_at: Some(pm.last_used_at),
default_payment_method_set: customer.default_payment_method_id.is_some()
&& customer.default_payment_method_id == Some(pm.payment_method_id),
billing: payment_method_billing,
};
if requires_cvv || mca_enabled.unwrap_or(false) {
customer_pms.push(pma.to_owned());
}
let redis_conn = state
.store
.get_redis_conn()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get redis connection")?;
let intent_fulfillment_time = business_profile
.as_ref()
.and_then(|b_profile| b_profile.get_order_fulfillment_time())
.unwrap_or(consts::DEFAULT_INTENT_FULFILLMENT_TIME);
let hyperswitch_token_data = pm_list_context
.hyperswitch_token_data
.get_required_value("PaymentTokenData")?;
ParentPaymentMethodToken::create_key_for_token((
&parent_payment_method_token,
pma.payment_method,
))
.insert(intent_fulfillment_time, hyperswitch_token_data, state)
.await?;
if let Some(metadata) = pma.metadata {
let pm_metadata_vec: payment_methods::PaymentMethodMetadata = metadata
.parse_value("PaymentMethodMetadata")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Failed to deserialize metadata to PaymentmethodMetadata struct",
)?;
for pm_metadata in pm_metadata_vec.payment_method_tokenization {
let key = format!(
"pm_token_{}_{}_{}",
parent_payment_method_token, pma.payment_method, pm_metadata.0
);
redis_conn
.set_key_with_expiry(&key.into(), pm_metadata.1, intent_fulfillment_time)
.await
.change_context(errors::StorageError::KVError)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to add data in redis")?;
}
}
}
let mut response = api::CustomerPaymentMethodsListResponse {
customer_payment_methods: customer_pms,
is_guest_customer: payment_intent.as_ref().map(|_| false), //to return this key only when the request is tied to a payment intent
};
Box::pin(perform_surcharge_ops(
payment_intent,
state,
merchant_context,
business_profile,
&mut response,
))
.await?;
Ok(services::ApplicationResponse::Json(response))
}
#[cfg(feature = "v1")]
#[allow(clippy::too_many_arguments)]
pub async fn get_pm_list_context(
state: &routes::SessionState,
payment_method: &enums::PaymentMethod,
#[cfg(feature = "payouts")] key_store: &domain::MerchantKeyStore,
#[cfg(not(feature = "payouts"))] _key_store: &domain::MerchantKeyStore,
pm: &domain::PaymentMethod,
#[cfg(feature = "payouts")] parent_payment_method_token: Option<String>,
#[cfg(not(feature = "payouts"))] _parent_payment_method_token: Option<String>,
is_payment_associated: bool,
force_fetch_card_from_vault: bool,
merchant_context: &domain::MerchantContext,
) -> Result<Option<PaymentMethodListContext>, error_stack::Report<errors::ApiErrorResponse>> {
let cards = PmCards {
state,
merchant_context,
};
let payment_method_retrieval_context = match payment_method {
enums::PaymentMethod::Card => {
let card_details = if force_fetch_card_from_vault {
Some(cards.get_card_details_from_locker(pm).await?)
} else {
cards.get_card_details_with_locker_fallback(pm).await?
};
card_details.as_ref().map(|card| PaymentMethodListContext {
card_details: Some(card.clone()),
#[cfg(feature = "payouts")]
bank_transfer_details: None,
hyperswitch_token_data: is_payment_associated.then_some(
PaymentTokenData::permanent_card(
Some(pm.get_id().clone()),
pm.locker_id.clone().or(Some(pm.get_id().clone())),
pm.locker_id.clone().unwrap_or(pm.get_id().clone()),
pm.network_token_requestor_reference_id
.clone()
.or(Some(pm.get_id().clone())),
),
),
})
}
enums::PaymentMethod::BankDebit => {
// Retrieve the pm_auth connector details so that it can be tokenized
let bank_account_token_data = get_bank_account_connector_details(pm)
.await
.unwrap_or_else(|err| {
logger::error!(error=?err);
None
});
bank_account_token_data.map(|data| {
let token_data = PaymentTokenData::AuthBankDebit(data);
PaymentMethodListContext {
card_details: None,
#[cfg(feature = "payouts")]
bank_transfer_details: None,
hyperswitch_token_data: is_payment_associated.then_some(token_data),
}
})
}
enums::PaymentMethod::Wallet => Some(PaymentMethodListContext {
card_details: None,
#[cfg(feature = "payouts")]
bank_transfer_details: None,
hyperswitch_token_data: is_payment_associated
.then_some(PaymentTokenData::wallet_token(pm.get_id().clone())),
}),
#[cfg(feature = "payouts")]
enums::PaymentMethod::BankTransfer => Some(PaymentMethodListContext {
card_details: None,
bank_transfer_details: Some(
get_bank_from_hs_locker(
state,
key_store,
parent_payment_method_token.as_ref(),
&pm.customer_id,
&pm.merchant_id,
pm.locker_id.as_ref().unwrap_or(pm.get_id()),
)
.await?,
),
hyperswitch_token_data: parent_payment_method_token
.map(|token| PaymentTokenData::temporary_generic(token.clone())),
}),
_ => Some(PaymentMethodListContext {
card_details: None,
#[cfg(feature = "payouts")]
bank_transfer_details: None,
hyperswitch_token_data: is_payment_associated.then_some(
PaymentTokenData::temporary_generic(generate_id(consts::ID_LENGTH, "token")),
),
}),
};
Ok(payment_method_retrieval_context)
}
#[cfg(feature = "v1")]
async fn perform_surcharge_ops(
payment_intent: Option<storage::PaymentIntent>,
state: &routes::SessionState,
merchant_context: domain::MerchantContext,
business_profile: Option<Profile>,
response: &mut api::CustomerPaymentMethodsListResponse,
) -> Result<(), error_stack::Report<errors::ApiErrorResponse>> {
let payment_attempt = payment_intent
.as_ref()
.async_map(|payment_intent| async {
state
.store
.find_payment_attempt_by_payment_id_merchant_id_attempt_id(
payment_intent.get_id(),
merchant_context.get_merchant_account().get_id(),
&payment_intent.active_attempt.get_id(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)
})
.await
.transpose()?;
if let Some((payment_attempt, payment_intent, business_profile)) = payment_attempt
.zip(payment_intent)
.zip(business_profile)
.map(|((pa, pi), bp)| (pa, pi, bp))
{
call_surcharge_decision_management_for_saved_card(
state,
&merchant_context,
&business_profile,
&payment_attempt,
payment_intent,
response,
)
.await?;
}
Ok(())
}
#[cfg(feature = "v2")]
pub async fn perform_surcharge_ops(
_payment_intent: Option<storage::PaymentIntent>,
_state: &routes::SessionState,
_merchant_context: &domain::MerchantContext,
_business_profile: Option<Profile>,
_response: &mut api_models::payment_methods::CustomerPaymentMethodsListResponse,
) -> Result<(), error_stack::Report<errors::ApiErrorResponse>> {
todo!()
}
#[cfg(feature = "v1")]
pub async fn get_mca_status(
state: &routes::SessionState,
key_store: &domain::MerchantKeyStore,
profile_id: Option<id_type::ProfileId>,
merchant_id: &id_type::MerchantId,
is_connector_agnostic_mit_enabled: bool,
connector_mandate_details: Option<CommonMandateReference>,
network_transaction_id: Option<&String>,
) -> errors::RouterResult<Option<bool>> {
if is_connector_agnostic_mit_enabled && network_transaction_id.is_some() {
return Ok(Some(true));
}
if let Some(connector_mandate_details) = connector_mandate_details {
let mcas = state
.store
.find_merchant_connector_account_by_merchant_id_and_disabled_list(
&state.into(),
merchant_id,
true,
key_store,
)
.await
.change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: merchant_id.get_string_repr().to_owned(),
})?;
return Ok(Some(
mcas.is_merchant_connector_account_id_in_connector_mandate_details(
profile_id.as_ref(),
&connector_mandate_details,
),
));
}
Ok(Some(false))
}
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments)]
pub async fn get_mca_status(
state: &routes::SessionState,
key_store: &domain::MerchantKeyStore,
profile_id: Option<id_type::ProfileId>,
merchant_id: &id_type::MerchantId,
is_connector_agnostic_mit_enabled: bool,
connector_mandate_details: Option<&CommonMandateReference>,
network_transaction_id: Option<&String>,
merchant_connector_accounts: &domain::MerchantConnectorAccounts,
) -> bool {
if is_connector_agnostic_mit_enabled && network_transaction_id.is_some() {
return true;
}
match connector_mandate_details {
Some(connector_mandate_details) => merchant_connector_accounts
.is_merchant_connector_account_id_in_connector_mandate_details(
profile_id.as_ref(),
connector_mandate_details,
),
None => false,
}
}
pub async fn decrypt_generic_data<T>(
state: &routes::SessionState,
data: Option<Encryption>,
key_store: &domain::MerchantKeyStore,
) -> errors::RouterResult<Option<T>>
where
T: serde::de::DeserializeOwned,
{
let key = key_store.key.get_inner().peek();
let identifier = Identifier::Merchant(key_store.merchant_id.clone());
let decrypted_data = domain::types::crypto_operation::<serde_json::Value, masking::WithType>(
&state.into(),
type_name!(T),
domain::types::CryptoOperation::DecryptOptional(data),
identifier,
key,
)
.await
.and_then(|val| val.try_into_optionaloperation())
.change_context(errors::StorageError::DecryptionError)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to decrypt data")?;
decrypted_data
.map(|decrypted_data| decrypted_data.into_inner().expose())
.map(|decrypted_value| decrypted_value.parse_value("generic_data"))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to parse generic data value")
}
#[cfg(feature = "v1")]
pub async fn get_card_details_from_locker(
state: &routes::SessionState,
pm: &domain::PaymentMethod,
) -> errors::RouterResult<api::CardDetailFromLocker> {
let card = get_card_from_locker(
state,
&pm.customer_id,
&pm.merchant_id,
pm.locker_id.as_ref().unwrap_or(pm.get_id()),
)
.await
.attach_printable("Error getting card from card vault")?;
payment_methods::get_card_detail(pm, card)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Get Card Details Failed")
}
#[cfg(feature = "v1")]
pub async fn get_lookup_key_from_locker(
state: &routes::SessionState,
payment_token: &str,
pm: &domain::PaymentMethod,
merchant_key_store: &domain::MerchantKeyStore,
) -> errors::RouterResult<api::CardDetailFromLocker> {
let card_detail = get_card_details_from_locker(state, pm).await?;
let card = card_detail.clone();
let resp = TempLockerCardSupport::create_payment_method_data_in_temp_locker(
state,
payment_token,
card,
pm,
merchant_key_store,
)
.await?;
Ok(resp)
}
pub async fn get_masked_bank_details(
pm: &domain::PaymentMethod,
) -> errors::RouterResult<Option<MaskedBankDetails>> {
#[cfg(feature = "v1")]
let payment_method_data = pm
.payment_method_data
.clone()
.map(|x| x.into_inner().expose())
.map(
|v| -> Result<PaymentMethodsData, error_stack::Report<errors::ApiErrorResponse>> {
v.parse_value::<PaymentMethodsData>("PaymentMethodsData")
.change_context(errors::StorageError::DeserializationFailed)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to deserialize Payment Method Auth config")
},
)
.transpose()?;
#[cfg(feature = "v2")]
let payment_method_data = pm.payment_method_data.clone().map(|x| x.into_inner());
match payment_method_data {
Some(pmd) => match pmd {
PaymentMethodsData::Card(_) => Ok(None),
PaymentMethodsData::BankDetails(bank_details) => Ok(Some(MaskedBankDetails {
mask: bank_details.mask,
})),
PaymentMethodsData::WalletDetails(_) => Ok(None),
},
None => Err(report!(errors::ApiErrorResponse::InternalServerError))
.attach_printable("Unable to fetch payment method data"),
}
}
#[cfg(feature = "v1")]
pub async fn get_bank_account_connector_details(
pm: &domain::PaymentMethod,
) -> errors::RouterResult<Option<BankAccountTokenData>> {
let payment_method_data = pm
.payment_method_data
.clone()
.map(|x| x.into_inner().expose())
.map(
|v| -> Result<PaymentMethodsData, error_stack::Report<errors::ApiErrorResponse>> {
v.parse_value::<PaymentMethodsData>("PaymentMethodsData")
.change_context(errors::StorageError::DeserializationFailed)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to deserialize Payment Method Auth config")
},
)
.transpose()?;
match payment_method_data {
Some(pmd) => match pmd {
PaymentMethodsData::Card(_) => Err(errors::ApiErrorResponse::UnprocessableEntity {
message: "Card is not a valid entity".to_string(),
}
.into()),
PaymentMethodsData::WalletDetails(_) => {
Err(errors::ApiErrorResponse::UnprocessableEntity {
message: "Wallet is not a valid entity".to_string(),
}
.into())
}
PaymentMethodsData::BankDetails(bank_details) => {
let connector_details = bank_details
.connector_details
.first()
.ok_or(errors::ApiErrorResponse::InternalServerError)?;
let pm_type = pm
.get_payment_method_subtype()
.get_required_value("payment_method_type")
.attach_printable("PaymentMethodType not found")?;
let pm = pm
.get_payment_method_type()
.get_required_value("payment_method")
.attach_printable("PaymentMethod not found")?;
let token_data = BankAccountTokenData {
payment_method_type: pm_type,
payment_method: pm,
connector_details: connector_details.clone(),
};
Ok(Some(token_data))
}
},
None => Ok(None),
}
}
pub async fn update_last_used_at(
payment_method: &domain::PaymentMethod,
state: &routes::SessionState,
storage_scheme: MerchantStorageScheme,
key_store: &domain::MerchantKeyStore,
) -> errors::RouterResult<()> {
let update_last_used = storage::PaymentMethodUpdate::LastUsedUpdate {
last_used_at: common_utils::date_time::now(),
};
state
.store
.update_payment_method(
&(state.into()),
key_store,
payment_method.clone(),
update_last_used,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update the last_used_at in db")?;
Ok(())
}
#[cfg(feature = "payouts")]
pub async fn get_bank_from_hs_locker(
state: &routes::SessionState,
key_store: &domain::MerchantKeyStore,
temp_token: Option<&String>,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
token_ref: &str,
) -> errors::RouterResult<api::BankPayout> {
let payment_method = get_payment_method_from_hs_locker(
state,
key_store,
customer_id,
merchant_id,
token_ref,
None,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error getting payment method from locker")?;
let pm_parsed: api::PayoutMethodData = payment_method
.peek()
.to_string()
.parse_struct("PayoutMethodData")
.change_context(errors::ApiErrorResponse::InternalServerError)?;
match &pm_parsed {
api::PayoutMethodData::Bank(bank) => {
if let Some(token) = temp_token {
vault::Vault::store_payout_method_data_in_locker(
state,
Some(token.clone()),
&pm_parsed,
Some(customer_id.to_owned()),
key_store,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error storing payout method data in temporary locker")?;
}
Ok(bank.to_owned())
}
api::PayoutMethodData::Card(_) => Err(errors::ApiErrorResponse::InvalidRequestData {
message: "Expected bank details, found card details instead".to_string(),
}
.into()),
api::PayoutMethodData::Wallet(_) => Err(errors::ApiErrorResponse::InvalidRequestData {
message: "Expected bank details, found wallet details instead".to_string(),
}
.into()),
api::PayoutMethodData::BankRedirect(_) => {
Err(errors::ApiErrorResponse::InvalidRequestData {
message: "Expected bank details, found bank redirect details instead".to_string(),
}
.into())
}
}
}
#[cfg(feature = "v1")]
pub struct TempLockerCardSupport;
#[cfg(feature = "v1")]
impl TempLockerCardSupport {
#[instrument(skip_all)]
async fn create_payment_method_data_in_temp_locker(
state: &routes::SessionState,
payment_token: &str,
card: api::CardDetailFromLocker,
pm: &domain::PaymentMethod,
merchant_key_store: &domain::MerchantKeyStore,
) -> errors::RouterResult<api::CardDetailFromLocker> {
let card_number = card.card_number.clone().get_required_value("card_number")?;
let card_exp_month = card
.expiry_month
.clone()
.expose_option()
.get_required_value("expiry_month")?;
let card_exp_year = card
.expiry_year
.clone()
.expose_option()
.get_required_value("expiry_year")?;
let card_holder_name = card
.card_holder_name
.clone()
.expose_option()
.unwrap_or_default();
let value1 = payment_methods::mk_card_value1(
card_number,
card_exp_year,
card_exp_month,
Some(card_holder_name),
None,
None,
None,
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error getting Value1 for locker")?;
let value2 = payment_methods::mk_card_value2(
None,
None,
None,
Some(pm.customer_id.clone()),
Some(pm.get_id().to_string()),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error getting Value2 for locker")?;
let value1 = vault::VaultPaymentMethod::Card(value1);
let value2 = vault::VaultPaymentMethod::Card(value2);
let value1 = value1
.encode_to_string_of_json()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Wrapped value1 construction failed when saving card to locker")?;
let value2 = value2
.encode_to_string_of_json()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Wrapped value2 construction failed when saving card to locker")?;
let lookup_key = vault::create_tokenize(
state,
value1,
Some(value2),
payment_token.to_string(),
merchant_key_store.key.get_inner(),
)
.await?;
vault::add_delete_tokenized_data_task(
&*state.store,
&lookup_key,
enums::PaymentMethod::Card,
)
.await?;
metrics::TOKENIZED_DATA_COUNT.add(1, &[]);
metrics::TASKS_ADDED_COUNT.add(
1,
router_env::metric_attributes!(("flow", "DeleteTokenizeData")),
);
Ok(card)
}
}
pub async fn create_encrypted_data<T>(
key_manager_state: &KeyManagerState,
key_store: &domain::MerchantKeyStore,
data: T,
) -> Result<Encryptable<Secret<serde_json::Value>>, error_stack::Report<errors::StorageError>>
where
T: Debug + serde::Serialize,
{
let key = key_store.key.get_inner().peek();
let identifier = Identifier::Merchant(key_store.merchant_id.clone());
let encoded_data = Encode::encode_to_value(&data)
.change_context(errors::StorageError::SerializationFailed)
.attach_printable("Unable to encode data")?;
let secret_data = Secret::<_, masking::WithType>::new(encoded_data);
let encrypted_data = domain::types::crypto_operation(
key_manager_state,
type_name!(payment_method::PaymentMethod),
domain::types::CryptoOperation::Encrypt(secret_data),
identifier.clone(),
key,
)
.await
.and_then(|val| val.try_into_operation())
.change_context(errors::StorageError::EncryptionError)
.attach_printable("Unable to encrypt data")?;
Ok(encrypted_data)
}
pub async fn list_countries_currencies_for_connector_payment_method(
state: routes::SessionState,
req: ListCountriesCurrenciesRequest,
_profile_id: Option<id_type::ProfileId>,
) -> errors::RouterResponse<ListCountriesCurrenciesResponse> {
Ok(services::ApplicationResponse::Json(
list_countries_currencies_for_connector_payment_method_util(
state.conf.pm_filters.clone(),
req.connector,
req.payment_method_type,
)
.await,
))
}
// This feature will be more efficient as a WASM function rather than as an API.
// So extracting this logic to a separate function so that it can be used in WASM as well.
pub async fn list_countries_currencies_for_connector_payment_method_util(
connector_filters: settings::ConnectorFilters,
connector: api_enums::Connector,
payment_method_type: api_enums::PaymentMethodType,
) -> ListCountriesCurrenciesResponse {
let payment_method_type =
settings::PaymentMethodFilterKey::PaymentMethodType(payment_method_type);
let (currencies, country_codes) = connector_filters
.0
.get(&connector.to_string())
.and_then(|filter| filter.0.get(&payment_method_type))
.map(|filter| (filter.currency.clone(), filter.country.clone()))
.unwrap_or_else(|| {
connector_filters
.0
.get("default")
.and_then(|filter| filter.0.get(&payment_method_type))
.map_or((None, None), |filter| {
(filter.currency.clone(), filter.country.clone())
})
});
let currencies =
currencies.unwrap_or_else(|| api_enums::Currency::iter().collect::<HashSet<_>>());
let country_codes =
country_codes.unwrap_or_else(|| api_enums::CountryAlpha2::iter().collect::<HashSet<_>>());
ListCountriesCurrenciesResponse {
currencies,
countries: country_codes
.into_iter()
.map(|country_code| CountryCodeWithName {
code: country_code,
name: common_enums::Country::from_alpha2(country_code),
})
.collect(),
}
}
#[cfg(feature = "v1")]
pub async fn tokenize_card_flow(
state: &routes::SessionState,
req: domain::CardNetworkTokenizeRequest,
merchant_context: &domain::MerchantContext,
) -> errors::RouterResult<api::CardNetworkTokenizeResponse> {
match req.data {
domain::TokenizeDataRequest::Card(ref card_req) => {
let executor = tokenize::CardNetworkTokenizeExecutor::new(
state,
merchant_context,
card_req,
&req.customer,
);
let builder =
tokenize::NetworkTokenizationBuilder::<tokenize::TokenizeWithCard>::default();
execute_card_tokenization(executor, builder, card_req).await
}
domain::TokenizeDataRequest::ExistingPaymentMethod(ref payment_method) => {
let executor = tokenize::CardNetworkTokenizeExecutor::new(
state,
merchant_context,
payment_method,
&req.customer,
);
let builder =
tokenize::NetworkTokenizationBuilder::<tokenize::TokenizeWithPmId>::default();
Box::pin(execute_payment_method_tokenization(
executor,
builder,
payment_method,
))
.await
}
}
}
#[cfg(feature = "v1")]
pub async fn execute_card_tokenization(
executor: tokenize::CardNetworkTokenizeExecutor<'_, domain::TokenizeCardRequest>,
builder: tokenize::NetworkTokenizationBuilder<'_, tokenize::TokenizeWithCard>,
req: &domain::TokenizeCardRequest,
) -> errors::RouterResult<api::CardNetworkTokenizeResponse> {
// Validate request and get optional customer
let optional_customer = executor
.validate_request_and_fetch_optional_customer()
.await?;
let builder = builder.set_validate_result();
// Perform BIN lookup and validate card network
let optional_card_info = executor
.fetch_bin_details_and_validate_card_network(
req.raw_card_number.clone(),
req.card_issuer.as_ref(),
req.card_network.as_ref(),
req.card_type.as_ref(),
req.card_issuing_country.as_ref(),
)
.await?;
let builder = builder.set_card_details(req, optional_card_info);
// Create customer if not present
let customer = match optional_customer {
Some(customer) => customer,
None => executor.create_customer().await?,
};
let builder = builder.set_customer(&customer);
// Tokenize card
let (optional_card, optional_cvc) = builder.get_optional_card_and_cvc();
let domain_card = optional_card
.get_required_value("card")
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let network_token_details = executor
.tokenize_card(&customer.id, &domain_card, optional_cvc)
.await?;
let builder = builder.set_token_details(&network_token_details);
// Store card and token in locker
let store_card_and_token_resp = executor
.store_card_and_token_in_locker(&network_token_details, &domain_card, &customer.id)
.await?;
let builder = builder.set_stored_card_response(&store_card_and_token_resp);
let builder = builder.set_stored_token_response(&store_card_and_token_resp);
// Create payment method
let payment_method = executor
.create_payment_method(
&store_card_and_token_resp,
&network_token_details,
&domain_card,
&customer.id,
)
.await?;
let builder = builder.set_payment_method_response(&payment_method);
Ok(builder.build())
}
#[cfg(feature = "v1")]
pub async fn execute_payment_method_tokenization(
executor: tokenize::CardNetworkTokenizeExecutor<'_, domain::TokenizePaymentMethodRequest>,
builder: tokenize::NetworkTokenizationBuilder<'_, tokenize::TokenizeWithPmId>,
req: &domain::TokenizePaymentMethodRequest,
) -> errors::RouterResult<api::CardNetworkTokenizeResponse> {
// Fetch payment method
let payment_method = executor
.fetch_payment_method(&req.payment_method_id)
.await?;
let builder = builder.set_payment_method(&payment_method);
// Validate payment method and customer
let (locker_id, customer) = executor
.validate_request_and_locker_reference_and_customer(&payment_method)
.await?;
let builder = builder.set_validate_result(&customer);
// Fetch card from locker
let card_details = get_card_from_locker(
executor.state,
&customer.id,
executor.merchant_account.get_id(),
&locker_id,
)
.await?;
// Perform BIN lookup and validate card network
let optional_card_info = executor
.fetch_bin_details_and_validate_card_network(
card_details.card_number.clone(),
None,
None,
None,
None,
)
.await?;
let builder = builder.set_card_details(&card_details, optional_card_info, req.card_cvc.clone());
// Tokenize card
let (optional_card, optional_cvc) = builder.get_optional_card_and_cvc();
let domain_card = optional_card.get_required_value("card")?;
let network_token_details = executor
.tokenize_card(&customer.id, &domain_card, optional_cvc)
.await?;
let builder = builder.set_token_details(&network_token_details);
// Store token in locker
let store_token_resp = executor
.store_network_token_in_locker(
&network_token_details,
&customer.id,
card_details.name_on_card.clone(),
card_details.nick_name.clone().map(Secret::new),
)
.await?;
let builder = builder.set_stored_token_response(&store_token_resp);
// Update payment method
let updated_payment_method = executor
.update_payment_method(
&store_token_resp,
payment_method,
&network_token_details,
&domain_card,
)
.await?;
let builder = builder.set_payment_method(&updated_payment_method);
Ok(builder.build())
}
|
crates/router/src/core/payment_methods/cards.rs
|
router::src::core::payment_methods::cards
| 39,397
| true
|
// File: crates/router/src/core/payment_methods/surcharge_decision_configs.rs
// Module: router::src::core::payment_methods::surcharge_decision_configs
use api_models::{
payment_methods::SurchargeDetailsResponse,
payments, routing,
surcharge_decision_configs::{self, SurchargeDecisionConfigs, SurchargeDecisionManagerRecord},
};
#[cfg(feature = "v1")]
use common_utils::{ext_traits::StringExt, types as common_utils_types};
#[cfg(feature = "v2")]
use common_utils::{
ext_traits::{OptionExt, StringExt},
types as common_utils_types,
};
use error_stack::{self, ResultExt};
use euclid::{
backend,
backend::{inputs as dsl_inputs, EuclidBackend},
};
use router_env::{instrument, logger, tracing};
use serde::{Deserialize, Serialize};
use storage_impl::redis::cache::{self, SURCHARGE_CACHE};
use crate::{
core::{
errors::{self, ConditionalConfigError as ConfigError},
payments::{
conditional_configs::ConditionalConfigResult, routing::make_dsl_input_for_surcharge,
types,
},
},
db::StorageInterface,
types::{
storage::{self, payment_attempt::PaymentAttemptExt},
transformers::ForeignTryFrom,
},
SessionState,
};
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct VirInterpreterBackendCacheWrapper {
cached_algorithm: backend::VirInterpreterBackend<SurchargeDecisionConfigs>,
merchant_surcharge_configs: surcharge_decision_configs::MerchantSurchargeConfigs,
}
impl TryFrom<SurchargeDecisionManagerRecord> for VirInterpreterBackendCacheWrapper {
type Error = error_stack::Report<ConfigError>;
fn try_from(value: SurchargeDecisionManagerRecord) -> Result<Self, Self::Error> {
let cached_algorithm = backend::VirInterpreterBackend::with_program(value.algorithm)
.change_context(ConfigError::DslBackendInitError)
.attach_printable("Error initializing DSL interpreter backend")?;
let merchant_surcharge_configs = value.merchant_surcharge_configs;
Ok(Self {
cached_algorithm,
merchant_surcharge_configs,
})
}
}
enum SurchargeSource {
/// Surcharge will be generated through the surcharge rules
Generate(VirInterpreterBackendCacheWrapper),
/// Surcharge is predefined by the merchant through payment create request
Predetermined(payments::RequestSurchargeDetails),
}
impl SurchargeSource {
pub fn generate_surcharge_details_and_populate_surcharge_metadata(
&self,
backend_input: &backend::BackendInput,
payment_attempt: &storage::PaymentAttempt,
surcharge_metadata_and_key: (&mut types::SurchargeMetadata, types::SurchargeKey),
) -> ConditionalConfigResult<Option<types::SurchargeDetails>> {
match self {
Self::Generate(interpreter) => {
let surcharge_output = execute_dsl_and_get_conditional_config(
backend_input.clone(),
&interpreter.cached_algorithm,
)?;
Ok(surcharge_output
.surcharge_details
.map(|surcharge_details| {
get_surcharge_details_from_surcharge_output(
surcharge_details,
payment_attempt,
)
})
.transpose()?
.inspect(|surcharge_details| {
let (surcharge_metadata, surcharge_key) = surcharge_metadata_and_key;
surcharge_metadata
.insert_surcharge_details(surcharge_key, surcharge_details.clone());
}))
}
Self::Predetermined(request_surcharge_details) => Ok(Some(
types::SurchargeDetails::from((request_surcharge_details, payment_attempt)),
)),
}
}
}
#[cfg(feature = "v2")]
pub async fn perform_surcharge_decision_management_for_payment_method_list(
_state: &SessionState,
_algorithm_ref: routing::RoutingAlgorithmRef,
_payment_attempt: &storage::PaymentAttempt,
_payment_intent: &storage::PaymentIntent,
_billing_address: Option<payments::Address>,
_response_payment_method_types: &mut [api_models::payment_methods::ResponsePaymentMethodsEnabled],
) -> ConditionalConfigResult<(
types::SurchargeMetadata,
surcharge_decision_configs::MerchantSurchargeConfigs,
)> {
todo!()
}
#[cfg(feature = "v1")]
pub async fn perform_surcharge_decision_management_for_payment_method_list(
state: &SessionState,
algorithm_ref: routing::RoutingAlgorithmRef,
payment_attempt: &storage::PaymentAttempt,
payment_intent: &storage::PaymentIntent,
billing_address: Option<hyperswitch_domain_models::address::Address>,
response_payment_method_types: &mut [api_models::payment_methods::ResponsePaymentMethodsEnabled],
) -> ConditionalConfigResult<(
types::SurchargeMetadata,
surcharge_decision_configs::MerchantSurchargeConfigs,
)> {
let mut surcharge_metadata = types::SurchargeMetadata::new(payment_attempt.attempt_id.clone());
let (surcharge_source, merchant_surcharge_configs) = match (
payment_attempt.get_surcharge_details(),
algorithm_ref.surcharge_config_algo_id,
) {
(Some(request_surcharge_details), _) => (
SurchargeSource::Predetermined(request_surcharge_details),
surcharge_decision_configs::MerchantSurchargeConfigs::default(),
),
(None, Some(algorithm_id)) => {
let cached_algo = ensure_algorithm_cached(
&*state.store,
&payment_attempt.merchant_id,
algorithm_id.as_str(),
)
.await?;
let merchant_surcharge_config = cached_algo.merchant_surcharge_configs.clone();
(
SurchargeSource::Generate(cached_algo),
merchant_surcharge_config,
)
}
(None, None) => {
return Ok((
surcharge_metadata,
surcharge_decision_configs::MerchantSurchargeConfigs::default(),
))
}
};
let surcharge_source_log_message = match &surcharge_source {
SurchargeSource::Generate(_) => "Surcharge was calculated through surcharge rules",
SurchargeSource::Predetermined(_) => "Surcharge was sent in payment create request",
};
logger::debug!(payment_method_list_surcharge_source = surcharge_source_log_message);
let mut backend_input =
make_dsl_input_for_surcharge(payment_attempt, payment_intent, billing_address)
.change_context(ConfigError::InputConstructionError)?;
for payment_methods_enabled in response_payment_method_types.iter_mut() {
for payment_method_type_response in
&mut payment_methods_enabled.payment_method_types.iter_mut()
{
let payment_method_type = payment_method_type_response.payment_method_type;
backend_input.payment_method.payment_method_type = Some(payment_method_type);
backend_input.payment_method.payment_method =
Some(payment_methods_enabled.payment_method);
if let Some(card_network_list) = &mut payment_method_type_response.card_networks {
for card_network_type in card_network_list.iter_mut() {
backend_input.payment_method.card_network =
Some(card_network_type.card_network.clone());
let surcharge_details = surcharge_source
.generate_surcharge_details_and_populate_surcharge_metadata(
&backend_input,
payment_attempt,
(
&mut surcharge_metadata,
types::SurchargeKey::PaymentMethodData(
payment_methods_enabled.payment_method,
payment_method_type_response.payment_method_type,
Some(card_network_type.card_network.clone()),
),
),
)?;
card_network_type.surcharge_details = surcharge_details
.map(|surcharge_details| {
SurchargeDetailsResponse::foreign_try_from((
&surcharge_details,
payment_attempt,
))
.change_context(ConfigError::DslExecutionError)
.attach_printable("Error while constructing Surcharge response type")
})
.transpose()?;
}
} else {
let surcharge_details = surcharge_source
.generate_surcharge_details_and_populate_surcharge_metadata(
&backend_input,
payment_attempt,
(
&mut surcharge_metadata,
types::SurchargeKey::PaymentMethodData(
payment_methods_enabled.payment_method,
payment_method_type_response.payment_method_type,
None,
),
),
)?;
payment_method_type_response.surcharge_details = surcharge_details
.map(|surcharge_details| {
SurchargeDetailsResponse::foreign_try_from((
&surcharge_details,
payment_attempt,
))
.change_context(ConfigError::DslExecutionError)
.attach_printable("Error while constructing Surcharge response type")
})
.transpose()?;
}
}
}
Ok((surcharge_metadata, merchant_surcharge_configs))
}
#[cfg(feature = "v1")]
pub async fn perform_surcharge_decision_management_for_session_flow(
state: &SessionState,
algorithm_ref: routing::RoutingAlgorithmRef,
payment_attempt: &storage::PaymentAttempt,
payment_intent: &storage::PaymentIntent,
billing_address: Option<hyperswitch_domain_models::address::Address>,
payment_method_type_list: &Vec<common_enums::PaymentMethodType>,
) -> ConditionalConfigResult<types::SurchargeMetadata> {
let mut surcharge_metadata = types::SurchargeMetadata::new(payment_attempt.attempt_id.clone());
let surcharge_source = match (
payment_attempt.get_surcharge_details(),
algorithm_ref.surcharge_config_algo_id,
) {
(Some(request_surcharge_details), _) => {
SurchargeSource::Predetermined(request_surcharge_details)
}
(None, Some(algorithm_id)) => {
let cached_algo = ensure_algorithm_cached(
&*state.store,
&payment_attempt.merchant_id,
algorithm_id.as_str(),
)
.await?;
SurchargeSource::Generate(cached_algo)
}
(None, None) => return Ok(surcharge_metadata),
};
let mut backend_input =
make_dsl_input_for_surcharge(payment_attempt, payment_intent, billing_address)
.change_context(ConfigError::InputConstructionError)?;
for payment_method_type in payment_method_type_list {
backend_input.payment_method.payment_method_type = Some(*payment_method_type);
// in case of session flow, payment_method will always be wallet
backend_input.payment_method.payment_method = Some(payment_method_type.to_owned().into());
surcharge_source.generate_surcharge_details_and_populate_surcharge_metadata(
&backend_input,
payment_attempt,
(
&mut surcharge_metadata,
types::SurchargeKey::PaymentMethodData(
payment_method_type.to_owned().into(),
*payment_method_type,
None,
),
),
)?;
}
Ok(surcharge_metadata)
}
#[cfg(feature = "v1")]
pub async fn perform_surcharge_decision_management_for_saved_cards(
state: &SessionState,
algorithm_ref: routing::RoutingAlgorithmRef,
payment_attempt: &storage::PaymentAttempt,
payment_intent: &storage::PaymentIntent,
customer_payment_method_list: &mut [api_models::payment_methods::CustomerPaymentMethod],
) -> ConditionalConfigResult<types::SurchargeMetadata> {
let mut surcharge_metadata = types::SurchargeMetadata::new(payment_attempt.attempt_id.clone());
let surcharge_source = match (
payment_attempt.get_surcharge_details(),
algorithm_ref.surcharge_config_algo_id,
) {
(Some(request_surcharge_details), _) => {
SurchargeSource::Predetermined(request_surcharge_details)
}
(None, Some(algorithm_id)) => {
let cached_algo = ensure_algorithm_cached(
&*state.store,
&payment_attempt.merchant_id,
algorithm_id.as_str(),
)
.await?;
SurchargeSource::Generate(cached_algo)
}
(None, None) => return Ok(surcharge_metadata),
};
let surcharge_source_log_message = match &surcharge_source {
SurchargeSource::Generate(_) => "Surcharge was calculated through surcharge rules",
SurchargeSource::Predetermined(_) => "Surcharge was sent in payment create request",
};
logger::debug!(customer_saved_card_list_surcharge_source = surcharge_source_log_message);
let mut backend_input = make_dsl_input_for_surcharge(payment_attempt, payment_intent, None)
.change_context(ConfigError::InputConstructionError)?;
for customer_payment_method in customer_payment_method_list.iter_mut() {
let payment_token = customer_payment_method.payment_token.clone();
backend_input.payment_method.payment_method = Some(customer_payment_method.payment_method);
backend_input.payment_method.payment_method_type =
customer_payment_method.payment_method_type;
let card_network = customer_payment_method
.card
.as_ref()
.and_then(|card| card.scheme.as_ref())
.map(|scheme| {
scheme
.clone()
.parse_enum("CardNetwork")
.change_context(ConfigError::DslExecutionError)
})
.transpose()?;
backend_input.payment_method.card_network = card_network;
let surcharge_details = surcharge_source
.generate_surcharge_details_and_populate_surcharge_metadata(
&backend_input,
payment_attempt,
(
&mut surcharge_metadata,
types::SurchargeKey::Token(payment_token),
),
)?;
customer_payment_method.surcharge_details = surcharge_details
.map(|surcharge_details| {
SurchargeDetailsResponse::foreign_try_from((&surcharge_details, payment_attempt))
.change_context(ConfigError::DslParsingError)
})
.transpose()?;
}
Ok(surcharge_metadata)
}
// TODO: uncomment and resolve compiler error when required
// #[cfg(feature = "v2")]
// pub async fn perform_surcharge_decision_management_for_saved_cards(
// state: &SessionState,
// algorithm_ref: routing::RoutingAlgorithmRef,
// payment_attempt: &storage::PaymentAttempt,
// payment_intent: &storage::PaymentIntent,
// customer_payment_method_list: &mut [api_models::payment_methods::CustomerPaymentMethod],
// ) -> ConditionalConfigResult<types::SurchargeMetadata> {
// // let mut surcharge_metadata = types::SurchargeMetadata::new(payment_attempt.id.clone());
// let mut surcharge_metadata = todo!();
// let surcharge_source = match (
// payment_attempt.get_surcharge_details(),
// algorithm_ref.surcharge_config_algo_id,
// ) {
// (Some(request_surcharge_details), _) => {
// SurchargeSource::Predetermined(request_surcharge_details)
// }
// (None, Some(algorithm_id)) => {
// let cached_algo = ensure_algorithm_cached(
// &*state.store,
// &payment_attempt.merchant_id,
// algorithm_id.as_str(),
// )
// .await?;
// SurchargeSource::Generate(cached_algo)
// }
// (None, None) => return Ok(surcharge_metadata),
// };
// let surcharge_source_log_message = match &surcharge_source {
// SurchargeSource::Generate(_) => "Surcharge was calculated through surcharge rules",
// SurchargeSource::Predetermined(_) => "Surcharge was sent in payment create request",
// };
// logger::debug!(customer_saved_card_list_surcharge_source = surcharge_source_log_message);
// let mut backend_input = make_dsl_input_for_surcharge(payment_attempt, payment_intent, None)
// .change_context(ConfigError::InputConstructionError)?;
// for customer_payment_method in customer_payment_method_list.iter_mut() {
// let payment_token = customer_payment_method
// .payment_token
// .clone()
// .get_required_value("payment_token")
// .change_context(ConfigError::InputConstructionError)?;
// backend_input.payment_method.payment_method =
// Some(customer_payment_method.payment_method_type);
// backend_input.payment_method.payment_method_type =
// customer_payment_method.payment_method_subtype;
// let card_network = match customer_payment_method.payment_method_data.as_ref() {
// Some(api_models::payment_methods::PaymentMethodListData::Card(card)) => {
// card.card_network.clone()
// }
// _ => None,
// };
// backend_input.payment_method.card_network = card_network;
// let surcharge_details = surcharge_source
// .generate_surcharge_details_and_populate_surcharge_metadata(
// &backend_input,
// payment_attempt,
// (
// &mut surcharge_metadata,
// types::SurchargeKey::Token(payment_token),
// ),
// )?;
// customer_payment_method.surcharge_details = surcharge_details
// .map(|surcharge_details| {
// SurchargeDetailsResponse::foreign_try_from((&surcharge_details, payment_attempt))
// .change_context(ConfigError::DslParsingError)
// })
// .transpose()?;
// }
// Ok(surcharge_metadata)
// }
#[cfg(feature = "v2")]
fn get_surcharge_details_from_surcharge_output(
_surcharge_details: surcharge_decision_configs::SurchargeDetailsOutput,
_payment_attempt: &storage::PaymentAttempt,
) -> ConditionalConfigResult<types::SurchargeDetails> {
todo!()
}
#[cfg(feature = "v1")]
fn get_surcharge_details_from_surcharge_output(
surcharge_details: surcharge_decision_configs::SurchargeDetailsOutput,
payment_attempt: &storage::PaymentAttempt,
) -> ConditionalConfigResult<types::SurchargeDetails> {
let surcharge_amount = match surcharge_details.surcharge.clone() {
surcharge_decision_configs::SurchargeOutput::Fixed { amount } => amount,
surcharge_decision_configs::SurchargeOutput::Rate(percentage) => percentage
.apply_and_ceil_result(payment_attempt.net_amount.get_total_amount())
.change_context(ConfigError::DslExecutionError)
.attach_printable("Failed to Calculate surcharge amount by applying percentage")?,
};
let tax_on_surcharge_amount = surcharge_details
.tax_on_surcharge
.clone()
.map(|tax_on_surcharge| {
tax_on_surcharge
.apply_and_ceil_result(surcharge_amount)
.change_context(ConfigError::DslExecutionError)
.attach_printable("Failed to Calculate tax amount")
})
.transpose()?
.unwrap_or_default();
Ok(types::SurchargeDetails {
original_amount: payment_attempt.net_amount.get_order_amount(),
surcharge: match surcharge_details.surcharge {
surcharge_decision_configs::SurchargeOutput::Fixed { amount } => {
common_utils_types::Surcharge::Fixed(amount)
}
surcharge_decision_configs::SurchargeOutput::Rate(percentage) => {
common_utils_types::Surcharge::Rate(percentage)
}
},
tax_on_surcharge: surcharge_details.tax_on_surcharge,
surcharge_amount,
tax_on_surcharge_amount,
})
}
#[instrument(skip_all)]
pub async fn ensure_algorithm_cached(
store: &dyn StorageInterface,
merchant_id: &common_utils::id_type::MerchantId,
algorithm_id: &str,
) -> ConditionalConfigResult<VirInterpreterBackendCacheWrapper> {
let key = merchant_id.get_surcharge_dsk_key();
let value_to_cache = || async {
let config: diesel_models::Config = store.find_config_by_key(algorithm_id).await?;
let record: SurchargeDecisionManagerRecord = config
.config
.parse_struct("Program")
.change_context(errors::StorageError::DeserializationFailed)
.attach_printable("Error parsing routing algorithm from configs")?;
VirInterpreterBackendCacheWrapper::try_from(record)
.change_context(errors::StorageError::ValueNotFound("Program".to_string()))
.attach_printable("Error initializing DSL interpreter backend")
};
let interpreter = cache::get_or_populate_in_memory(
store.get_cache_store().as_ref(),
&key,
value_to_cache,
&SURCHARGE_CACHE,
)
.await
.change_context(ConfigError::CacheMiss)
.attach_printable("Unable to retrieve cached routing algorithm even after refresh")?;
Ok(interpreter)
}
pub fn execute_dsl_and_get_conditional_config(
backend_input: dsl_inputs::BackendInput,
interpreter: &backend::VirInterpreterBackend<SurchargeDecisionConfigs>,
) -> ConditionalConfigResult<SurchargeDecisionConfigs> {
let routing_output = interpreter
.execute(backend_input)
.map(|out| out.connector_selection)
.change_context(ConfigError::DslExecutionError)?;
Ok(routing_output)
}
|
crates/router/src/core/payment_methods/surcharge_decision_configs.rs
|
router::src::core::payment_methods::surcharge_decision_configs
| 4,309
| true
|
// File: crates/router/src/core/payment_methods/transformers.rs
// Module: router::src::core::payment_methods::transformers
pub use ::payment_methods::controller::{DataDuplicationCheck, DeleteCardResp};
#[cfg(feature = "v2")]
use api_models::payment_methods::PaymentMethodResponseItem;
use api_models::{enums as api_enums, payment_methods::Card};
use common_utils::{
ext_traits::{Encode, StringExt},
id_type,
pii::Email,
request::RequestContent,
};
use error_stack::ResultExt;
#[cfg(feature = "v2")]
use hyperswitch_domain_models::payment_method_data;
use josekit::jwe;
use router_env::tracing_actix_web::RequestId;
use serde::{Deserialize, Serialize};
#[cfg(feature = "v2")]
use crate::types::{payment_methods as pm_types, transformers};
use crate::{
configs::settings,
core::errors::{self, CustomResult},
headers,
pii::{prelude::*, Secret},
services::{api as services, encryption, EncryptionAlgorithm},
types::{api, domain},
utils::OptionExt,
};
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum StoreLockerReq {
LockerCard(StoreCardReq),
LockerGeneric(StoreGenericReq),
}
impl StoreLockerReq {
pub fn update_requestor_card_reference(&mut self, card_reference: Option<String>) {
match self {
Self::LockerCard(c) => c.requestor_card_reference = card_reference,
Self::LockerGeneric(_) => (),
}
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct StoreCardReq {
pub merchant_id: id_type::MerchantId,
pub merchant_customer_id: id_type::CustomerId,
#[serde(skip_serializing_if = "Option::is_none")]
pub requestor_card_reference: Option<String>,
pub card: Card,
pub ttl: i64,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct StoreGenericReq {
pub merchant_id: id_type::MerchantId,
pub merchant_customer_id: id_type::CustomerId,
#[serde(rename = "enc_card_data")]
pub enc_data: String,
pub ttl: i64,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct StoreCardResp {
pub status: String,
pub error_message: Option<String>,
pub error_code: Option<String>,
pub payload: Option<StoreCardRespPayload>,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct StoreCardRespPayload {
pub card_reference: String,
pub duplication_check: Option<DataDuplicationCheck>,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct CardReqBody {
pub merchant_id: id_type::MerchantId,
pub merchant_customer_id: id_type::CustomerId,
pub card_reference: String,
}
#[cfg(feature = "v2")]
#[derive(Debug, Deserialize, Serialize)]
pub struct CardReqBodyV2 {
pub merchant_id: id_type::MerchantId,
pub merchant_customer_id: String, // Not changing this as it might lead to api contract failure
pub card_reference: String,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct RetrieveCardResp {
pub status: String,
pub error_message: Option<String>,
pub error_code: Option<String>,
pub payload: Option<RetrieveCardRespPayload>,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct RetrieveCardRespPayload {
pub card: Option<Card>,
pub enc_card_data: Option<Secret<String>>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AddCardRequest {
pub card_number: cards::CardNumber,
pub customer_id: id_type::CustomerId,
pub card_exp_month: Secret<String>,
pub card_exp_year: Secret<String>,
pub merchant_id: id_type::MerchantId,
pub email_address: Option<Email>,
pub name_on_card: Option<Secret<String>>,
pub nickname: Option<String>,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AddCardResponse {
pub card_id: String,
pub external_id: String,
pub card_fingerprint: Secret<String>,
pub card_global_fingerprint: Secret<String>,
#[serde(rename = "merchant_id")]
pub merchant_id: Option<id_type::MerchantId>,
pub card_number: Option<cards::CardNumber>,
pub card_exp_year: Option<Secret<String>>,
pub card_exp_month: Option<Secret<String>>,
pub name_on_card: Option<Secret<String>>,
pub nickname: Option<String>,
pub customer_id: Option<id_type::CustomerId>,
pub duplicate: Option<bool>,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AddPaymentMethodResponse {
pub payment_method_id: String,
pub external_id: String,
#[serde(rename = "merchant_id")]
pub merchant_id: Option<id_type::MerchantId>,
pub nickname: Option<String>,
pub customer_id: Option<id_type::CustomerId>,
pub duplicate: Option<bool>,
pub payment_method_data: Secret<String>,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct GetPaymentMethodResponse {
pub payment_method: AddPaymentMethodResponse,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct GetCardResponse {
pub card: AddCardResponse,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetCard<'a> {
merchant_id: &'a str,
card_id: &'a str,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DeleteCardResponse {
pub card_id: Option<String>,
pub external_id: Option<String>,
pub card_isin: Option<Secret<String>>,
pub status: String,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(transparent)]
pub struct PaymentMethodMetadata {
pub payment_method_tokenization: std::collections::HashMap<String, String>,
}
pub fn get_dotted_jwe(jwe: encryption::JweBody) -> String {
let header = jwe.header;
let encryption_key = jwe.encrypted_key;
let iv = jwe.iv;
let encryption_payload = jwe.encrypted_payload;
let tag = jwe.tag;
format!("{header}.{encryption_key}.{iv}.{encryption_payload}.{tag}")
}
pub fn get_dotted_jws(jws: encryption::JwsBody) -> String {
let header = jws.header;
let payload = jws.payload;
let signature = jws.signature;
format!("{header}.{payload}.{signature}")
}
pub async fn get_decrypted_response_payload(
jwekey: &settings::Jwekey,
jwe_body: encryption::JweBody,
locker_choice: Option<api_enums::LockerChoice>,
decryption_scheme: settings::DecryptionScheme,
) -> CustomResult<String, errors::VaultError> {
let target_locker = locker_choice.unwrap_or(api_enums::LockerChoice::HyperswitchCardVault);
let public_key = match target_locker {
api_enums::LockerChoice::HyperswitchCardVault => {
jwekey.vault_encryption_key.peek().as_bytes()
}
};
let private_key = jwekey.vault_private_key.peek().as_bytes();
let jwt = get_dotted_jwe(jwe_body);
let alg = match decryption_scheme {
settings::DecryptionScheme::RsaOaep => jwe::RSA_OAEP,
settings::DecryptionScheme::RsaOaep256 => jwe::RSA_OAEP_256,
};
let jwe_decrypted = encryption::decrypt_jwe(
&jwt,
encryption::KeyIdCheck::SkipKeyIdCheck,
private_key,
alg,
)
.await
.change_context(errors::VaultError::SaveCardFailed)
.attach_printable("Jwe Decryption failed for JweBody for vault")?;
let jws = jwe_decrypted
.parse_struct("JwsBody")
.change_context(errors::VaultError::ResponseDeserializationFailed)?;
let jws_body = get_dotted_jws(jws);
encryption::verify_sign(jws_body, public_key)
.change_context(errors::VaultError::SaveCardFailed)
.attach_printable("Jws Decryption failed for JwsBody for vault")
}
pub async fn get_decrypted_vault_response_payload(
jwekey: &settings::Jwekey,
jwe_body: encryption::JweBody,
decryption_scheme: settings::DecryptionScheme,
) -> CustomResult<String, errors::VaultError> {
let public_key = jwekey.vault_encryption_key.peek().as_bytes();
let private_key = jwekey.vault_private_key.peek().as_bytes();
let jwt = get_dotted_jwe(jwe_body);
let alg = match decryption_scheme {
settings::DecryptionScheme::RsaOaep => jwe::RSA_OAEP,
settings::DecryptionScheme::RsaOaep256 => jwe::RSA_OAEP_256,
};
let jwe_decrypted = encryption::decrypt_jwe(
&jwt,
encryption::KeyIdCheck::SkipKeyIdCheck,
private_key,
alg,
)
.await
.change_context(errors::VaultError::SaveCardFailed)
.attach_printable("Jwe Decryption failed for JweBody for vault")?;
let jws = jwe_decrypted
.parse_struct("JwsBody")
.change_context(errors::VaultError::ResponseDeserializationFailed)?;
let jws_body = get_dotted_jws(jws);
encryption::verify_sign(jws_body, public_key)
.change_context(errors::VaultError::SaveCardFailed)
.attach_printable("Jws Decryption failed for JwsBody for vault")
}
#[cfg(feature = "v2")]
pub async fn create_jwe_body_for_vault(
jwekey: &settings::Jwekey,
jws: &str,
) -> CustomResult<encryption::JweBody, errors::VaultError> {
let jws_payload: Vec<&str> = jws.split('.').collect();
let generate_jws_body = |payload: Vec<&str>| -> Option<encryption::JwsBody> {
Some(encryption::JwsBody {
header: payload.first()?.to_string(),
payload: payload.get(1)?.to_string(),
signature: payload.get(2)?.to_string(),
})
};
let jws_body =
generate_jws_body(jws_payload).ok_or(errors::VaultError::RequestEncryptionFailed)?;
let payload = jws_body
.encode_to_vec()
.change_context(errors::VaultError::RequestEncodingFailed)?;
let public_key = jwekey.vault_encryption_key.peek().as_bytes();
let jwe_encrypted =
encryption::encrypt_jwe(&payload, public_key, EncryptionAlgorithm::A256GCM, None)
.await
.change_context(errors::VaultError::SaveCardFailed)
.attach_printable("Error on jwe encrypt")?;
let jwe_payload: Vec<&str> = jwe_encrypted.split('.').collect();
let generate_jwe_body = |payload: Vec<&str>| -> Option<encryption::JweBody> {
Some(encryption::JweBody {
header: payload.first()?.to_string(),
iv: payload.get(2)?.to_string(),
encrypted_payload: payload.get(3)?.to_string(),
tag: payload.get(4)?.to_string(),
encrypted_key: payload.get(1)?.to_string(),
})
};
let jwe_body =
generate_jwe_body(jwe_payload).ok_or(errors::VaultError::RequestEncodingFailed)?;
Ok(jwe_body)
}
pub async fn mk_basilisk_req(
jwekey: &settings::Jwekey,
jws: &str,
locker_choice: api_enums::LockerChoice,
) -> CustomResult<encryption::JweBody, errors::VaultError> {
let jws_payload: Vec<&str> = jws.split('.').collect();
let generate_jws_body = |payload: Vec<&str>| -> Option<encryption::JwsBody> {
Some(encryption::JwsBody {
header: payload.first()?.to_string(),
payload: payload.get(1)?.to_string(),
signature: payload.get(2)?.to_string(),
})
};
let jws_body = generate_jws_body(jws_payload).ok_or(errors::VaultError::SaveCardFailed)?;
let payload = jws_body
.encode_to_vec()
.change_context(errors::VaultError::SaveCardFailed)?;
let public_key = match locker_choice {
api_enums::LockerChoice::HyperswitchCardVault => {
jwekey.vault_encryption_key.peek().as_bytes()
}
};
let jwe_encrypted =
encryption::encrypt_jwe(&payload, public_key, EncryptionAlgorithm::A256GCM, None)
.await
.change_context(errors::VaultError::SaveCardFailed)
.attach_printable("Error on jwe encrypt")?;
let jwe_payload: Vec<&str> = jwe_encrypted.split('.').collect();
let generate_jwe_body = |payload: Vec<&str>| -> Option<encryption::JweBody> {
Some(encryption::JweBody {
header: payload.first()?.to_string(),
iv: payload.get(2)?.to_string(),
encrypted_payload: payload.get(3)?.to_string(),
tag: payload.get(4)?.to_string(),
encrypted_key: payload.get(1)?.to_string(),
})
};
let jwe_body = generate_jwe_body(jwe_payload).ok_or(errors::VaultError::SaveCardFailed)?;
Ok(jwe_body)
}
pub async fn mk_add_locker_request_hs(
jwekey: &settings::Jwekey,
locker: &settings::Locker,
payload: &StoreLockerReq,
locker_choice: api_enums::LockerChoice,
tenant_id: id_type::TenantId,
request_id: Option<RequestId>,
) -> CustomResult<services::Request, errors::VaultError> {
let payload = payload
.encode_to_vec()
.change_context(errors::VaultError::RequestEncodingFailed)?;
let private_key = jwekey.vault_private_key.peek().as_bytes();
let jws = encryption::jws_sign_payload(&payload, &locker.locker_signing_key_id, private_key)
.await
.change_context(errors::VaultError::RequestEncodingFailed)?;
let jwe_payload = mk_basilisk_req(jwekey, &jws, locker_choice).await?;
let mut url = match locker_choice {
api_enums::LockerChoice::HyperswitchCardVault => locker.host.to_owned(),
};
url.push_str("/cards/add");
let mut request = services::Request::new(services::Method::Post, &url);
request.add_header(headers::CONTENT_TYPE, "application/json".into());
request.add_header(
headers::X_TENANT_ID,
tenant_id.get_string_repr().to_owned().into(),
);
if let Some(req_id) = request_id {
request.add_header(
headers::X_REQUEST_ID,
req_id.as_hyphenated().to_string().into(),
);
}
request.set_body(RequestContent::Json(Box::new(jwe_payload)));
Ok(request)
}
#[cfg(all(feature = "v1", feature = "payouts"))]
pub fn mk_add_bank_response_hs(
bank: api::BankPayout,
bank_reference: String,
req: api::PaymentMethodCreate,
merchant_id: &id_type::MerchantId,
) -> api::PaymentMethodResponse {
api::PaymentMethodResponse {
merchant_id: merchant_id.to_owned(),
customer_id: req.customer_id,
payment_method_id: bank_reference,
payment_method: req.payment_method,
payment_method_type: req.payment_method_type,
bank_transfer: Some(bank),
card: None,
metadata: req.metadata,
created: Some(common_utils::date_time::now()),
recurring_enabled: Some(false), // [#256]
installment_payment_enabled: Some(false), // #[#256]
payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]),
last_used_at: Some(common_utils::date_time::now()),
client_secret: None,
}
}
#[cfg(all(feature = "v2", feature = "payouts"))]
pub fn mk_add_bank_response_hs(
_bank: api::BankPayout,
_bank_reference: String,
_req: api::PaymentMethodCreate,
_merchant_id: &id_type::MerchantId,
) -> api::PaymentMethodResponse {
todo!()
}
#[cfg(feature = "v1")]
pub fn mk_add_card_response_hs(
card: api::CardDetail,
card_reference: String,
req: api::PaymentMethodCreate,
merchant_id: &id_type::MerchantId,
) -> api::PaymentMethodResponse {
let card_number = card.card_number.clone();
let last4_digits = card_number.get_last4();
let card_isin = card_number.get_card_isin();
let card = api::CardDetailFromLocker {
scheme: card
.card_network
.clone()
.map(|card_network| card_network.to_string()),
last4_digits: Some(last4_digits),
issuer_country: card.card_issuing_country,
card_number: Some(card.card_number.clone()),
expiry_month: Some(card.card_exp_month.clone()),
expiry_year: Some(card.card_exp_year.clone()),
card_token: None,
card_fingerprint: None,
card_holder_name: card.card_holder_name.clone(),
nick_name: card.nick_name.clone(),
card_isin: Some(card_isin),
card_issuer: card.card_issuer,
card_network: card.card_network,
card_type: card.card_type,
saved_to_locker: true,
};
api::PaymentMethodResponse {
merchant_id: merchant_id.to_owned(),
customer_id: req.customer_id,
payment_method_id: card_reference,
payment_method: req.payment_method,
payment_method_type: req.payment_method_type,
#[cfg(feature = "payouts")]
bank_transfer: None,
card: Some(card),
metadata: req.metadata,
created: Some(common_utils::date_time::now()),
recurring_enabled: Some(false), // [#256]
installment_payment_enabled: Some(false), // #[#256]
payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]),
last_used_at: Some(common_utils::date_time::now()), // [#256]
client_secret: req.client_secret,
}
}
#[cfg(feature = "v2")]
pub fn mk_add_card_response_hs(
card: api::CardDetail,
card_reference: String,
req: api::PaymentMethodCreate,
merchant_id: &id_type::MerchantId,
) -> api::PaymentMethodResponse {
todo!()
}
#[cfg(feature = "v2")]
pub fn generate_pm_vaulting_req_from_update_request(
pm_create: domain::PaymentMethodVaultingData,
pm_update: api::PaymentMethodUpdateData,
) -> domain::PaymentMethodVaultingData {
match (pm_create, pm_update) {
(
domain::PaymentMethodVaultingData::Card(card_create),
api::PaymentMethodUpdateData::Card(update_card),
) => domain::PaymentMethodVaultingData::Card(api::CardDetail {
card_number: card_create.card_number,
card_exp_month: card_create.card_exp_month,
card_exp_year: card_create.card_exp_year,
card_issuing_country: card_create.card_issuing_country,
card_network: card_create.card_network,
card_issuer: card_create.card_issuer,
card_type: card_create.card_type,
card_holder_name: update_card
.card_holder_name
.or(card_create.card_holder_name),
nick_name: update_card.nick_name.or(card_create.nick_name),
card_cvc: None,
}),
_ => todo!(), //todo! - since support for network tokenization is not added PaymentMethodUpdateData. should be handled later.
}
}
#[cfg(feature = "v2")]
pub fn generate_payment_method_response(
payment_method: &domain::PaymentMethod,
single_use_token: &Option<payment_method_data::SingleUsePaymentMethodToken>,
) -> errors::RouterResult<api::PaymentMethodResponse> {
let pmd = payment_method
.payment_method_data
.clone()
.map(|data| data.into_inner())
.and_then(|data| match data {
api::PaymentMethodsData::Card(card) => {
Some(api::PaymentMethodResponseData::Card(card.into()))
}
_ => None,
});
let mut connector_tokens = payment_method
.connector_mandate_details
.as_ref()
.and_then(|connector_token_details| connector_token_details.payments.clone())
.map(|payment_token_details| payment_token_details.0)
.map(|payment_token_details| {
payment_token_details
.into_iter()
.map(transformers::ForeignFrom::foreign_from)
.collect::<Vec<_>>()
})
.unwrap_or_default();
if let Some(token) = single_use_token {
let connector_token_single_use = transformers::ForeignFrom::foreign_from(token);
connector_tokens.push(connector_token_single_use);
}
let connector_tokens = if connector_tokens.is_empty() {
None
} else {
Some(connector_tokens)
};
let network_token_pmd = payment_method
.network_token_payment_method_data
.clone()
.map(|data| data.into_inner())
.and_then(|data| match data {
domain::PaymentMethodsData::NetworkToken(token) => {
Some(api::NetworkTokenDetailsPaymentMethod::from(token))
}
_ => None,
});
let network_token = network_token_pmd.map(|pmd| api::NetworkTokenResponse {
payment_method_data: pmd,
});
let resp = api::PaymentMethodResponse {
merchant_id: payment_method.merchant_id.to_owned(),
customer_id: payment_method.customer_id.to_owned(),
id: payment_method.id.to_owned(),
payment_method_type: payment_method.get_payment_method_type(),
payment_method_subtype: payment_method.get_payment_method_subtype(),
created: Some(payment_method.created_at),
recurring_enabled: Some(false),
last_used_at: Some(payment_method.last_used_at),
payment_method_data: pmd,
connector_tokens,
network_token,
};
Ok(resp)
}
#[allow(clippy::too_many_arguments)]
pub async fn mk_get_card_request_hs(
jwekey: &settings::Jwekey,
locker: &settings::Locker,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
card_reference: &str,
locker_choice: Option<api_enums::LockerChoice>,
tenant_id: id_type::TenantId,
request_id: Option<RequestId>,
) -> CustomResult<services::Request, errors::VaultError> {
let merchant_customer_id = customer_id.to_owned();
let card_req_body = CardReqBody {
merchant_id: merchant_id.to_owned(),
merchant_customer_id,
card_reference: card_reference.to_owned(),
};
let payload = card_req_body
.encode_to_vec()
.change_context(errors::VaultError::RequestEncodingFailed)?;
let private_key = jwekey.vault_private_key.peek().as_bytes();
let jws = encryption::jws_sign_payload(&payload, &locker.locker_signing_key_id, private_key)
.await
.change_context(errors::VaultError::RequestEncodingFailed)?;
let target_locker = locker_choice.unwrap_or(api_enums::LockerChoice::HyperswitchCardVault);
let jwe_payload = mk_basilisk_req(jwekey, &jws, target_locker).await?;
let mut url = match target_locker {
api_enums::LockerChoice::HyperswitchCardVault => locker.host.to_owned(),
};
url.push_str("/cards/retrieve");
let mut request = services::Request::new(services::Method::Post, &url);
request.add_header(headers::CONTENT_TYPE, "application/json".into());
request.add_header(
headers::X_TENANT_ID,
tenant_id.get_string_repr().to_owned().into(),
);
if let Some(req_id) = request_id {
request.add_header(
headers::X_REQUEST_ID,
req_id.as_hyphenated().to_string().into(),
);
}
request.set_body(RequestContent::Json(Box::new(jwe_payload)));
Ok(request)
}
pub fn mk_get_card_request(
locker: &settings::Locker,
locker_id: &'static str,
card_id: &'static str,
) -> CustomResult<services::Request, errors::VaultError> {
let get_card_req = GetCard {
merchant_id: locker_id,
card_id,
};
let mut url = locker.host.to_owned();
url.push_str("/card/getCard");
let mut request = services::Request::new(services::Method::Post, &url);
request.set_body(RequestContent::FormUrlEncoded(Box::new(get_card_req)));
Ok(request)
}
pub fn mk_get_card_response(card: GetCardResponse) -> errors::RouterResult<Card> {
Ok(Card {
card_number: card.card.card_number.get_required_value("card_number")?,
name_on_card: card.card.name_on_card,
card_exp_month: card
.card
.card_exp_month
.get_required_value("card_exp_month")?,
card_exp_year: card
.card
.card_exp_year
.get_required_value("card_exp_year")?,
card_brand: None,
card_isin: None,
nick_name: card.card.nickname,
})
}
pub async fn mk_delete_card_request_hs(
jwekey: &settings::Jwekey,
locker: &settings::Locker,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
card_reference: &str,
tenant_id: id_type::TenantId,
request_id: Option<RequestId>,
) -> CustomResult<services::Request, errors::VaultError> {
let merchant_customer_id = customer_id.to_owned();
let card_req_body = CardReqBody {
merchant_id: merchant_id.to_owned(),
merchant_customer_id,
card_reference: card_reference.to_owned(),
};
let payload = card_req_body
.encode_to_vec()
.change_context(errors::VaultError::RequestEncodingFailed)?;
let private_key = jwekey.vault_private_key.peek().as_bytes();
let jws = encryption::jws_sign_payload(&payload, &locker.locker_signing_key_id, private_key)
.await
.change_context(errors::VaultError::RequestEncodingFailed)?;
let jwe_payload =
mk_basilisk_req(jwekey, &jws, api_enums::LockerChoice::HyperswitchCardVault).await?;
let mut url = locker.host.to_owned();
url.push_str("/cards/delete");
let mut request = services::Request::new(services::Method::Post, &url);
request.add_header(headers::CONTENT_TYPE, "application/json".into());
request.add_header(
headers::X_TENANT_ID,
tenant_id.get_string_repr().to_owned().into(),
);
if let Some(req_id) = request_id {
request.add_header(
headers::X_REQUEST_ID,
req_id.as_hyphenated().to_string().into(),
);
}
request.set_body(RequestContent::Json(Box::new(jwe_payload)));
Ok(request)
}
// Need to fix this once we start moving to v2 completion
#[cfg(feature = "v2")]
pub async fn mk_delete_card_request_hs_by_id(
jwekey: &settings::Jwekey,
locker: &settings::Locker,
id: &String,
merchant_id: &id_type::MerchantId,
card_reference: &str,
tenant_id: id_type::TenantId,
request_id: Option<RequestId>,
) -> CustomResult<services::Request, errors::VaultError> {
let merchant_customer_id = id.to_owned();
let card_req_body = CardReqBodyV2 {
merchant_id: merchant_id.to_owned(),
merchant_customer_id,
card_reference: card_reference.to_owned(),
};
let payload = card_req_body
.encode_to_vec()
.change_context(errors::VaultError::RequestEncodingFailed)?;
let private_key = jwekey.vault_private_key.peek().as_bytes();
let jws = encryption::jws_sign_payload(&payload, &locker.locker_signing_key_id, private_key)
.await
.change_context(errors::VaultError::RequestEncodingFailed)?;
let jwe_payload =
mk_basilisk_req(jwekey, &jws, api_enums::LockerChoice::HyperswitchCardVault).await?;
let mut url = locker.host.to_owned();
url.push_str("/cards/delete");
let mut request = services::Request::new(services::Method::Post, &url);
request.add_header(headers::CONTENT_TYPE, "application/json".into());
request.add_header(
headers::X_TENANT_ID,
tenant_id.get_string_repr().to_owned().into(),
);
if let Some(req_id) = request_id {
request.add_header(
headers::X_REQUEST_ID,
req_id.as_hyphenated().to_string().into(),
);
}
request.set_body(RequestContent::Json(Box::new(jwe_payload)));
Ok(request)
}
pub fn mk_delete_card_response(
response: DeleteCardResponse,
) -> errors::RouterResult<DeleteCardResp> {
Ok(DeleteCardResp {
status: response.status,
error_message: None,
error_code: None,
})
}
#[cfg(feature = "v1")]
pub fn get_card_detail(
pm: &domain::PaymentMethod,
response: Card,
) -> CustomResult<api::CardDetailFromLocker, errors::VaultError> {
let card_number = response.card_number;
let last4_digits = card_number.clone().get_last4();
//fetch form card bin
let card_detail = api::CardDetailFromLocker {
scheme: pm.scheme.to_owned(),
issuer_country: pm.issuer_country.clone(),
last4_digits: Some(last4_digits),
card_number: Some(card_number),
expiry_month: Some(response.card_exp_month),
expiry_year: Some(response.card_exp_year),
card_token: None,
card_fingerprint: None,
card_holder_name: response.name_on_card,
nick_name: response.nick_name.map(Secret::new),
card_isin: None,
card_issuer: None,
card_network: None,
card_type: None,
saved_to_locker: true,
};
Ok(card_detail)
}
#[cfg(feature = "v2")]
pub fn get_card_detail(
_pm: &domain::PaymentMethod,
response: Card,
) -> CustomResult<api::CardDetailFromLocker, errors::VaultError> {
let card_number = response.card_number;
let last4_digits = card_number.clone().get_last4();
//fetch form card bin
let card_detail = api::CardDetailFromLocker {
issuer_country: None,
last4_digits: Some(last4_digits),
card_number: Some(card_number),
expiry_month: Some(response.card_exp_month),
expiry_year: Some(response.card_exp_year),
card_fingerprint: None,
card_holder_name: response.name_on_card,
nick_name: response.nick_name.map(Secret::new),
card_isin: None,
card_issuer: None,
card_network: None,
card_type: None,
saved_to_locker: true,
};
Ok(card_detail)
}
//------------------------------------------------TokenizeService------------------------------------------------
pub fn mk_crud_locker_request(
locker: &settings::Locker,
path: &str,
req: api::TokenizePayloadEncrypted,
tenant_id: id_type::TenantId,
request_id: Option<RequestId>,
) -> CustomResult<services::Request, errors::VaultError> {
let mut url = locker.basilisk_host.to_owned();
url.push_str(path);
let mut request = services::Request::new(services::Method::Post, &url);
request.add_default_headers();
request.add_header(headers::CONTENT_TYPE, "application/json".into());
request.add_header(
headers::X_TENANT_ID,
tenant_id.get_string_repr().to_owned().into(),
);
if let Some(req_id) = request_id {
request.add_header(
headers::X_REQUEST_ID,
req_id.as_hyphenated().to_string().into(),
);
}
request.set_body(RequestContent::Json(Box::new(req)));
Ok(request)
}
pub fn mk_card_value1(
card_number: cards::CardNumber,
exp_year: String,
exp_month: String,
name_on_card: Option<String>,
nickname: Option<String>,
card_last_four: Option<String>,
card_token: Option<String>,
) -> CustomResult<String, errors::VaultError> {
let value1 = api::TokenizedCardValue1 {
card_number: card_number.peek().clone(),
exp_year,
exp_month,
name_on_card,
nickname,
card_last_four,
card_token,
};
let value1_req = value1
.encode_to_string_of_json()
.change_context(errors::VaultError::FetchCardFailed)?;
Ok(value1_req)
}
pub fn mk_card_value2(
card_security_code: Option<String>,
card_fingerprint: Option<String>,
external_id: Option<String>,
customer_id: Option<id_type::CustomerId>,
payment_method_id: Option<String>,
) -> CustomResult<String, errors::VaultError> {
let value2 = api::TokenizedCardValue2 {
card_security_code,
card_fingerprint,
external_id,
customer_id,
payment_method_id,
};
let value2_req = value2
.encode_to_string_of_json()
.change_context(errors::VaultError::FetchCardFailed)?;
Ok(value2_req)
}
#[cfg(feature = "v2")]
impl transformers::ForeignTryFrom<(domain::PaymentMethod, String)>
for api::CustomerPaymentMethodResponseItem
{
type Error = error_stack::Report<errors::ValidationError>;
fn foreign_try_from(
(item, payment_token): (domain::PaymentMethod, String),
) -> Result<Self, Self::Error> {
// For payment methods that are active we should always have the payment method subtype
let payment_method_subtype =
item.payment_method_subtype
.ok_or(errors::ValidationError::MissingRequiredField {
field_name: "payment_method_subtype".to_string(),
})?;
// For payment methods that are active we should always have the payment method type
let payment_method_type =
item.payment_method_type
.ok_or(errors::ValidationError::MissingRequiredField {
field_name: "payment_method_type".to_string(),
})?;
let payment_method_data = item
.payment_method_data
.map(|payment_method_data| payment_method_data.into_inner())
.map(|payment_method_data| match payment_method_data {
api_models::payment_methods::PaymentMethodsData::Card(
card_details_payment_method,
) => {
let card_details = api::CardDetailFromLocker::from(card_details_payment_method);
api_models::payment_methods::PaymentMethodListData::Card(card_details)
}
api_models::payment_methods::PaymentMethodsData::BankDetails(..) => todo!(),
api_models::payment_methods::PaymentMethodsData::WalletDetails(..) => {
todo!()
}
});
let payment_method_billing = item
.payment_method_billing_address
.clone()
.map(|billing| billing.into_inner())
.map(From::from);
// TODO: check how we can get this field
let recurring_enabled = true;
Ok(Self {
id: item.id,
customer_id: item.customer_id,
payment_method_type,
payment_method_subtype,
created: item.created_at,
last_used_at: item.last_used_at,
recurring_enabled,
payment_method_data,
bank: None,
requires_cvv: true,
is_default: false,
billing: payment_method_billing,
payment_token,
})
}
}
#[cfg(feature = "v2")]
impl transformers::ForeignTryFrom<domain::PaymentMethod> for PaymentMethodResponseItem {
type Error = error_stack::Report<errors::ValidationError>;
fn foreign_try_from(item: domain::PaymentMethod) -> Result<Self, Self::Error> {
// For payment methods that are active we should always have the payment method subtype
let payment_method_subtype =
item.payment_method_subtype
.ok_or(errors::ValidationError::MissingRequiredField {
field_name: "payment_method_subtype".to_string(),
})?;
// For payment methods that are active we should always have the payment method type
let payment_method_type =
item.payment_method_type
.ok_or(errors::ValidationError::MissingRequiredField {
field_name: "payment_method_type".to_string(),
})?;
let payment_method_data = item
.payment_method_data
.map(|payment_method_data| payment_method_data.into_inner())
.map(|payment_method_data| match payment_method_data {
api_models::payment_methods::PaymentMethodsData::Card(
card_details_payment_method,
) => {
let card_details = api::CardDetailFromLocker::from(card_details_payment_method);
api_models::payment_methods::PaymentMethodListData::Card(card_details)
}
api_models::payment_methods::PaymentMethodsData::BankDetails(..) => todo!(),
api_models::payment_methods::PaymentMethodsData::WalletDetails(..) => {
todo!()
}
});
let payment_method_billing = item
.payment_method_billing_address
.clone()
.map(|billing| billing.into_inner())
.map(From::from);
let network_token_pmd = item
.network_token_payment_method_data
.clone()
.map(|data| data.into_inner())
.and_then(|data| match data {
domain::PaymentMethodsData::NetworkToken(token) => {
Some(api::NetworkTokenDetailsPaymentMethod::from(token))
}
_ => None,
});
let network_token_resp = network_token_pmd.map(|pmd| api::NetworkTokenResponse {
payment_method_data: pmd,
});
// TODO: check how we can get this field
let recurring_enabled = Some(true);
let psp_tokenization_enabled = item.connector_mandate_details.and_then(|details| {
details.payments.map(|payments| {
payments.values().any(|connector_token_reference| {
connector_token_reference.connector_token_status
== api_enums::ConnectorTokenStatus::Active
})
})
});
Ok(Self {
id: item.id,
customer_id: item.customer_id,
payment_method_type,
payment_method_subtype,
created: item.created_at,
last_used_at: item.last_used_at,
recurring_enabled,
payment_method_data,
bank: None,
requires_cvv: true,
is_default: false,
billing: payment_method_billing,
network_tokenization: network_token_resp,
psp_tokenization_enabled: psp_tokenization_enabled.unwrap_or(false),
})
}
}
#[cfg(feature = "v2")]
pub fn generate_payment_method_session_response(
payment_method_session: hyperswitch_domain_models::payment_methods::PaymentMethodSession,
client_secret: Secret<String>,
associated_payment: Option<api_models::payments::PaymentsResponse>,
tokenization_service_response: Option<api_models::tokenization::GenericTokenizationResponse>,
) -> api_models::payment_methods::PaymentMethodSessionResponse {
let next_action = associated_payment
.as_ref()
.and_then(|payment| payment.next_action.clone());
let authentication_details =
associated_payment.map(
|payment| api_models::payment_methods::AuthenticationDetails {
status: payment.status,
error: payment.error,
},
);
let token_id = tokenization_service_response
.as_ref()
.map(|tokenization_service_response| tokenization_service_response.id.clone());
api_models::payment_methods::PaymentMethodSessionResponse {
id: payment_method_session.id,
customer_id: payment_method_session.customer_id,
billing: payment_method_session
.billing
.map(|address| address.into_inner())
.map(From::from),
psp_tokenization: payment_method_session.psp_tokenization,
network_tokenization: payment_method_session.network_tokenization,
tokenization_data: payment_method_session.tokenization_data,
expires_at: payment_method_session.expires_at,
client_secret,
next_action,
return_url: payment_method_session.return_url,
associated_payment_methods: payment_method_session.associated_payment_methods,
authentication_details,
associated_token_id: token_id,
}
}
#[cfg(feature = "v2")]
impl transformers::ForeignFrom<api_models::payment_methods::ConnectorTokenDetails>
for hyperswitch_domain_models::mandates::ConnectorTokenReferenceRecord
{
fn foreign_from(item: api_models::payment_methods::ConnectorTokenDetails) -> Self {
let api_models::payment_methods::ConnectorTokenDetails {
status,
connector_token_request_reference_id,
original_payment_authorized_amount,
original_payment_authorized_currency,
metadata,
token,
..
} = item;
Self {
connector_token: token.expose().clone(),
// TODO: check why do we need this field
payment_method_subtype: None,
original_payment_authorized_amount,
original_payment_authorized_currency,
metadata,
connector_token_status: status,
connector_token_request_reference_id,
}
}
}
#[cfg(feature = "v2")]
impl
transformers::ForeignFrom<(
id_type::MerchantConnectorAccountId,
hyperswitch_domain_models::mandates::ConnectorTokenReferenceRecord,
)> for api_models::payment_methods::ConnectorTokenDetails
{
fn foreign_from(
(connector_id, mandate_reference_record): (
id_type::MerchantConnectorAccountId,
hyperswitch_domain_models::mandates::ConnectorTokenReferenceRecord,
),
) -> Self {
let hyperswitch_domain_models::mandates::ConnectorTokenReferenceRecord {
connector_token_request_reference_id,
original_payment_authorized_amount,
original_payment_authorized_currency,
metadata,
connector_token,
connector_token_status,
..
} = mandate_reference_record;
Self {
connector_id,
status: connector_token_status,
connector_token_request_reference_id,
original_payment_authorized_amount,
original_payment_authorized_currency,
metadata,
token: Secret::new(connector_token),
// Token that is derived from payments mandate reference will always be multi use token
token_type: common_enums::TokenizationType::MultiUse,
}
}
}
#[cfg(feature = "v2")]
impl transformers::ForeignFrom<&payment_method_data::SingleUsePaymentMethodToken>
for api_models::payment_methods::ConnectorTokenDetails
{
fn foreign_from(token: &payment_method_data::SingleUsePaymentMethodToken) -> Self {
Self {
connector_id: token.clone().merchant_connector_id,
token_type: common_enums::TokenizationType::SingleUse,
status: api_enums::ConnectorTokenStatus::Active,
connector_token_request_reference_id: None,
original_payment_authorized_amount: None,
original_payment_authorized_currency: None,
metadata: None,
token: token.clone().token,
}
}
}
|
crates/router/src/core/payment_methods/transformers.rs
|
router::src::core::payment_methods::transformers
| 9,467
| true
|
// File: crates/router/src/core/payment_methods/network_tokenization.rs
// Module: router::src::core::payment_methods::network_tokenization
#[cfg(feature = "v2")]
use std::fmt::Debug;
#[cfg(feature = "v2")]
use std::str::FromStr;
use ::payment_methods::controller::PaymentMethodsController;
use api_models::payment_methods as api_payment_methods;
#[cfg(feature = "v2")]
use cards::{CardNumber, NetworkToken};
use common_utils::{
errors::CustomResult,
ext_traits::{BytesExt, Encode},
id_type,
metrics::utils::record_operation_time,
request::RequestContent,
};
#[cfg(feature = "v1")]
use error_stack::ResultExt;
#[cfg(feature = "v2")]
use error_stack::{report, ResultExt};
#[cfg(feature = "v2")]
use hyperswitch_domain_models::payment_method_data::{
NetworkTokenDetails, NetworkTokenDetailsPaymentMethod,
};
use josekit::jwe;
use masking::{ExposeInterface, Mask, PeekInterface, Secret};
use super::transformers::DeleteCardResp;
use crate::{
core::{errors, payment_methods, payments::helpers},
headers, logger,
routes::{self, metrics},
services::{self, encryption},
settings,
types::{api, domain, payment_methods as pm_types},
};
pub const NETWORK_TOKEN_SERVICE: &str = "NETWORK_TOKEN";
#[cfg(feature = "v1")]
pub async fn mk_tokenization_req(
state: &routes::SessionState,
payload_bytes: &[u8],
customer_id: id_type::CustomerId,
tokenization_service: &settings::NetworkTokenizationService,
) -> CustomResult<
(pm_types::CardNetworkTokenResponsePayload, Option<String>),
errors::NetworkTokenizationError,
> {
let enc_key = tokenization_service.public_key.peek().clone();
let key_id = tokenization_service.key_id.clone();
let jwt = encryption::encrypt_jwe(
payload_bytes,
enc_key,
services::EncryptionAlgorithm::A128GCM,
Some(key_id.as_str()),
)
.await
.change_context(errors::NetworkTokenizationError::SaveNetworkTokenFailed)
.attach_printable("Error on jwe encrypt")?;
let order_data = pm_types::OrderData {
consent_id: uuid::Uuid::new_v4().to_string(),
customer_id,
};
let api_payload = pm_types::ApiPayload {
service: NETWORK_TOKEN_SERVICE.to_string(),
card_data: Secret::new(jwt),
order_data,
key_id,
should_send_token: true,
};
let mut request = services::Request::new(
services::Method::Post,
tokenization_service.generate_token_url.as_str(),
);
request.add_header(headers::CONTENT_TYPE, "application/json".into());
request.add_header(
headers::AUTHORIZATION,
tokenization_service
.token_service_api_key
.peek()
.clone()
.into_masked(),
);
request.add_default_headers();
request.set_body(RequestContent::Json(Box::new(api_payload)));
logger::info!("Request to generate token: {:?}", request);
let response = services::call_connector_api(state, request, "generate_token")
.await
.change_context(errors::NetworkTokenizationError::ApiError);
let res = response
.change_context(errors::NetworkTokenizationError::ResponseDeserializationFailed)
.attach_printable("Error while receiving response")
.and_then(|inner| match inner {
Err(err_res) => {
let parsed_error: pm_types::NetworkTokenErrorResponse = err_res
.response
.parse_struct("Card Network Tokenization Response")
.change_context(
errors::NetworkTokenizationError::ResponseDeserializationFailed,
)?;
logger::error!(
error_code = %parsed_error.error_info.code,
developer_message = %parsed_error.error_info.developer_message,
"Network tokenization error: {}",
parsed_error.error_message
);
Err(errors::NetworkTokenizationError::ResponseDeserializationFailed)
.attach_printable(format!("Response Deserialization Failed: {err_res:?}"))
}
Ok(res) => Ok(res),
})
.inspect_err(|err| {
logger::error!("Error while deserializing response: {:?}", err);
})?;
let network_response: pm_types::CardNetworkTokenResponse = res
.response
.parse_struct("Card Network Tokenization Response")
.change_context(errors::NetworkTokenizationError::ResponseDeserializationFailed)?;
let dec_key = tokenization_service.private_key.peek().clone();
let card_network_token_response = services::decrypt_jwe(
network_response.payload.peek(),
services::KeyIdCheck::SkipKeyIdCheck,
dec_key,
jwe::RSA_OAEP_256,
)
.await
.change_context(errors::NetworkTokenizationError::SaveNetworkTokenFailed)
.attach_printable(
"Failed to decrypt the tokenization response from the tokenization service",
)?;
let cn_response: pm_types::CardNetworkTokenResponsePayload =
serde_json::from_str(&card_network_token_response)
.change_context(errors::NetworkTokenizationError::ResponseDeserializationFailed)?;
Ok((cn_response.clone(), Some(cn_response.card_reference)))
}
#[cfg(feature = "v2")]
pub async fn generate_network_token(
state: &routes::SessionState,
payload_bytes: &[u8],
customer_id: id_type::GlobalCustomerId,
tokenization_service: &settings::NetworkTokenizationService,
) -> CustomResult<
(pm_types::GenerateNetworkTokenResponsePayload, String),
errors::NetworkTokenizationError,
> {
let enc_key = tokenization_service.public_key.peek().clone();
let key_id = tokenization_service.key_id.clone();
let jwt = encryption::encrypt_jwe(
payload_bytes,
enc_key,
services::EncryptionAlgorithm::A128GCM,
Some(key_id.as_str()),
)
.await
.change_context(errors::NetworkTokenizationError::SaveNetworkTokenFailed)
.attach_printable("Error on jwe encrypt")?;
let order_data = pm_types::OrderData {
consent_id: uuid::Uuid::new_v4().to_string(),
customer_id,
};
let api_payload = pm_types::ApiPayload {
service: NETWORK_TOKEN_SERVICE.to_string(),
card_data: Secret::new(jwt),
order_data,
key_id,
should_send_token: true,
};
let mut request = services::Request::new(
services::Method::Post,
tokenization_service.generate_token_url.as_str(),
);
request.add_header(headers::CONTENT_TYPE, "application/json".into());
request.add_header(
headers::AUTHORIZATION,
tokenization_service
.token_service_api_key
.peek()
.clone()
.into_masked(),
);
request.add_default_headers();
request.set_body(RequestContent::Json(Box::new(api_payload)));
logger::info!("Request to generate token: {:?}", request);
let response = services::call_connector_api(state, request, "generate_token")
.await
.change_context(errors::NetworkTokenizationError::ApiError);
let res = response
.change_context(errors::NetworkTokenizationError::ResponseDeserializationFailed)
.attach_printable("Error while receiving response")
.and_then(|inner| match inner {
Err(err_res) => {
let parsed_error: pm_types::NetworkTokenErrorResponse = err_res
.response
.parse_struct("Card Network Tokenization Response")
.change_context(
errors::NetworkTokenizationError::ResponseDeserializationFailed,
)?;
logger::error!(
error_code = %parsed_error.error_info.code,
developer_message = %parsed_error.error_info.developer_message,
"Network tokenization error: {}",
parsed_error.error_message
);
Err(errors::NetworkTokenizationError::ResponseDeserializationFailed)
.attach_printable(format!("Response Deserialization Failed: {err_res:?}"))
}
Ok(res) => Ok(res),
})
.inspect_err(|err| {
logger::error!("Error while deserializing response: {:?}", err);
})?;
let network_response: pm_types::CardNetworkTokenResponse = res
.response
.parse_struct("Card Network Tokenization Response")
.change_context(errors::NetworkTokenizationError::ResponseDeserializationFailed)?;
logger::debug!("Network Token Response: {:?}", network_response);
let dec_key = tokenization_service.private_key.peek().clone();
let card_network_token_response = services::decrypt_jwe(
network_response.payload.peek(),
services::KeyIdCheck::SkipKeyIdCheck,
dec_key,
jwe::RSA_OAEP_256,
)
.await
.change_context(errors::NetworkTokenizationError::SaveNetworkTokenFailed)
.attach_printable(
"Failed to decrypt the tokenization response from the tokenization service",
)?;
let cn_response: pm_types::GenerateNetworkTokenResponsePayload =
serde_json::from_str(&card_network_token_response)
.change_context(errors::NetworkTokenizationError::ResponseDeserializationFailed)?;
Ok((cn_response.clone(), cn_response.card_reference))
}
#[cfg(feature = "v1")]
pub async fn make_card_network_tokenization_request(
state: &routes::SessionState,
card: &domain::CardDetail,
optional_cvc: Option<Secret<String>>,
customer_id: &id_type::CustomerId,
) -> CustomResult<
(pm_types::CardNetworkTokenResponsePayload, Option<String>),
errors::NetworkTokenizationError,
> {
let card_data = pm_types::CardData {
card_number: card.card_number.clone(),
exp_month: card.card_exp_month.clone(),
exp_year: card.card_exp_year.clone(),
card_security_code: optional_cvc,
};
let payload = card_data
.encode_to_string_of_json()
.and_then(|x| x.encode_to_string_of_json())
.change_context(errors::NetworkTokenizationError::RequestEncodingFailed)?;
let payload_bytes = payload.as_bytes();
if let Some(network_tokenization_service) = &state.conf.network_tokenization_service {
record_operation_time(
async {
mk_tokenization_req(
state,
payload_bytes,
customer_id.clone(),
network_tokenization_service.get_inner(),
)
.await
.inspect_err(
|e| logger::error!(error=?e, "Error while making tokenization request"),
)
},
&metrics::GENERATE_NETWORK_TOKEN_TIME,
router_env::metric_attributes!(("locker", "rust")),
)
.await
} else {
Err(errors::NetworkTokenizationError::NetworkTokenizationServiceNotConfigured)
.inspect_err(|_| {
logger::error!("Network Tokenization Service not configured");
})
.attach_printable("Network Tokenization Service not configured")
}
}
#[cfg(feature = "v2")]
pub async fn make_card_network_tokenization_request(
state: &routes::SessionState,
card: &api_payment_methods::CardDetail,
customer_id: &id_type::GlobalCustomerId,
) -> CustomResult<(NetworkTokenDetails, String), errors::NetworkTokenizationError> {
let card_data = pm_types::CardData {
card_number: card.card_number.clone(),
exp_month: card.card_exp_month.clone(),
exp_year: card.card_exp_year.clone(),
card_security_code: None,
};
let payload = card_data
.encode_to_string_of_json()
.and_then(|x| x.encode_to_string_of_json())
.change_context(errors::NetworkTokenizationError::RequestEncodingFailed)?;
let payload_bytes = payload.as_bytes();
let network_tokenization_service = match &state.conf.network_tokenization_service {
Some(nt_service) => Ok(nt_service.get_inner()),
None => Err(report!(
errors::NetworkTokenizationError::NetworkTokenizationServiceNotConfigured
)),
}?;
let (resp, network_token_req_ref_id) = record_operation_time(
async {
generate_network_token(
state,
payload_bytes,
customer_id.clone(),
network_tokenization_service,
)
.await
.inspect_err(|e| logger::error!(error=?e, "Error while making tokenization request"))
},
&metrics::GENERATE_NETWORK_TOKEN_TIME,
router_env::metric_attributes!(("locker", "rust")),
)
.await?;
let network_token_details = NetworkTokenDetails {
network_token: resp.token,
network_token_exp_month: resp.token_expiry_month,
network_token_exp_year: resp.token_expiry_year,
card_issuer: card.card_issuer.clone(),
card_network: Some(resp.card_brand),
card_type: card.card_type.clone(),
card_issuing_country: card.card_issuing_country,
card_holder_name: card.card_holder_name.clone(),
nick_name: card.nick_name.clone(),
};
Ok((network_token_details, network_token_req_ref_id))
}
#[cfg(feature = "v1")]
pub async fn get_network_token(
state: &routes::SessionState,
customer_id: id_type::CustomerId,
network_token_requestor_ref_id: String,
tokenization_service: &settings::NetworkTokenizationService,
) -> CustomResult<pm_types::TokenResponse, errors::NetworkTokenizationError> {
let mut request = services::Request::new(
services::Method::Post,
tokenization_service.fetch_token_url.as_str(),
);
let payload = pm_types::GetCardToken {
card_reference: network_token_requestor_ref_id,
customer_id,
};
request.add_header(headers::CONTENT_TYPE, "application/json".into());
request.add_header(
headers::AUTHORIZATION,
tokenization_service
.token_service_api_key
.clone()
.peek()
.clone()
.into_masked(),
);
request.add_default_headers();
request.set_body(RequestContent::Json(Box::new(payload)));
logger::info!("Request to fetch network token: {:?}", request);
// Send the request using `call_connector_api`
let response = services::call_connector_api(state, request, "get network token")
.await
.change_context(errors::NetworkTokenizationError::ApiError);
let res = response
.change_context(errors::NetworkTokenizationError::ResponseDeserializationFailed)
.attach_printable("Error while receiving response")
.and_then(|inner| match inner {
Err(err_res) => {
let parsed_error: pm_types::NetworkTokenErrorResponse = err_res
.response
.parse_struct("Card Network Tokenization Response")
.change_context(
errors::NetworkTokenizationError::ResponseDeserializationFailed,
)?;
logger::error!(
error_code = %parsed_error.error_info.code,
developer_message = %parsed_error.error_info.developer_message,
"Network tokenization error: {}",
parsed_error.error_message
);
Err(errors::NetworkTokenizationError::ResponseDeserializationFailed)
.attach_printable(format!("Response Deserialization Failed: {err_res:?}"))
}
Ok(res) => Ok(res),
})?;
let token_response: pm_types::TokenResponse = res
.response
.parse_struct("Get Network Token Response")
.change_context(errors::NetworkTokenizationError::ResponseDeserializationFailed)?;
logger::info!("Fetch Network Token Response: {:?}", token_response);
Ok(token_response)
}
#[cfg(feature = "v2")]
pub async fn get_network_token(
state: &routes::SessionState,
customer_id: &id_type::GlobalCustomerId,
network_token_requestor_ref_id: String,
tokenization_service: &settings::NetworkTokenizationService,
) -> CustomResult<pm_types::TokenResponse, errors::NetworkTokenizationError> {
let mut request = services::Request::new(
services::Method::Post,
tokenization_service.fetch_token_url.as_str(),
);
let payload = pm_types::GetCardToken {
card_reference: network_token_requestor_ref_id,
customer_id: customer_id.clone(),
};
request.add_header(headers::CONTENT_TYPE, "application/json".into());
request.add_header(
headers::AUTHORIZATION,
tokenization_service
.token_service_api_key
.clone()
.peek()
.clone()
.into_masked(),
);
request.add_default_headers();
request.set_body(RequestContent::Json(Box::new(payload)));
logger::info!("Request to fetch network token: {:?}", request);
// Send the request using `call_connector_api`
let response = services::call_connector_api(state, request, "get network token")
.await
.change_context(errors::NetworkTokenizationError::ApiError);
let res = response
.change_context(errors::NetworkTokenizationError::ResponseDeserializationFailed)
.attach_printable("Error while receiving response")
.and_then(|inner| match inner {
Err(err_res) => {
let parsed_error: pm_types::NetworkTokenErrorResponse = err_res
.response
.parse_struct("Card Network Tokenization Response")
.change_context(
errors::NetworkTokenizationError::ResponseDeserializationFailed,
)?;
logger::error!(
error_code = %parsed_error.error_info.code,
developer_message = %parsed_error.error_info.developer_message,
"Network tokenization error: {}",
parsed_error.error_message
);
Err(errors::NetworkTokenizationError::ResponseDeserializationFailed)
.attach_printable(format!("Response Deserialization Failed: {err_res:?}"))
}
Ok(res) => Ok(res),
})?;
let token_response: pm_types::TokenResponse = res
.response
.parse_struct("Get Network Token Response")
.change_context(errors::NetworkTokenizationError::ResponseDeserializationFailed)?;
logger::info!("Fetch Network Token Response: {:?}", token_response);
Ok(token_response)
}
#[cfg(feature = "v1")]
pub async fn get_token_from_tokenization_service(
state: &routes::SessionState,
network_token_requestor_ref_id: String,
pm_data: &domain::PaymentMethod,
) -> errors::RouterResult<domain::NetworkTokenData> {
let token_response =
if let Some(network_tokenization_service) = &state.conf.network_tokenization_service {
record_operation_time(
async {
get_network_token(
state,
pm_data.customer_id.clone(),
network_token_requestor_ref_id,
network_tokenization_service.get_inner(),
)
.await
.inspect_err(
|e| logger::error!(error=?e, "Error while fetching token from tokenization service")
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Fetch network token failed")
},
&metrics::FETCH_NETWORK_TOKEN_TIME,
&[],
)
.await
} else {
Err(errors::NetworkTokenizationError::NetworkTokenizationServiceNotConfigured)
.inspect_err(|err| {
logger::error!(error=? err);
})
.change_context(errors::ApiErrorResponse::InternalServerError)
}?;
let token_decrypted = pm_data
.network_token_payment_method_data
.clone()
.map(|x| x.into_inner().expose())
.and_then(|v| serde_json::from_value::<api_payment_methods::PaymentMethodsData>(v).ok())
.and_then(|pmd| match pmd {
api_payment_methods::PaymentMethodsData::Card(token) => {
Some(api::CardDetailFromLocker::from(token))
}
_ => None,
})
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to obtain decrypted token object from db")?;
let network_token_data = domain::NetworkTokenData {
token_number: token_response.authentication_details.token,
token_cryptogram: Some(token_response.authentication_details.cryptogram),
token_exp_month: token_decrypted
.expiry_month
.unwrap_or(token_response.token_details.exp_month),
token_exp_year: token_decrypted
.expiry_year
.unwrap_or(token_response.token_details.exp_year),
nick_name: token_decrypted.card_holder_name,
card_issuer: None,
card_network: Some(token_response.network),
card_type: None,
card_issuing_country: None,
bank_code: None,
eci: token_response.eci,
};
Ok(network_token_data)
}
#[cfg(feature = "v2")]
pub async fn get_token_from_tokenization_service(
state: &routes::SessionState,
network_token_requestor_ref_id: String,
pm_data: &domain::PaymentMethod,
) -> errors::RouterResult<domain::NetworkTokenData> {
let token_response =
if let Some(network_tokenization_service) = &state.conf.network_tokenization_service {
record_operation_time(
async {
get_network_token(
state,
&pm_data.customer_id,
network_token_requestor_ref_id,
network_tokenization_service.get_inner(),
)
.await
.inspect_err(
|e| logger::error!(error=?e, "Error while fetching token from tokenization service")
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Fetch network token failed")
},
&metrics::FETCH_NETWORK_TOKEN_TIME,
&[],
)
.await
} else {
Err(errors::NetworkTokenizationError::NetworkTokenizationServiceNotConfigured)
.inspect_err(|err| {
logger::error!(error=? err);
})
.change_context(errors::ApiErrorResponse::InternalServerError)
}?;
let token_decrypted = pm_data
.network_token_payment_method_data
.clone()
.map(|value| value.into_inner())
.and_then(|payment_method_data| match payment_method_data {
hyperswitch_domain_models::payment_method_data::PaymentMethodsData::NetworkToken(
token,
) => Some(token),
_ => None,
})
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to obtain decrypted token object from db")?;
let network_token_data = domain::NetworkTokenData {
network_token: token_response.authentication_details.token,
cryptogram: Some(token_response.authentication_details.cryptogram),
network_token_exp_month: token_decrypted
.network_token_expiry_month
.unwrap_or(token_response.token_details.exp_month),
network_token_exp_year: token_decrypted
.network_token_expiry_year
.unwrap_or(token_response.token_details.exp_year),
card_holder_name: token_decrypted.card_holder_name,
nick_name: token_decrypted.nick_name.or(token_response.nickname),
card_issuer: token_decrypted.card_issuer.or(token_response.issuer),
card_network: Some(token_response.network),
card_type: token_decrypted
.card_type
.or(token_response.card_type)
.as_ref()
.map(|c| api_payment_methods::CardType::from_str(c))
.transpose()
.ok()
.flatten(),
card_issuing_country: token_decrypted.issuer_country,
bank_code: None,
eci: token_response.eci,
};
Ok(network_token_data)
}
#[cfg(feature = "v1")]
pub async fn do_status_check_for_network_token(
state: &routes::SessionState,
payment_method_info: &domain::PaymentMethod,
) -> CustomResult<(Option<Secret<String>>, Option<Secret<String>>), errors::ApiErrorResponse> {
let network_token_data_decrypted = payment_method_info
.network_token_payment_method_data
.clone()
.map(|x| x.into_inner().expose())
.and_then(|v| serde_json::from_value::<api_payment_methods::PaymentMethodsData>(v).ok())
.and_then(|pmd| match pmd {
api_payment_methods::PaymentMethodsData::Card(token) => {
Some(api::CardDetailFromLocker::from(token))
}
_ => None,
});
let network_token_requestor_reference_id = payment_method_info
.network_token_requestor_reference_id
.clone();
if network_token_data_decrypted
.and_then(|token_data| token_data.expiry_month.zip(token_data.expiry_year))
.and_then(|(exp_month, exp_year)| helpers::validate_card_expiry(&exp_month, &exp_year).ok())
.is_none()
{
if let Some(ref_id) = network_token_requestor_reference_id {
if let Some(network_tokenization_service) = &state.conf.network_tokenization_service {
let (token_exp_month, token_exp_year) = record_operation_time(
async {
check_token_status_with_tokenization_service(
state,
&payment_method_info.customer_id.clone(),
ref_id,
network_tokenization_service.get_inner(),
)
.await
.inspect_err(
|e| logger::error!(error=?e, "Error while fetching token from tokenization service")
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Check network token status with tokenization service failed",
)
},
&metrics::CHECK_NETWORK_TOKEN_STATUS_TIME,
&[],
)
.await?;
Ok((token_exp_month, token_exp_year))
} else {
Err(errors::NetworkTokenizationError::NetworkTokenizationServiceNotConfigured)
.change_context(errors::ApiErrorResponse::InternalServerError)
.inspect_err(|_| {
logger::error!("Network Tokenization Service not configured");
})
}
} else {
Err(errors::NetworkTokenizationError::FetchNetworkTokenFailed)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Check network token status failed")?
}
} else {
Ok((None, None))
}
}
#[cfg(feature = "v1")]
pub async fn check_token_status_with_tokenization_service(
state: &routes::SessionState,
customer_id: &id_type::CustomerId,
network_token_requestor_reference_id: String,
tokenization_service: &settings::NetworkTokenizationService,
) -> CustomResult<(Option<Secret<String>>, Option<Secret<String>>), errors::NetworkTokenizationError>
{
let mut request = services::Request::new(
services::Method::Post,
tokenization_service.check_token_status_url.as_str(),
);
let payload = pm_types::CheckTokenStatus {
card_reference: network_token_requestor_reference_id,
customer_id: customer_id.clone(),
};
request.add_header(headers::CONTENT_TYPE, "application/json".into());
request.add_header(
headers::AUTHORIZATION,
tokenization_service
.token_service_api_key
.clone()
.peek()
.clone()
.into_masked(),
);
request.add_default_headers();
request.set_body(RequestContent::Json(Box::new(payload)));
// Send the request using `call_connector_api`
let response = services::call_connector_api(state, request, "Check Network token Status")
.await
.change_context(errors::NetworkTokenizationError::ApiError);
let res = response
.change_context(errors::NetworkTokenizationError::ResponseDeserializationFailed)
.attach_printable("Error while receiving response")
.and_then(|inner| match inner {
Err(err_res) => {
let parsed_error: pm_types::NetworkTokenErrorResponse = err_res
.response
.parse_struct("Delete Network Tokenization Response")
.change_context(
errors::NetworkTokenizationError::ResponseDeserializationFailed,
)?;
logger::error!(
error_code = %parsed_error.error_info.code,
developer_message = %parsed_error.error_info.developer_message,
"Network tokenization error: {}",
parsed_error.error_message
);
Err(errors::NetworkTokenizationError::ResponseDeserializationFailed)
.attach_printable(format!("Response Deserialization Failed: {err_res:?}"))
}
Ok(res) => Ok(res),
})
.inspect_err(|err| {
logger::error!("Error while deserializing response: {:?}", err);
})?;
let check_token_status_response: pm_types::CheckTokenStatusResponse = res
.response
.parse_struct("Delete Network Tokenization Response")
.change_context(errors::NetworkTokenizationError::ResponseDeserializationFailed)?;
match check_token_status_response.token_status {
pm_types::TokenStatus::Active => Ok((
Some(check_token_status_response.token_expiry_month),
Some(check_token_status_response.token_expiry_year),
)),
_ => Ok((None, None)),
}
}
#[cfg(feature = "v2")]
pub async fn check_token_status_with_tokenization_service(
state: &routes::SessionState,
customer_id: &id_type::GlobalCustomerId,
network_token_requestor_reference_id: String,
tokenization_service: &settings::NetworkTokenizationService,
) -> CustomResult<pm_types::CheckTokenStatusResponse, errors::NetworkTokenizationError> {
let mut request = services::Request::new(
services::Method::Post,
tokenization_service.check_token_status_url.as_str(),
);
let payload = pm_types::CheckTokenStatus {
card_reference: network_token_requestor_reference_id,
customer_id: customer_id.clone(),
};
request.add_header(headers::CONTENT_TYPE, "application/json".into());
request.add_header(
headers::AUTHORIZATION,
tokenization_service
.token_service_api_key
.clone()
.peek()
.clone()
.into_masked(),
);
request.add_default_headers();
request.set_body(RequestContent::Json(Box::new(payload)));
// Send the request using `call_connector_api`
let response = services::call_connector_api(state, request, "Check Network token Status")
.await
.change_context(errors::NetworkTokenizationError::ApiError);
let res = response
.change_context(errors::NetworkTokenizationError::ResponseDeserializationFailed)
.attach_printable("Error while receiving response")
.and_then(|inner| match inner {
Err(err_res) => {
let parsed_error: pm_types::NetworkTokenErrorResponse = err_res
.response
.parse_struct("Network Tokenization Error Response")
.change_context(
errors::NetworkTokenizationError::ResponseDeserializationFailed,
)?;
logger::error!(
error_code = %parsed_error.error_info.code,
developer_message = %parsed_error.error_info.developer_message,
"Network tokenization error: {}",
parsed_error.error_message
);
Err(errors::NetworkTokenizationError::ResponseDeserializationFailed)
.attach_printable(format!("Response Deserialization Failed: {err_res:?}"))
}
Ok(res) => Ok(res),
})
.inspect_err(|err| {
logger::error!("Error while deserializing response: {:?}", err);
})?;
let check_token_status_response: pm_types::CheckTokenStatusResponse = res
.response
.parse_struct("CheckTokenStatusResponse")
.change_context(errors::NetworkTokenizationError::ResponseDeserializationFailed)?;
Ok(check_token_status_response)
}
#[cfg(feature = "v2")]
pub async fn do_status_check_for_network_token(
state: &routes::SessionState,
payment_method_info: &domain::PaymentMethod,
) -> CustomResult<pm_types::CheckTokenStatusResponse, errors::NetworkTokenizationError> {
let network_token_requestor_reference_id = payment_method_info
.network_token_requestor_reference_id
.clone();
if let Some(ref_id) = network_token_requestor_reference_id {
if let Some(network_tokenization_service) = &state.conf.network_tokenization_service {
let network_token_details = record_operation_time(
async {
check_token_status_with_tokenization_service(
state,
&payment_method_info.customer_id,
ref_id,
network_tokenization_service.get_inner(),
)
.await
.inspect_err(
|e| logger::error!(error=?e, "Error while fetching token from tokenization service")
)
.attach_printable(
"Check network token status with tokenization service failed",
)
},
&metrics::CHECK_NETWORK_TOKEN_STATUS_TIME,
&[],
)
.await?;
Ok(network_token_details)
} else {
Err(errors::NetworkTokenizationError::NetworkTokenizationServiceNotConfigured)
.attach_printable("Network Tokenization Service not configured")
.inspect_err(|_| {
logger::error!("Network Tokenization Service not configured");
})
}
} else {
Err(errors::NetworkTokenizationError::FetchNetworkTokenFailed)
.attach_printable("Check network token status failed")?
}
}
#[cfg(feature = "v1")]
pub async fn delete_network_token_from_locker_and_token_service(
state: &routes::SessionState,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
payment_method_id: String,
network_token_locker_id: Option<String>,
network_token_requestor_reference_id: String,
merchant_context: &domain::MerchantContext,
) -> errors::RouterResult<DeleteCardResp> {
//deleting network token from locker
let resp = payment_methods::cards::PmCards {
state,
merchant_context,
}
.delete_card_from_locker(
customer_id,
merchant_id,
network_token_locker_id
.as_ref()
.unwrap_or(&payment_method_id),
)
.await?;
if let Some(tokenization_service) = &state.conf.network_tokenization_service {
let delete_token_resp = record_operation_time(
async {
delete_network_token_from_tokenization_service(
state,
network_token_requestor_reference_id,
customer_id,
tokenization_service.get_inner(),
)
.await
},
&metrics::DELETE_NETWORK_TOKEN_TIME,
&[],
)
.await;
match delete_token_resp {
Ok(_) => logger::info!("Token From Tokenization Service deleted Successfully!"),
Err(e) => {
logger::error!(error=?e, "Error while deleting Token From Tokenization Service!")
}
};
};
Ok(resp)
}
#[cfg(feature = "v1")]
pub async fn delete_network_token_from_tokenization_service(
state: &routes::SessionState,
network_token_requestor_reference_id: String,
customer_id: &id_type::CustomerId,
tokenization_service: &settings::NetworkTokenizationService,
) -> CustomResult<bool, errors::NetworkTokenizationError> {
let mut request = services::Request::new(
services::Method::Post,
tokenization_service.delete_token_url.as_str(),
);
let payload = pm_types::DeleteCardToken {
card_reference: network_token_requestor_reference_id,
customer_id: customer_id.clone(),
};
request.add_header(headers::CONTENT_TYPE, "application/json".into());
request.add_header(
headers::AUTHORIZATION,
tokenization_service
.token_service_api_key
.clone()
.peek()
.clone()
.into_masked(),
);
request.add_default_headers();
request.set_body(RequestContent::Json(Box::new(payload)));
logger::info!("Request to delete network token: {:?}", request);
// Send the request using `call_connector_api`
let response = services::call_connector_api(state, request, "delete network token")
.await
.change_context(errors::NetworkTokenizationError::ApiError);
let res = response
.change_context(errors::NetworkTokenizationError::ResponseDeserializationFailed)
.attach_printable("Error while receiving response")
.and_then(|inner| match inner {
Err(err_res) => {
let parsed_error: pm_types::NetworkTokenErrorResponse = err_res
.response
.parse_struct("Delete Network Tokenization Response")
.change_context(
errors::NetworkTokenizationError::ResponseDeserializationFailed,
)?;
logger::error!(
error_code = %parsed_error.error_info.code,
developer_message = %parsed_error.error_info.developer_message,
"Network tokenization error: {}",
parsed_error.error_message
);
Err(errors::NetworkTokenizationError::ResponseDeserializationFailed)
.attach_printable(format!("Response Deserialization Failed: {err_res:?}"))
}
Ok(res) => Ok(res),
})
.inspect_err(|err| {
logger::error!("Error while deserializing response: {:?}", err);
})?;
let delete_token_response: pm_types::DeleteNetworkTokenResponse = res
.response
.parse_struct("Delete Network Tokenization Response")
.change_context(errors::NetworkTokenizationError::ResponseDeserializationFailed)?;
logger::info!("Delete Network Token Response: {:?}", delete_token_response);
if delete_token_response.status == pm_types::DeleteNetworkTokenStatus::Success {
Ok(true)
} else {
Err(errors::NetworkTokenizationError::DeleteNetworkTokenFailed)
.attach_printable("Delete Token at Token service failed")
}
}
#[cfg(feature = "v2")]
pub async fn delete_network_token_from_locker_and_token_service(
_state: &routes::SessionState,
_customer_id: &id_type::GlobalCustomerId,
_merchant_id: &id_type::MerchantId,
_payment_method_id: String,
_network_token_locker_id: Option<String>,
_network_token_requestor_reference_id: String,
) -> errors::RouterResult<DeleteCardResp> {
todo!()
}
|
crates/router/src/core/payment_methods/network_tokenization.rs
|
router::src::core::payment_methods::network_tokenization
| 8,042
| true
|
// File: crates/router/src/core/payment_methods/validator.rs
// Module: router::src::core::payment_methods::validator
use api_models::{admin, payment_methods::PaymentMethodCollectLinkRequest};
use common_utils::link_utils;
use diesel_models::generic_link::PaymentMethodCollectLinkData;
use error_stack::ResultExt;
use masking::Secret;
use crate::{
consts,
core::{
errors::{self, RouterResult},
utils as core_utils,
},
routes::{app::StorageInterface, SessionState},
types::domain,
utils,
};
#[cfg(feature = "v2")]
pub async fn validate_request_and_initiate_payment_method_collect_link(
_state: &SessionState,
_merchant_context: &domain::MerchantContext,
_req: &PaymentMethodCollectLinkRequest,
) -> RouterResult<PaymentMethodCollectLinkData> {
todo!()
}
#[cfg(feature = "v1")]
pub async fn validate_request_and_initiate_payment_method_collect_link(
state: &SessionState,
merchant_context: &domain::MerchantContext,
req: &PaymentMethodCollectLinkRequest,
) -> RouterResult<PaymentMethodCollectLinkData> {
// Validate customer_id
let db: &dyn StorageInterface = &*state.store;
let customer_id = req.customer_id.clone();
let merchant_id = merchant_context.get_merchant_account().get_id().clone();
#[cfg(feature = "v1")]
match db
.find_customer_by_customer_id_merchant_id(
&state.into(),
&customer_id,
&merchant_id,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
{
Ok(_) => Ok(()),
Err(err) => {
if err.current_context().is_db_not_found() {
Err(err).change_context(errors::ApiErrorResponse::InvalidRequestData {
message: format!(
"customer [{}] not found for merchant [{:?}]",
customer_id.get_string_repr(),
merchant_id
),
})
} else {
Err(err)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("database error while finding customer")
}
}
}?;
// Create payment method collect link ID
let pm_collect_link_id = core_utils::get_or_generate_id(
"pm_collect_link_id",
&req.pm_collect_link_id,
"pm_collect_link",
)?;
// Fetch all configs
let default_config = &state.conf.generic_link.payment_method_collect;
#[cfg(feature = "v1")]
let merchant_config = merchant_context
.get_merchant_account()
.pm_collect_link_config
.as_ref()
.map(|config| {
common_utils::ext_traits::ValueExt::parse_value::<admin::BusinessCollectLinkConfig>(
config.clone(),
"BusinessCollectLinkConfig",
)
})
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "pm_collect_link_config in merchant_account",
})?;
#[cfg(feature = "v2")]
let merchant_config = Option::<admin::BusinessCollectLinkConfig>::None;
let merchant_ui_config = merchant_config.as_ref().map(|c| c.config.ui_config.clone());
let ui_config = req
.ui_config
.as_ref()
.or(merchant_ui_config.as_ref())
.cloned();
// Form data to be injected in the link
let (logo, merchant_name, theme) = match ui_config {
Some(config) => (config.logo, config.merchant_name, config.theme),
_ => (None, None, None),
};
let pm_collect_link_config = link_utils::GenericLinkUiConfig {
logo,
merchant_name,
theme,
};
let client_secret = utils::generate_id(consts::ID_LENGTH, "pm_collect_link_secret");
let domain = merchant_config
.clone()
.and_then(|c| c.config.domain_name)
.map(|domain| format!("https://{domain}"))
.unwrap_or(state.base_url.clone());
let session_expiry = match req.session_expiry {
Some(expiry) => expiry,
None => default_config.expiry,
};
let link = Secret::new(format!(
"{domain}/payment_methods/collect/{}/{pm_collect_link_id}",
merchant_id.get_string_repr()
));
let enabled_payment_methods = match (&req.enabled_payment_methods, &merchant_config) {
(Some(enabled_payment_methods), _) => enabled_payment_methods.clone(),
(None, Some(config)) => config.enabled_payment_methods.clone(),
_ => {
let mut default_enabled_payout_methods: Vec<link_utils::EnabledPaymentMethod> = vec![];
for (payment_method, payment_method_types) in
default_config.enabled_payment_methods.clone().into_iter()
{
let enabled_payment_method = link_utils::EnabledPaymentMethod {
payment_method,
payment_method_types: payment_method_types.into_iter().collect(),
};
default_enabled_payout_methods.push(enabled_payment_method);
}
default_enabled_payout_methods
}
};
Ok(PaymentMethodCollectLinkData {
pm_collect_link_id: pm_collect_link_id.clone(),
customer_id,
link,
client_secret: Secret::new(client_secret),
session_expiry,
ui_config: pm_collect_link_config,
enabled_payment_methods: Some(enabled_payment_methods),
})
}
|
crates/router/src/core/payment_methods/validator.rs
|
router::src::core::payment_methods::validator
| 1,154
| true
|
// File: crates/router/src/core/payment_methods/tokenize.rs
// Module: router::src::core::payment_methods::tokenize
use actix_multipart::form::{bytes::Bytes, text::Text, MultipartForm};
use api_models::{enums as api_enums, payment_methods as payment_methods_api};
use cards::CardNumber;
use common_utils::{
crypto::Encryptable,
id_type,
transformers::{ForeignFrom, ForeignTryFrom},
};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::router_request_types as domain_request_types;
use masking::{ExposeInterface, Secret};
use router_env::logger;
use crate::{
core::payment_methods::{
cards::{add_card_to_hs_locker, create_encrypted_data, tokenize_card_flow},
network_tokenization, transformers as pm_transformers,
},
errors::{self, RouterResult},
services,
types::{api, domain, payment_methods as pm_types},
SessionState,
};
pub mod card_executor;
pub mod payment_method_executor;
pub use card_executor::*;
pub use payment_method_executor::*;
use rdkafka::message::ToBytes;
#[derive(Debug, MultipartForm)]
pub struct CardNetworkTokenizeForm {
#[multipart(limit = "1MB")]
pub file: Bytes,
pub merchant_id: Text<id_type::MerchantId>,
}
pub fn parse_csv(
merchant_id: &id_type::MerchantId,
data: &[u8],
) -> csv::Result<Vec<payment_methods_api::CardNetworkTokenizeRequest>> {
let mut csv_reader = csv::ReaderBuilder::new()
.has_headers(true)
.from_reader(data);
let mut records = Vec::new();
let mut id_counter = 0;
for (i, result) in csv_reader
.deserialize::<domain::CardNetworkTokenizeRecord>()
.enumerate()
{
match result {
Ok(mut record) => {
logger::info!("Parsed Record (line {}): {:?}", i + 1, record);
id_counter += 1;
record.line_number = Some(id_counter);
record.merchant_id = Some(merchant_id.clone());
match payment_methods_api::CardNetworkTokenizeRequest::foreign_try_from(record) {
Ok(record) => {
records.push(record);
}
Err(err) => {
logger::error!("Error parsing line {}: {}", i + 1, err.to_string());
}
}
}
Err(e) => logger::error!("Error parsing line {}: {}", i + 1, e),
}
}
Ok(records)
}
pub fn get_tokenize_card_form_records(
form: CardNetworkTokenizeForm,
) -> Result<
(
id_type::MerchantId,
Vec<payment_methods_api::CardNetworkTokenizeRequest>,
),
errors::ApiErrorResponse,
> {
match parse_csv(&form.merchant_id, form.file.data.to_bytes()) {
Ok(records) => {
logger::info!("Parsed a total of {} records", records.len());
Ok((form.merchant_id.0, records))
}
Err(e) => {
logger::error!("Failed to parse CSV: {:?}", e);
Err(errors::ApiErrorResponse::PreconditionFailed {
message: e.to_string(),
})
}
}
}
pub async fn tokenize_cards(
state: &SessionState,
records: Vec<payment_methods_api::CardNetworkTokenizeRequest>,
merchant_context: &domain::MerchantContext,
) -> errors::RouterResponse<Vec<payment_methods_api::CardNetworkTokenizeResponse>> {
use futures::stream::StreamExt;
// Process all records in parallel
let responses = futures::stream::iter(records.into_iter())
.map(|record| async move {
let tokenize_request = record.data.clone();
let customer = record.customer.clone();
Box::pin(tokenize_card_flow(
state,
domain::CardNetworkTokenizeRequest::foreign_from(record),
merchant_context,
))
.await
.unwrap_or_else(|e| {
let err = e.current_context();
payment_methods_api::CardNetworkTokenizeResponse {
tokenization_data: Some(tokenize_request),
error_code: Some(err.error_code()),
error_message: Some(err.error_message()),
card_tokenized: false,
payment_method_response: None,
customer: Some(customer),
}
})
})
.buffer_unordered(10)
.collect()
.await;
// Return the final response
Ok(services::ApplicationResponse::Json(responses))
}
// Data types
type NetworkTokenizationResponse = (pm_types::CardNetworkTokenResponsePayload, Option<String>);
pub struct StoreLockerResponse {
pub store_card_resp: pm_transformers::StoreCardRespPayload,
pub store_token_resp: pm_transformers::StoreCardRespPayload,
}
// Builder
pub struct NetworkTokenizationBuilder<'a, S: State> {
/// Current state
state: std::marker::PhantomData<S>,
/// Customer details
pub customer: Option<&'a api::CustomerDetails>,
/// Card details
pub card: Option<domain::CardDetail>,
/// CVC
pub card_cvc: Option<Secret<String>>,
/// Network token details
pub network_token: Option<&'a pm_types::CardNetworkTokenResponsePayload>,
/// Stored card details
pub stored_card: Option<&'a pm_transformers::StoreCardRespPayload>,
/// Stored token details
pub stored_token: Option<&'a pm_transformers::StoreCardRespPayload>,
/// Payment method response
pub payment_method_response: Option<api::PaymentMethodResponse>,
/// Card network tokenization status
pub card_tokenized: bool,
/// Error code
pub error_code: Option<&'a String>,
/// Error message
pub error_message: Option<&'a String>,
}
// Async executor
pub struct CardNetworkTokenizeExecutor<'a, D> {
pub state: &'a SessionState,
pub merchant_account: &'a domain::MerchantAccount,
key_store: &'a domain::MerchantKeyStore,
data: &'a D,
customer: &'a domain_request_types::CustomerDetails,
}
// State machine
pub trait State {}
pub trait TransitionTo<S: State> {}
// Trait for network tokenization
#[async_trait::async_trait]
pub trait NetworkTokenizationProcess<'a, D> {
fn new(
state: &'a SessionState,
merchant_context: &'a domain::MerchantContext,
data: &'a D,
customer: &'a domain_request_types::CustomerDetails,
) -> Self;
async fn encrypt_card(
&self,
card_details: &domain::CardDetail,
saved_to_locker: bool,
) -> RouterResult<Encryptable<Secret<serde_json::Value>>>;
async fn encrypt_network_token(
&self,
network_token_details: &NetworkTokenizationResponse,
card_details: &domain::CardDetail,
saved_to_locker: bool,
) -> RouterResult<Encryptable<Secret<serde_json::Value>>>;
async fn fetch_bin_details_and_validate_card_network(
&self,
card_number: CardNumber,
card_issuer: Option<&String>,
card_network: Option<&api_enums::CardNetwork>,
card_type: Option<&api_models::payment_methods::CardType>,
card_issuing_country: Option<&String>,
) -> RouterResult<Option<diesel_models::CardInfo>>;
fn validate_card_network(
&self,
optional_card_network: Option<&api_enums::CardNetwork>,
) -> RouterResult<()>;
async fn tokenize_card(
&self,
customer_id: &id_type::CustomerId,
card: &domain::CardDetail,
optional_cvc: Option<Secret<String>>,
) -> RouterResult<NetworkTokenizationResponse>;
async fn store_network_token_in_locker(
&self,
network_token: &NetworkTokenizationResponse,
customer_id: &id_type::CustomerId,
card_holder_name: Option<Secret<String>>,
nick_name: Option<Secret<String>>,
) -> RouterResult<pm_transformers::StoreCardRespPayload>;
}
// Generic implementation
#[async_trait::async_trait]
impl<'a, D> NetworkTokenizationProcess<'a, D> for CardNetworkTokenizeExecutor<'a, D>
where
D: Send + Sync + 'static,
{
fn new(
state: &'a SessionState,
merchant_context: &'a domain::MerchantContext,
data: &'a D,
customer: &'a domain_request_types::CustomerDetails,
) -> Self {
Self {
data,
customer,
state,
merchant_account: merchant_context.get_merchant_account(),
key_store: merchant_context.get_merchant_key_store(),
}
}
async fn encrypt_card(
&self,
card_details: &domain::CardDetail,
saved_to_locker: bool,
) -> RouterResult<Encryptable<Secret<serde_json::Value>>> {
let pm_data = api::PaymentMethodsData::Card(api::CardDetailsPaymentMethod {
last4_digits: Some(card_details.card_number.get_last4()),
expiry_month: Some(card_details.card_exp_month.clone()),
expiry_year: Some(card_details.card_exp_year.clone()),
card_isin: Some(card_details.card_number.get_card_isin()),
nick_name: card_details.nick_name.clone(),
card_holder_name: card_details.card_holder_name.clone(),
issuer_country: card_details.card_issuing_country.clone(),
card_issuer: card_details.card_issuer.clone(),
card_network: card_details.card_network.clone(),
card_type: card_details.card_type.clone(),
saved_to_locker,
co_badged_card_data: card_details
.co_badged_card_data
.as_ref()
.map(|data| data.into()),
});
create_encrypted_data(&self.state.into(), self.key_store, pm_data)
.await
.inspect_err(|err| logger::info!("Error encrypting payment method data: {:?}", err))
.change_context(errors::ApiErrorResponse::InternalServerError)
}
async fn encrypt_network_token(
&self,
network_token_details: &NetworkTokenizationResponse,
card_details: &domain::CardDetail,
saved_to_locker: bool,
) -> RouterResult<Encryptable<Secret<serde_json::Value>>> {
let network_token = &network_token_details.0;
let token_data = api::PaymentMethodsData::Card(api::CardDetailsPaymentMethod {
last4_digits: Some(network_token.token_last_four.clone()),
expiry_month: Some(network_token.token_expiry_month.clone()),
expiry_year: Some(network_token.token_expiry_year.clone()),
card_isin: Some(network_token.token_isin.clone()),
nick_name: card_details.nick_name.clone(),
card_holder_name: card_details.card_holder_name.clone(),
issuer_country: card_details.card_issuing_country.clone(),
card_issuer: card_details.card_issuer.clone(),
card_network: card_details.card_network.clone(),
card_type: card_details.card_type.clone(),
saved_to_locker,
co_badged_card_data: None,
});
create_encrypted_data(&self.state.into(), self.key_store, token_data)
.await
.inspect_err(|err| logger::info!("Error encrypting network token data: {:?}", err))
.change_context(errors::ApiErrorResponse::InternalServerError)
}
async fn fetch_bin_details_and_validate_card_network(
&self,
card_number: CardNumber,
card_issuer: Option<&String>,
card_network: Option<&api_enums::CardNetwork>,
card_type: Option<&api_models::payment_methods::CardType>,
card_issuing_country: Option<&String>,
) -> RouterResult<Option<diesel_models::CardInfo>> {
let db = &*self.state.store;
if card_issuer.is_some()
&& card_network.is_some()
&& card_type.is_some()
&& card_issuing_country.is_some()
{
self.validate_card_network(card_network)?;
return Ok(None);
}
db.get_card_info(&card_number.get_card_isin())
.await
.attach_printable("Failed to perform BIN lookup")
.change_context(errors::ApiErrorResponse::InternalServerError)?
.map(|card_info| {
self.validate_card_network(card_info.card_network.as_ref())?;
Ok(card_info)
})
.transpose()
}
async fn tokenize_card(
&self,
customer_id: &id_type::CustomerId,
card: &domain::CardDetail,
optional_cvc: Option<Secret<String>>,
) -> RouterResult<NetworkTokenizationResponse> {
network_tokenization::make_card_network_tokenization_request(
self.state,
card,
optional_cvc,
customer_id,
)
.await
.map_err(|err| {
logger::error!("Failed to tokenize card with the network: {:?}", err);
report!(errors::ApiErrorResponse::InternalServerError)
})
}
fn validate_card_network(
&self,
optional_card_network: Option<&api_enums::CardNetwork>,
) -> RouterResult<()> {
optional_card_network.map_or(
Err(report!(errors::ApiErrorResponse::NotSupported {
message: "Unknown card network".to_string()
})),
|card_network| {
if self
.state
.conf
.network_tokenization_supported_card_networks
.card_networks
.contains(card_network)
{
Ok(())
} else {
Err(report!(errors::ApiErrorResponse::NotSupported {
message: format!(
"Network tokenization for {card_network} is not supported",
)
}))
}
},
)
}
async fn store_network_token_in_locker(
&self,
network_token: &NetworkTokenizationResponse,
customer_id: &id_type::CustomerId,
card_holder_name: Option<Secret<String>>,
nick_name: Option<Secret<String>>,
) -> RouterResult<pm_transformers::StoreCardRespPayload> {
let network_token = &network_token.0;
let merchant_id = self.merchant_account.get_id();
let locker_req =
pm_transformers::StoreLockerReq::LockerCard(pm_transformers::StoreCardReq {
merchant_id: merchant_id.clone(),
merchant_customer_id: customer_id.clone(),
card: payment_methods_api::Card {
card_number: network_token.token.clone(),
card_exp_month: network_token.token_expiry_month.clone(),
card_exp_year: network_token.token_expiry_year.clone(),
card_brand: Some(network_token.card_brand.to_string()),
card_isin: Some(network_token.token_isin.clone()),
name_on_card: card_holder_name,
nick_name: nick_name.map(|nick_name| nick_name.expose()),
},
requestor_card_reference: None,
ttl: self.state.conf.locker.ttl_for_storage_in_secs,
});
let stored_resp = add_card_to_hs_locker(
self.state,
&locker_req,
customer_id,
api_enums::LockerChoice::HyperswitchCardVault,
)
.await
.inspect_err(|err| logger::info!("Error adding card in locker: {:?}", err))
.change_context(errors::ApiErrorResponse::InternalServerError)?;
Ok(stored_resp)
}
}
|
crates/router/src/core/payment_methods/tokenize.rs
|
router::src::core::payment_methods::tokenize
| 3,275
| true
|
// File: crates/router/src/core/payment_methods/migration.rs
// Module: router::src::core::payment_methods::migration
use actix_multipart::form::{self, bytes, text};
use api_models::payment_methods as pm_api;
use common_utils::{errors::CustomResult, id_type};
use csv::Reader;
use error_stack::ResultExt;
use hyperswitch_domain_models::{
api::ApplicationResponse, errors::api_error_response as errors, merchant_context,
payment_methods::PaymentMethodUpdate,
};
use masking::{ExposeInterface, PeekInterface};
use payment_methods::core::migration::MerchantConnectorValidator;
use rdkafka::message::ToBytes;
use router_env::logger;
use crate::{
core::{errors::StorageErrorExt, payment_methods::cards::create_encrypted_data},
routes::SessionState,
};
type PmMigrationResult<T> = CustomResult<ApplicationResponse<T>, errors::ApiErrorResponse>;
#[cfg(feature = "v1")]
pub async fn update_payment_methods(
state: &SessionState,
payment_methods: Vec<pm_api::UpdatePaymentMethodRecord>,
merchant_id: &id_type::MerchantId,
merchant_context: &merchant_context::MerchantContext,
) -> PmMigrationResult<Vec<pm_api::PaymentMethodUpdateResponse>> {
let mut result = Vec::with_capacity(payment_methods.len());
for record in payment_methods {
let update_res =
update_payment_method_record(state, record.clone(), merchant_id, merchant_context)
.await;
let res = match update_res {
Ok(ApplicationResponse::Json(response)) => Ok(response),
Err(e) => Err(e.to_string()),
_ => Err("Failed to update payment method".to_string()),
};
result.push(pm_api::PaymentMethodUpdateResponse::from((res, record)));
}
Ok(ApplicationResponse::Json(result))
}
#[cfg(feature = "v1")]
pub async fn update_payment_method_record(
state: &SessionState,
req: pm_api::UpdatePaymentMethodRecord,
merchant_id: &id_type::MerchantId,
merchant_context: &merchant_context::MerchantContext,
) -> CustomResult<
ApplicationResponse<pm_api::PaymentMethodRecordUpdateResponse>,
errors::ApiErrorResponse,
> {
use std::collections::HashMap;
use common_enums::enums;
use common_utils::pii;
use hyperswitch_domain_models::mandates::{
CommonMandateReference, PaymentsMandateReference, PaymentsMandateReferenceRecord,
PayoutsMandateReference, PayoutsMandateReferenceRecord,
};
let db = &*state.store;
let payment_method_id = req.payment_method_id.clone();
let network_transaction_id = req.network_transaction_id.clone();
let status = req.status;
let key_manager_state = state.into();
let mut updated_card_expiry = false;
let payment_method = db
.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)?;
if payment_method.merchant_id != *merchant_id {
return Err(errors::ApiErrorResponse::InvalidRequestData {
message: "Merchant ID in the request does not match the Merchant ID in the payment method record.".to_string(),
}.into());
}
let updated_payment_method_data = match payment_method.payment_method_data.as_ref() {
Some(data) => {
match serde_json::from_value::<pm_api::PaymentMethodsData>(
data.clone().into_inner().expose(),
) {
Ok(pm_api::PaymentMethodsData::Card(mut card_data)) => {
if let Some(new_month) = &req.card_expiry_month {
card_data.expiry_month = Some(new_month.clone());
updated_card_expiry = true;
}
if let Some(new_year) = &req.card_expiry_year {
card_data.expiry_year = Some(new_year.clone());
updated_card_expiry = true;
}
if updated_card_expiry {
Some(
create_encrypted_data(
&key_manager_state,
merchant_context.get_merchant_key_store(),
pm_api::PaymentMethodsData::Card(card_data),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt payment method data")
.map(Into::into),
)
} else {
None
}
}
_ => None,
}
}
None => None,
}
.transpose()?;
let mca_data_cache = if let Some(merchant_connector_ids) = &req.merchant_connector_ids {
let parsed_mca_ids =
MerchantConnectorValidator::parse_comma_separated_ids(merchant_connector_ids)?;
let mut cache = HashMap::new();
for merchant_connector_id in parsed_mca_ids {
let mca = db
.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
&state.into(),
merchant_context.get_merchant_account().get_id(),
&merchant_connector_id,
merchant_context.get_merchant_key_store(),
)
.await
.to_not_found_response(
errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: merchant_connector_id.get_string_repr().to_string(),
},
)?;
cache.insert(merchant_connector_id, mca);
}
Some(cache)
} else {
None
};
let (customer, updated_customer) = match (&req.connector_customer_id, &mca_data_cache) {
(Some(connector_customer_id), Some(cache)) => {
let customer = db
.find_customer_by_customer_id_merchant_id(
&state.into(),
&payment_method.customer_id,
merchant_id,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?;
let customer_update =
build_connector_customer_update(&customer, connector_customer_id, cache)?;
(Some(customer), Some(customer_update))
}
_ => (None, None),
};
let pm_update = match (&req.payment_instrument_id, &mca_data_cache) {
(Some(payment_instrument_id), Some(cache)) => {
let mandate_details = payment_method
.get_common_mandate_reference()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to deserialize to Payment Mandate Reference ")?;
let mut existing_payments_mandate = mandate_details
.payments
.clone()
.unwrap_or(PaymentsMandateReference(HashMap::new()));
let mut existing_payouts_mandate = mandate_details
.payouts
.clone()
.unwrap_or(PayoutsMandateReference(HashMap::new()));
for (merchant_connector_id, mca) in cache.iter() {
match mca.connector_type {
enums::ConnectorType::PayoutProcessor => {
let new_payout_record = PayoutsMandateReferenceRecord {
transfer_method_id: Some(payment_instrument_id.peek().to_string()),
};
if let Some(existing_record) =
existing_payouts_mandate.0.get_mut(merchant_connector_id)
{
if let Some(transfer_method_id) = &new_payout_record.transfer_method_id
{
existing_record.transfer_method_id =
Some(transfer_method_id.clone());
}
} else {
existing_payouts_mandate
.0
.insert(merchant_connector_id.clone(), new_payout_record);
}
}
_ => {
if let Some(existing_record) =
existing_payments_mandate.0.get_mut(merchant_connector_id)
{
existing_record.connector_mandate_id =
payment_instrument_id.peek().to_string();
} else {
existing_payments_mandate.0.insert(
merchant_connector_id.clone(),
PaymentsMandateReferenceRecord {
connector_mandate_id: payment_instrument_id.peek().to_string(),
payment_method_type: None,
original_payment_authorized_amount: None,
original_payment_authorized_currency: None,
mandate_metadata: None,
connector_mandate_status: None,
connector_mandate_request_reference_id: None,
},
);
}
}
}
}
let updated_connector_mandate_details = CommonMandateReference {
payments: if !existing_payments_mandate.0.is_empty() {
Some(existing_payments_mandate)
} else {
mandate_details.payments
},
payouts: if !existing_payouts_mandate.0.is_empty() {
Some(existing_payouts_mandate)
} else {
mandate_details.payouts
},
};
let connector_mandate_details_value = updated_connector_mandate_details
.get_mandate_details_value()
.map_err(|err| {
logger::error!("Failed to get get_mandate_details_value : {:?}", err);
errors::ApiErrorResponse::MandateUpdateFailed
})?;
PaymentMethodUpdate::PaymentMethodBatchUpdate {
connector_mandate_details: Some(pii::SecretSerdeValue::new(
connector_mandate_details_value,
)),
network_transaction_id,
status,
payment_method_data: updated_payment_method_data.clone(),
}
}
_ => {
if updated_payment_method_data.is_some() {
PaymentMethodUpdate::PaymentMethodDataUpdate {
payment_method_data: updated_payment_method_data,
}
} else {
PaymentMethodUpdate::NetworkTransactionIdAndStatusUpdate {
network_transaction_id,
status,
}
}
}
};
let response = db
.update_payment_method(
&state.into(),
merchant_context.get_merchant_key_store(),
payment_method,
pm_update,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(format!(
"Failed to update payment method for existing pm_id: {payment_method_id:?} in db",
))?;
let connector_customer_response =
if let (Some(customer_data), Some(customer_update)) = (customer, updated_customer) {
let updated_customer = db
.update_customer_by_customer_id_merchant_id(
&state.into(),
response.customer_id.clone(),
merchant_id.clone(),
customer_data,
customer_update,
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 connector data")?;
updated_customer.connector_customer
} else {
None
};
Ok(ApplicationResponse::Json(
pm_api::PaymentMethodRecordUpdateResponse {
payment_method_id: response.payment_method_id,
status: response.status,
network_transaction_id: response.network_transaction_id,
connector_mandate_details: response
.connector_mandate_details
.map(pii::SecretSerdeValue::new),
updated_payment_method_data: Some(updated_card_expiry),
connector_customer: connector_customer_response,
},
))
}
#[derive(Debug, form::MultipartForm)]
pub struct PaymentMethodsUpdateForm {
#[multipart(limit = "1MB")]
pub file: bytes::Bytes,
pub merchant_id: text::Text<id_type::MerchantId>,
}
fn parse_update_csv(data: &[u8]) -> csv::Result<Vec<pm_api::UpdatePaymentMethodRecord>> {
let mut csv_reader = Reader::from_reader(data);
let mut records = Vec::new();
let mut id_counter = 0;
for result in csv_reader.deserialize() {
let mut record: pm_api::UpdatePaymentMethodRecord = result?;
id_counter += 1;
record.line_number = Some(id_counter);
records.push(record);
}
Ok(records)
}
type UpdateValidationResult =
Result<(id_type::MerchantId, Vec<pm_api::UpdatePaymentMethodRecord>), errors::ApiErrorResponse>;
impl PaymentMethodsUpdateForm {
pub fn validate_and_get_payment_method_records(self) -> UpdateValidationResult {
let records = parse_update_csv(self.file.data.to_bytes()).map_err(|e| {
errors::ApiErrorResponse::PreconditionFailed {
message: e.to_string(),
}
})?;
Ok((self.merchant_id.clone(), records))
}
}
#[cfg(feature = "v1")]
fn build_connector_customer_update(
customer: &hyperswitch_domain_models::customer::Customer,
connector_customer_id: &str,
mca_cache: &std::collections::HashMap<
id_type::MerchantConnectorAccountId,
hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount,
>,
) -> CustomResult<hyperswitch_domain_models::customer::CustomerUpdate, errors::ApiErrorResponse> {
use common_enums::enums;
use common_utils::pii;
let mut updated_connector_customer_data: std::collections::HashMap<String, serde_json::Value> =
customer
.connector_customer
.as_ref()
.and_then(|cc| serde_json::from_value(cc.peek().clone()).ok())
.unwrap_or_default();
for (_, mca) in mca_cache.iter() {
let key = match mca.connector_type {
enums::ConnectorType::PayoutProcessor => {
format!(
"{}_{}",
mca.profile_id.get_string_repr(),
mca.connector_name
)
}
_ => mca.merchant_connector_id.get_string_repr().to_string(),
};
updated_connector_customer_data.insert(
key,
serde_json::Value::String(connector_customer_id.to_string()),
);
}
Ok(
hyperswitch_domain_models::customer::CustomerUpdate::ConnectorCustomer {
connector_customer: Some(pii::SecretSerdeValue::new(
serde_json::to_value(updated_connector_customer_data)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to serialize connector customer data")?,
)),
},
)
}
|
crates/router/src/core/payment_methods/migration.rs
|
router::src::core::payment_methods::migration
| 3,008
| true
|
// File: crates/router/src/core/payment_methods/vault.rs
// Module: router::src::core::payment_methods::vault
use common_enums::PaymentMethodType;
#[cfg(feature = "v2")]
use common_utils::request;
use common_utils::{
crypto::{DecodeMessage, EncodeMessage, GcmAes256},
ext_traits::{BytesExt, Encode},
generate_id_with_default_len, id_type,
pii::Email,
};
use error_stack::{report, ResultExt};
#[cfg(feature = "v2")]
use hyperswitch_domain_models::router_flow_types::{
ExternalVaultDeleteFlow, ExternalVaultRetrieveFlow,
};
use hyperswitch_domain_models::{
router_data_v2::flow_common_types::VaultConnectorFlowData, types::VaultRouterData,
};
use masking::PeekInterface;
use router_env::{instrument, tracing};
use scheduler::{types::process_data, utils as process_tracker_utils};
#[cfg(feature = "payouts")]
use crate::types::api::payouts;
use crate::{
consts,
core::{
errors::{self, ConnectorErrorExt, CustomResult, RouterResult},
payments, utils as core_utils,
},
db, logger,
routes::{self, metrics},
services::{self, connector_integration_interface::RouterDataConversion},
types::{
self, api, domain,
storage::{self, enums},
},
utils::StringExt,
};
#[cfg(feature = "v2")]
use crate::{
core::{
errors::StorageErrorExt,
payment_methods::{transformers as pm_transforms, utils},
payments::{self as payments_core, helpers as payment_helpers},
},
headers, settings,
types::payment_methods as pm_types,
utils::{ext_traits::OptionExt, ConnectorResponseExt},
};
const VAULT_SERVICE_NAME: &str = "CARD";
pub struct SupplementaryVaultData {
pub customer_id: Option<id_type::CustomerId>,
pub payment_method_id: Option<String>,
}
pub trait Vaultable: Sized {
fn get_value1(
&self,
customer_id: Option<id_type::CustomerId>,
) -> CustomResult<String, errors::VaultError>;
fn get_value2(
&self,
_customer_id: Option<id_type::CustomerId>,
) -> CustomResult<String, errors::VaultError> {
Ok(String::new())
}
fn from_values(
value1: String,
value2: String,
) -> CustomResult<(Self, SupplementaryVaultData), errors::VaultError>;
}
impl Vaultable for domain::Card {
fn get_value1(
&self,
_customer_id: Option<id_type::CustomerId>,
) -> CustomResult<String, errors::VaultError> {
let value1 = domain::TokenizedCardValue1 {
card_number: self.card_number.peek().clone(),
exp_year: self.card_exp_year.peek().clone(),
exp_month: self.card_exp_month.peek().clone(),
nickname: self.nick_name.as_ref().map(|name| name.peek().clone()),
card_last_four: None,
card_token: None,
card_holder_name: self.card_holder_name.clone(),
};
value1
.encode_to_string_of_json()
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode card value1")
}
fn get_value2(
&self,
customer_id: Option<id_type::CustomerId>,
) -> CustomResult<String, errors::VaultError> {
let value2 = domain::TokenizedCardValue2 {
card_security_code: Some(self.card_cvc.peek().clone()),
card_fingerprint: None,
external_id: None,
customer_id,
payment_method_id: None,
};
value2
.encode_to_string_of_json()
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode card value2")
}
fn from_values(
value1: String,
value2: String,
) -> CustomResult<(Self, SupplementaryVaultData), errors::VaultError> {
let value1: domain::TokenizedCardValue1 = value1
.parse_struct("TokenizedCardValue1")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Could not deserialize into card value1")?;
let value2: domain::TokenizedCardValue2 = value2
.parse_struct("TokenizedCardValue2")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Could not deserialize into card value2")?;
let card = Self {
card_number: cards::CardNumber::try_from(value1.card_number)
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Invalid card number format from the mock locker")?,
card_exp_month: value1.exp_month.into(),
card_exp_year: value1.exp_year.into(),
card_cvc: value2.card_security_code.unwrap_or_default().into(),
card_issuer: None,
card_network: None,
bank_code: None,
card_issuing_country: None,
card_type: None,
nick_name: value1.nickname.map(masking::Secret::new),
card_holder_name: value1.card_holder_name,
co_badged_card_data: None,
};
let supp_data = SupplementaryVaultData {
customer_id: value2.customer_id,
payment_method_id: value2.payment_method_id,
};
Ok((card, supp_data))
}
}
impl Vaultable for domain::BankTransferData {
fn get_value1(
&self,
_customer_id: Option<id_type::CustomerId>,
) -> CustomResult<String, errors::VaultError> {
let value1 = domain::TokenizedBankTransferValue1 {
data: self.to_owned(),
};
value1
.encode_to_string_of_json()
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode bank transfer data")
}
fn get_value2(
&self,
customer_id: Option<id_type::CustomerId>,
) -> CustomResult<String, errors::VaultError> {
let value2 = domain::TokenizedBankTransferValue2 { customer_id };
value2
.encode_to_string_of_json()
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode bank transfer supplementary data")
}
fn from_values(
value1: String,
value2: String,
) -> CustomResult<(Self, SupplementaryVaultData), errors::VaultError> {
let value1: domain::TokenizedBankTransferValue1 = value1
.parse_struct("TokenizedBankTransferValue1")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Could not deserialize into bank transfer data")?;
let value2: domain::TokenizedBankTransferValue2 = value2
.parse_struct("TokenizedBankTransferValue2")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Could not deserialize into supplementary bank transfer data")?;
let bank_transfer_data = value1.data;
let supp_data = SupplementaryVaultData {
customer_id: value2.customer_id,
payment_method_id: None,
};
Ok((bank_transfer_data, supp_data))
}
}
impl Vaultable for domain::WalletData {
fn get_value1(
&self,
_customer_id: Option<id_type::CustomerId>,
) -> CustomResult<String, errors::VaultError> {
let value1 = domain::TokenizedWalletValue1 {
data: self.to_owned(),
};
value1
.encode_to_string_of_json()
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode wallet data value1")
}
fn get_value2(
&self,
customer_id: Option<id_type::CustomerId>,
) -> CustomResult<String, errors::VaultError> {
let value2 = domain::TokenizedWalletValue2 { customer_id };
value2
.encode_to_string_of_json()
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode wallet data value2")
}
fn from_values(
value1: String,
value2: String,
) -> CustomResult<(Self, SupplementaryVaultData), errors::VaultError> {
let value1: domain::TokenizedWalletValue1 = value1
.parse_struct("TokenizedWalletValue1")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Could not deserialize into wallet data value1")?;
let value2: domain::TokenizedWalletValue2 = value2
.parse_struct("TokenizedWalletValue2")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Could not deserialize into wallet data value2")?;
let wallet = value1.data;
let supp_data = SupplementaryVaultData {
customer_id: value2.customer_id,
payment_method_id: None,
};
Ok((wallet, supp_data))
}
}
impl Vaultable for domain::BankRedirectData {
fn get_value1(
&self,
_customer_id: Option<id_type::CustomerId>,
) -> CustomResult<String, errors::VaultError> {
let value1 = domain::TokenizedBankRedirectValue1 {
data: self.to_owned(),
};
value1
.encode_to_string_of_json()
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode bank redirect data")
}
fn get_value2(
&self,
customer_id: Option<id_type::CustomerId>,
) -> CustomResult<String, errors::VaultError> {
let value2 = domain::TokenizedBankRedirectValue2 { customer_id };
value2
.encode_to_string_of_json()
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode bank redirect supplementary data")
}
fn from_values(
value1: String,
value2: String,
) -> CustomResult<(Self, SupplementaryVaultData), errors::VaultError> {
let value1: domain::TokenizedBankRedirectValue1 = value1
.parse_struct("TokenizedBankRedirectValue1")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Could not deserialize into bank redirect data")?;
let value2: domain::TokenizedBankRedirectValue2 = value2
.parse_struct("TokenizedBankRedirectValue2")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Could not deserialize into supplementary bank redirect data")?;
let bank_transfer_data = value1.data;
let supp_data = SupplementaryVaultData {
customer_id: value2.customer_id,
payment_method_id: None,
};
Ok((bank_transfer_data, supp_data))
}
}
impl Vaultable for domain::BankDebitData {
fn get_value1(
&self,
_customer_id: Option<id_type::CustomerId>,
) -> CustomResult<String, errors::VaultError> {
let value1 = domain::TokenizedBankDebitValue1 {
data: self.to_owned(),
};
value1
.encode_to_string_of_json()
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode bank debit data")
}
fn get_value2(
&self,
customer_id: Option<id_type::CustomerId>,
) -> CustomResult<String, errors::VaultError> {
let value2 = domain::TokenizedBankDebitValue2 { customer_id };
value2
.encode_to_string_of_json()
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode bank debit supplementary data")
}
fn from_values(
value1: String,
value2: String,
) -> CustomResult<(Self, SupplementaryVaultData), errors::VaultError> {
let value1: domain::TokenizedBankDebitValue1 = value1
.parse_struct("TokenizedBankDebitValue1")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Could not deserialize into bank debit data")?;
let value2: domain::TokenizedBankDebitValue2 = value2
.parse_struct("TokenizedBankDebitValue2")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Could not deserialize into supplementary bank debit data")?;
let bank_transfer_data = value1.data;
let supp_data = SupplementaryVaultData {
customer_id: value2.customer_id,
payment_method_id: None,
};
Ok((bank_transfer_data, supp_data))
}
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(tag = "type", content = "value", rename_all = "snake_case")]
pub enum VaultPaymentMethod {
Card(String),
Wallet(String),
BankTransfer(String),
BankRedirect(String),
BankDebit(String),
}
impl Vaultable for domain::PaymentMethodData {
fn get_value1(
&self,
customer_id: Option<id_type::CustomerId>,
) -> CustomResult<String, errors::VaultError> {
let value1 = match self {
Self::Card(card) => VaultPaymentMethod::Card(card.get_value1(customer_id)?),
Self::Wallet(wallet) => VaultPaymentMethod::Wallet(wallet.get_value1(customer_id)?),
Self::BankTransfer(bank_transfer) => {
VaultPaymentMethod::BankTransfer(bank_transfer.get_value1(customer_id)?)
}
Self::BankRedirect(bank_redirect) => {
VaultPaymentMethod::BankRedirect(bank_redirect.get_value1(customer_id)?)
}
Self::BankDebit(bank_debit) => {
VaultPaymentMethod::BankDebit(bank_debit.get_value1(customer_id)?)
}
_ => Err(errors::VaultError::PaymentMethodNotSupported)
.attach_printable("Payment method not supported")?,
};
value1
.encode_to_string_of_json()
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode payment method value1")
}
fn get_value2(
&self,
customer_id: Option<id_type::CustomerId>,
) -> CustomResult<String, errors::VaultError> {
let value2 = match self {
Self::Card(card) => VaultPaymentMethod::Card(card.get_value2(customer_id)?),
Self::Wallet(wallet) => VaultPaymentMethod::Wallet(wallet.get_value2(customer_id)?),
Self::BankTransfer(bank_transfer) => {
VaultPaymentMethod::BankTransfer(bank_transfer.get_value2(customer_id)?)
}
Self::BankRedirect(bank_redirect) => {
VaultPaymentMethod::BankRedirect(bank_redirect.get_value2(customer_id)?)
}
Self::BankDebit(bank_debit) => {
VaultPaymentMethod::BankDebit(bank_debit.get_value2(customer_id)?)
}
_ => Err(errors::VaultError::PaymentMethodNotSupported)
.attach_printable("Payment method not supported")?,
};
value2
.encode_to_string_of_json()
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode payment method value2")
}
fn from_values(
value1: String,
value2: String,
) -> CustomResult<(Self, SupplementaryVaultData), errors::VaultError> {
let value1: VaultPaymentMethod = value1
.parse_struct("PaymentMethodValue1")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Could not deserialize into payment method value 1")?;
let value2: VaultPaymentMethod = value2
.parse_struct("PaymentMethodValue2")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Could not deserialize into payment method value 2")?;
match (value1, value2) {
(VaultPaymentMethod::Card(mvalue1), VaultPaymentMethod::Card(mvalue2)) => {
let (card, supp_data) = domain::Card::from_values(mvalue1, mvalue2)?;
Ok((Self::Card(card), supp_data))
}
(VaultPaymentMethod::Wallet(mvalue1), VaultPaymentMethod::Wallet(mvalue2)) => {
let (wallet, supp_data) = domain::WalletData::from_values(mvalue1, mvalue2)?;
Ok((Self::Wallet(wallet), supp_data))
}
(
VaultPaymentMethod::BankTransfer(mvalue1),
VaultPaymentMethod::BankTransfer(mvalue2),
) => {
let (bank_transfer, supp_data) =
domain::BankTransferData::from_values(mvalue1, mvalue2)?;
Ok((Self::BankTransfer(Box::new(bank_transfer)), supp_data))
}
(
VaultPaymentMethod::BankRedirect(mvalue1),
VaultPaymentMethod::BankRedirect(mvalue2),
) => {
let (bank_redirect, supp_data) =
domain::BankRedirectData::from_values(mvalue1, mvalue2)?;
Ok((Self::BankRedirect(bank_redirect), supp_data))
}
(VaultPaymentMethod::BankDebit(mvalue1), VaultPaymentMethod::BankDebit(mvalue2)) => {
let (bank_debit, supp_data) = domain::BankDebitData::from_values(mvalue1, mvalue2)?;
Ok((Self::BankDebit(bank_debit), supp_data))
}
_ => Err(errors::VaultError::PaymentMethodNotSupported)
.attach_printable("Payment method not supported"),
}
}
}
#[cfg(feature = "payouts")]
impl Vaultable for api::CardPayout {
fn get_value1(
&self,
_customer_id: Option<id_type::CustomerId>,
) -> CustomResult<String, errors::VaultError> {
let value1 = api::TokenizedCardValue1 {
card_number: self.card_number.peek().clone(),
exp_year: self.expiry_year.peek().clone(),
exp_month: self.expiry_month.peek().clone(),
name_on_card: self.card_holder_name.clone().map(|n| n.peek().to_string()),
nickname: None,
card_last_four: None,
card_token: None,
};
value1
.encode_to_string_of_json()
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode card value1")
}
fn get_value2(
&self,
customer_id: Option<id_type::CustomerId>,
) -> CustomResult<String, errors::VaultError> {
let value2 = api::TokenizedCardValue2 {
card_security_code: None,
card_fingerprint: None,
external_id: None,
customer_id,
payment_method_id: None,
};
value2
.encode_to_string_of_json()
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode card value2")
}
fn from_values(
value1: String,
value2: String,
) -> CustomResult<(Self, SupplementaryVaultData), errors::VaultError> {
let value1: api::TokenizedCardValue1 = value1
.parse_struct("TokenizedCardValue1")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Could not deserialize into card value1")?;
let value2: api::TokenizedCardValue2 = value2
.parse_struct("TokenizedCardValue2")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Could not deserialize into card value2")?;
let card = Self {
card_number: value1
.card_number
.parse()
.map_err(|_| errors::VaultError::FetchCardFailed)?,
expiry_month: value1.exp_month.into(),
expiry_year: value1.exp_year.into(),
card_holder_name: value1.name_on_card.map(masking::Secret::new),
};
let supp_data = SupplementaryVaultData {
customer_id: value2.customer_id,
payment_method_id: value2.payment_method_id,
};
Ok((card, supp_data))
}
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct TokenizedWalletSensitiveValues {
pub email: Option<Email>,
pub telephone_number: Option<masking::Secret<String>>,
pub wallet_id: Option<masking::Secret<String>>,
pub wallet_type: PaymentMethodType,
pub dpan: Option<cards::CardNumber>,
pub expiry_month: Option<masking::Secret<String>>,
pub expiry_year: Option<masking::Secret<String>>,
pub card_holder_name: Option<masking::Secret<String>>,
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct TokenizedWalletInsensitiveValues {
pub customer_id: Option<id_type::CustomerId>,
}
#[cfg(feature = "payouts")]
impl Vaultable for api::WalletPayout {
fn get_value1(
&self,
_customer_id: Option<id_type::CustomerId>,
) -> CustomResult<String, errors::VaultError> {
let value1 = match self {
Self::Paypal(paypal_data) => TokenizedWalletSensitiveValues {
email: paypal_data.email.clone(),
telephone_number: paypal_data.telephone_number.clone(),
wallet_id: paypal_data.paypal_id.clone(),
wallet_type: PaymentMethodType::Paypal,
dpan: None,
expiry_month: None,
expiry_year: None,
card_holder_name: None,
},
Self::Venmo(venmo_data) => TokenizedWalletSensitiveValues {
email: None,
telephone_number: venmo_data.telephone_number.clone(),
wallet_id: None,
wallet_type: PaymentMethodType::Venmo,
dpan: None,
expiry_month: None,
expiry_year: None,
card_holder_name: None,
},
Self::ApplePayDecrypt(apple_pay_decrypt_data) => TokenizedWalletSensitiveValues {
email: None,
telephone_number: None,
wallet_id: None,
wallet_type: PaymentMethodType::ApplePay,
dpan: Some(apple_pay_decrypt_data.dpan.clone()),
expiry_month: Some(apple_pay_decrypt_data.expiry_month.clone()),
expiry_year: Some(apple_pay_decrypt_data.expiry_year.clone()),
card_holder_name: apple_pay_decrypt_data.card_holder_name.clone(),
},
};
value1
.encode_to_string_of_json()
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode wallet data - TokenizedWalletSensitiveValues")
}
fn get_value2(
&self,
customer_id: Option<id_type::CustomerId>,
) -> CustomResult<String, errors::VaultError> {
let value2 = TokenizedWalletInsensitiveValues { customer_id };
value2
.encode_to_string_of_json()
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode data - TokenizedWalletInsensitiveValues")
}
fn from_values(
value1: String,
value2: String,
) -> CustomResult<(Self, SupplementaryVaultData), errors::VaultError> {
let value1: TokenizedWalletSensitiveValues = value1
.parse_struct("TokenizedWalletSensitiveValues")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Could not deserialize into wallet data wallet_sensitive_data")?;
let value2: TokenizedWalletInsensitiveValues = value2
.parse_struct("TokenizedWalletInsensitiveValues")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Could not deserialize into wallet data wallet_insensitive_data")?;
let wallet = match value1.wallet_type {
PaymentMethodType::Paypal => Self::Paypal(api_models::payouts::Paypal {
email: value1.email,
telephone_number: value1.telephone_number,
paypal_id: value1.wallet_id,
}),
PaymentMethodType::Venmo => Self::Venmo(api_models::payouts::Venmo {
telephone_number: value1.telephone_number,
}),
PaymentMethodType::ApplePay => {
match (value1.dpan, value1.expiry_month, value1.expiry_year) {
(Some(dpan), Some(expiry_month), Some(expiry_year)) => {
Self::ApplePayDecrypt(api_models::payouts::ApplePayDecrypt {
dpan,
expiry_month,
expiry_year,
card_holder_name: value1.card_holder_name,
})
}
_ => Err(errors::VaultError::ResponseDeserializationFailed)?,
}
}
_ => Err(errors::VaultError::PayoutMethodNotSupported)?,
};
let supp_data = SupplementaryVaultData {
customer_id: value2.customer_id,
payment_method_id: None,
};
Ok((wallet, supp_data))
}
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct TokenizedBankSensitiveValues {
pub bank_account_number: Option<masking::Secret<String>>,
pub bank_routing_number: Option<masking::Secret<String>>,
pub bic: Option<masking::Secret<String>>,
pub bank_sort_code: Option<masking::Secret<String>>,
pub iban: Option<masking::Secret<String>>,
pub pix_key: Option<masking::Secret<String>>,
pub tax_id: Option<masking::Secret<String>>,
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct TokenizedBankInsensitiveValues {
pub customer_id: Option<id_type::CustomerId>,
pub bank_name: Option<String>,
pub bank_country_code: Option<api::enums::CountryAlpha2>,
pub bank_city: Option<String>,
pub bank_branch: Option<String>,
}
#[cfg(feature = "payouts")]
impl Vaultable for api::BankPayout {
fn get_value1(
&self,
_customer_id: Option<id_type::CustomerId>,
) -> CustomResult<String, errors::VaultError> {
let bank_sensitive_data = match self {
Self::Ach(b) => TokenizedBankSensitiveValues {
bank_account_number: Some(b.bank_account_number.clone()),
bank_routing_number: Some(b.bank_routing_number.to_owned()),
bic: None,
bank_sort_code: None,
iban: None,
pix_key: None,
tax_id: None,
},
Self::Bacs(b) => TokenizedBankSensitiveValues {
bank_account_number: Some(b.bank_account_number.to_owned()),
bank_routing_number: None,
bic: None,
bank_sort_code: Some(b.bank_sort_code.to_owned()),
iban: None,
pix_key: None,
tax_id: None,
},
Self::Sepa(b) => TokenizedBankSensitiveValues {
bank_account_number: None,
bank_routing_number: None,
bic: b.bic.to_owned(),
bank_sort_code: None,
iban: Some(b.iban.to_owned()),
pix_key: None,
tax_id: None,
},
Self::Pix(bank_details) => TokenizedBankSensitiveValues {
bank_account_number: Some(bank_details.bank_account_number.to_owned()),
bank_routing_number: None,
bic: None,
bank_sort_code: None,
iban: None,
pix_key: Some(bank_details.pix_key.to_owned()),
tax_id: bank_details.tax_id.to_owned(),
},
};
bank_sensitive_data
.encode_to_string_of_json()
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode data - bank_sensitive_data")
}
fn get_value2(
&self,
customer_id: Option<id_type::CustomerId>,
) -> CustomResult<String, errors::VaultError> {
let bank_insensitive_data = match self {
Self::Ach(b) => TokenizedBankInsensitiveValues {
customer_id,
bank_name: b.bank_name.to_owned(),
bank_country_code: b.bank_country_code.to_owned(),
bank_city: b.bank_city.to_owned(),
bank_branch: None,
},
Self::Bacs(b) => TokenizedBankInsensitiveValues {
customer_id,
bank_name: b.bank_name.to_owned(),
bank_country_code: b.bank_country_code.to_owned(),
bank_city: b.bank_city.to_owned(),
bank_branch: None,
},
Self::Sepa(bank_details) => TokenizedBankInsensitiveValues {
customer_id,
bank_name: bank_details.bank_name.to_owned(),
bank_country_code: bank_details.bank_country_code.to_owned(),
bank_city: bank_details.bank_city.to_owned(),
bank_branch: None,
},
Self::Pix(bank_details) => TokenizedBankInsensitiveValues {
customer_id,
bank_name: bank_details.bank_name.to_owned(),
bank_country_code: None,
bank_city: None,
bank_branch: bank_details.bank_branch.to_owned(),
},
};
bank_insensitive_data
.encode_to_string_of_json()
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode wallet data bank_insensitive_data")
}
fn from_values(
bank_sensitive_data: String,
bank_insensitive_data: String,
) -> CustomResult<(Self, SupplementaryVaultData), errors::VaultError> {
let bank_sensitive_data: TokenizedBankSensitiveValues = bank_sensitive_data
.parse_struct("TokenizedBankValue1")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Could not deserialize into bank data bank_sensitive_data")?;
let bank_insensitive_data: TokenizedBankInsensitiveValues = bank_insensitive_data
.parse_struct("TokenizedBankValue2")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Could not deserialize into wallet data bank_insensitive_data")?;
let bank = match (
// ACH + BACS + PIX
bank_sensitive_data.bank_account_number.to_owned(),
bank_sensitive_data.bank_routing_number.to_owned(), // ACH
bank_sensitive_data.bank_sort_code.to_owned(), // BACS
// SEPA
bank_sensitive_data.iban.to_owned(),
bank_sensitive_data.bic,
// PIX
bank_sensitive_data.pix_key,
bank_sensitive_data.tax_id,
) {
(Some(ban), Some(brn), None, None, None, None, None) => {
Self::Ach(payouts::AchBankTransfer {
bank_account_number: ban,
bank_routing_number: brn,
bank_name: bank_insensitive_data.bank_name,
bank_country_code: bank_insensitive_data.bank_country_code,
bank_city: bank_insensitive_data.bank_city,
})
}
(Some(ban), None, Some(bsc), None, None, None, None) => {
Self::Bacs(payouts::BacsBankTransfer {
bank_account_number: ban,
bank_sort_code: bsc,
bank_name: bank_insensitive_data.bank_name,
bank_country_code: bank_insensitive_data.bank_country_code,
bank_city: bank_insensitive_data.bank_city,
})
}
(None, None, None, Some(iban), bic, None, None) => {
Self::Sepa(payouts::SepaBankTransfer {
iban,
bic,
bank_name: bank_insensitive_data.bank_name,
bank_country_code: bank_insensitive_data.bank_country_code,
bank_city: bank_insensitive_data.bank_city,
})
}
(Some(ban), None, None, None, None, Some(pix_key), tax_id) => {
Self::Pix(payouts::PixBankTransfer {
bank_account_number: ban,
bank_branch: bank_insensitive_data.bank_branch,
bank_name: bank_insensitive_data.bank_name,
pix_key,
tax_id,
})
}
_ => Err(errors::VaultError::ResponseDeserializationFailed)?,
};
let supp_data = SupplementaryVaultData {
customer_id: bank_insensitive_data.customer_id,
payment_method_id: None,
};
Ok((bank, supp_data))
}
}
#[cfg(feature = "payouts")]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(tag = "type", content = "value", rename_all = "snake_case")]
pub enum VaultPayoutMethod {
Card(String),
Bank(String),
Wallet(String),
BankRedirect(String),
}
#[cfg(feature = "payouts")]
impl Vaultable for api::PayoutMethodData {
fn get_value1(
&self,
customer_id: Option<id_type::CustomerId>,
) -> CustomResult<String, errors::VaultError> {
let value1 = match self {
Self::Card(card) => VaultPayoutMethod::Card(card.get_value1(customer_id)?),
Self::Bank(bank) => VaultPayoutMethod::Bank(bank.get_value1(customer_id)?),
Self::Wallet(wallet) => VaultPayoutMethod::Wallet(wallet.get_value1(customer_id)?),
Self::BankRedirect(bank_redirect) => {
VaultPayoutMethod::BankRedirect(bank_redirect.get_value1(customer_id)?)
}
};
value1
.encode_to_string_of_json()
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode payout method value1")
}
fn get_value2(
&self,
customer_id: Option<id_type::CustomerId>,
) -> CustomResult<String, errors::VaultError> {
let value2 = match self {
Self::Card(card) => VaultPayoutMethod::Card(card.get_value2(customer_id)?),
Self::Bank(bank) => VaultPayoutMethod::Bank(bank.get_value2(customer_id)?),
Self::Wallet(wallet) => VaultPayoutMethod::Wallet(wallet.get_value2(customer_id)?),
Self::BankRedirect(bank_redirect) => {
VaultPayoutMethod::BankRedirect(bank_redirect.get_value2(customer_id)?)
}
};
value2
.encode_to_string_of_json()
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode payout method value2")
}
fn from_values(
value1: String,
value2: String,
) -> CustomResult<(Self, SupplementaryVaultData), errors::VaultError> {
let value1: VaultPayoutMethod = value1
.parse_struct("VaultMethodValue1")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Could not deserialize into vault method value 1")?;
let value2: VaultPayoutMethod = value2
.parse_struct("VaultMethodValue2")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Could not deserialize into vault method value 2")?;
match (value1, value2) {
(VaultPayoutMethod::Card(mvalue1), VaultPayoutMethod::Card(mvalue2)) => {
let (card, supp_data) = api::CardPayout::from_values(mvalue1, mvalue2)?;
Ok((Self::Card(card), supp_data))
}
(VaultPayoutMethod::Bank(mvalue1), VaultPayoutMethod::Bank(mvalue2)) => {
let (bank, supp_data) = api::BankPayout::from_values(mvalue1, mvalue2)?;
Ok((Self::Bank(bank), supp_data))
}
(VaultPayoutMethod::Wallet(mvalue1), VaultPayoutMethod::Wallet(mvalue2)) => {
let (wallet, supp_data) = api::WalletPayout::from_values(mvalue1, mvalue2)?;
Ok((Self::Wallet(wallet), supp_data))
}
(
VaultPayoutMethod::BankRedirect(mvalue1),
VaultPayoutMethod::BankRedirect(mvalue2),
) => {
let (bank_redirect, supp_data) =
api::BankRedirectPayout::from_values(mvalue1, mvalue2)?;
Ok((Self::BankRedirect(bank_redirect), supp_data))
}
_ => Err(errors::VaultError::PayoutMethodNotSupported)
.attach_printable("Payout method not supported"),
}
}
}
#[cfg(feature = "payouts")]
impl Vaultable for api::BankRedirectPayout {
fn get_value1(
&self,
_customer_id: Option<id_type::CustomerId>,
) -> CustomResult<String, errors::VaultError> {
let value1 = match self {
Self::Interac(interac_data) => TokenizedBankRedirectSensitiveValues {
email: interac_data.email.clone(),
bank_redirect_type: PaymentMethodType::Interac,
},
};
value1
.encode_to_string_of_json()
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable(
"Failed to encode bank redirect data - TokenizedBankRedirectSensitiveValues",
)
}
fn get_value2(
&self,
customer_id: Option<id_type::CustomerId>,
) -> CustomResult<String, errors::VaultError> {
let value2 = TokenizedBankRedirectInsensitiveValues { customer_id };
value2
.encode_to_string_of_json()
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode wallet data value2")
}
fn from_values(
value1: String,
value2: String,
) -> CustomResult<(Self, SupplementaryVaultData), errors::VaultError> {
let value1: TokenizedBankRedirectSensitiveValues = value1
.parse_struct("TokenizedBankRedirectSensitiveValues")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Could not deserialize into wallet data value1")?;
let value2: TokenizedBankRedirectInsensitiveValues = value2
.parse_struct("TokenizedBankRedirectInsensitiveValues")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Could not deserialize into wallet data value2")?;
let bank_redirect = match value1.bank_redirect_type {
PaymentMethodType::Interac => Self::Interac(api_models::payouts::Interac {
email: value1.email,
}),
_ => Err(errors::VaultError::PayoutMethodNotSupported)
.attach_printable("Payout method not supported")?,
};
let supp_data = SupplementaryVaultData {
customer_id: value2.customer_id,
payment_method_id: None,
};
Ok((bank_redirect, supp_data))
}
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct TokenizedBankRedirectSensitiveValues {
pub email: Email,
pub bank_redirect_type: PaymentMethodType,
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct TokenizedBankRedirectInsensitiveValues {
pub customer_id: Option<id_type::CustomerId>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct MockTokenizeDBValue {
pub value1: String,
pub value2: String,
}
pub struct Vault;
impl Vault {
#[instrument(skip_all)]
pub async fn get_payment_method_data_from_locker(
state: &routes::SessionState,
lookup_key: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> RouterResult<(Option<domain::PaymentMethodData>, SupplementaryVaultData)> {
let de_tokenize =
get_tokenized_data(state, lookup_key, true, merchant_key_store.key.get_inner()).await?;
let (payment_method, customer_id) =
domain::PaymentMethodData::from_values(de_tokenize.value1, de_tokenize.value2)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error parsing Payment Method from Values")?;
Ok((Some(payment_method), customer_id))
}
#[instrument(skip_all)]
pub async fn store_payment_method_data_in_locker(
state: &routes::SessionState,
token_id: Option<String>,
payment_method: &domain::PaymentMethodData,
customer_id: Option<id_type::CustomerId>,
pm: enums::PaymentMethod,
merchant_key_store: &domain::MerchantKeyStore,
) -> RouterResult<String> {
let value1 = payment_method
.get_value1(customer_id.clone())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error getting Value1 for locker")?;
let value2 = payment_method
.get_value2(customer_id)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error getting Value12 for locker")?;
let lookup_key = token_id.unwrap_or_else(|| generate_id_with_default_len("token"));
let lookup_key = create_tokenize(
state,
value1,
Some(value2),
lookup_key,
merchant_key_store.key.get_inner(),
)
.await?;
add_delete_tokenized_data_task(&*state.store, &lookup_key, pm).await?;
metrics::TOKENIZED_DATA_COUNT.add(1, &[]);
Ok(lookup_key)
}
#[cfg(feature = "payouts")]
#[instrument(skip_all)]
pub async fn get_payout_method_data_from_temporary_locker(
state: &routes::SessionState,
lookup_key: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> RouterResult<(Option<api::PayoutMethodData>, SupplementaryVaultData)> {
let de_tokenize =
get_tokenized_data(state, lookup_key, true, merchant_key_store.key.get_inner()).await?;
let (payout_method, supp_data) =
api::PayoutMethodData::from_values(de_tokenize.value1, de_tokenize.value2)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error parsing Payout Method from Values")?;
Ok((Some(payout_method), supp_data))
}
#[cfg(feature = "payouts")]
#[instrument(skip_all)]
pub async fn store_payout_method_data_in_locker(
state: &routes::SessionState,
token_id: Option<String>,
payout_method: &api::PayoutMethodData,
customer_id: Option<id_type::CustomerId>,
merchant_key_store: &domain::MerchantKeyStore,
) -> RouterResult<String> {
let value1 = payout_method
.get_value1(customer_id.clone())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error getting Value1 for locker")?;
let value2 = payout_method
.get_value2(customer_id)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error getting Value2 for locker")?;
let lookup_key =
token_id.unwrap_or_else(|| generate_id_with_default_len("temporary_token"));
let lookup_key = create_tokenize(
state,
value1,
Some(value2),
lookup_key,
merchant_key_store.key.get_inner(),
)
.await?;
// add_delete_tokenized_data_task(&*state.store, &lookup_key, pm).await?;
// scheduler_metrics::TOKENIZED_DATA_COUNT.add(1, &[]);
Ok(lookup_key)
}
#[instrument(skip_all)]
pub async fn delete_locker_payment_method_by_lookup_key(
state: &routes::SessionState,
lookup_key: &Option<String>,
) {
if let Some(lookup_key) = lookup_key {
delete_tokenized_data(state, lookup_key)
.await
.map(|_| logger::info!("Card From locker deleted Successfully"))
.map_err(|err| logger::error!("Error: Deleting Card From Redis Locker : {:?}", err))
.ok();
}
}
}
//------------------------------------------------TokenizeService------------------------------------------------
#[inline(always)]
fn get_redis_locker_key(lookup_key: &str) -> String {
format!("{}_{}", consts::LOCKER_REDIS_PREFIX, lookup_key)
}
#[instrument(skip(state, value1, value2))]
pub async fn create_tokenize(
state: &routes::SessionState,
value1: String,
value2: Option<String>,
lookup_key: String,
encryption_key: &masking::Secret<Vec<u8>>,
) -> RouterResult<String> {
let redis_key = get_redis_locker_key(lookup_key.as_str());
let func = || async {
metrics::CREATED_TOKENIZED_CARD.add(1, &[]);
let payload_to_be_encrypted = api::TokenizePayloadRequest {
value1: value1.clone(),
value2: value2.clone().unwrap_or_default(),
lookup_key: lookup_key.clone(),
service_name: VAULT_SERVICE_NAME.to_string(),
};
let payload = payload_to_be_encrypted
.encode_to_string_of_json()
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let encrypted_payload = GcmAes256
.encode_message(encryption_key.peek().as_ref(), payload.as_bytes())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to encode redis temp locker data")?;
let redis_conn = state
.store
.get_redis_conn()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get redis connection")?;
redis_conn
.set_key_if_not_exists_with_expiry(
&redis_key.as_str().into(),
bytes::Bytes::from(encrypted_payload),
Some(i64::from(consts::LOCKER_REDIS_EXPIRY_SECONDS)),
)
.await
.map(|_| lookup_key.clone())
.inspect_err(|error| {
metrics::TEMP_LOCKER_FAILURES.add(1, &[]);
logger::error!(?error, "Failed to store tokenized data in Redis");
})
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error from redis locker")
};
match func().await {
Ok(s) => {
logger::info!(
"Insert payload in redis locker successful with lookup key: {:?}",
redis_key
);
Ok(s)
}
Err(err) => {
logger::error!("Redis Temp locker Failed: {:?}", err);
Err(err)
}
}
}
#[instrument(skip(state))]
pub async fn get_tokenized_data(
state: &routes::SessionState,
lookup_key: &str,
_should_get_value2: bool,
encryption_key: &masking::Secret<Vec<u8>>,
) -> RouterResult<api::TokenizePayloadRequest> {
let redis_key = get_redis_locker_key(lookup_key);
let func = || async {
metrics::GET_TOKENIZED_CARD.add(1, &[]);
let redis_conn = state
.store
.get_redis_conn()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get redis connection")?;
let response = redis_conn
.get_key::<bytes::Bytes>(&redis_key.as_str().into())
.await;
match response {
Ok(resp) => {
let decrypted_payload = GcmAes256
.decode_message(
encryption_key.peek().as_ref(),
masking::Secret::new(resp.into()),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to decode redis temp locker data")?;
let get_response: api::TokenizePayloadRequest =
bytes::Bytes::from(decrypted_payload)
.parse_struct("TokenizePayloadRequest")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Error getting TokenizePayloadRequest from tokenize response",
)?;
Ok(get_response)
}
Err(err) => {
metrics::TEMP_LOCKER_FAILURES.add(1, &[]);
Err(err).change_context(errors::ApiErrorResponse::UnprocessableEntity {
message: "Token is invalid or expired".into(),
})
}
}
};
match func().await {
Ok(s) => {
logger::info!(
"Fetch payload in redis locker successful with lookup key: {:?}",
redis_key
);
Ok(s)
}
Err(err) => {
logger::error!("Redis Temp locker Failed: {:?}", err);
Err(err)
}
}
}
#[instrument(skip(state))]
pub async fn delete_tokenized_data(
state: &routes::SessionState,
lookup_key: &str,
) -> RouterResult<()> {
let redis_key = get_redis_locker_key(lookup_key);
let func = || async {
metrics::DELETED_TOKENIZED_CARD.add(1, &[]);
let redis_conn = state
.store
.get_redis_conn()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get redis connection")?;
let response = redis_conn.delete_key(&redis_key.as_str().into()).await;
match response {
Ok(redis_interface::DelReply::KeyDeleted) => Ok(()),
Ok(redis_interface::DelReply::KeyNotDeleted) => {
Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Token invalid or expired")
}
Err(err) => {
metrics::TEMP_LOCKER_FAILURES.add(1, &[]);
Err(errors::ApiErrorResponse::InternalServerError).attach_printable_lazy(|| {
format!("Failed to delete from redis locker: {err:?}")
})
}
}
};
match func().await {
Ok(s) => {
logger::info!(
"Delete payload in redis locker successful with lookup key: {:?}",
redis_key
);
Ok(s)
}
Err(err) => {
logger::error!("Redis Temp locker Failed: {:?}", err);
Err(err)
}
}
}
#[cfg(feature = "v2")]
async fn create_vault_request<R: pm_types::VaultingInterface>(
jwekey: &settings::Jwekey,
locker: &settings::Locker,
payload: Vec<u8>,
tenant_id: id_type::TenantId,
) -> CustomResult<request::Request, errors::VaultError> {
let private_key = jwekey.vault_private_key.peek().as_bytes();
let jws = services::encryption::jws_sign_payload(
&payload,
&locker.locker_signing_key_id,
private_key,
)
.await
.change_context(errors::VaultError::RequestEncryptionFailed)?;
let jwe_payload = pm_transforms::create_jwe_body_for_vault(jwekey, &jws).await?;
let mut url = locker.host.to_owned();
url.push_str(R::get_vaulting_request_url());
let mut request = request::Request::new(services::Method::Post, &url);
request.add_header(
headers::CONTENT_TYPE,
consts::VAULT_HEADER_CONTENT_TYPE.into(),
);
request.add_header(
headers::X_TENANT_ID,
tenant_id.get_string_repr().to_owned().into(),
);
request.set_body(request::RequestContent::Json(Box::new(jwe_payload)));
Ok(request)
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
pub async fn call_to_vault<V: pm_types::VaultingInterface>(
state: &routes::SessionState,
payload: Vec<u8>,
) -> CustomResult<String, errors::VaultError> {
let locker = &state.conf.locker;
let jwekey = state.conf.jwekey.get_inner();
let request =
create_vault_request::<V>(jwekey, locker, payload, state.tenant.tenant_id.to_owned())
.await?;
let response = services::call_connector_api(state, request, V::get_vaulting_flow_name())
.await
.change_context(errors::VaultError::VaultAPIError);
let jwe_body: services::JweBody = response
.get_response_inner("JweBody")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Failed to get JweBody from vault response")?;
let decrypted_payload = pm_transforms::get_decrypted_vault_response_payload(
jwekey,
jwe_body,
locker.decryption_scheme.clone(),
)
.await
.change_context(errors::VaultError::ResponseDecryptionFailed)
.attach_printable("Error getting decrypted vault response payload")?;
Ok(decrypted_payload)
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
pub async fn get_fingerprint_id_from_vault<D: domain::VaultingDataInterface + serde::Serialize>(
state: &routes::SessionState,
data: &D,
key: String,
) -> CustomResult<String, errors::VaultError> {
let data = serde_json::to_string(data)
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode Vaulting data to string")?;
let payload = pm_types::VaultFingerprintRequest { key, data }
.encode_to_vec()
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode VaultFingerprintRequest")?;
let resp = call_to_vault::<pm_types::GetVaultFingerprint>(state, payload)
.await
.change_context(errors::VaultError::VaultAPIError)
.attach_printable("Call to vault failed")?;
let fingerprint_resp: pm_types::VaultFingerprintResponse = resp
.parse_struct("VaultFingerprintResponse")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Failed to parse data into VaultFingerprintResponse")?;
Ok(fingerprint_resp.fingerprint_id)
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
pub async fn add_payment_method_to_vault(
state: &routes::SessionState,
merchant_context: &domain::MerchantContext,
pmd: &domain::PaymentMethodVaultingData,
existing_vault_id: Option<domain::VaultId>,
customer_id: &id_type::GlobalCustomerId,
) -> CustomResult<pm_types::AddVaultResponse, errors::VaultError> {
let payload = pm_types::AddVaultRequest {
entity_id: customer_id.to_owned(),
vault_id: existing_vault_id
.unwrap_or(domain::VaultId::generate(uuid::Uuid::now_v7().to_string())),
data: pmd,
ttl: state.conf.locker.ttl_for_storage_in_secs,
}
.encode_to_vec()
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode AddVaultRequest")?;
let resp = call_to_vault::<pm_types::AddVault>(state, payload)
.await
.change_context(errors::VaultError::VaultAPIError)
.attach_printable("Call to vault failed")?;
let stored_pm_resp: pm_types::AddVaultResponse = resp
.parse_struct("AddVaultResponse")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Failed to parse data into AddVaultResponse")?;
Ok(stored_pm_resp)
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
pub async fn retrieve_payment_method_from_vault_internal(
state: &routes::SessionState,
merchant_context: &domain::MerchantContext,
vault_id: &domain::VaultId,
customer_id: &id_type::GlobalCustomerId,
) -> CustomResult<pm_types::VaultRetrieveResponse, errors::VaultError> {
let payload = pm_types::VaultRetrieveRequest {
entity_id: customer_id.to_owned(),
vault_id: vault_id.to_owned(),
}
.encode_to_vec()
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode VaultRetrieveRequest")?;
let resp = call_to_vault::<pm_types::VaultRetrieve>(state, payload)
.await
.change_context(errors::VaultError::VaultAPIError)
.attach_printable("Call to vault failed")?;
let stored_pm_resp: pm_types::VaultRetrieveResponse = resp
.parse_struct("VaultRetrieveResponse")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Failed to parse data into VaultRetrieveResponse")?;
Ok(stored_pm_resp)
}
#[cfg(all(feature = "v2", feature = "tokenization_v2"))]
#[instrument(skip_all)]
pub async fn retrieve_value_from_vault(
state: &routes::SessionState,
request: pm_types::VaultRetrieveRequest,
) -> CustomResult<serde_json::value::Value, errors::VaultError> {
let payload = request
.encode_to_vec()
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode VaultRetrieveRequest")?;
let resp = call_to_vault::<pm_types::VaultRetrieve>(state, payload)
.await
.change_context(errors::VaultError::VaultAPIError)
.attach_printable("Call to vault failed")?;
let stored_resp: serde_json::Value = resp
.parse_struct("VaultRetrieveResponse")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Failed to parse data into VaultRetrieveResponse")?;
Ok(stored_resp)
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
pub async fn retrieve_payment_method_from_vault_external(
state: &routes::SessionState,
merchant_account: &domain::MerchantAccount,
pm: &domain::PaymentMethod,
merchant_connector_account: domain::MerchantConnectorAccountTypeDetails,
) -> RouterResult<pm_types::VaultRetrieveResponse> {
let connector_vault_id = pm
.locker_id
.clone()
.map(|id| id.get_string_repr().to_owned());
let merchant_connector_account = match &merchant_connector_account {
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 router_data = core_utils::construct_vault_router_data(
state,
merchant_account.get_id(),
merchant_connector_account,
None,
connector_vault_id,
None,
)
.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 retrieve api call",
)?;
let connector_name = merchant_connector_account.get_connector_name_as_string(); // always get the connector name from this call
let connector_data = api::ConnectorData::get_external_vault_connector_by_name(
&state.conf.connectors,
connector_name,
api::GetToken::Connector,
Some(merchant_connector_account.get_id()),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get the connector data")?;
let connector_integration: services::BoxedVaultConnectorIntegrationInterface<
ExternalVaultRetrieveFlow,
types::VaultRequestData,
types::VaultResponseData,
> = connector_data.connector.get_connector_integration();
let router_data_resp = services::execute_connector_processing_step(
state,
connector_integration,
&old_router_data,
payments_core::CallConnectorAction::Trigger,
None,
None,
)
.await
.to_vault_failed_response()?;
get_vault_response_for_retrieve_payment_method_data::<ExternalVaultRetrieveFlow>(
router_data_resp,
)
}
#[cfg(feature = "v2")]
pub fn get_vault_response_for_retrieve_payment_method_data<F>(
router_data: VaultRouterData<F>,
) -> RouterResult<pm_types::VaultRetrieveResponse> {
match router_data.response {
Ok(response) => match response {
types::VaultResponseData::ExternalVaultRetrieveResponse { vault_data } => {
Ok(pm_types::VaultRetrieveResponse { data: vault_data })
}
types::VaultResponseData::ExternalVaultInsertResponse { .. }
| types::VaultResponseData::ExternalVaultDeleteResponse { .. }
| types::VaultResponseData::ExternalVaultCreateResponse { .. } => {
Err(report!(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Invalid Vault Response"))
}
},
Err(err) => Err(report!(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to retrieve payment method")),
}
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
pub async fn retrieve_payment_method_from_vault_using_payment_token(
state: &routes::SessionState,
merchant_context: &domain::MerchantContext,
profile: &domain::Profile,
payment_token: &String,
payment_method_type: &common_enums::PaymentMethod,
) -> RouterResult<(domain::PaymentMethod, domain::PaymentMethodVaultingData)> {
let pm_token_data = utils::retrieve_payment_token_data(
state,
payment_token.to_string(),
Some(payment_method_type),
)
.await?;
let payment_method_id = match pm_token_data {
storage::PaymentTokenData::PermanentCard(card_token_data) => {
card_token_data.payment_method_id
}
storage::PaymentTokenData::TemporaryGeneric(_) => {
Err(errors::ApiErrorResponse::NotImplemented {
message: errors::NotImplementedMessage::Reason(
"TemporaryGeneric Token not implemented".to_string(),
),
})?
}
storage::PaymentTokenData::AuthBankDebit(_) => {
Err(errors::ApiErrorResponse::NotImplemented {
message: errors::NotImplementedMessage::Reason(
"AuthBankDebit Token not implemented".to_string(),
),
})?
}
};
let db = &*state.store;
let key_manager_state = &state.into();
let storage_scheme = merchant_context.get_merchant_account().storage_scheme;
let payment_method = db
.find_payment_method(
key_manager_state,
merchant_context.get_merchant_key_store(),
&payment_method_id,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
let vault_data =
retrieve_payment_method_from_vault(state, merchant_context, profile, &payment_method)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to retrieve payment method from vault")?
.data;
Ok((payment_method, vault_data))
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct TemporaryVaultCvc {
card_cvc: masking::Secret<String>,
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
pub async fn insert_cvc_using_payment_token(
state: &routes::SessionState,
payment_token: &String,
payment_method_data: api_models::payment_methods::PaymentMethodCreateData,
payment_method: common_enums::PaymentMethod,
fulfillment_time: i64,
encryption_key: &masking::Secret<Vec<u8>>,
) -> RouterResult<()> {
let card_cvc = domain::PaymentMethodVaultingData::try_from(payment_method_data)?
.get_card()
.and_then(|card| card.card_cvc.clone());
if let Some(card_cvc) = card_cvc {
let redis_conn = state
.store
.get_redis_conn()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get redis connection")?;
let key = format!("pm_token_{payment_token}_{payment_method}_hyperswitch_cvc");
let payload_to_be_encrypted = TemporaryVaultCvc { card_cvc };
let payload = payload_to_be_encrypted
.encode_to_string_of_json()
.change_context(errors::ApiErrorResponse::InternalServerError)?;
// Encrypt the CVC and store it in Redis
let encrypted_payload = GcmAes256
.encode_message(encryption_key.peek().as_ref(), payload.as_bytes())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to encode TemporaryVaultCvc for vault")?;
redis_conn
.set_key_if_not_exists_with_expiry(
&key.as_str().into(),
bytes::Bytes::from(encrypted_payload),
Some(fulfillment_time),
)
.await
.change_context(errors::StorageError::KVError)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to add token in redis")?;
};
Ok(())
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
pub async fn retrieve_and_delete_cvc_from_payment_token(
state: &routes::SessionState,
payment_token: &String,
payment_method: common_enums::PaymentMethod,
encryption_key: &masking::Secret<Vec<u8>>,
) -> RouterResult<masking::Secret<String>> {
let redis_conn = state
.store
.get_redis_conn()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get redis connection")?;
let key = format!("pm_token_{payment_token}_{payment_method}_hyperswitch_cvc",);
let data = redis_conn
.get_key::<bytes::Bytes>(&key.clone().into())
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to fetch the token from redis")?;
// decrypt the cvc data
let decrypted_payload = GcmAes256
.decode_message(
encryption_key.peek().as_ref(),
masking::Secret::new(data.into()),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to decode TemporaryVaultCvc from vault")?;
let cvc_data: TemporaryVaultCvc = bytes::Bytes::from(decrypted_payload)
.parse_struct("TemporaryVaultCvc")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to deserialize TemporaryVaultCvc")?;
// delete key after retrieving the cvc
redis_conn.delete_key(&key.into()).await.map_err(|err| {
logger::error!("Failed to delete token from redis: {:?}", err);
});
Ok(cvc_data.card_cvc)
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
pub async fn delete_payment_token(
state: &routes::SessionState,
key_for_token: &str,
intent_status: enums::IntentStatus,
) -> RouterResult<()> {
if ![
enums::IntentStatus::RequiresCustomerAction,
enums::IntentStatus::RequiresMerchantAction,
]
.contains(&intent_status)
{
utils::delete_payment_token_data(state, key_for_token)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to delete payment_token")?;
}
Ok(())
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
pub async fn retrieve_payment_method_from_vault(
state: &routes::SessionState,
merchant_context: &domain::MerchantContext,
profile: &domain::Profile,
pm: &domain::PaymentMethod,
) -> RouterResult<pm_types::VaultRetrieveResponse> {
let is_external_vault_enabled = profile.is_external_vault_enabled();
match is_external_vault_enabled {
true => {
let external_vault_source = pm.external_vault_source.as_ref();
let merchant_connector_account =
domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(Box::new(
payments_core::helpers::get_merchant_connector_account_v2(
state,
merchant_context.get_merchant_key_store(),
external_vault_source,
)
.await
.attach_printable(
"failed to fetch merchant connector account for external vault retrieve",
)?,
));
retrieve_payment_method_from_vault_external(
state,
merchant_context.get_merchant_account(),
pm,
merchant_connector_account,
)
.await
}
false => {
let vault_id = pm
.locker_id
.clone()
.ok_or(errors::VaultError::MissingRequiredField {
field_name: "locker_id",
})
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Missing locker_id for VaultRetrieveRequest")?;
retrieve_payment_method_from_vault_internal(
state,
merchant_context,
&vault_id,
&pm.customer_id,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to retrieve payment method from vault")
}
}
}
#[cfg(feature = "v2")]
pub async fn delete_payment_method_data_from_vault_internal(
state: &routes::SessionState,
merchant_context: &domain::MerchantContext,
vault_id: domain::VaultId,
customer_id: &id_type::GlobalCustomerId,
) -> CustomResult<pm_types::VaultDeleteResponse, errors::VaultError> {
let payload = pm_types::VaultDeleteRequest {
entity_id: customer_id.to_owned(),
vault_id,
}
.encode_to_vec()
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode VaultDeleteRequest")?;
let resp = call_to_vault::<pm_types::VaultDelete>(state, payload)
.await
.change_context(errors::VaultError::VaultAPIError)
.attach_printable("Call to vault failed")?;
let stored_pm_resp: pm_types::VaultDeleteResponse = resp
.parse_struct("VaultDeleteResponse")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Failed to parse data into VaultDeleteResponse")?;
Ok(stored_pm_resp)
}
#[cfg(feature = "v2")]
pub async fn delete_payment_method_data_from_vault_external(
state: &routes::SessionState,
merchant_account: &domain::MerchantAccount,
merchant_connector_account: domain::MerchantConnectorAccountTypeDetails,
vault_id: domain::VaultId,
customer_id: &id_type::GlobalCustomerId,
) -> RouterResult<pm_types::VaultDeleteResponse> {
let connector_vault_id = vault_id.get_string_repr().to_owned();
// Extract MerchantConnectorAccount from the enum
let merchant_connector_account = match &merchant_connector_account {
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 router_data = core_utils::construct_vault_router_data(
state,
merchant_account.get_id(),
merchant_connector_account,
None,
Some(connector_vault_id),
None,
)
.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 delete api call",
)?;
let connector_name = merchant_connector_account.get_connector_name_as_string(); // always get the connector name from this call
let connector_data = api::ConnectorData::get_external_vault_connector_by_name(
&state.conf.connectors,
connector_name,
api::GetToken::Connector,
Some(merchant_connector_account.get_id()),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get the connector data")?;
let connector_integration: services::BoxedVaultConnectorIntegrationInterface<
ExternalVaultDeleteFlow,
types::VaultRequestData,
types::VaultResponseData,
> = connector_data.connector.get_connector_integration();
let router_data_resp = services::execute_connector_processing_step(
state,
connector_integration,
&old_router_data,
payments_core::CallConnectorAction::Trigger,
None,
None,
)
.await
.to_vault_failed_response()?;
get_vault_response_for_delete_payment_method_data::<ExternalVaultDeleteFlow>(
router_data_resp,
customer_id.to_owned(),
)
}
#[cfg(feature = "v2")]
pub fn get_vault_response_for_delete_payment_method_data<F>(
router_data: VaultRouterData<F>,
customer_id: id_type::GlobalCustomerId,
) -> RouterResult<pm_types::VaultDeleteResponse> {
match router_data.response {
Ok(response) => match response {
types::VaultResponseData::ExternalVaultDeleteResponse { connector_vault_id } => {
Ok(pm_types::VaultDeleteResponse {
vault_id: domain::VaultId::generate(connector_vault_id), // converted to VaultId type
entity_id: customer_id,
})
}
types::VaultResponseData::ExternalVaultInsertResponse { .. }
| types::VaultResponseData::ExternalVaultRetrieveResponse { .. }
| types::VaultResponseData::ExternalVaultCreateResponse { .. } => {
Err(report!(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Invalid Vault Response"))
}
},
Err(err) => Err(report!(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to retrieve payment method")),
}
}
#[cfg(feature = "v2")]
pub async fn delete_payment_method_data_from_vault(
state: &routes::SessionState,
merchant_context: &domain::MerchantContext,
profile: &domain::Profile,
pm: &domain::PaymentMethod,
) -> RouterResult<pm_types::VaultDeleteResponse> {
let is_external_vault_enabled = profile.is_external_vault_enabled();
let vault_id = pm
.locker_id
.clone()
.get_required_value("locker_id")
.attach_printable("Missing locker_id in PaymentMethod")?;
match is_external_vault_enabled {
true => {
let external_vault_source = pm.external_vault_source.as_ref();
let merchant_connector_account =
domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(Box::new(
payments_core::helpers::get_merchant_connector_account_v2(
state,
merchant_context.get_merchant_key_store(),
external_vault_source,
)
.await
.attach_printable(
"failed to fetch merchant connector account for external vault delete",
)?,
));
delete_payment_method_data_from_vault_external(
state,
merchant_context.get_merchant_account(),
merchant_connector_account,
vault_id.clone(),
&pm.customer_id,
)
.await
}
false => delete_payment_method_data_from_vault_internal(
state,
merchant_context,
vault_id,
&pm.customer_id,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to delete payment method from vault"),
}
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
pub async fn retrieve_payment_method_from_vault_external_v1(
state: &routes::SessionState,
merchant_id: &id_type::MerchantId,
pm: &domain::PaymentMethod,
merchant_connector_account: hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount,
) -> RouterResult<hyperswitch_domain_models::vault::PaymentMethodVaultingData> {
let connector_vault_id = pm.locker_id.clone().map(|id| id.to_string());
let router_data = core_utils::construct_vault_router_data(
state,
merchant_id,
&merchant_connector_account,
None,
connector_vault_id,
None,
)
.await?;
let 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 retrieve api call",
)?;
let connector_name = merchant_connector_account.get_connector_name_as_string();
let connector_data = api::ConnectorData::get_external_vault_connector_by_name(
&state.conf.connectors,
connector_name,
api::GetToken::Connector,
Some(merchant_connector_account.get_id()),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get the connector data")?;
let connector_integration: services::BoxedVaultConnectorIntegrationInterface<
hyperswitch_domain_models::router_flow_types::ExternalVaultRetrieveFlow,
types::VaultRequestData,
types::VaultResponseData,
> = connector_data.connector.get_connector_integration();
let router_data_resp = services::execute_connector_processing_step(
state,
connector_integration,
&old_router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.to_vault_failed_response()?;
get_vault_response_for_retrieve_payment_method_data_v1(router_data_resp)
}
pub fn get_vault_response_for_retrieve_payment_method_data_v1<F>(
router_data: VaultRouterData<F>,
) -> RouterResult<hyperswitch_domain_models::vault::PaymentMethodVaultingData> {
match router_data.response {
Ok(response) => match response {
types::VaultResponseData::ExternalVaultRetrieveResponse { vault_data } => {
Ok(vault_data)
}
types::VaultResponseData::ExternalVaultInsertResponse { .. }
| types::VaultResponseData::ExternalVaultDeleteResponse { .. }
| types::VaultResponseData::ExternalVaultCreateResponse { .. } => {
Err(report!(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Invalid Vault Response"))
}
},
Err(err) => {
logger::error!(
"Failed to retrieve payment method from external vault: {:?}",
err
);
Err(report!(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to retrieve payment method from external vault"))
}
}
}
// ********************************************** PROCESS TRACKER **********************************************
pub async fn add_delete_tokenized_data_task(
db: &dyn db::StorageInterface,
lookup_key: &str,
pm: enums::PaymentMethod,
) -> RouterResult<()> {
let runner = storage::ProcessTrackerRunner::DeleteTokenizeDataWorkflow;
let process_tracker_id = format!("{runner}_{lookup_key}");
let task = runner.to_string();
let tag = ["BASILISK-V3"];
let tracking_data = storage::TokenizeCoreWorkflow {
lookup_key: lookup_key.to_owned(),
pm,
};
let schedule_time = get_delete_tokenize_schedule_time(db, pm, 0)
.await
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to obtain initial process tracker schedule time")?;
let process_tracker_entry = storage::ProcessTrackerNew::new(
process_tracker_id,
&task,
runner,
tag,
tracking_data,
None,
schedule_time,
common_types::consts::API_VERSION,
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to construct delete tokenized data process tracker task")?;
let response = db.insert_process(process_tracker_entry).await;
response.map(|_| ()).or_else(|err| {
if err.current_context().is_db_unique_violation() {
Ok(())
} else {
Err(report!(errors::ApiErrorResponse::InternalServerError))
}
})
}
pub async fn start_tokenize_data_workflow(
state: &routes::SessionState,
tokenize_tracker: &storage::ProcessTracker,
) -> Result<(), errors::ProcessTrackerError> {
let db = &*state.store;
let delete_tokenize_data = serde_json::from_value::<storage::TokenizeCoreWorkflow>(
tokenize_tracker.tracking_data.clone(),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| {
format!(
"unable to convert into DeleteTokenizeByTokenRequest {:?}",
tokenize_tracker.tracking_data
)
})?;
match delete_tokenized_data(state, &delete_tokenize_data.lookup_key).await {
Ok(()) => {
logger::info!("Card From locker deleted Successfully");
//mark task as finished
db.as_scheduler()
.finish_process_with_business_status(
tokenize_tracker.clone(),
diesel_models::process_tracker::business_status::COMPLETED_BY_PT,
)
.await?;
}
Err(err) => {
logger::error!("Err: Deleting Card From Locker : {:?}", err);
retry_delete_tokenize(db, delete_tokenize_data.pm, tokenize_tracker.to_owned()).await?;
metrics::RETRIED_DELETE_DATA_COUNT.add(1, &[]);
}
}
Ok(())
}
pub async fn get_delete_tokenize_schedule_time(
db: &dyn db::StorageInterface,
pm: enums::PaymentMethod,
retry_count: i32,
) -> Option<time::PrimitiveDateTime> {
let redis_mapping = db::get_and_deserialize_key(
db,
&format!("pt_mapping_delete_{pm}_tokenize_data"),
"PaymentMethodsPTMapping",
)
.await;
let mapping = match redis_mapping {
Ok(x) => x,
Err(error) => {
logger::info!(?error, "Redis Mapping Error");
process_data::PaymentMethodsPTMapping::default()
}
};
let time_delta = process_tracker_utils::get_pm_schedule_time(mapping, pm, retry_count + 1);
process_tracker_utils::get_time_from_delta(time_delta)
}
pub async fn retry_delete_tokenize(
db: &dyn db::StorageInterface,
pm: enums::PaymentMethod,
pt: storage::ProcessTracker,
) -> Result<(), errors::ProcessTrackerError> {
let schedule_time = get_delete_tokenize_schedule_time(db, pm, pt.retry_count).await;
match schedule_time {
Some(s_time) => {
let retry_schedule = db
.as_scheduler()
.retry_process(pt, s_time)
.await
.map_err(Into::into);
metrics::TASKS_RESET_COUNT.add(
1,
router_env::metric_attributes!(("flow", "DeleteTokenizeData")),
);
retry_schedule
}
None => db
.as_scheduler()
.finish_process_with_business_status(
pt,
diesel_models::process_tracker::business_status::RETRIES_EXCEEDED,
)
.await
.map_err(Into::into),
}
}
// Fallback logic of old temp locker needs to be removed later
|
crates/router/src/core/payment_methods/vault.rs
|
router::src::core::payment_methods::vault
| 17,846
| true
|
// File: crates/router/src/core/payment_methods/utils.rs
// Module: router::src::core::payment_methods::utils
use std::{str::FromStr, sync::Arc};
use api_models::{
admin::{self, PaymentMethodsEnabled},
enums as api_enums,
payment_methods::RequestPaymentMethodTypes,
};
use common_enums::enums;
#[cfg(feature = "v2")]
use common_utils::ext_traits::{OptionExt, StringExt};
#[cfg(feature = "v2")]
use error_stack::ResultExt;
use euclid::frontend::dir;
use hyperswitch_constraint_graph as cgraph;
use kgraph_utils::{error::KgraphError, transformers::IntoDirValue};
use masking::ExposeInterface;
use storage_impl::redis::cache::{CacheKey, PM_FILTERS_CGRAPH_CACHE};
use crate::{configs::settings, routes::SessionState};
#[cfg(feature = "v2")]
use crate::{
db::{
errors,
storage::{self, enums as storage_enums},
},
services::logger,
};
pub fn make_pm_graph(
builder: &mut cgraph::ConstraintGraphBuilder<dir::DirValue>,
domain_id: cgraph::DomainId,
payment_methods: &[masking::Secret<serde_json::value::Value>],
connector: String,
pm_config_mapping: &settings::ConnectorFilters,
supported_payment_methods_for_mandate: &settings::SupportedPaymentMethodsForMandate,
supported_payment_methods_for_update_mandate: &settings::SupportedPaymentMethodsForMandate,
) -> Result<(), KgraphError> {
for payment_method in payment_methods.iter() {
let pm_enabled =
serde_json::from_value::<PaymentMethodsEnabled>(payment_method.clone().expose());
if let Ok(payment_methods_enabled) = pm_enabled {
compile_pm_graph(
builder,
domain_id,
payment_methods_enabled.clone(),
connector.clone(),
pm_config_mapping,
supported_payment_methods_for_mandate,
supported_payment_methods_for_update_mandate,
)?;
};
}
Ok(())
}
pub async fn get_merchant_pm_filter_graph(
state: &SessionState,
key: &str,
) -> Option<Arc<hyperswitch_constraint_graph::ConstraintGraph<dir::DirValue>>> {
PM_FILTERS_CGRAPH_CACHE
.get_val::<Arc<hyperswitch_constraint_graph::ConstraintGraph<dir::DirValue>>>(CacheKey {
key: key.to_string(),
prefix: state.tenant.redis_key_prefix.clone(),
})
.await
}
pub async fn refresh_pm_filters_cache(
state: &SessionState,
key: &str,
graph: cgraph::ConstraintGraph<dir::DirValue>,
) -> Arc<hyperswitch_constraint_graph::ConstraintGraph<dir::DirValue>> {
let pm_filter_graph = Arc::new(graph);
PM_FILTERS_CGRAPH_CACHE
.push(
CacheKey {
key: key.to_string(),
prefix: state.tenant.redis_key_prefix.clone(),
},
pm_filter_graph.clone(),
)
.await;
pm_filter_graph
}
fn compile_pm_graph(
builder: &mut cgraph::ConstraintGraphBuilder<dir::DirValue>,
domain_id: cgraph::DomainId,
pm_enabled: PaymentMethodsEnabled,
connector: String,
config: &settings::ConnectorFilters,
supported_payment_methods_for_mandate: &settings::SupportedPaymentMethodsForMandate,
supported_payment_methods_for_update_mandate: &settings::SupportedPaymentMethodsForMandate,
) -> Result<(), KgraphError> {
if let Some(payment_method_types) = pm_enabled.payment_method_types {
for pmt in payment_method_types {
let mut agg_nodes: Vec<(cgraph::NodeId, cgraph::Relation, cgraph::Strength)> =
Vec::new();
let mut agg_or_nodes_for_mandate_filters: Vec<(
cgraph::NodeId,
cgraph::Relation,
cgraph::Strength,
)> = Vec::new();
// Connector supported for Update mandate filter
let res = construct_supported_connectors_for_update_mandate_node(
builder,
domain_id,
supported_payment_methods_for_update_mandate,
pmt.clone(),
pm_enabled.payment_method,
);
if let Ok(Some(connector_eligible_for_update_mandates_node)) = res {
agg_or_nodes_for_mandate_filters.push((
connector_eligible_for_update_mandates_node,
cgraph::Relation::Positive,
cgraph::Strength::Strong,
))
}
// Connector supported for mandates filter
if let Some(supported_pm_for_mandates) = supported_payment_methods_for_mandate
.0
.get(&pm_enabled.payment_method)
{
if let Some(supported_connector_for_mandates) =
supported_pm_for_mandates.0.get(&pmt.payment_method_type)
{
let supported_connectors: Vec<api_enums::Connector> =
supported_connector_for_mandates
.connector_list
.clone()
.into_iter()
.collect();
if let Ok(Some(connector_eligible_for_mandates_node)) =
construct_supported_connectors_for_mandate_node(
builder,
domain_id,
supported_connectors,
)
{
agg_or_nodes_for_mandate_filters.push((
connector_eligible_for_mandates_node,
cgraph::Relation::Positive,
cgraph::Strength::Strong,
))
}
}
}
// Non Prominent Mandate flows
let payment_type_non_mandate_value_node = builder.make_value_node(
cgraph::NodeValue::Value(dir::DirValue::PaymentType(
euclid::enums::PaymentType::NonMandate,
)),
None,
None::<()>,
);
let payment_type_setup_mandate_value_node = builder.make_value_node(
cgraph::NodeValue::Value(dir::DirValue::PaymentType(
euclid::enums::PaymentType::SetupMandate,
)),
None,
None::<()>,
);
let non_major_mandate_any_node = builder
.make_any_aggregator(
&[
(
payment_type_non_mandate_value_node,
cgraph::Relation::Positive,
cgraph::Strength::Strong,
),
(
payment_type_setup_mandate_value_node,
cgraph::Relation::Positive,
cgraph::Strength::Strong,
),
],
None,
None::<()>,
Some(domain_id),
)
.map_err(KgraphError::GraphConstructionError)?;
agg_or_nodes_for_mandate_filters.push((
non_major_mandate_any_node,
cgraph::Relation::Positive,
cgraph::Strength::Strong,
));
let agg_or_node = builder
.make_any_aggregator(
&agg_or_nodes_for_mandate_filters,
None,
None::<()>,
Some(domain_id),
)
.map_err(KgraphError::GraphConstructionError)?;
agg_nodes.push((
agg_or_node,
cgraph::Relation::Positive,
cgraph::Strength::Strong,
));
// Capture Method filter
config
.0
.get(connector.as_str())
.or_else(|| config.0.get("default"))
.map(|inner| {
if let Ok(Some(capture_method_filter)) =
construct_capture_method_node(builder, inner, pmt.payment_method_type)
{
agg_nodes.push((
capture_method_filter,
cgraph::Relation::Negative,
cgraph::Strength::Strong,
))
}
});
// Country filter
if let Ok(Some(country_node)) = compile_accepted_countries_for_mca(
builder,
domain_id,
pmt.payment_method_type,
pmt.accepted_countries,
config,
connector.clone(),
) {
agg_nodes.push((
country_node,
cgraph::Relation::Positive,
cgraph::Strength::Strong,
))
}
// Currency filter
if let Ok(Some(currency_node)) = compile_accepted_currency_for_mca(
builder,
domain_id,
pmt.payment_method_type,
pmt.accepted_currencies,
config,
connector.clone(),
) {
agg_nodes.push((
currency_node,
cgraph::Relation::Positive,
cgraph::Strength::Strong,
))
}
let and_node_for_all_the_filters = builder
.make_all_aggregator(&agg_nodes, None, None::<()>, Some(domain_id))
.map_err(KgraphError::GraphConstructionError)?;
// Making our output node
let pmt_info = "PaymentMethodType";
let dir_node: cgraph::NodeValue<dir::DirValue> =
(pmt.payment_method_type, pm_enabled.payment_method)
.into_dir_value()
.map(Into::into)?;
let payment_method_type_value_node =
builder.make_value_node(dir_node, Some(pmt_info), None::<()>);
builder
.make_edge(
and_node_for_all_the_filters,
payment_method_type_value_node,
cgraph::Strength::Normal,
cgraph::Relation::Positive,
Some(domain_id),
)
.map_err(KgraphError::GraphConstructionError)?;
}
}
Ok(())
}
fn construct_supported_connectors_for_update_mandate_node(
builder: &mut cgraph::ConstraintGraphBuilder<dir::DirValue>,
domain_id: cgraph::DomainId,
supported_payment_methods_for_update_mandate: &settings::SupportedPaymentMethodsForMandate,
pmt: RequestPaymentMethodTypes,
payment_method: enums::PaymentMethod,
) -> Result<Option<cgraph::NodeId>, KgraphError> {
let card_value_node = builder.make_value_node(
cgraph::NodeValue::Value(dir::DirValue::PaymentMethod(enums::PaymentMethod::Card)),
None,
None::<()>,
);
let payment_type_value_node = builder.make_value_node(
cgraph::NodeValue::Value(dir::DirValue::PaymentType(
euclid::enums::PaymentType::UpdateMandate,
)),
None,
None::<()>,
);
let mut agg_nodes: Vec<(cgraph::NodeId, cgraph::Relation, cgraph::Strength)> = Vec::new();
let mut card_dir_values = Vec::new();
let mut non_card_dir_values = Vec::new();
if let Some(supported_pm_for_mandates) = supported_payment_methods_for_update_mandate
.0
.get(&payment_method)
{
if payment_method == enums::PaymentMethod::Card {
if let Some(credit_connector_list) = supported_pm_for_mandates
.0
.get(&api_enums::PaymentMethodType::Credit)
{
card_dir_values.extend(
credit_connector_list
.connector_list
.clone()
.into_iter()
.filter_map(|connector| {
api_enums::RoutableConnectors::from_str(connector.to_string().as_str())
.ok()
.map(|connector| {
dir::DirValue::Connector(Box::new(
api_models::routing::ast::ConnectorChoice { connector },
))
})
}),
);
}
if let Some(debit_connector_list) = supported_pm_for_mandates
.0
.get(&api_enums::PaymentMethodType::Debit)
{
card_dir_values.extend(
debit_connector_list
.connector_list
.clone()
.into_iter()
.filter_map(|connector| {
api_enums::RoutableConnectors::from_str(connector.to_string().as_str())
.ok()
.map(|connector| {
dir::DirValue::Connector(Box::new(
api_models::routing::ast::ConnectorChoice { connector },
))
})
}),
);
}
let card_in_node = builder
.make_in_aggregator(card_dir_values, None, None::<()>)
.map_err(KgraphError::GraphConstructionError)?;
let card_and_node = builder
.make_all_aggregator(
&[
(
card_value_node,
cgraph::Relation::Positive,
cgraph::Strength::Strong,
),
(
payment_type_value_node,
cgraph::Relation::Positive,
cgraph::Strength::Strong,
),
(
card_in_node,
cgraph::Relation::Positive,
cgraph::Strength::Strong,
),
],
None,
None::<()>,
Some(domain_id),
)
.map_err(KgraphError::GraphConstructionError)?;
agg_nodes.push((
card_and_node,
cgraph::Relation::Positive,
cgraph::Strength::Strong,
));
} else if let Some(connector_list) =
supported_pm_for_mandates.0.get(&pmt.payment_method_type)
{
non_card_dir_values.extend(
connector_list
.connector_list
.clone()
.into_iter()
.filter_map(|connector| {
api_enums::RoutableConnectors::from_str(connector.to_string().as_str())
.ok()
.map(|connector| {
dir::DirValue::Connector(Box::new(
api_models::routing::ast::ConnectorChoice { connector },
))
})
}),
);
let non_card_mandate_in_node = builder
.make_in_aggregator(non_card_dir_values, None, None::<()>)
.map_err(KgraphError::GraphConstructionError)?;
let non_card_and_node = builder
.make_all_aggregator(
&[
(
card_value_node,
cgraph::Relation::Negative,
cgraph::Strength::Strong,
),
(
payment_type_value_node,
cgraph::Relation::Positive,
cgraph::Strength::Strong,
),
(
non_card_mandate_in_node,
cgraph::Relation::Positive,
cgraph::Strength::Strong,
),
],
None,
None::<()>,
Some(domain_id),
)
.map_err(KgraphError::GraphConstructionError)?;
agg_nodes.push((
non_card_and_node,
cgraph::Relation::Positive,
cgraph::Strength::Strong,
));
}
}
if !agg_nodes.is_empty() {
Ok(Some(
builder
.make_any_aggregator(
&agg_nodes,
Some("any node for card and non card pm"),
None::<()>,
Some(domain_id),
)
.map_err(KgraphError::GraphConstructionError)?,
))
} else {
Ok(None)
}
}
fn construct_supported_connectors_for_mandate_node(
builder: &mut cgraph::ConstraintGraphBuilder<dir::DirValue>,
domain_id: cgraph::DomainId,
eligible_connectors: Vec<api_enums::Connector>,
) -> Result<Option<cgraph::NodeId>, KgraphError> {
let payment_type_value_node = builder.make_value_node(
cgraph::NodeValue::Value(dir::DirValue::PaymentType(
euclid::enums::PaymentType::NewMandate,
)),
None,
None::<()>,
);
let connectors_from_config: Vec<dir::DirValue> = eligible_connectors
.into_iter()
.filter_map(|connector| {
match api_enums::RoutableConnectors::from_str(connector.to_string().as_str()) {
Ok(connector) => Some(dir::DirValue::Connector(Box::new(
api_models::routing::ast::ConnectorChoice { connector },
))),
Err(_) => None,
}
})
.collect();
if connectors_from_config.is_empty() {
Ok(None)
} else {
let connector_in_aggregator = builder
.make_in_aggregator(connectors_from_config, None, None::<()>)
.map_err(KgraphError::GraphConstructionError)?;
Ok(Some(
builder
.make_all_aggregator(
&[
(
payment_type_value_node,
cgraph::Relation::Positive,
cgraph::Strength::Strong,
),
(
connector_in_aggregator,
cgraph::Relation::Positive,
cgraph::Strength::Strong,
),
],
None,
None::<()>,
Some(domain_id),
)
.map_err(KgraphError::GraphConstructionError)?,
))
}
}
fn construct_capture_method_node(
builder: &mut cgraph::ConstraintGraphBuilder<dir::DirValue>,
payment_method_filters: &settings::PaymentMethodFilters,
payment_method_type: api_enums::PaymentMethodType,
) -> Result<Option<cgraph::NodeId>, KgraphError> {
if !payment_method_filters
.0
.get(&settings::PaymentMethodFilterKey::PaymentMethodType(
payment_method_type,
))
.and_then(|v| v.not_available_flows)
.and_then(|v| v.capture_method)
.map(|v| !matches!(v, api_enums::CaptureMethod::Manual))
.unwrap_or(true)
{
return Ok(Some(builder.make_value_node(
cgraph::NodeValue::Value(dir::DirValue::CaptureMethod(
common_enums::CaptureMethod::Manual,
)),
None,
None::<()>,
)));
}
Ok(None)
}
// fn construct_card_network_nodes(
// builder: &mut cgraph::ConstraintGraphBuilder<dir::DirValue>,
// mca_card_networks: Vec<api_enums::CardNetwork>,
// ) -> Result<Option<cgraph::NodeId>, KgraphError> {
// Ok(Some(
// builder
// .make_in_aggregator(
// mca_card_networks
// .into_iter()
// .map(dir::DirValue::CardNetwork)
// .collect(),
// None,
// None::<()>,
// )
// .map_err(KgraphError::GraphConstructionError)?,
// ))
// }
fn compile_accepted_countries_for_mca(
builder: &mut cgraph::ConstraintGraphBuilder<dir::DirValue>,
domain_id: cgraph::DomainId,
payment_method_type: enums::PaymentMethodType,
pm_countries: Option<admin::AcceptedCountries>,
config: &settings::ConnectorFilters,
connector: String,
) -> Result<Option<cgraph::NodeId>, KgraphError> {
let mut agg_nodes: Vec<(cgraph::NodeId, cgraph::Relation, cgraph::Strength)> = Vec::new();
// Country from the MCA
if let Some(pm_obj_countries) = pm_countries {
match pm_obj_countries {
admin::AcceptedCountries::EnableOnly(countries) => {
let pm_object_country_value_node = builder
.make_in_aggregator(
countries
.into_iter()
.map(|country| {
dir::DirValue::BillingCountry(common_enums::Country::from_alpha2(
country,
))
})
.collect(),
None,
None::<()>,
)
.map_err(KgraphError::GraphConstructionError)?;
agg_nodes.push((
pm_object_country_value_node,
cgraph::Relation::Positive,
cgraph::Strength::Weak,
));
}
admin::AcceptedCountries::DisableOnly(countries) => {
let pm_object_country_value_node = builder
.make_in_aggregator(
countries
.into_iter()
.map(|country| {
dir::DirValue::BillingCountry(common_enums::Country::from_alpha2(
country,
))
})
.collect(),
None,
None::<()>,
)
.map_err(KgraphError::GraphConstructionError)?;
agg_nodes.push((
pm_object_country_value_node,
cgraph::Relation::Negative,
cgraph::Strength::Weak,
));
}
admin::AcceptedCountries::AllAccepted => return Ok(None),
}
}
// country from config
if let Some(derived_config) = config
.0
.get(connector.as_str())
.or_else(|| config.0.get("default"))
{
if let Some(value) =
derived_config
.0
.get(&settings::PaymentMethodFilterKey::PaymentMethodType(
payment_method_type,
))
{
if let Some(config_countries) = value.country.as_ref() {
let config_countries: Vec<common_enums::Country> = Vec::from_iter(config_countries)
.into_iter()
.map(|country| common_enums::Country::from_alpha2(*country))
.collect();
let dir_countries: Vec<dir::DirValue> = config_countries
.into_iter()
.map(dir::DirValue::BillingCountry)
.collect();
let config_country_agg_node = builder
.make_in_aggregator(dir_countries, None, None::<()>)
.map_err(KgraphError::GraphConstructionError)?;
agg_nodes.push((
config_country_agg_node,
cgraph::Relation::Positive,
cgraph::Strength::Weak,
));
}
} else if let Some(default_derived_config) = config.0.get("default") {
if let Some(value) =
default_derived_config
.0
.get(&settings::PaymentMethodFilterKey::PaymentMethodType(
payment_method_type,
))
{
if let Some(config_countries) = value.country.as_ref() {
let config_countries: Vec<common_enums::Country> =
Vec::from_iter(config_countries)
.into_iter()
.map(|country| common_enums::Country::from_alpha2(*country))
.collect();
let dir_countries: Vec<dir::DirValue> = config_countries
.into_iter()
.map(dir::DirValue::BillingCountry)
.collect();
let config_country_agg_node = builder
.make_in_aggregator(dir_countries, None, None::<()>)
.map_err(KgraphError::GraphConstructionError)?;
agg_nodes.push((
config_country_agg_node,
cgraph::Relation::Positive,
cgraph::Strength::Weak,
));
}
}
};
}
Ok(Some(
builder
.make_all_aggregator(&agg_nodes, None, None::<()>, Some(domain_id))
.map_err(KgraphError::GraphConstructionError)?,
))
}
fn compile_accepted_currency_for_mca(
builder: &mut cgraph::ConstraintGraphBuilder<dir::DirValue>,
domain_id: cgraph::DomainId,
payment_method_type: enums::PaymentMethodType,
pm_currency: Option<admin::AcceptedCurrencies>,
config: &settings::ConnectorFilters,
connector: String,
) -> Result<Option<cgraph::NodeId>, KgraphError> {
let mut agg_nodes: Vec<(cgraph::NodeId, cgraph::Relation, cgraph::Strength)> = Vec::new();
// Currency from the MCA
if let Some(pm_obj_currency) = pm_currency {
match pm_obj_currency {
admin::AcceptedCurrencies::EnableOnly(currency) => {
let pm_object_currency_value_node = builder
.make_in_aggregator(
currency
.into_iter()
.map(dir::DirValue::PaymentCurrency)
.collect(),
None,
None::<()>,
)
.map_err(KgraphError::GraphConstructionError)?;
agg_nodes.push((
pm_object_currency_value_node,
cgraph::Relation::Positive,
cgraph::Strength::Weak,
));
}
admin::AcceptedCurrencies::DisableOnly(currency) => {
let pm_object_currency_value_node = builder
.make_in_aggregator(
currency
.into_iter()
.map(dir::DirValue::PaymentCurrency)
.collect(),
None,
None::<()>,
)
.map_err(KgraphError::GraphConstructionError)?;
agg_nodes.push((
pm_object_currency_value_node,
cgraph::Relation::Negative,
cgraph::Strength::Weak,
));
}
admin::AcceptedCurrencies::AllAccepted => return Ok(None),
}
}
// currency from config
if let Some(derived_config) = config
.0
.get(connector.as_str())
.or_else(|| config.0.get("default"))
{
if let Some(value) =
derived_config
.0
.get(&settings::PaymentMethodFilterKey::PaymentMethodType(
payment_method_type,
))
{
if let Some(config_currencies) = value.currency.as_ref() {
let config_currency: Vec<common_enums::Currency> =
Vec::from_iter(config_currencies)
.into_iter()
.copied()
.collect();
let dir_currencies: Vec<dir::DirValue> = config_currency
.into_iter()
.map(dir::DirValue::PaymentCurrency)
.collect();
let config_currency_agg_node = builder
.make_in_aggregator(dir_currencies, None, None::<()>)
.map_err(KgraphError::GraphConstructionError)?;
agg_nodes.push((
config_currency_agg_node,
cgraph::Relation::Positive,
cgraph::Strength::Weak,
));
}
} else if let Some(default_derived_config) = config.0.get("default") {
if let Some(value) =
default_derived_config
.0
.get(&settings::PaymentMethodFilterKey::PaymentMethodType(
payment_method_type,
))
{
if let Some(config_currencies) = value.currency.as_ref() {
let config_currency: Vec<common_enums::Currency> =
Vec::from_iter(config_currencies)
.into_iter()
.copied()
.collect();
let dir_currencies: Vec<dir::DirValue> = config_currency
.into_iter()
.map(dir::DirValue::PaymentCurrency)
.collect();
let config_currency_agg_node = builder
.make_in_aggregator(dir_currencies, None, None::<()>)
.map_err(KgraphError::GraphConstructionError)?;
agg_nodes.push((
config_currency_agg_node,
cgraph::Relation::Positive,
cgraph::Strength::Weak,
))
}
}
};
}
Ok(Some(
builder
.make_all_aggregator(&agg_nodes, None, None::<()>, Some(domain_id))
.map_err(KgraphError::GraphConstructionError)?,
))
}
#[cfg(feature = "v2")]
pub(super) async fn retrieve_payment_token_data(
state: &SessionState,
token: String,
payment_method: Option<&storage_enums::PaymentMethod>,
) -> errors::RouterResult<storage::PaymentTokenData> {
let redis_conn = state
.store
.get_redis_conn()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get redis connection")?;
let key = format!(
"pm_token_{}_{}_hyperswitch",
token,
payment_method
.get_required_value("payment_method")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Payment method is required")?
);
let token_data_string = redis_conn
.get_key::<Option<String>>(&key.into())
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to fetch the token from redis")?
.ok_or(error_stack::Report::new(
errors::ApiErrorResponse::UnprocessableEntity {
message: "Token is invalid or expired".to_owned(),
},
))?;
token_data_string
.clone()
.parse_struct("PaymentTokenData")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed to deserialize hyperswitch token data")
}
#[cfg(feature = "v2")]
pub(super) async fn delete_payment_token_data(
state: &SessionState,
key_for_token: &str,
) -> errors::RouterResult<()> {
let redis_conn = state
.store
.get_redis_conn()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get redis connection")?;
match redis_conn.delete_key(&key_for_token.into()).await {
Ok(_) => Ok(()),
Err(err) => {
{
logger::error!("Error while deleting redis key: {:?}", err)
};
Ok(())
}
}
}
|
crates/router/src/core/payment_methods/utils.rs
|
router::src::core::payment_methods::utils
| 6,103
| true
|
// File: crates/router/src/core/payment_methods/tokenize/card_executor.rs
// Module: router::src::core::payment_methods::tokenize::card_executor
use std::str::FromStr;
use ::payment_methods::{controller::PaymentMethodsController, core::migration};
use api_models::{enums as api_enums, payment_methods as payment_methods_api};
use common_utils::{
consts,
ext_traits::OptionExt,
generate_customer_id_of_default_length, id_type,
pii::Email,
type_name,
types::keymanager::{Identifier, KeyManagerState, ToEncryptable},
};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::type_encryption::{crypto_operation, CryptoOperation};
use masking::{ExposeInterface, PeekInterface, SwitchStrategy};
use router_env::logger;
use super::{
CardNetworkTokenizeExecutor, NetworkTokenizationBuilder, NetworkTokenizationProcess,
NetworkTokenizationResponse, State, StoreLockerResponse, TransitionTo,
};
use crate::{
core::payment_methods::{
cards::{add_card_to_hs_locker, PmCards},
transformers as pm_transformers,
},
errors::{self, RouterResult},
types::{api, domain},
utils,
};
// Available states for card tokenization
pub struct TokenizeWithCard;
pub struct CardRequestValidated;
pub struct CardDetailsAssigned;
pub struct CustomerAssigned;
pub struct CardTokenized;
pub struct CardStored;
pub struct CardTokenStored;
pub struct PaymentMethodCreated;
impl State for TokenizeWithCard {}
impl State for CustomerAssigned {}
impl State for CardRequestValidated {}
impl State for CardDetailsAssigned {}
impl State for CardTokenized {}
impl State for CardStored {}
impl State for CardTokenStored {}
impl State for PaymentMethodCreated {}
// State transitions for card tokenization
impl TransitionTo<CardRequestValidated> for TokenizeWithCard {}
impl TransitionTo<CardDetailsAssigned> for CardRequestValidated {}
impl TransitionTo<CustomerAssigned> for CardDetailsAssigned {}
impl TransitionTo<CardTokenized> for CustomerAssigned {}
impl TransitionTo<CardTokenStored> for CardTokenized {}
impl TransitionTo<PaymentMethodCreated> for CardTokenStored {}
impl Default for NetworkTokenizationBuilder<'_, TokenizeWithCard> {
fn default() -> Self {
Self::new()
}
}
impl<'a> NetworkTokenizationBuilder<'a, TokenizeWithCard> {
pub fn new() -> Self {
Self {
state: std::marker::PhantomData,
customer: None,
card: None,
card_cvc: None,
network_token: None,
stored_card: None,
stored_token: None,
payment_method_response: None,
card_tokenized: false,
error_code: None,
error_message: None,
}
}
pub fn set_validate_result(self) -> NetworkTokenizationBuilder<'a, CardRequestValidated> {
NetworkTokenizationBuilder {
state: std::marker::PhantomData,
customer: self.customer,
card: self.card,
card_cvc: self.card_cvc,
network_token: self.network_token,
stored_card: self.stored_card,
stored_token: self.stored_token,
payment_method_response: self.payment_method_response,
card_tokenized: self.card_tokenized,
error_code: self.error_code,
error_message: self.error_message,
}
}
}
impl<'a> NetworkTokenizationBuilder<'a, CardRequestValidated> {
pub fn set_card_details(
self,
card_req: &'a domain::TokenizeCardRequest,
optional_card_info: Option<diesel_models::CardInfo>,
) -> NetworkTokenizationBuilder<'a, CardDetailsAssigned> {
let card = domain::CardDetail {
card_number: card_req.raw_card_number.clone(),
card_exp_month: card_req.card_expiry_month.clone(),
card_exp_year: card_req.card_expiry_year.clone(),
bank_code: optional_card_info
.as_ref()
.and_then(|card_info| card_info.bank_code.clone()),
nick_name: card_req.nick_name.clone(),
card_holder_name: card_req.card_holder_name.clone(),
card_issuer: optional_card_info
.as_ref()
.map_or(card_req.card_issuer.clone(), |card_info| {
card_info.card_issuer.clone()
}),
card_network: optional_card_info
.as_ref()
.map_or(card_req.card_network.clone(), |card_info| {
card_info.card_network.clone()
}),
card_type: optional_card_info.as_ref().map_or(
card_req
.card_type
.as_ref()
.map(|card_type| card_type.to_string()),
|card_info| card_info.card_type.clone(),
),
card_issuing_country: optional_card_info
.as_ref()
.map_or(card_req.card_issuing_country.clone(), |card_info| {
card_info.card_issuing_country.clone()
}),
co_badged_card_data: None,
};
NetworkTokenizationBuilder {
state: std::marker::PhantomData,
card: Some(card),
card_cvc: card_req.card_cvc.clone(),
customer: self.customer,
network_token: self.network_token,
stored_card: self.stored_card,
stored_token: self.stored_token,
payment_method_response: self.payment_method_response,
card_tokenized: self.card_tokenized,
error_code: self.error_code,
error_message: self.error_message,
}
}
}
impl<'a> NetworkTokenizationBuilder<'a, CardDetailsAssigned> {
pub fn set_customer(
self,
customer: &'a api::CustomerDetails,
) -> NetworkTokenizationBuilder<'a, CustomerAssigned> {
NetworkTokenizationBuilder {
state: std::marker::PhantomData,
customer: Some(customer),
card: self.card,
card_cvc: self.card_cvc,
network_token: self.network_token,
stored_card: self.stored_card,
stored_token: self.stored_token,
payment_method_response: self.payment_method_response,
card_tokenized: self.card_tokenized,
error_code: self.error_code,
error_message: self.error_message,
}
}
}
impl<'a> NetworkTokenizationBuilder<'a, CustomerAssigned> {
pub fn get_optional_card_and_cvc(
&self,
) -> (Option<domain::CardDetail>, Option<masking::Secret<String>>) {
(self.card.clone(), self.card_cvc.clone())
}
pub fn set_token_details(
self,
network_token: &'a NetworkTokenizationResponse,
) -> NetworkTokenizationBuilder<'a, CardTokenized> {
NetworkTokenizationBuilder {
state: std::marker::PhantomData,
network_token: Some(&network_token.0),
customer: self.customer,
card: self.card,
card_cvc: self.card_cvc,
stored_card: self.stored_card,
stored_token: self.stored_token,
payment_method_response: self.payment_method_response,
card_tokenized: self.card_tokenized,
error_code: self.error_code,
error_message: self.error_message,
}
}
}
impl<'a> NetworkTokenizationBuilder<'a, CardTokenized> {
pub fn set_stored_card_response(
self,
store_card_response: &'a StoreLockerResponse,
) -> NetworkTokenizationBuilder<'a, CardStored> {
NetworkTokenizationBuilder {
state: std::marker::PhantomData,
stored_card: Some(&store_card_response.store_card_resp),
customer: self.customer,
card: self.card,
card_cvc: self.card_cvc,
network_token: self.network_token,
stored_token: self.stored_token,
payment_method_response: self.payment_method_response,
card_tokenized: self.card_tokenized,
error_code: self.error_code,
error_message: self.error_message,
}
}
}
impl<'a> NetworkTokenizationBuilder<'a, CardStored> {
pub fn set_stored_token_response(
self,
store_token_response: &'a StoreLockerResponse,
) -> NetworkTokenizationBuilder<'a, CardTokenStored> {
NetworkTokenizationBuilder {
state: std::marker::PhantomData,
card_tokenized: true,
stored_token: Some(&store_token_response.store_token_resp),
customer: self.customer,
card: self.card,
card_cvc: self.card_cvc,
network_token: self.network_token,
stored_card: self.stored_card,
payment_method_response: self.payment_method_response,
error_code: self.error_code,
error_message: self.error_message,
}
}
}
impl<'a> NetworkTokenizationBuilder<'a, CardTokenStored> {
pub fn set_payment_method_response(
self,
payment_method: &'a domain::PaymentMethod,
) -> NetworkTokenizationBuilder<'a, PaymentMethodCreated> {
let card_detail_from_locker = self.card.as_ref().map(|card| api::CardDetailFromLocker {
scheme: None,
issuer_country: card.card_issuing_country.clone(),
last4_digits: Some(card.card_number.clone().get_last4()),
card_number: None,
expiry_month: Some(card.card_exp_month.clone().clone()),
expiry_year: Some(card.card_exp_year.clone().clone()),
card_token: None,
card_holder_name: card.card_holder_name.clone(),
card_fingerprint: None,
nick_name: card.nick_name.clone(),
card_network: card.card_network.clone(),
card_isin: Some(card.card_number.clone().get_card_isin()),
card_issuer: card.card_issuer.clone(),
card_type: card.card_type.clone(),
saved_to_locker: true,
});
let payment_method_response = api::PaymentMethodResponse {
merchant_id: payment_method.merchant_id.clone(),
customer_id: Some(payment_method.customer_id.clone()),
payment_method_id: payment_method.payment_method_id.clone(),
payment_method: payment_method.payment_method,
payment_method_type: payment_method.payment_method_type,
card: card_detail_from_locker,
recurring_enabled: Some(true),
installment_payment_enabled: Some(false),
metadata: payment_method.metadata.clone(),
created: Some(payment_method.created_at),
last_used_at: Some(payment_method.last_used_at),
client_secret: payment_method.client_secret.clone(),
bank_transfer: None,
payment_experience: None,
};
NetworkTokenizationBuilder {
state: std::marker::PhantomData,
payment_method_response: Some(payment_method_response),
customer: self.customer,
card: self.card,
card_cvc: self.card_cvc,
network_token: self.network_token,
stored_card: self.stored_card,
stored_token: self.stored_token,
card_tokenized: self.card_tokenized,
error_code: self.error_code,
error_message: self.error_message,
}
}
}
impl NetworkTokenizationBuilder<'_, PaymentMethodCreated> {
pub fn build(self) -> api::CardNetworkTokenizeResponse {
api::CardNetworkTokenizeResponse {
payment_method_response: self.payment_method_response,
customer: self.customer.cloned(),
card_tokenized: self.card_tokenized,
error_code: self.error_code.cloned(),
error_message: self.error_message.cloned(),
// Below field is mutated by caller functions for batched API operations
tokenization_data: None,
}
}
}
// Specific executor for card tokenization
impl CardNetworkTokenizeExecutor<'_, domain::TokenizeCardRequest> {
pub async fn validate_request_and_fetch_optional_customer(
&self,
) -> RouterResult<Option<api::CustomerDetails>> {
// Validate card's expiry
migration::validate_card_expiry(&self.data.card_expiry_month, &self.data.card_expiry_year)?;
// Validate customer ID
let customer_id = self
.customer
.customer_id
.as_ref()
.get_required_value("customer_id")
.change_context(errors::ApiErrorResponse::MissingRequiredField {
field_name: "customer.customer_id",
})?;
// Fetch customer details if present
let db = &*self.state.store;
let key_manager_state: &KeyManagerState = &self.state.into();
db.find_customer_optional_by_customer_id_merchant_id(
key_manager_state,
customer_id,
self.merchant_account.get_id(),
self.key_store,
self.merchant_account.storage_scheme,
)
.await
.inspect_err(|err| logger::info!("Error fetching customer: {:?}", err))
.change_context(errors::ApiErrorResponse::InternalServerError)
.map_or(
// Validate if customer creation is feasible
if self.customer.name.is_some()
|| self.customer.email.is_some()
|| self.customer.phone.is_some()
{
Ok(None)
} else {
Err(report!(errors::ApiErrorResponse::MissingRequiredFields {
field_names: vec!["customer.name", "customer.email", "customer.phone"],
}))
},
// If found, send back CustomerDetails from DB
|optional_customer| {
Ok(optional_customer.map(|customer| api::CustomerDetails {
id: customer.customer_id.clone(),
name: customer.name.clone().map(|name| name.into_inner()),
email: customer.email.clone().map(Email::from),
phone: customer.phone.clone().map(|phone| phone.into_inner()),
phone_country_code: customer.phone_country_code.clone(),
tax_registration_id: customer
.tax_registration_id
.clone()
.map(|tax_registration_id| tax_registration_id.into_inner()),
}))
},
)
}
pub async fn create_customer(&self) -> RouterResult<api::CustomerDetails> {
let db = &*self.state.store;
let customer_id = self
.customer
.customer_id
.as_ref()
.get_required_value("customer_id")
.change_context(errors::ApiErrorResponse::MissingRequiredField {
field_name: "customer_id",
})?;
let key_manager_state: &KeyManagerState = &self.state.into();
let encrypted_data = crypto_operation(
key_manager_state,
type_name!(domain::Customer),
CryptoOperation::BatchEncrypt(domain::FromRequestEncryptableCustomer::to_encryptable(
domain::FromRequestEncryptableCustomer {
name: self.customer.name.clone(),
email: self
.customer
.email
.clone()
.map(|email| email.expose().switch_strategy()),
phone: self.customer.phone.clone(),
tax_registration_id: self.customer.tax_registration_id.clone(),
},
)),
Identifier::Merchant(self.merchant_account.get_id().clone()),
self.key_store.key.get_inner().peek(),
)
.await
.inspect_err(|err| logger::info!("Error encrypting customer: {:?}", err))
.and_then(|val| val.try_into_batchoperation())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to encrypt customer")?;
let encryptable_customer =
domain::FromRequestEncryptableCustomer::from_encryptable(encrypted_data)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to form EncryptableCustomer")?;
let new_customer_id = generate_customer_id_of_default_length();
let domain_customer = domain::Customer {
customer_id: new_customer_id.clone(),
merchant_id: self.merchant_account.get_id().clone(),
name: encryptable_customer.name,
email: encryptable_customer.email.map(|email| {
utils::Encryptable::new(
email.clone().into_inner().switch_strategy(),
email.into_encrypted(),
)
}),
phone: encryptable_customer.phone,
description: None,
phone_country_code: self.customer.phone_country_code.to_owned(),
metadata: None,
connector_customer: None,
created_at: common_utils::date_time::now(),
modified_at: common_utils::date_time::now(),
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,
};
db.insert_customer(
domain_customer,
key_manager_state,
self.key_store,
self.merchant_account.storage_scheme,
)
.await
.inspect_err(|err| logger::info!("Error creating a customer: {:?}", err))
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| {
format!(
"Failed to insert customer [id - {:?}] for merchant [id - {:?}]",
customer_id,
self.merchant_account.get_id()
)
})?;
Ok(api::CustomerDetails {
id: new_customer_id,
name: self.customer.name.clone(),
email: self.customer.email.clone(),
phone: self.customer.phone.clone(),
phone_country_code: self.customer.phone_country_code.clone(),
tax_registration_id: self.customer.tax_registration_id.clone(),
})
}
pub async fn store_card_and_token_in_locker(
&self,
network_token: &NetworkTokenizationResponse,
card: &domain::CardDetail,
customer_id: &id_type::CustomerId,
) -> RouterResult<StoreLockerResponse> {
let stored_card_resp = self.store_card_in_locker(card, customer_id).await?;
let stored_token_resp = self
.store_network_token_in_locker(
network_token,
customer_id,
card.card_holder_name.clone(),
card.nick_name.clone(),
)
.await?;
let store_locker_response = StoreLockerResponse {
store_card_resp: stored_card_resp,
store_token_resp: stored_token_resp,
};
Ok(store_locker_response)
}
pub async fn store_card_in_locker(
&self,
card: &domain::CardDetail,
customer_id: &id_type::CustomerId,
) -> RouterResult<pm_transformers::StoreCardRespPayload> {
let merchant_id = self.merchant_account.get_id();
let locker_req =
pm_transformers::StoreLockerReq::LockerCard(pm_transformers::StoreCardReq {
merchant_id: merchant_id.clone(),
merchant_customer_id: customer_id.clone(),
card: payment_methods_api::Card {
card_number: card.card_number.clone(),
card_exp_month: card.card_exp_month.clone(),
card_exp_year: card.card_exp_year.clone(),
card_isin: Some(card.card_number.get_card_isin().clone()),
name_on_card: card.card_holder_name.clone(),
nick_name: card
.nick_name
.as_ref()
.map(|nick_name| nick_name.clone().expose()),
card_brand: None,
},
requestor_card_reference: None,
ttl: self.state.conf.locker.ttl_for_storage_in_secs,
});
let stored_resp = add_card_to_hs_locker(
self.state,
&locker_req,
customer_id,
api_enums::LockerChoice::HyperswitchCardVault,
)
.await
.inspect_err(|err| logger::info!("Error adding card in locker: {:?}", err))
.change_context(errors::ApiErrorResponse::InternalServerError)?;
Ok(stored_resp)
}
pub async fn create_payment_method(
&self,
stored_locker_resp: &StoreLockerResponse,
network_token_details: &NetworkTokenizationResponse,
card_details: &domain::CardDetail,
customer_id: &id_type::CustomerId,
) -> RouterResult<domain::PaymentMethod> {
let payment_method_id = common_utils::generate_id(consts::ID_LENGTH, "pm");
// Form encrypted PM data (original card)
let enc_pm_data = self.encrypt_card(card_details, true).await?;
// Form encrypted network token data
let enc_token_data = self
.encrypt_network_token(network_token_details, card_details, true)
.await?;
// Form PM create entry
let payment_method_create = api::PaymentMethodCreate {
payment_method: Some(api_enums::PaymentMethod::Card),
payment_method_type: card_details
.card_type
.as_ref()
.and_then(|card_type| api_enums::PaymentMethodType::from_str(card_type).ok()),
payment_method_issuer: card_details.card_issuer.clone(),
payment_method_issuer_code: None,
card: Some(api::CardDetail {
card_number: card_details.card_number.clone(),
card_exp_month: card_details.card_exp_month.clone(),
card_exp_year: card_details.card_exp_year.clone(),
card_holder_name: card_details.card_holder_name.clone(),
nick_name: card_details.nick_name.clone(),
card_issuing_country: card_details.card_issuing_country.clone(),
card_network: card_details.card_network.clone(),
card_issuer: card_details.card_issuer.clone(),
card_type: card_details.card_type.clone(),
}),
metadata: None,
customer_id: Some(customer_id.clone()),
card_network: card_details
.card_network
.as_ref()
.map(|network| network.to_string()),
bank_transfer: None,
wallet: None,
client_secret: None,
payment_method_data: None,
billing: None,
connector_mandate_details: None,
network_transaction_id: None,
};
PmCards {
state: self.state,
merchant_context: &domain::MerchantContext::NormalMerchant(Box::new(domain::Context(
self.merchant_account.clone(),
self.key_store.clone(),
))),
}
.create_payment_method(
&payment_method_create,
customer_id,
&payment_method_id,
Some(stored_locker_resp.store_card_resp.card_reference.clone()),
self.merchant_account.get_id(),
None,
None,
Some(enc_pm_data),
None,
None,
None,
None,
None,
network_token_details.1.clone(),
Some(stored_locker_resp.store_token_resp.card_reference.clone()),
Some(enc_token_data),
Default::default(), // this method is used only for card bulk tokenization, and currently external vault is not supported for this hence passing Default i.e. InternalVault
)
.await
}
}
|
crates/router/src/core/payment_methods/tokenize/card_executor.rs
|
router::src::core::payment_methods::tokenize::card_executor
| 4,734
| true
|
// File: crates/router/src/core/payment_methods/tokenize/payment_method_executor.rs
// Module: router::src::core::payment_methods::tokenize::payment_method_executor
use api_models::enums as api_enums;
use common_utils::{
ext_traits::OptionExt, fp_utils::when, pii::Email, types::keymanager::KeyManagerState,
};
use error_stack::{report, ResultExt};
use masking::Secret;
use router_env::logger;
use super::{
CardNetworkTokenizeExecutor, NetworkTokenizationBuilder, NetworkTokenizationProcess,
NetworkTokenizationResponse, State, TransitionTo,
};
use crate::{
core::payment_methods::transformers as pm_transformers,
errors::{self, RouterResult},
types::{api, domain},
};
// Available states for payment method tokenization
pub struct TokenizeWithPmId;
pub struct PmValidated;
pub struct PmFetched;
pub struct PmAssigned;
pub struct PmTokenized;
pub struct PmTokenStored;
pub struct PmTokenUpdated;
impl State for TokenizeWithPmId {}
impl State for PmValidated {}
impl State for PmFetched {}
impl State for PmAssigned {}
impl State for PmTokenized {}
impl State for PmTokenStored {}
impl State for PmTokenUpdated {}
// State transitions for payment method tokenization
impl TransitionTo<PmFetched> for TokenizeWithPmId {}
impl TransitionTo<PmValidated> for PmFetched {}
impl TransitionTo<PmAssigned> for PmValidated {}
impl TransitionTo<PmTokenized> for PmAssigned {}
impl TransitionTo<PmTokenStored> for PmTokenized {}
impl TransitionTo<PmTokenUpdated> for PmTokenStored {}
impl Default for NetworkTokenizationBuilder<'_, TokenizeWithPmId> {
fn default() -> Self {
Self::new()
}
}
impl<'a> NetworkTokenizationBuilder<'a, TokenizeWithPmId> {
pub fn new() -> Self {
Self {
state: std::marker::PhantomData,
customer: None,
card: None,
card_cvc: None,
network_token: None,
stored_card: None,
stored_token: None,
payment_method_response: None,
card_tokenized: false,
error_code: None,
error_message: None,
}
}
pub fn set_payment_method(
self,
payment_method: &domain::PaymentMethod,
) -> NetworkTokenizationBuilder<'a, PmFetched> {
let payment_method_response = api::PaymentMethodResponse {
merchant_id: payment_method.merchant_id.clone(),
customer_id: Some(payment_method.customer_id.clone()),
payment_method_id: payment_method.payment_method_id.clone(),
payment_method: payment_method.payment_method,
payment_method_type: payment_method.payment_method_type,
recurring_enabled: Some(true),
installment_payment_enabled: Some(false),
metadata: payment_method.metadata.clone(),
created: Some(payment_method.created_at),
last_used_at: Some(payment_method.last_used_at),
client_secret: payment_method.client_secret.clone(),
card: None,
bank_transfer: None,
payment_experience: None,
};
NetworkTokenizationBuilder {
state: std::marker::PhantomData,
payment_method_response: Some(payment_method_response),
customer: self.customer,
card: self.card,
card_cvc: self.card_cvc,
network_token: self.network_token,
stored_card: self.stored_card,
stored_token: self.stored_token,
card_tokenized: self.card_tokenized,
error_code: self.error_code,
error_message: self.error_message,
}
}
}
impl<'a> NetworkTokenizationBuilder<'a, PmFetched> {
pub fn set_validate_result(
self,
customer: &'a api::CustomerDetails,
) -> NetworkTokenizationBuilder<'a, PmValidated> {
NetworkTokenizationBuilder {
state: std::marker::PhantomData,
customer: Some(customer),
card: self.card,
card_cvc: self.card_cvc,
network_token: self.network_token,
stored_card: self.stored_card,
stored_token: self.stored_token,
payment_method_response: self.payment_method_response,
card_tokenized: self.card_tokenized,
error_code: self.error_code,
error_message: self.error_message,
}
}
}
impl<'a> NetworkTokenizationBuilder<'a, PmValidated> {
pub fn set_card_details(
self,
card_from_locker: &'a api_models::payment_methods::Card,
optional_card_info: Option<diesel_models::CardInfo>,
card_cvc: Option<Secret<String>>,
) -> NetworkTokenizationBuilder<'a, PmAssigned> {
let card = domain::CardDetail {
card_number: card_from_locker.card_number.clone(),
card_exp_month: card_from_locker.card_exp_month.clone(),
card_exp_year: card_from_locker.card_exp_year.clone(),
bank_code: optional_card_info
.as_ref()
.and_then(|card_info| card_info.bank_code.clone()),
nick_name: card_from_locker
.nick_name
.as_ref()
.map(|nick_name| Secret::new(nick_name.clone())),
card_holder_name: card_from_locker.name_on_card.clone(),
card_issuer: optional_card_info
.as_ref()
.and_then(|card_info| card_info.card_issuer.clone()),
card_network: optional_card_info
.as_ref()
.and_then(|card_info| card_info.card_network.clone()),
card_type: optional_card_info
.as_ref()
.and_then(|card_info| card_info.card_type.clone()),
card_issuing_country: optional_card_info
.as_ref()
.and_then(|card_info| card_info.card_issuing_country.clone()),
co_badged_card_data: None,
};
NetworkTokenizationBuilder {
state: std::marker::PhantomData,
card: Some(card),
card_cvc,
customer: self.customer,
network_token: self.network_token,
stored_card: self.stored_card,
stored_token: self.stored_token,
payment_method_response: self.payment_method_response,
card_tokenized: self.card_tokenized,
error_code: self.error_code,
error_message: self.error_message,
}
}
}
impl<'a> NetworkTokenizationBuilder<'a, PmAssigned> {
pub fn get_optional_card_and_cvc(
&self,
) -> (Option<domain::CardDetail>, Option<Secret<String>>) {
(self.card.clone(), self.card_cvc.clone())
}
pub fn set_token_details(
self,
network_token: &'a NetworkTokenizationResponse,
) -> NetworkTokenizationBuilder<'a, PmTokenized> {
NetworkTokenizationBuilder {
state: std::marker::PhantomData,
network_token: Some(&network_token.0),
card_tokenized: true,
customer: self.customer,
card: self.card,
card_cvc: self.card_cvc,
stored_card: self.stored_card,
stored_token: self.stored_token,
payment_method_response: self.payment_method_response,
error_code: self.error_code,
error_message: self.error_message,
}
}
}
impl<'a> NetworkTokenizationBuilder<'a, PmTokenized> {
pub fn set_stored_token_response(
self,
store_token_response: &'a pm_transformers::StoreCardRespPayload,
) -> NetworkTokenizationBuilder<'a, PmTokenStored> {
NetworkTokenizationBuilder {
state: std::marker::PhantomData,
stored_token: Some(store_token_response),
customer: self.customer,
card: self.card,
card_cvc: self.card_cvc,
network_token: self.network_token,
stored_card: self.stored_card,
payment_method_response: self.payment_method_response,
card_tokenized: self.card_tokenized,
error_code: self.error_code,
error_message: self.error_message,
}
}
}
impl<'a> NetworkTokenizationBuilder<'a, PmTokenStored> {
pub fn set_payment_method(
self,
payment_method: &'a domain::PaymentMethod,
) -> NetworkTokenizationBuilder<'a, PmTokenUpdated> {
let payment_method_response = api::PaymentMethodResponse {
merchant_id: payment_method.merchant_id.clone(),
customer_id: Some(payment_method.customer_id.clone()),
payment_method_id: payment_method.payment_method_id.clone(),
payment_method: payment_method.payment_method,
payment_method_type: payment_method.payment_method_type,
recurring_enabled: Some(true),
installment_payment_enabled: Some(false),
metadata: payment_method.metadata.clone(),
created: Some(payment_method.created_at),
last_used_at: Some(payment_method.last_used_at),
client_secret: payment_method.client_secret.clone(),
card: None,
bank_transfer: None,
payment_experience: None,
};
NetworkTokenizationBuilder {
state: std::marker::PhantomData,
payment_method_response: Some(payment_method_response),
customer: self.customer,
card: self.card,
card_cvc: self.card_cvc,
stored_token: self.stored_token,
network_token: self.network_token,
stored_card: self.stored_card,
card_tokenized: self.card_tokenized,
error_code: self.error_code,
error_message: self.error_message,
}
}
}
impl NetworkTokenizationBuilder<'_, PmTokenUpdated> {
pub fn build(self) -> api::CardNetworkTokenizeResponse {
api::CardNetworkTokenizeResponse {
payment_method_response: self.payment_method_response,
customer: self.customer.cloned(),
card_tokenized: self.card_tokenized,
error_code: self.error_code.cloned(),
error_message: self.error_message.cloned(),
// Below field is mutated by caller functions for batched API operations
tokenization_data: None,
}
}
}
// Specific executor for payment method tokenization
impl CardNetworkTokenizeExecutor<'_, domain::TokenizePaymentMethodRequest> {
pub async fn fetch_payment_method(
&self,
payment_method_id: &str,
) -> RouterResult<domain::PaymentMethod> {
self.state
.store
.find_payment_method(
&self.state.into(),
self.key_store,
payment_method_id,
self.merchant_account.storage_scheme,
)
.await
.map_err(|err| match err.current_context() {
errors::StorageError::DatabaseError(err)
if matches!(
err.current_context(),
diesel_models::errors::DatabaseError::NotFound
) =>
{
report!(errors::ApiErrorResponse::InvalidRequestData {
message: "Invalid payment_method_id".into(),
})
}
errors::StorageError::ValueNotFound(_) => {
report!(errors::ApiErrorResponse::InvalidRequestData {
message: "Invalid payment_method_id".to_string(),
})
}
err => {
logger::info!("Error fetching payment_method: {:?}", err);
report!(errors::ApiErrorResponse::InternalServerError)
}
})
}
pub async fn validate_request_and_locker_reference_and_customer(
&self,
payment_method: &domain::PaymentMethod,
) -> RouterResult<(String, api::CustomerDetails)> {
// Ensure customer ID matches
let customer_id_in_req = self
.customer
.customer_id
.clone()
.get_required_value("customer_id")
.change_context(errors::ApiErrorResponse::MissingRequiredField {
field_name: "customer",
})?;
when(payment_method.customer_id != customer_id_in_req, || {
Err(report!(errors::ApiErrorResponse::InvalidRequestData {
message: "Payment method does not belong to the customer".to_string()
}))
})?;
// Ensure payment method is card
match payment_method.payment_method {
Some(api_enums::PaymentMethod::Card) => Ok(()),
Some(_) => Err(report!(errors::ApiErrorResponse::InvalidRequestData {
message: "Payment method is not card".to_string()
})),
None => Err(report!(errors::ApiErrorResponse::InvalidRequestData {
message: "Payment method is empty".to_string()
})),
}?;
// Ensure card is not tokenized already
when(
payment_method
.network_token_requestor_reference_id
.is_some(),
|| {
Err(report!(errors::ApiErrorResponse::InvalidRequestData {
message: "Card is already tokenized".to_string()
}))
},
)?;
// Ensure locker reference is present
let locker_id = payment_method.locker_id.clone().ok_or(report!(
errors::ApiErrorResponse::InvalidRequestData {
message: "locker_id not found for given payment_method_id".to_string()
}
))?;
// Fetch customer
let db = &*self.state.store;
let key_manager_state: &KeyManagerState = &self.state.into();
let customer = db
.find_customer_by_customer_id_merchant_id(
key_manager_state,
&payment_method.customer_id,
self.merchant_account.get_id(),
self.key_store,
self.merchant_account.storage_scheme,
)
.await
.inspect_err(|err| logger::info!("Error fetching customer: {:?}", err))
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let customer_details = api::CustomerDetails {
id: customer.customer_id.clone(),
name: customer.name.clone().map(|name| name.into_inner()),
email: customer.email.clone().map(Email::from),
phone: customer.phone.clone().map(|phone| phone.into_inner()),
phone_country_code: customer.phone_country_code.clone(),
tax_registration_id: customer
.tax_registration_id
.clone()
.map(|tax_registration_id| tax_registration_id.into_inner()),
};
Ok((locker_id, customer_details))
}
pub async fn update_payment_method(
&self,
store_token_response: &pm_transformers::StoreCardRespPayload,
payment_method: domain::PaymentMethod,
network_token_details: &NetworkTokenizationResponse,
card_details: &domain::CardDetail,
) -> RouterResult<domain::PaymentMethod> {
// Form encrypted network token data
let enc_token_data = self
.encrypt_network_token(network_token_details, card_details, true)
.await?;
// Update payment method
let payment_method_update = diesel_models::PaymentMethodUpdate::NetworkTokenDataUpdate {
network_token_requestor_reference_id: network_token_details.1.clone(),
network_token_locker_id: Some(store_token_response.card_reference.clone()),
network_token_payment_method_data: Some(enc_token_data.into()),
};
self.state
.store
.update_payment_method(
&self.state.into(),
self.key_store,
payment_method,
payment_method_update,
self.merchant_account.storage_scheme,
)
.await
.inspect_err(|err| logger::info!("Error updating payment method: {:?}", err))
.change_context(errors::ApiErrorResponse::InternalServerError)
}
}
|
crates/router/src/core/payment_methods/tokenize/payment_method_executor.rs
|
router::src::core::payment_methods::tokenize::payment_method_executor
| 3,261
| true
|
// File: crates/router/src/core/pm_auth/transformers.rs
// Module: router::src::core::pm_auth::transformers
use pm_auth::types as pm_auth_types;
use crate::{core::errors, types, types::transformers::ForeignTryFrom};
impl From<types::MerchantAccountData> for pm_auth_types::MerchantAccountData {
fn from(from: types::MerchantAccountData) -> Self {
match from {
types::MerchantAccountData::Iban { iban, name, .. } => Self::Iban { iban, name },
types::MerchantAccountData::Bacs {
account_number,
sort_code,
name,
..
} => Self::Bacs {
account_number,
sort_code,
name,
},
types::MerchantAccountData::FasterPayments {
account_number,
sort_code,
name,
..
} => Self::FasterPayments {
account_number,
sort_code,
name,
},
types::MerchantAccountData::Sepa { iban, name, .. } => Self::Sepa { iban, name },
types::MerchantAccountData::SepaInstant { iban, name, .. } => {
Self::SepaInstant { iban, name }
}
types::MerchantAccountData::Elixir {
account_number,
iban,
name,
..
} => Self::Elixir {
account_number,
iban,
name,
},
types::MerchantAccountData::Bankgiro { number, name, .. } => {
Self::Bankgiro { number, name }
}
types::MerchantAccountData::Plusgiro { number, name, .. } => {
Self::Plusgiro { number, name }
}
}
}
}
impl From<types::MerchantRecipientData> for pm_auth_types::MerchantRecipientData {
fn from(value: types::MerchantRecipientData) -> Self {
match value {
types::MerchantRecipientData::ConnectorRecipientId(id) => {
Self::ConnectorRecipientId(id)
}
types::MerchantRecipientData::WalletId(id) => Self::WalletId(id),
types::MerchantRecipientData::AccountData(data) => Self::AccountData(data.into()),
}
}
}
impl ForeignTryFrom<types::ConnectorAuthType> for pm_auth_types::ConnectorAuthType {
type Error = errors::ConnectorError;
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::BodyKey {
client_id: api_key.to_owned(),
secret: key1.to_owned(),
})
}
_ => Err(errors::ConnectorError::FailedToObtainAuthType),
}
}
}
|
crates/router/src/core/pm_auth/transformers.rs
|
router::src::core::pm_auth::transformers
| 620
| true
|
// File: crates/router/src/core/pm_auth/helpers.rs
// Module: router::src::core::pm_auth::helpers
use common_utils::ext_traits::ValueExt;
use error_stack::ResultExt;
use pm_auth::types::{self as pm_auth_types, api::BoxedPaymentAuthConnector};
use crate::{
core::errors::{self, ApiErrorResponse},
types::{self, domain, transformers::ForeignTryFrom},
};
pub trait PaymentAuthConnectorDataExt {
fn get_connector_by_name(name: &str) -> errors::CustomResult<Self, ApiErrorResponse>
where
Self: Sized;
fn convert_connector(
connector_name: pm_auth_types::PaymentMethodAuthConnectors,
) -> errors::CustomResult<BoxedPaymentAuthConnector, ApiErrorResponse>;
}
pub fn get_connector_auth_type(
merchant_connector_account: domain::MerchantConnectorAccount,
) -> errors::CustomResult<pm_auth_types::ConnectorAuthType, ApiErrorResponse> {
let auth_type: types::ConnectorAuthType = merchant_connector_account
.connector_account_details
.parse_value("ConnectorAuthType")
.change_context(ApiErrorResponse::MerchantConnectorAccountNotFound {
id: "ConnectorAuthType".to_string(),
})?;
pm_auth_types::ConnectorAuthType::foreign_try_from(auth_type)
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed while converting ConnectorAuthType")
}
|
crates/router/src/core/pm_auth/helpers.rs
|
router::src::core::pm_auth::helpers
| 294
| true
|
// File: crates/router/src/core/authentication/types.rs
// Module: router::src::core::authentication::types
use error_stack::{Report, ResultExt};
pub use hyperswitch_domain_models::router_request_types::authentication::{
AcquirerDetails, ExternalThreeDSConnectorMetadata, PreAuthenticationData, ThreeDsMethodData,
};
use crate::{
core::errors,
types::{storage, transformers::ForeignTryFrom},
utils::OptionExt,
};
impl ForeignTryFrom<&storage::Authentication> for PreAuthenticationData {
type Error = Report<errors::ApiErrorResponse>;
fn foreign_try_from(authentication: &storage::Authentication) -> Result<Self, Self::Error> {
let error_message = errors::ApiErrorResponse::UnprocessableEntity { message: "Pre Authentication must be completed successfully before Authentication can be performed".to_string() };
let threeds_server_transaction_id = authentication
.threeds_server_transaction_id
.clone()
.get_required_value("threeds_server_transaction_id")
.change_context(error_message)?;
let message_version = authentication
.message_version
.clone()
.get_required_value("message_version")?;
Ok(Self {
threeds_server_transaction_id,
message_version,
acquirer_bin: authentication.acquirer_bin.clone(),
acquirer_merchant_id: authentication.acquirer_merchant_id.clone(),
acquirer_country_code: authentication.acquirer_country_code.clone(),
connector_metadata: authentication.connector_metadata.clone(),
})
}
}
|
crates/router/src/core/authentication/types.rs
|
router::src::core::authentication::types
| 312
| true
|
// File: crates/router/src/core/authentication/transformers.rs
// Module: router::src::core::authentication::transformers
use std::marker::PhantomData;
use api_models::payments;
use common_enums::PaymentMethod;
use common_utils::ext_traits::ValueExt;
use error_stack::ResultExt;
use crate::{
core::{
errors::{self, RouterResult},
payments::helpers as payments_helpers,
},
types::{
self, domain, storage,
transformers::{ForeignFrom, ForeignTryFrom},
},
utils::ext_traits::OptionExt,
SessionState,
};
const IRRELEVANT_ATTEMPT_ID_IN_AUTHENTICATION_FLOW: &str =
"irrelevant_attempt_id_in_AUTHENTICATION_flow";
const IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_AUTHENTICATION_FLOW: &str =
"irrelevant_connector_request_reference_id_in_AUTHENTICATION_flow";
#[allow(clippy::too_many_arguments)]
pub fn construct_authentication_router_data(
state: &SessionState,
merchant_id: common_utils::id_type::MerchantId,
authentication_connector: String,
payment_method_data: domain::PaymentMethodData,
payment_method: PaymentMethod,
billing_address: hyperswitch_domain_models::address::Address,
shipping_address: Option<hyperswitch_domain_models::address::Address>,
browser_details: Option<types::BrowserInformation>,
amount: Option<common_utils::types::MinorUnit>,
currency: Option<common_enums::Currency>,
message_category: types::api::authentication::MessageCategory,
device_channel: payments::DeviceChannel,
merchant_connector_account: payments_helpers::MerchantConnectorAccountType,
authentication_data: storage::Authentication,
return_url: Option<String>,
sdk_information: Option<payments::SdkInformation>,
threeds_method_comp_ind: payments::ThreeDsCompletionIndicator,
email: Option<common_utils::pii::Email>,
webhook_url: String,
three_ds_requestor_url: String,
psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>,
payment_id: common_utils::id_type::PaymentId,
force_3ds_challenge: bool,
) -> RouterResult<types::authentication::ConnectorAuthenticationRouterData> {
let router_request = types::authentication::ConnectorAuthenticationRequestData {
payment_method_data,
billing_address,
shipping_address,
browser_details,
amount: amount.map(|amt| amt.get_amount_as_i64()),
currency,
message_category,
device_channel,
pre_authentication_data: super::types::PreAuthenticationData::foreign_try_from(
&authentication_data,
)?,
return_url,
sdk_information,
email,
three_ds_requestor_url,
threeds_method_comp_ind,
webhook_url,
force_3ds_challenge,
};
construct_router_data(
state,
authentication_connector,
payment_method,
merchant_id.clone(),
types::PaymentAddress::default(),
router_request,
&merchant_connector_account,
psd2_sca_exemption_type,
payment_id,
)
}
pub fn construct_post_authentication_router_data(
state: &SessionState,
authentication_connector: String,
business_profile: domain::Profile,
merchant_connector_account: payments_helpers::MerchantConnectorAccountType,
authentication_data: &storage::Authentication,
payment_id: &common_utils::id_type::PaymentId,
) -> RouterResult<types::authentication::ConnectorPostAuthenticationRouterData> {
let threeds_server_transaction_id = authentication_data
.threeds_server_transaction_id
.clone()
.get_required_value("threeds_server_transaction_id")
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let router_request = types::authentication::ConnectorPostAuthenticationRequestData {
threeds_server_transaction_id,
};
construct_router_data(
state,
authentication_connector,
PaymentMethod::default(),
business_profile.merchant_id.clone(),
types::PaymentAddress::default(),
router_request,
&merchant_connector_account,
None,
payment_id.clone(),
)
}
pub fn construct_pre_authentication_router_data<F: Clone>(
state: &SessionState,
authentication_connector: String,
card: hyperswitch_domain_models::payment_method_data::Card,
merchant_connector_account: &payments_helpers::MerchantConnectorAccountType,
merchant_id: common_utils::id_type::MerchantId,
payment_id: common_utils::id_type::PaymentId,
) -> RouterResult<
types::RouterData<
F,
types::authentication::PreAuthNRequestData,
types::authentication::AuthenticationResponseData,
>,
> {
let router_request = types::authentication::PreAuthNRequestData { card };
construct_router_data(
state,
authentication_connector,
PaymentMethod::default(),
merchant_id,
types::PaymentAddress::default(),
router_request,
merchant_connector_account,
None,
payment_id,
)
}
#[allow(clippy::too_many_arguments)]
pub fn construct_router_data<F: Clone, Req, Res>(
state: &SessionState,
authentication_connector_name: String,
payment_method: PaymentMethod,
merchant_id: common_utils::id_type::MerchantId,
address: types::PaymentAddress,
request_data: Req,
merchant_connector_account: &payments_helpers::MerchantConnectorAccountType,
psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>,
payment_id: common_utils::id_type::PaymentId,
) -> RouterResult<types::RouterData<F, Req, Res>> {
let test_mode: Option<bool> = merchant_connector_account.is_test_mode_on();
let auth_type: types::ConnectorAuthType = merchant_connector_account
.get_connector_account_details()
.parse_value("ConnectorAuthType")
.change_context(errors::ApiErrorResponse::InternalServerError)?;
Ok(types::RouterData {
flow: PhantomData,
merchant_id,
customer_id: None,
tenant_id: state.tenant.tenant_id.clone(),
connector_customer: None,
connector: authentication_connector_name,
payment_id: payment_id.get_string_repr().to_owned(),
attempt_id: IRRELEVANT_ATTEMPT_ID_IN_AUTHENTICATION_FLOW.to_owned(),
status: common_enums::AttemptStatus::default(),
payment_method,
payment_method_type: None,
connector_auth_type: auth_type,
description: None,
address,
auth_type: common_enums::AuthenticationType::NoThreeDs,
connector_meta_data: merchant_connector_account.get_metadata(),
connector_wallets_details: merchant_connector_account.get_connector_wallets_details(),
amount_captured: None,
minor_amount_captured: None,
access_token: None,
session_token: None,
reference_id: None,
payment_method_token: None,
recurring_mandate_payment_data: None,
preprocessing_id: None,
payment_method_balance: None,
connector_api_version: None,
request: request_data,
response: Err(types::ErrorResponse::default()),
connector_request_reference_id:
IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_AUTHENTICATION_FLOW.to_owned(),
#[cfg(feature = "payouts")]
payout_method_data: None,
#[cfg(feature = "payouts")]
quote_id: None,
test_mode,
connector_http_status_code: None,
external_latency: None,
apple_pay_flow: None,
frm_metadata: None,
dispute_id: None,
refund_id: None,
payment_method_status: None,
connector_response: None,
integrity_check: Ok(()),
additional_merchant_data: None,
header_payload: None,
connector_mandate_request_reference_id: None,
authentication_id: None,
psd2_sca_exemption_type,
raw_connector_response: None,
is_payment_id_from_merchant: None,
l2_l3_data: None,
minor_amount_capturable: None,
authorized_amount: None,
})
}
impl ForeignFrom<common_enums::TransactionStatus> for common_enums::AuthenticationStatus {
fn foreign_from(trans_status: common_enums::TransactionStatus) -> Self {
match trans_status {
common_enums::TransactionStatus::Success => Self::Success,
common_enums::TransactionStatus::Failure
| common_enums::TransactionStatus::Rejected
| common_enums::TransactionStatus::VerificationNotPerformed
| common_enums::TransactionStatus::NotVerified => Self::Failed,
common_enums::TransactionStatus::ChallengeRequired
| common_enums::TransactionStatus::ChallengeRequiredDecoupledAuthentication
| common_enums::TransactionStatus::InformationOnly => Self::Pending,
}
}
}
|
crates/router/src/core/authentication/transformers.rs
|
router::src::core::authentication::transformers
| 1,841
| true
|
// File: crates/router/src/core/authentication/utils.rs
// Module: router::src::core::authentication::utils
use common_utils::ext_traits::AsyncExt;
use error_stack::ResultExt;
use hyperswitch_domain_models::router_data_v2::ExternalAuthenticationFlowData;
use masking::ExposeInterface;
use crate::{
consts,
core::{
errors::{self, ConnectorErrorExt, StorageErrorExt},
payments,
},
errors::RouterResult,
routes::SessionState,
services::{self, execute_connector_processing_step},
types::{
api, authentication::AuthenticationResponseData, domain, storage,
transformers::ForeignFrom, RouterData,
},
utils::OptionExt,
};
#[cfg(feature = "v1")]
pub fn get_connector_data_if_separate_authn_supported(
connector_call_type: &api::ConnectorCallType,
) -> Option<api::ConnectorData> {
match connector_call_type {
api::ConnectorCallType::PreDetermined(connector_routing_data) => {
if connector_routing_data
.connector_data
.connector_name
.is_separate_authentication_supported()
{
Some(connector_routing_data.connector_data.clone())
} else {
None
}
}
api::ConnectorCallType::Retryable(connector_routing_data) => connector_routing_data
.first()
.and_then(|connector_routing_data| {
if connector_routing_data
.connector_data
.connector_name
.is_separate_authentication_supported()
{
Some(connector_routing_data.connector_data.clone())
} else {
None
}
}),
api::ConnectorCallType::SessionMultiple(_) => None,
}
}
pub async fn update_trackers<F: Clone, Req>(
state: &SessionState,
router_data: RouterData<F, Req, AuthenticationResponseData>,
authentication: storage::Authentication,
acquirer_details: Option<super::types::AcquirerDetails>,
merchant_key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore,
) -> RouterResult<storage::Authentication> {
let authentication_update = match router_data.response {
Ok(response) => match response {
AuthenticationResponseData::PreAuthNResponse {
threeds_server_transaction_id,
maximum_supported_3ds_version,
connector_authentication_id,
three_ds_method_data,
three_ds_method_url,
message_version,
connector_metadata,
directory_server_id,
} => storage::AuthenticationUpdate::PreAuthenticationUpdate {
threeds_server_transaction_id,
maximum_supported_3ds_version,
connector_authentication_id,
three_ds_method_data,
three_ds_method_url,
message_version,
connector_metadata,
authentication_status: common_enums::AuthenticationStatus::Pending,
acquirer_bin: acquirer_details
.as_ref()
.map(|acquirer_details| acquirer_details.acquirer_bin.clone()),
acquirer_merchant_id: acquirer_details
.as_ref()
.map(|acquirer_details| acquirer_details.acquirer_merchant_id.clone()),
acquirer_country_code: acquirer_details
.and_then(|acquirer_details| acquirer_details.acquirer_country_code),
directory_server_id,
billing_address: None,
shipping_address: None,
browser_info: Box::new(None),
email: None,
},
AuthenticationResponseData::AuthNResponse {
authn_flow_type,
authentication_value,
trans_status,
connector_metadata,
ds_trans_id,
eci,
challenge_code,
challenge_cancel,
challenge_code_reason,
message_extension,
} => {
authentication_value
.async_map(|auth_val| {
crate::core::payment_methods::vault::create_tokenize(
state,
auth_val.expose(),
None,
authentication
.authentication_id
.get_string_repr()
.to_string(),
merchant_key_store.key.get_inner(),
)
})
.await
.transpose()?;
let authentication_status =
common_enums::AuthenticationStatus::foreign_from(trans_status.clone());
storage::AuthenticationUpdate::AuthenticationUpdate {
trans_status,
acs_url: authn_flow_type.get_acs_url(),
challenge_request: authn_flow_type.get_challenge_request(),
challenge_request_key: authn_flow_type.get_challenge_request_key(),
acs_reference_number: authn_flow_type.get_acs_reference_number(),
acs_trans_id: authn_flow_type.get_acs_trans_id(),
acs_signed_content: authn_flow_type.get_acs_signed_content(),
authentication_type: authn_flow_type.get_decoupled_authentication_type(),
authentication_status,
connector_metadata,
ds_trans_id,
eci,
challenge_code,
challenge_cancel,
challenge_code_reason,
message_extension,
}
}
AuthenticationResponseData::PostAuthNResponse {
trans_status,
authentication_value,
eci,
challenge_cancel,
challenge_code_reason,
} => {
authentication_value
.async_map(|auth_val| {
crate::core::payment_methods::vault::create_tokenize(
state,
auth_val.expose(),
None,
authentication
.authentication_id
.get_string_repr()
.to_string(),
merchant_key_store.key.get_inner(),
)
})
.await
.transpose()?;
storage::AuthenticationUpdate::PostAuthenticationUpdate {
authentication_status: common_enums::AuthenticationStatus::foreign_from(
trans_status.clone(),
),
trans_status,
eci,
challenge_cancel,
challenge_code_reason,
}
}
AuthenticationResponseData::PreAuthVersionCallResponse {
maximum_supported_3ds_version,
} => storage::AuthenticationUpdate::PreAuthenticationVersionCallUpdate {
message_version: maximum_supported_3ds_version.clone(),
maximum_supported_3ds_version,
},
AuthenticationResponseData::PreAuthThreeDsMethodCallResponse {
threeds_server_transaction_id,
three_ds_method_data,
three_ds_method_url,
connector_metadata,
} => storage::AuthenticationUpdate::PreAuthenticationThreeDsMethodCall {
threeds_server_transaction_id,
three_ds_method_data,
three_ds_method_url,
connector_metadata,
acquirer_bin: acquirer_details
.as_ref()
.map(|acquirer_details| acquirer_details.acquirer_bin.clone()),
acquirer_merchant_id: acquirer_details
.map(|acquirer_details| acquirer_details.acquirer_merchant_id),
},
},
Err(error) => storage::AuthenticationUpdate::ErrorUpdate {
connector_authentication_id: error.connector_transaction_id,
authentication_status: common_enums::AuthenticationStatus::Failed,
error_message: error
.reason
.map(|reason| format!("message: {}, reason: {}", error.message, reason))
.or(Some(error.message)),
error_code: Some(error.code),
},
};
state
.store
.update_authentication_by_merchant_id_authentication_id(
authentication,
authentication_update,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error while updating authentication")
}
impl ForeignFrom<common_enums::AuthenticationStatus> for common_enums::AttemptStatus {
fn foreign_from(from: common_enums::AuthenticationStatus) -> Self {
match from {
common_enums::AuthenticationStatus::Started
| common_enums::AuthenticationStatus::Pending => Self::AuthenticationPending,
common_enums::AuthenticationStatus::Success => Self::AuthenticationSuccessful,
common_enums::AuthenticationStatus::Failed => Self::AuthenticationFailed,
}
}
}
#[allow(clippy::too_many_arguments)]
pub async fn create_new_authentication(
state: &SessionState,
merchant_id: common_utils::id_type::MerchantId,
authentication_connector: String,
token: String,
profile_id: common_utils::id_type::ProfileId,
payment_id: common_utils::id_type::PaymentId,
merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId,
organization_id: common_utils::id_type::OrganizationId,
force_3ds_challenge: Option<bool>,
psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>,
) -> RouterResult<storage::Authentication> {
let authentication_id = common_utils::id_type::AuthenticationId::generate_authentication_id(
consts::AUTHENTICATION_ID_PREFIX,
);
let authentication_client_secret = Some(common_utils::generate_id_with_default_len(&format!(
"{}_secret",
authentication_id.get_string_repr()
)));
let new_authorization = storage::AuthenticationNew {
authentication_id: authentication_id.clone(),
merchant_id,
authentication_connector: Some(authentication_connector),
connector_authentication_id: None,
payment_method_id: format!("eph_{token}"),
authentication_type: None,
authentication_status: common_enums::AuthenticationStatus::Started,
authentication_lifecycle_status: common_enums::AuthenticationLifecycleStatus::Unused,
error_message: None,
error_code: None,
connector_metadata: None,
maximum_supported_version: None,
threeds_server_transaction_id: None,
cavv: None,
authentication_flow_type: None,
message_version: None,
eci: None,
trans_status: None,
acquirer_bin: None,
acquirer_merchant_id: None,
three_ds_method_data: None,
three_ds_method_url: None,
acs_url: None,
challenge_request: None,
challenge_request_key: None,
acs_reference_number: None,
acs_trans_id: None,
acs_signed_content: None,
profile_id,
payment_id: Some(payment_id),
merchant_connector_id: Some(merchant_connector_id),
ds_trans_id: None,
directory_server_id: None,
acquirer_country_code: None,
service_details: None,
organization_id,
authentication_client_secret,
force_3ds_challenge,
psd2_sca_exemption_type,
return_url: None,
amount: None,
currency: None,
billing_address: None,
shipping_address: None,
browser_info: None,
email: None,
profile_acquirer_id: None,
challenge_code: None,
challenge_cancel: None,
challenge_code_reason: None,
message_extension: None,
};
state
.store
.insert_authentication(new_authorization)
.await
.to_duplicate_response(errors::ApiErrorResponse::GenericDuplicateError {
message: format!(
"Authentication with authentication_id {} already exists",
authentication_id.get_string_repr()
),
})
}
pub async fn do_auth_connector_call<F, Req, Res>(
state: &SessionState,
authentication_connector_name: String,
router_data: RouterData<F, Req, Res>,
) -> RouterResult<RouterData<F, Req, Res>>
where
Req: std::fmt::Debug + Clone + 'static,
Res: std::fmt::Debug + Clone + 'static,
F: std::fmt::Debug + Clone + 'static,
dyn api::Connector + Sync: services::api::ConnectorIntegration<F, Req, Res>,
dyn api::ConnectorV2 + Sync:
services::api::ConnectorIntegrationV2<F, ExternalAuthenticationFlowData, Req, Res>,
{
let connector_data =
api::AuthenticationConnectorData::get_connector_by_name(&authentication_connector_name)?;
let connector_integration: services::BoxedExternalAuthenticationConnectorIntegrationInterface<
F,
Req,
Res,
> = connector_data.connector.get_connector_integration();
let router_data = execute_connector_processing_step(
state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.to_payment_failed_response()?;
Ok(router_data)
}
pub async fn get_authentication_connector_data(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
business_profile: &domain::Profile,
authentication_connector: Option<String>,
) -> RouterResult<(
common_enums::AuthenticationConnectors,
payments::helpers::MerchantConnectorAccountType,
)> {
let authentication_connector = if let Some(authentication_connector) = authentication_connector
{
api_models::enums::convert_authentication_connector(&authentication_connector).ok_or(
errors::ApiErrorResponse::UnprocessableEntity {
message: format!(
"Invalid authentication_connector found in request : {authentication_connector}",
),
},
)?
} else {
let authentication_details = business_profile
.authentication_connector_details
.clone()
.get_required_value("authentication_details")
.change_context(errors::ApiErrorResponse::UnprocessableEntity {
message: "authentication_connector_details is not available in business profile"
.into(),
})
.attach_printable("authentication_connector_details not configured by the merchant")?;
authentication_details
.authentication_connectors
.first()
.ok_or(errors::ApiErrorResponse::UnprocessableEntity {
message: format!(
"No authentication_connector found for profile_id {:?}",
business_profile.get_id()
),
})
.attach_printable(
"No authentication_connector found from merchant_account.authentication_details",
)?
.to_owned()
};
let profile_id = business_profile.get_id();
let authentication_connector_mca = payments::helpers::get_merchant_connector_account(
state,
&business_profile.merchant_id,
None,
key_store,
profile_id,
authentication_connector.to_string().as_str(),
None,
)
.await?;
Ok((authentication_connector, authentication_connector_mca))
}
|
crates/router/src/core/authentication/utils.rs
|
router::src::core::authentication::utils
| 2,886
| true
|
// File: crates/router/src/core/payouts/transformers.rs
// Module: router::src::core::payouts::transformers
use std::collections::HashMap;
use common_utils::link_utils::EnabledPaymentMethod;
#[cfg(all(feature = "v1", feature = "olap"))]
use crate::types::transformers::ForeignInto;
#[cfg(feature = "olap")]
use crate::types::{api::payments, domain, storage};
use crate::{
settings::PayoutRequiredFields,
types::{api, transformers::ForeignFrom},
};
#[cfg(all(feature = "v2", feature = "olap"))]
impl
ForeignFrom<(
storage::Payouts,
storage::PayoutAttempt,
Option<domain::Customer>,
Option<payments::Address>,
)> for api::PayoutCreateResponse
{
fn foreign_from(
item: (
storage::Payouts,
storage::PayoutAttempt,
Option<domain::Customer>,
Option<payments::Address>,
),
) -> Self {
todo!()
}
}
#[cfg(all(feature = "v1", feature = "olap"))]
impl
ForeignFrom<(
storage::Payouts,
storage::PayoutAttempt,
Option<domain::Customer>,
Option<payments::Address>,
)> for api::PayoutCreateResponse
{
fn foreign_from(
item: (
storage::Payouts,
storage::PayoutAttempt,
Option<domain::Customer>,
Option<payments::Address>,
),
) -> Self {
let (payout, payout_attempt, customer, address) = item;
let attempt = api::PayoutAttemptResponse {
attempt_id: payout_attempt.payout_attempt_id,
status: payout_attempt.status,
amount: payout.amount,
currency: Some(payout.destination_currency),
connector: payout_attempt.connector.clone(),
error_code: payout_attempt.error_code.clone(),
error_message: payout_attempt.error_message.clone(),
payment_method: payout.payout_type,
payout_method_type: None,
connector_transaction_id: payout_attempt.connector_payout_id,
cancellation_reason: None,
unified_code: None,
unified_message: None,
};
Self {
payout_id: payout.payout_id,
merchant_id: payout.merchant_id,
merchant_connector_id: payout_attempt.merchant_connector_id,
merchant_order_reference_id: payout_attempt.merchant_order_reference_id.clone(),
amount: payout.amount,
currency: payout.destination_currency,
connector: payout_attempt.connector,
payout_type: payout.payout_type,
auto_fulfill: payout.auto_fulfill,
customer_id: customer.as_ref().map(|cust| cust.customer_id.clone()),
customer: customer.as_ref().map(|cust| cust.foreign_into()),
return_url: payout.return_url,
business_country: payout_attempt.business_country,
business_label: payout_attempt.business_label,
description: payout.description,
entity_type: payout.entity_type,
recurring: payout.recurring,
metadata: payout.metadata,
status: payout_attempt.status,
error_message: payout_attempt.error_message,
error_code: payout_attempt.error_code,
profile_id: payout.profile_id,
created: Some(payout.created_at),
connector_transaction_id: attempt.connector_transaction_id.clone(),
priority: payout.priority,
billing: address,
payout_method_data: payout_attempt.additional_payout_method_data.map(From::from),
client_secret: None,
payout_link: None,
unified_code: attempt.unified_code.clone(),
unified_message: attempt.unified_message.clone(),
attempts: Some(vec![attempt]),
email: customer
.as_ref()
.and_then(|customer| customer.email.clone()),
name: customer.as_ref().and_then(|customer| customer.name.clone()),
phone: customer
.as_ref()
.and_then(|customer| customer.phone.clone()),
phone_country_code: customer
.as_ref()
.and_then(|customer| customer.phone_country_code.clone()),
payout_method_id: payout.payout_method_id,
}
}
}
#[cfg(feature = "v1")]
impl
ForeignFrom<(
&PayoutRequiredFields,
Vec<EnabledPaymentMethod>,
api::RequiredFieldsOverrideRequest,
)> for Vec<api::PayoutEnabledPaymentMethodsInfo>
{
fn foreign_from(
(payout_required_fields, enabled_payout_methods, value_overrides): (
&PayoutRequiredFields,
Vec<EnabledPaymentMethod>,
api::RequiredFieldsOverrideRequest,
),
) -> Self {
let value_overrides = value_overrides.flat_struct();
enabled_payout_methods
.into_iter()
.map(|enabled_payout_method| {
let payment_method = enabled_payout_method.payment_method;
let payment_method_types_info = enabled_payout_method
.payment_method_types
.into_iter()
.filter_map(|pmt| {
payout_required_fields
.0
.get(&payment_method)
.and_then(|pmt_info| {
pmt_info.0.get(&pmt).map(|connector_fields| {
let mut required_fields = HashMap::new();
for required_field_final in connector_fields.fields.values() {
required_fields.extend(required_field_final.common.clone());
}
for (key, value) in &value_overrides {
required_fields.entry(key.to_string()).and_modify(
|required_field| {
required_field.value =
Some(masking::Secret::new(value.to_string()));
},
);
}
api::PaymentMethodTypeInfo {
payment_method_type: pmt,
required_fields: if required_fields.is_empty() {
None
} else {
Some(required_fields)
},
}
})
})
.or(Some(api::PaymentMethodTypeInfo {
payment_method_type: pmt,
required_fields: None,
}))
})
.collect();
api::PayoutEnabledPaymentMethodsInfo {
payment_method,
payment_method_types_info,
}
})
.collect()
}
}
|
crates/router/src/core/payouts/transformers.rs
|
router::src::core::payouts::transformers
| 1,294
| true
|
// File: crates/router/src/core/payouts/validator.rs
// Module: router::src::core::payouts::validator
use std::collections::HashSet;
use actix_web::http::header;
#[cfg(feature = "olap")]
use common_utils::errors::CustomResult;
use common_utils::{
id_type::{self, GenerateId},
validation::validate_domain_against_allowed_domains,
};
use diesel_models::generic_link::PayoutLink;
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::payment_methods::PaymentMethod;
use router_env::{instrument, tracing, which as router_env_which, Env};
use url::Url;
use super::helpers;
#[cfg(feature = "v1")]
use crate::core::payment_methods::cards::get_pm_list_context;
use crate::{
core::{
errors::{self, RouterResult},
utils as core_utils,
},
db::StorageInterface,
errors::StorageError,
routes::SessionState,
types::{api::payouts, domain, storage},
utils,
utils::OptionExt,
};
#[instrument(skip(db))]
pub async fn validate_uniqueness_of_payout_id_against_merchant_id(
db: &dyn StorageInterface,
payout_id: &id_type::PayoutId,
merchant_id: &id_type::MerchantId,
storage_scheme: storage::enums::MerchantStorageScheme,
) -> RouterResult<Option<storage::Payouts>> {
let maybe_payouts = db
.find_optional_payout_by_merchant_id_payout_id(merchant_id, payout_id, storage_scheme)
.await;
match maybe_payouts {
Err(err) => {
let storage_err = err.current_context();
match storage_err {
StorageError::ValueNotFound(_) => Ok(None),
_ => Err(err
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while finding payout_attempt, database error")),
}
}
Ok(payout) => Ok(payout),
}
}
#[cfg(feature = "v2")]
pub async fn validate_create_request(
_state: &SessionState,
_merchant_context: &domain::MerchantContext,
_req: &payouts::PayoutCreateRequest,
) -> RouterResult<(
String,
Option<payouts::PayoutMethodData>,
String,
Option<domain::Customer>,
Option<PaymentMethod>,
)> {
todo!()
}
/// Validates the request on below checks
/// - merchant_id passed is same as the one in merchant_account table
/// - payout_id is unique against merchant_id
/// - payout_token provided is legitimate
#[cfg(feature = "v1")]
pub async fn validate_create_request(
state: &SessionState,
merchant_context: &domain::MerchantContext,
req: &payouts::PayoutCreateRequest,
) -> RouterResult<(
id_type::PayoutId,
Option<payouts::PayoutMethodData>,
id_type::ProfileId,
Option<domain::Customer>,
Option<PaymentMethod>,
)> {
if req.payout_method_id.is_some() && req.confirm != Some(true) {
return Err(report!(errors::ApiErrorResponse::InvalidRequestData {
message: "Confirm must be true for recurring payouts".to_string(),
}));
}
let merchant_id = merchant_context.get_merchant_account().get_id();
if let Some(payout_link) = &req.payout_link {
if *payout_link {
validate_payout_link_request(req)?;
}
};
// Merchant ID
let predicate = req.merchant_id.as_ref().map(|mid| mid != merchant_id);
utils::when(predicate.unwrap_or(false), || {
Err(report!(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "merchant_id".to_string(),
expected_format: "merchant_id from merchant account".to_string(),
})
.attach_printable("invalid merchant_id in request"))
})?;
// Payout ID
let db: &dyn StorageInterface = &*state.store;
let payout_id = match req.payout_id.as_ref() {
Some(provided_payout_id) => provided_payout_id.clone(),
None => id_type::PayoutId::generate(),
};
match validate_uniqueness_of_payout_id_against_merchant_id(
db,
&payout_id,
merchant_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.attach_printable_lazy(|| {
format!(
"Unique violation while checking payout_id: {payout_id:?} against merchant_id: {merchant_id:?}"
)
})? {
Some(_) => Err(report!(errors::ApiErrorResponse::DuplicatePayout {
payout_id: payout_id.clone()
})),
None => Ok(()),
}?;
// Fetch customer details (merge of loose fields + customer object) and create DB entry
let customer_in_request = helpers::get_customer_details_from_request(req);
let customer = if customer_in_request.customer_id.is_some()
|| customer_in_request.name.is_some()
|| customer_in_request.email.is_some()
|| customer_in_request.phone.is_some()
|| customer_in_request.phone_country_code.is_some()
{
helpers::get_or_create_customer_details(state, &customer_in_request, merchant_context)
.await?
} else {
None
};
#[cfg(feature = "v1")]
let profile_id = core_utils::get_profile_id_from_business_details(
&state.into(),
req.business_country,
req.business_label.as_ref(),
merchant_context,
req.profile_id.as_ref(),
&*state.store,
false,
)
.await?;
#[cfg(feature = "v2")]
// Profile id will be mandatory in v2 in the request / headers
let profile_id = req
.profile_id
.clone()
.ok_or(errors::ApiErrorResponse::MissingRequiredField {
field_name: "profile_id",
})
.attach_printable("Profile id is a mandatory parameter")?;
let payment_method: Option<PaymentMethod> =
match (req.payout_token.as_ref(), req.payout_method_id.clone()) {
(Some(_), Some(_)) => Err(report!(errors::ApiErrorResponse::InvalidRequestData {
message: "Only one of payout_method_id or payout_token should be provided."
.to_string(),
})),
(None, Some(payment_method_id)) => match customer.as_ref() {
Some(customer) => {
let payment_method = db
.find_payment_method(
&state.into(),
merchant_context.get_merchant_key_store(),
&payment_method_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::PaymentMethodNotFound)
.attach_printable("Unable to find payment method")?;
utils::when(payment_method.customer_id != customer.customer_id, || {
Err(report!(errors::ApiErrorResponse::InvalidRequestData {
message: "Payment method does not belong to this customer_id".to_string(),
})
.attach_printable(
"customer_id in payment_method does not match with customer_id in request",
))
})?;
Ok(Some(payment_method))
}
None => Err(report!(errors::ApiErrorResponse::MissingRequiredField {
field_name: "customer_id when payment_method_id is passed",
})),
},
_ => Ok(None),
}?;
// payout_token
let payout_method_data = match (
req.payout_token.as_ref(),
customer.as_ref(),
payment_method.as_ref(),
) {
(Some(_), None, _) => Err(report!(errors::ApiErrorResponse::MissingRequiredField {
field_name: "customer or customer_id when payout_token is provided"
})),
(Some(payout_token), Some(customer), _) => {
helpers::make_payout_method_data(
state,
req.payout_method_data.as_ref(),
Some(payout_token),
&customer.customer_id,
merchant_context.get_merchant_account().get_id(),
req.payout_type,
merchant_context.get_merchant_key_store(),
None,
merchant_context.get_merchant_account().storage_scheme,
)
.await
}
(_, Some(_), Some(payment_method)) => {
// Check if we have a stored transfer_method_id first
if payment_method
.get_common_mandate_reference()
.ok()
.and_then(|common_mandate_ref| common_mandate_ref.payouts)
.map(|payouts_mandate_ref| !payouts_mandate_ref.0.is_empty())
.unwrap_or(false)
{
Ok(None)
} else {
// No transfer_method_id available, proceed with vault fetch for raw card details
match get_pm_list_context(
state,
payment_method
.payment_method
.as_ref()
.get_required_value("payment_method_id")?,
merchant_context.get_merchant_key_store(),
payment_method,
None,
false,
true,
merchant_context,
)
.await?
{
Some(pm) => match (pm.card_details, pm.bank_transfer_details) {
(Some(card), _) => Ok(Some(payouts::PayoutMethodData::Card(
api_models::payouts::CardPayout {
card_number: card.card_number.get_required_value("card_number")?,
card_holder_name: card.card_holder_name,
expiry_month: card
.expiry_month
.get_required_value("expiry_month")?,
expiry_year: card.expiry_year.get_required_value("expiry_year")?,
},
))),
(_, Some(bank)) => Ok(Some(payouts::PayoutMethodData::Bank(bank))),
_ => Ok(None),
},
None => Ok(None),
}
}
}
_ => Ok(None),
}?;
Ok((
payout_id,
payout_method_data,
profile_id,
customer,
payment_method,
))
}
pub fn validate_payout_link_request(
req: &payouts::PayoutCreateRequest,
) -> Result<(), errors::ApiErrorResponse> {
if req.confirm.unwrap_or(false) {
return Err(errors::ApiErrorResponse::InvalidRequestData {
message: "cannot confirm a payout while creating a payout link".to_string(),
});
}
if req.customer_id.is_none() {
return Err(errors::ApiErrorResponse::MissingRequiredField {
field_name: "customer or customer_id when payout_link is true",
});
}
Ok(())
}
#[cfg(feature = "olap")]
pub(super) fn validate_payout_list_request(
req: &payouts::PayoutListConstraints,
) -> CustomResult<(), errors::ApiErrorResponse> {
use common_utils::consts::PAYOUTS_LIST_MAX_LIMIT_GET;
utils::when(
req.limit > PAYOUTS_LIST_MAX_LIMIT_GET || req.limit < 1,
|| {
Err(errors::ApiErrorResponse::InvalidRequestData {
message: format!("limit should be in between 1 and {PAYOUTS_LIST_MAX_LIMIT_GET}"),
})
},
)?;
Ok(())
}
#[cfg(feature = "olap")]
pub(super) fn validate_payout_list_request_for_joins(
limit: u32,
) -> CustomResult<(), errors::ApiErrorResponse> {
use common_utils::consts::PAYOUTS_LIST_MAX_LIMIT_POST;
utils::when(!(1..=PAYOUTS_LIST_MAX_LIMIT_POST).contains(&limit), || {
Err(errors::ApiErrorResponse::InvalidRequestData {
message: format!("limit should be in between 1 and {PAYOUTS_LIST_MAX_LIMIT_POST}"),
})
})?;
Ok(())
}
pub fn validate_payout_link_render_request_and_get_allowed_domains(
request_headers: &header::HeaderMap,
payout_link: &PayoutLink,
) -> RouterResult<HashSet<String>> {
let link_id = payout_link.link_id.to_owned();
let link_data = payout_link.link_data.to_owned();
let is_test_mode_enabled = link_data.test_mode.unwrap_or(false);
match (router_env_which(), is_test_mode_enabled) {
// Throw error in case test_mode was enabled in production
(Env::Production, true) => Err(report!(errors::ApiErrorResponse::LinkConfigurationError {
message: "test_mode cannot be true for rendering payout_links in production"
.to_string()
})),
// Skip all validations when test mode is enabled in non prod env
(_, true) => Ok(HashSet::new()),
// Otherwise, perform validations
(_, false) => {
// Fetch destination is "iframe"
match request_headers.get("sec-fetch-dest").and_then(|v| v.to_str().ok()) {
Some("iframe") => Ok(()),
Some(requestor) => Err(report!(errors::ApiErrorResponse::AccessForbidden {
resource: "payout_link".to_string(),
}))
.attach_printable_lazy(|| {
format!(
"Access to payout_link [{link_id}] is forbidden when requested through {requestor}",
)
}),
None => Err(report!(errors::ApiErrorResponse::AccessForbidden {
resource: "payout_link".to_string(),
}))
.attach_printable_lazy(|| {
format!(
"Access to payout_link [{link_id}] is forbidden when sec-fetch-dest is not present in request headers",
)
}),
}?;
// Validate origin / referer
let domain_in_req = {
let origin_or_referer = request_headers
.get("origin")
.or_else(|| request_headers.get("referer"))
.and_then(|v| v.to_str().ok())
.ok_or_else(|| {
report!(errors::ApiErrorResponse::AccessForbidden {
resource: "payout_link".to_string(),
})
})
.attach_printable_lazy(|| {
format!(
"Access to payout_link [{link_id}] is forbidden when origin or referer is not present in request headers",
)
})?;
let url = Url::parse(origin_or_referer)
.map_err(|_| {
report!(errors::ApiErrorResponse::AccessForbidden {
resource: "payout_link".to_string(),
})
})
.attach_printable_lazy(|| {
format!("Invalid URL found in request headers {origin_or_referer}")
})?;
url.host_str()
.and_then(|host| url.port().map(|port| format!("{host}:{port}")))
.or_else(|| url.host_str().map(String::from))
.ok_or_else(|| {
report!(errors::ApiErrorResponse::AccessForbidden {
resource: "payout_link".to_string(),
})
})
.attach_printable_lazy(|| {
format!("host or port not found in request headers {url:?}")
})?
};
if validate_domain_against_allowed_domains(
&domain_in_req,
link_data.allowed_domains.clone(),
) {
Ok(link_data.allowed_domains)
} else {
Err(report!(errors::ApiErrorResponse::AccessForbidden {
resource: "payout_link".to_string(),
}))
.attach_printable_lazy(|| {
format!(
"Access to payout_link [{link_id}] is forbidden from requestor - {domain_in_req}",
)
})
}
}
}
}
|
crates/router/src/core/payouts/validator.rs
|
router::src::core::payouts::validator
| 3,273
| true
|
// File: crates/router/src/core/payouts/access_token.rs
// Module: router::src::core::payouts::access_token
use common_utils::ext_traits::AsyncExt;
use error_stack::ResultExt;
use crate::{
consts,
core::{
errors::{self, RouterResult},
payments,
},
routes::{metrics, SessionState},
services,
types::{self, api as api_types, domain, storage::enums},
};
/// After we get the access token, check if there was an error and if the flow should proceed further
/// Everything is well, continue with the flow
/// There was an error, cannot proceed further
#[cfg(feature = "payouts")]
pub async fn create_access_token<F: Clone + 'static>(
state: &SessionState,
connector_data: &api_types::ConnectorData,
merchant_context: &domain::MerchantContext,
router_data: &mut types::PayoutsRouterData<F>,
payout_type: Option<enums::PayoutType>,
) -> RouterResult<()> {
let connector_access_token = add_access_token_for_payout(
state,
connector_data,
merchant_context,
router_data,
payout_type,
)
.await?;
if connector_access_token.connector_supports_access_token {
match connector_access_token.access_token_result {
Ok(access_token) => {
router_data.access_token = access_token;
}
Err(connector_error) => {
router_data.response = Err(connector_error);
}
}
}
Ok(())
}
#[cfg(feature = "payouts")]
pub async fn add_access_token_for_payout<F: Clone + 'static>(
state: &SessionState,
connector: &api_types::ConnectorData,
merchant_context: &domain::MerchantContext,
router_data: &types::PayoutsRouterData<F>,
payout_type: Option<enums::PayoutType>,
) -> RouterResult<types::AddAccessTokenResult> {
use crate::types::api::ConnectorCommon;
if connector
.connector_name
.supports_access_token_for_payout(payout_type)
{
let merchant_id = merchant_context.get_merchant_account().get_id();
let store = &*state.store;
let old_access_token = store
.get_access_token(merchant_id, connector.connector.id())
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("DB error when accessing the access token")?;
let res = match old_access_token {
Some(access_token) => Ok(Some(access_token)),
None => {
let cloned_router_data = router_data.clone();
let refresh_token_request_data = types::AccessTokenRequestData::try_from(
router_data.connector_auth_type.clone(),
)
.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 {
//Store the access token in db
let store = &*state.store;
// This error should not be propagated, we don't want payments to fail once we have
// the access token, the next request will create new access token
let _ = store
.set_access_token(
merchant_id,
connector.connector.id(),
access_token.clone(),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("DB error when setting the access token");
Some(access_token)
})
.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,
})
}
}
#[cfg(feature = "payouts")]
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)
}
|
crates/router/src/core/payouts/access_token.rs
|
router::src::core::payouts::access_token
| 1,374
| true
|
// File: crates/router/src/core/payouts/helpers.rs
// Module: router::src::core::payouts::helpers
use ::payment_methods::controller::PaymentMethodsController;
use api_models::{enums, payment_methods::Card, payouts};
use common_utils::{
crypto::Encryptable,
encryption::Encryption,
errors::CustomResult,
ext_traits::{AsyncExt, StringExt, ValueExt},
fp_utils, id_type, payout_method_utils as payout_additional, pii, type_name,
types::{
keymanager::{Identifier, KeyManagerState},
MinorUnit, UnifiedCode, UnifiedMessage,
},
};
#[cfg(feature = "v1")]
use common_utils::{generate_customer_id_of_default_length, types::keymanager::ToEncryptable};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::type_encryption::{crypto_operation, CryptoOperation};
use masking::{ExposeInterface, PeekInterface, Secret, SwitchStrategy};
use router_env::logger;
use super::PayoutData;
#[cfg(feature = "payouts")]
use crate::core::payments::route_connector_v1_for_payouts;
use crate::{
consts,
core::{
errors::{self, RouterResult, StorageErrorExt},
payment_methods::{
cards,
transformers::{DataDuplicationCheck, StoreCardReq, StoreGenericReq, StoreLockerReq},
vault,
},
payments::{helpers as payment_helpers, routing, CustomerDetails},
routing::TransactionData,
utils as core_utils,
},
db::StorageInterface,
routes::{metrics, SessionState},
services,
types::{
self as router_types,
api::{self, enums as api_enums},
domain::{self, types::AsyncLift},
storage,
transformers::ForeignFrom,
},
utils::{self, OptionExt},
};
#[allow(clippy::too_many_arguments)]
pub async fn make_payout_method_data(
state: &SessionState,
payout_method_data: Option<&api::PayoutMethodData>,
payout_token: Option<&str>,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
payout_type: Option<api_enums::PayoutType>,
merchant_key_store: &domain::MerchantKeyStore,
payout_data: Option<&mut PayoutData>,
storage_scheme: storage::enums::MerchantStorageScheme,
) -> RouterResult<Option<api::PayoutMethodData>> {
let db = &*state.store;
let hyperswitch_token = if let Some(payout_token) = payout_token {
if payout_token.starts_with("temporary_token_") {
Some(payout_token.to_string())
} else {
let certain_payout_type = payout_type.get_required_value("payout_type")?.to_owned();
let key = format!(
"pm_token_{}_{}_hyperswitch",
payout_token,
api_enums::PaymentMethod::foreign_from(certain_payout_type)
);
let redis_conn = state
.store
.get_redis_conn()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get redis connection")?;
let hyperswitch_token = redis_conn
.get_key::<Option<String>>(&key.into())
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to fetch the token from redis")?
.ok_or(error_stack::Report::new(
errors::ApiErrorResponse::UnprocessableEntity {
message: "Token is invalid or expired".to_owned(),
},
))?;
let payment_token_data = hyperswitch_token
.clone()
.parse_struct("PaymentTokenData")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed to deserialize hyperswitch token data")?;
let payment_token = match payment_token_data {
storage::PaymentTokenData::PermanentCard(storage::CardTokenData {
locker_id,
token,
..
}) => locker_id.or(Some(token)),
storage::PaymentTokenData::TemporaryGeneric(storage::GenericTokenData {
token,
}) => Some(token),
_ => None,
};
payment_token.or(Some(payout_token.to_string()))
}
} else {
None
};
match (
payout_method_data.to_owned(),
hyperswitch_token,
payout_data,
) {
// Get operation
(None, Some(payout_token), _) => {
if payout_token.starts_with("temporary_token_")
|| payout_type == Some(api_enums::PayoutType::Bank)
{
let (pm, supplementary_data) = vault::Vault::get_payout_method_data_from_temporary_locker(
state,
&payout_token,
merchant_key_store,
)
.await
.attach_printable(
"Payout method for given token not found or there was a problem fetching it",
)?;
utils::when(
supplementary_data
.customer_id
.ne(&Some(customer_id.to_owned())),
|| {
Err(errors::ApiErrorResponse::PreconditionFailed { message: "customer associated with payout method and customer passed in payout are not same".into() })
},
)?;
Ok(pm)
} else {
let resp = cards::get_card_from_locker(
state,
customer_id,
merchant_id,
payout_token.as_ref(),
)
.await
.attach_printable("Payout method [card] could not be fetched from HS locker")?;
Ok(Some({
api::PayoutMethodData::Card(api::CardPayout {
card_number: resp.card_number,
expiry_month: resp.card_exp_month,
expiry_year: resp.card_exp_year,
card_holder_name: resp.name_on_card,
})
}))
}
}
// Create / Update operation
(Some(payout_method), payout_token, Some(payout_data)) => {
let lookup_key = vault::Vault::store_payout_method_data_in_locker(
state,
payout_token.to_owned(),
payout_method,
Some(customer_id.to_owned()),
merchant_key_store,
)
.await?;
// Update payout_token in payout_attempt table
if payout_token.is_none() {
let updated_payout_attempt = storage::PayoutAttemptUpdate::PayoutTokenUpdate {
payout_token: lookup_key,
};
payout_data.payout_attempt = db
.update_payout_attempt(
&payout_data.payout_attempt,
updated_payout_attempt,
&payout_data.payouts,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating token in payout attempt")?;
}
Ok(Some(payout_method.clone()))
}
// Ignore if nothing is passed
_ => Ok(None),
}
}
pub fn should_create_connector_transfer_method(
payout_data: &PayoutData,
connector_data: &api::ConnectorData,
) -> RouterResult<Option<String>> {
let connector_transfer_method_id = payout_data.payment_method.as_ref().and_then(|pm| {
let common_mandate_reference = pm
.get_common_mandate_reference()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to deserialize connector mandate details")
.ok()?;
connector_data
.merchant_connector_id
.as_ref()
.and_then(|merchant_connector_id| {
common_mandate_reference
.payouts
.and_then(|payouts_mandate_reference| {
payouts_mandate_reference
.get(merchant_connector_id)
.and_then(|payouts_mandate_reference_record| {
payouts_mandate_reference_record.transfer_method_id.clone()
})
})
})
});
Ok(connector_transfer_method_id)
}
pub async fn fetch_payout_method_data(
state: &SessionState,
payout_data: &mut PayoutData,
connector_data: &api::ConnectorData,
merchant_context: &domain::MerchantContext,
) -> RouterResult<()> {
let connector_transfer_method_id =
should_create_connector_transfer_method(payout_data, connector_data)?;
if connector_transfer_method_id.is_some() {
logger::info!("Using stored transfer_method_id, skipping payout_method_data fetch");
} else {
let customer_id = payout_data
.payouts
.customer_id
.clone()
.get_required_value("customer_id")?;
let payout_method_data_clone = payout_data.payout_method_data.clone();
let payout_token = payout_data.payout_attempt.payout_token.clone();
let merchant_id = payout_data.payout_attempt.merchant_id.clone();
let payout_type = payout_data.payouts.payout_type;
let payout_method_data = make_payout_method_data(
state,
payout_method_data_clone.as_ref(),
payout_token.as_deref(),
&customer_id,
&merchant_id,
payout_type,
merchant_context.get_merchant_key_store(),
Some(payout_data),
merchant_context.get_merchant_account().storage_scheme,
)
.await?
.get_required_value("payout_method_data")?;
payout_data.payout_method_data = Some(payout_method_data);
}
Ok(())
}
#[cfg(feature = "v1")]
pub async fn save_payout_data_to_locker(
state: &SessionState,
payout_data: &mut PayoutData,
customer_id: &id_type::CustomerId,
payout_method_data: &api::PayoutMethodData,
connector_mandate_details: Option<serde_json::Value>,
merchant_context: &domain::MerchantContext,
) -> RouterResult<()> {
let mut pm_id: Option<String> = None;
let payouts = &payout_data.payouts;
let key_manager_state = state.into();
let (mut locker_req, card_details, bank_details, wallet_details, payment_method_type) =
match payout_method_data {
payouts::PayoutMethodData::Card(card) => {
let card_detail = api::CardDetail {
card_number: card.card_number.to_owned(),
card_holder_name: card.card_holder_name.to_owned(),
card_exp_month: card.expiry_month.to_owned(),
card_exp_year: card.expiry_year.to_owned(),
nick_name: None,
card_issuing_country: None,
card_network: None,
card_issuer: None,
card_type: None,
};
let payload = StoreLockerReq::LockerCard(StoreCardReq {
merchant_id: merchant_context.get_merchant_account().get_id().clone(),
merchant_customer_id: customer_id.to_owned(),
card: Card {
card_number: card.card_number.to_owned(),
name_on_card: card.card_holder_name.to_owned(),
card_exp_month: card.expiry_month.to_owned(),
card_exp_year: card.expiry_year.to_owned(),
card_brand: None,
card_isin: None,
nick_name: None,
},
requestor_card_reference: None,
ttl: state.conf.locker.ttl_for_storage_in_secs,
});
(
payload,
Some(card_detail),
None,
None,
api_enums::PaymentMethodType::Debit,
)
}
_ => {
let key = merchant_context
.get_merchant_key_store()
.key
.get_inner()
.peek();
let key_manager_state: KeyManagerState = state.into();
let enc_data = async {
serde_json::to_value(payout_method_data.to_owned())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encode payout method data")
.ok()
.map(|v| {
let secret: Secret<String> = Secret::new(v.to_string());
secret
})
.async_lift(|inner| async {
crypto_operation(
&key_manager_state,
type_name!(storage::PaymentMethod),
CryptoOperation::EncryptOptional(inner),
Identifier::Merchant(
merchant_context
.get_merchant_key_store()
.merchant_id
.clone(),
),
key,
)
.await
.and_then(|val| val.try_into_optionaloperation())
})
.await
}
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to encrypt payout method data")?
.map(Encryption::from)
.map(|e| e.into_inner())
.map_or(Err(errors::ApiErrorResponse::InternalServerError), |e| {
Ok(hex::encode(e.peek()))
})?;
let payload = StoreLockerReq::LockerGeneric(StoreGenericReq {
merchant_id: merchant_context.get_merchant_account().get_id().to_owned(),
merchant_customer_id: customer_id.to_owned(),
enc_data,
ttl: state.conf.locker.ttl_for_storage_in_secs,
});
match payout_method_data {
payouts::PayoutMethodData::Bank(bank) => (
payload,
None,
Some(bank.to_owned()),
None,
api_enums::PaymentMethodType::foreign_from(bank),
),
payouts::PayoutMethodData::Wallet(wallet) => (
payload,
None,
None,
Some(wallet.to_owned()),
api_enums::PaymentMethodType::foreign_from(wallet),
),
payouts::PayoutMethodData::Card(_)
| payouts::PayoutMethodData::BankRedirect(_) => {
Err(errors::ApiErrorResponse::InternalServerError)?
}
}
}
};
// Store payout method in locker
let stored_resp = cards::add_card_to_hs_locker(
state,
&locker_req,
customer_id,
api_enums::LockerChoice::HyperswitchCardVault,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let db = &*state.store;
// Handle duplicates
let (should_insert_in_pm_table, metadata_update) = match stored_resp.duplication_check {
// Check if equivalent entry exists in payment_methods
Some(duplication_check) => {
let locker_ref = stored_resp.card_reference.clone();
// Use locker ref as payment_method_id
let existing_pm_by_pmid = db
.find_payment_method(
&(state.into()),
merchant_context.get_merchant_key_store(),
&locker_ref,
merchant_context.get_merchant_account().storage_scheme,
)
.await;
match existing_pm_by_pmid {
// If found, update locker's metadata [DELETE + INSERT OP], don't insert in payment_method's table
Ok(pm) => {
pm_id = Some(pm.payment_method_id.clone());
(
false,
if duplication_check == DataDuplicationCheck::MetaDataChanged {
Some(pm.clone())
} else {
None
},
)
}
// If not found, use locker ref as locker_id
Err(err) => {
if err.current_context().is_db_not_found() {
match db
.find_payment_method_by_locker_id(
&(state.into()),
merchant_context.get_merchant_key_store(),
&locker_ref,
merchant_context.get_merchant_account().storage_scheme,
)
.await
{
// If found, update locker's metadata [DELETE + INSERT OP], don't insert in payment_methods table
Ok(pm) => {
pm_id = Some(pm.payment_method_id.clone());
(
false,
if duplication_check == DataDuplicationCheck::MetaDataChanged {
Some(pm.clone())
} else {
None
},
)
}
Err(err) => {
// If not found, update locker's metadata [DELETE + INSERT OP], and insert in payment_methods table
if err.current_context().is_db_not_found() {
(true, None)
// Misc. DB errors
} else {
Err(err)
.change_context(
errors::ApiErrorResponse::InternalServerError,
)
.attach_printable(
"DB failures while finding payment method by locker ID",
)?
}
}
}
// Misc. DB errors
} else {
Err(err)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("DB failures while finding payment method by pm ID")?
}
}
}
}
// Not duplicate, should be inserted in payment_methods table
None => (true, None),
};
// Form payment method entry and card's metadata whenever insertion or metadata update is required
let (card_details_encrypted, new_payment_method) =
if let (api::PayoutMethodData::Card(_), true, _)
| (api::PayoutMethodData::Card(_), _, Some(_)) = (
payout_method_data,
should_insert_in_pm_table,
metadata_update.as_ref(),
) {
// Fetch card info from db
let card_isin = card_details.as_ref().map(|c| c.card_number.get_card_isin());
let mut payment_method = api::PaymentMethodCreate {
payment_method: Some(api_enums::PaymentMethod::foreign_from(payout_method_data)),
payment_method_type: Some(payment_method_type),
payment_method_issuer: None,
payment_method_issuer_code: None,
bank_transfer: None,
card: card_details.clone(),
wallet: None,
metadata: None,
customer_id: Some(customer_id.to_owned()),
card_network: None,
client_secret: None,
payment_method_data: None,
billing: None,
connector_mandate_details: None,
network_transaction_id: None,
};
let pm_data = 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| {
payment_method
.payment_method_issuer
.clone_from(&card_info.card_issuer);
payment_method.card_network =
card_info.card_network.clone().map(|cn| cn.to_string());
api::payment_methods::PaymentMethodsData::Card(
api::payment_methods::CardDetailsPaymentMethod {
last4_digits: card_details.as_ref().map(|c| c.card_number.get_last4()),
issuer_country: card_info.card_issuing_country,
expiry_month: card_details.as_ref().map(|c| c.card_exp_month.clone()),
expiry_year: card_details.as_ref().map(|c| c.card_exp_year.clone()),
nick_name: card_details.as_ref().and_then(|c| c.nick_name.clone()),
card_holder_name: card_details
.as_ref()
.and_then(|c| c.card_holder_name.clone()),
card_isin: card_isin.clone(),
card_issuer: card_info.card_issuer,
card_network: card_info.card_network,
card_type: card_info.card_type,
saved_to_locker: true,
co_badged_card_data: None,
},
)
})
.unwrap_or_else(|| {
api::payment_methods::PaymentMethodsData::Card(
api::payment_methods::CardDetailsPaymentMethod {
last4_digits: card_details.as_ref().map(|c| c.card_number.get_last4()),
issuer_country: None,
expiry_month: card_details.as_ref().map(|c| c.card_exp_month.clone()),
expiry_year: card_details.as_ref().map(|c| c.card_exp_year.clone()),
nick_name: card_details.as_ref().and_then(|c| c.nick_name.clone()),
card_holder_name: card_details
.as_ref()
.and_then(|c| c.card_holder_name.clone()),
card_isin: card_isin.clone(),
card_issuer: None,
card_network: None,
card_type: None,
saved_to_locker: true,
co_badged_card_data: None,
},
)
});
(
Some(
cards::create_encrypted_data(
&key_manager_state,
merchant_context.get_merchant_key_store(),
pm_data,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt customer details")?,
),
payment_method,
)
} else {
(
None,
api::PaymentMethodCreate {
payment_method: Some(api_enums::PaymentMethod::foreign_from(
payout_method_data,
)),
payment_method_type: Some(payment_method_type),
payment_method_issuer: None,
payment_method_issuer_code: None,
bank_transfer: bank_details,
card: None,
wallet: wallet_details,
metadata: None,
customer_id: Some(customer_id.to_owned()),
card_network: None,
client_secret: None,
payment_method_data: None,
billing: None,
connector_mandate_details: None,
network_transaction_id: None,
},
)
};
let payment_method_billing_address = payout_data
.billing_address
.clone()
.async_map(|billing_addr| async {
cards::create_encrypted_data(
&key_manager_state,
merchant_context.get_merchant_key_store(),
billing_addr,
)
.await
})
.await
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt billing address")?;
// Insert new entry in payment_methods table
if should_insert_in_pm_table {
let payment_method_id = common_utils::generate_id(consts::ID_LENGTH, "pm");
payout_data.payment_method = Some(
cards::PmCards {
state,
merchant_context,
}
.create_payment_method(
&new_payment_method,
customer_id,
&payment_method_id,
Some(stored_resp.card_reference.clone()),
merchant_context.get_merchant_account().get_id(),
None,
None,
card_details_encrypted.clone(),
connector_mandate_details,
None,
None,
payment_method_billing_address,
None,
None,
None,
None,
Default::default(),
)
.await?,
);
}
/* 1. Delete from locker
* 2. Create new entry in locker
* 3. Handle creation response from locker
* 4. Update card's metadata in payment_methods table
*/
if let Some(existing_pm) = metadata_update {
let card_reference = &existing_pm
.locker_id
.clone()
.unwrap_or(existing_pm.payment_method_id.clone());
// Delete from locker
cards::delete_card_from_hs_locker(
state,
customer_id,
merchant_context.get_merchant_account().get_id(),
card_reference,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Failed to delete PMD from locker as a part of metadata update operation",
)?;
locker_req.update_requestor_card_reference(Some(card_reference.to_string()));
// Store in locker
let stored_resp = cards::add_card_to_hs_locker(
state,
&locker_req,
customer_id,
api_enums::LockerChoice::HyperswitchCardVault,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError);
// Check if locker operation was successful or not, if not, delete the entry from payment_methods table
if let Err(err) = stored_resp {
logger::error!(vault_err=?err);
db.delete_payment_method_by_merchant_id_payment_method_id(
&(state.into()),
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().get_id(),
&existing_pm.payment_method_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
Err(errors::ApiErrorResponse::InternalServerError).attach_printable(
"Failed to insert PMD from locker as a part of metadata update operation",
)?
};
// Update card's metadata in payment_methods table
let pm_update = storage::PaymentMethodUpdate::PaymentMethodDataUpdate {
payment_method_data: card_details_encrypted.map(Into::into),
};
payout_data.payment_method = Some(
db.update_payment_method(
&(state.into()),
merchant_context.get_merchant_key_store(),
existing_pm,
pm_update,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to add payment method in db")?,
);
};
// Store card_reference in payouts table
let payout_method_id = match &payout_data.payment_method {
Some(pm) => pm.payment_method_id.clone(),
None => {
if let Some(id) = pm_id {
id
} else {
Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Payment method was not found")?
}
}
};
let updated_payout = storage::PayoutsUpdate::PayoutMethodIdUpdate { payout_method_id };
payout_data.payouts = db
.update_payout(
payouts,
updated_payout,
&payout_data.payout_attempt,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating payouts in saved payout method")?;
Ok(())
}
#[cfg(feature = "v2")]
pub async fn save_payout_data_to_locker(
_state: &SessionState,
_payout_data: &mut PayoutData,
_customer_id: &id_type::CustomerId,
_payout_method_data: &api::PayoutMethodData,
_connector_mandate_details: Option<serde_json::Value>,
_merchant_context: &domain::MerchantContext,
) -> RouterResult<()> {
todo!()
}
#[cfg(feature = "v2")]
pub(super) async fn get_or_create_customer_details(
_state: &SessionState,
_customer_details: &CustomerDetails,
_merchant_context: &domain::MerchantContext,
) -> RouterResult<Option<domain::Customer>> {
todo!()
}
#[cfg(feature = "v1")]
pub(super) async fn get_or_create_customer_details(
state: &SessionState,
customer_details: &CustomerDetails,
merchant_context: &domain::MerchantContext,
) -> RouterResult<Option<domain::Customer>> {
let db: &dyn StorageInterface = &*state.store;
// Create customer_id if not passed in request
let customer_id = customer_details
.customer_id
.clone()
.unwrap_or_else(generate_customer_id_of_default_length);
let merchant_id = merchant_context.get_merchant_account().get_id();
let key = merchant_context
.get_merchant_key_store()
.key
.get_inner()
.peek();
let key_manager_state = &state.into();
match db
.find_customer_optional_by_customer_id_merchant_id(
key_manager_state,
&customer_id,
merchant_id,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?
{
// Customer found
Some(customer) => Ok(Some(customer)),
// Customer not found
// create only if atleast one of the fields were provided for customer creation or else throw error
None => {
if customer_details.name.is_some()
|| customer_details.email.is_some()
|| customer_details.phone.is_some()
|| customer_details.phone_country_code.is_some()
{
let encrypted_data = crypto_operation(
&state.into(),
type_name!(domain::Customer),
CryptoOperation::BatchEncrypt(
domain::FromRequestEncryptableCustomer::to_encryptable(
domain::FromRequestEncryptableCustomer {
name: customer_details.name.clone(),
email: customer_details
.email
.clone()
.map(|a| a.expose().switch_strategy()),
phone: customer_details.phone.clone(),
tax_registration_id: customer_details.tax_registration_id.clone(),
},
),
),
Identifier::Merchant(
merchant_context
.get_merchant_key_store()
.merchant_id
.clone(),
),
key,
)
.await
.and_then(|val| val.try_into_batchoperation())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to encrypt customer")?;
let encryptable_customer =
domain::FromRequestEncryptableCustomer::from_encryptable(encrypted_data)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to form EncryptableCustomer")?;
let customer = domain::Customer {
customer_id: customer_id.clone(),
merchant_id: merchant_id.to_owned().clone(),
name: encryptable_customer.name,
email: encryptable_customer.email.map(|email| {
let encryptable: Encryptable<Secret<String, pii::EmailStrategy>> =
Encryptable::new(
email.clone().into_inner().switch_strategy(),
email.into_encrypted(),
);
encryptable
}),
phone: encryptable_customer.phone,
description: None,
phone_country_code: customer_details.phone_country_code.to_owned(),
metadata: None,
connector_customer: None,
created_at: common_utils::date_time::now(),
modified_at: common_utils::date_time::now(),
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,
};
Ok(Some(
db.insert_customer(
customer,
key_manager_state,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| {
format!(
"Failed to insert customer [id - {customer_id:?}] for merchant [id - {merchant_id:?}]",
)
})?,
))
} else {
Err(report!(errors::ApiErrorResponse::InvalidRequestData {
message: format!("customer for id - {customer_id:?} not found"),
}))
}
}
}
}
#[cfg(all(feature = "payouts", feature = "v1"))]
pub async fn decide_payout_connector(
state: &SessionState,
merchant_context: &domain::MerchantContext,
request_straight_through: Option<api::routing::StraightThroughAlgorithm>,
routing_data: &mut storage::RoutingData,
payout_data: &mut PayoutData,
eligible_connectors: Option<Vec<enums::RoutableConnectors>>,
) -> RouterResult<api::ConnectorCallType> {
// 1. For existing attempts, use stored connector
let payout_attempt = &payout_data.payout_attempt;
if let Some(connector_name) = payout_attempt.connector.clone() {
// Connector was already decided previously, use the same connector
let connector_data = api::ConnectorData::get_payout_connector_by_name(
&state.conf.connectors,
&connector_name,
api::GetToken::Connector,
payout_attempt.merchant_connector_id.clone(),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Invalid connector name received in 'routed_through'")?;
routing_data.routed_through = Some(connector_name.clone());
return Ok(api::ConnectorCallType::PreDetermined(connector_data.into()));
}
// Validate and get the business_profile from payout_attempt
let business_profile = core_utils::validate_and_get_business_profile(
state.store.as_ref(),
&(state).into(),
merchant_context.get_merchant_key_store(),
Some(&payout_attempt.profile_id),
merchant_context.get_merchant_account().get_id(),
)
.await?
.get_required_value("Profile")?;
// 2. Check routing algorithm passed in the request
if let Some(routing_algorithm) = request_straight_through {
let (mut connectors, check_eligibility) =
routing::perform_straight_through_routing(&routing_algorithm, None)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed execution of straight through routing")?;
if check_eligibility {
connectors = routing::perform_eligibility_analysis_with_fallback(
state,
merchant_context.get_merchant_key_store(),
connectors,
&TransactionData::Payout(payout_data),
eligible_connectors,
&business_profile,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed eligibility analysis and fallback")?;
}
let first_connector_choice = connectors
.first()
.ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)
.attach_printable("Empty connector list returned")?
.clone();
let connector_data = connectors
.into_iter()
.map(|conn| {
api::ConnectorData::get_payout_connector_by_name(
&state.conf.connectors,
&conn.connector.to_string(),
api::GetToken::Connector,
payout_attempt.merchant_connector_id.clone(),
)
.map(|connector_data| connector_data.into())
})
.collect::<CustomResult<Vec<_>, _>>()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Invalid connector name received")?;
routing_data.routed_through = Some(first_connector_choice.connector.to_string());
routing_data.merchant_connector_id = first_connector_choice.merchant_connector_id;
routing_data.routing_info.algorithm = Some(routing_algorithm);
return Ok(api::ConnectorCallType::Retryable(connector_data));
}
// 3. Check algorithm passed in routing data
if let Some(ref routing_algorithm) = routing_data.algorithm {
let (mut connectors, check_eligibility) =
routing::perform_straight_through_routing(routing_algorithm, None)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed execution of straight through routing")?;
if check_eligibility {
connectors = routing::perform_eligibility_analysis_with_fallback(
state,
merchant_context.get_merchant_key_store(),
connectors,
&TransactionData::Payout(payout_data),
eligible_connectors,
&business_profile,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed eligibility analysis and fallback")?;
}
let first_connector_choice = connectors
.first()
.ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)
.attach_printable("Empty connector list returned")?
.clone();
connectors.remove(0);
let connector_data = connectors
.into_iter()
.map(|conn| {
api::ConnectorData::get_payout_connector_by_name(
&state.conf.connectors,
&conn.connector.to_string(),
api::GetToken::Connector,
payout_attempt.merchant_connector_id.clone(),
)
.map(|connector_data| connector_data.into())
})
.collect::<CustomResult<Vec<_>, _>>()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Invalid connector name received")?;
routing_data.routed_through = Some(first_connector_choice.connector.to_string());
routing_data.merchant_connector_id = first_connector_choice.merchant_connector_id;
return Ok(api::ConnectorCallType::Retryable(connector_data));
}
// 4. Route connector
route_connector_v1_for_payouts(
state,
merchant_context,
&payout_data.business_profile,
payout_data,
routing_data,
eligible_connectors,
)
.await
}
pub async fn get_default_payout_connector(
_state: &SessionState,
request_connector: Option<serde_json::Value>,
) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> {
Ok(request_connector.map_or(
api::ConnectorChoice::Decide,
api::ConnectorChoice::StraightThrough,
))
}
#[cfg(feature = "v1")]
pub fn should_call_payout_connector_create_customer<'a>(
state: &'a SessionState,
connector: &'a api::ConnectorData,
customer: &'a Option<domain::Customer>,
connector_label: &'a str,
) -> (bool, Option<&'a str>) {
// Check if create customer is required for the connector
match enums::PayoutConnectors::try_from(connector.connector_name) {
Ok(connector) => {
let connector_needs_customer = state
.conf
.connector_customer
.payout_connector_list
.contains(&connector);
if connector_needs_customer {
let connector_customer_details = customer
.as_ref()
.and_then(|customer| customer.get_connector_customer_id(connector_label));
let should_call_connector = connector_customer_details.is_none();
(should_call_connector, connector_customer_details)
} else {
(false, None)
}
}
_ => (false, None),
}
}
#[cfg(feature = "v2")]
pub fn should_call_payout_connector_create_customer<'a>(
state: &'a SessionState,
connector: &'a api::ConnectorData,
customer: &'a Option<domain::Customer>,
merchant_connector_id: &'a domain::MerchantConnectorAccountTypeDetails,
) -> (bool, Option<&'a str>) {
// Check if create customer is required for the connector
match enums::PayoutConnectors::try_from(connector.connector_name) {
Ok(connector) => {
let connector_needs_customer = state
.conf
.connector_customer
.payout_connector_list
.contains(&connector);
if connector_needs_customer {
let connector_customer_details = customer
.as_ref()
.and_then(|customer| customer.get_connector_customer_id(merchant_connector_id));
let should_call_connector = connector_customer_details.is_none();
(should_call_connector, connector_customer_details)
} else {
(false, None)
}
}
_ => (false, None),
}
}
pub async fn get_gsm_record(
state: &SessionState,
error_code: Option<String>,
error_message: Option<String>,
connector_name: Option<String>,
flow: &str,
) -> Option<hyperswitch_domain_models::gsm::GatewayStatusMap> {
let connector_name = connector_name.unwrap_or_default();
let get_gsm = || async {
state.store.find_gsm_rule(
connector_name.clone(),
flow.to_string(),
"sub_flow".to_string(),
error_code.clone().unwrap_or_default(), // TODO: make changes in connector to get a mandatory code in case of success or error response
error_message.clone().unwrap_or_default(),
)
.await
.map_err(|err| {
if err.current_context().is_db_not_found() {
logger::warn!(
"GSM miss for connector - {}, flow - {}, error_code - {:?}, error_message - {:?}",
connector_name,
flow,
error_code,
error_message
);
metrics::AUTO_PAYOUT_RETRY_GSM_MISS_COUNT.add( 1, &[]);
} else {
metrics::AUTO_PAYOUT_RETRY_GSM_FETCH_FAILURE_COUNT.add( 1, &[]);
};
err.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed to fetch decision from gsm")
})
};
get_gsm()
.await
.inspect_err(|err| {
// warn log should suffice here because we are not propagating this error
logger::warn!(get_gsm_decision_fetch_error=?err, "error fetching gsm decision");
})
.ok()
}
pub fn is_payout_initiated(status: api_enums::PayoutStatus) -> bool {
!matches!(
status,
api_enums::PayoutStatus::RequiresCreation
| api_enums::PayoutStatus::RequiresConfirmation
| api_enums::PayoutStatus::RequiresPayoutMethodData
| api_enums::PayoutStatus::RequiresVendorAccountCreation
| api_enums::PayoutStatus::Initiated
)
}
pub(crate) fn validate_payout_status_against_not_allowed_statuses(
payout_status: api_enums::PayoutStatus,
not_allowed_statuses: &[api_enums::PayoutStatus],
action: &'static str,
) -> Result<(), errors::ApiErrorResponse> {
fp_utils::when(not_allowed_statuses.contains(&payout_status), || {
Err(errors::ApiErrorResponse::PreconditionFailed {
message: format!(
"You cannot {action} this payout because it has status {payout_status}",
),
})
})
}
pub fn is_payout_terminal_state(status: api_enums::PayoutStatus) -> bool {
!matches!(
status,
api_enums::PayoutStatus::RequiresCreation
| api_enums::PayoutStatus::RequiresConfirmation
| api_enums::PayoutStatus::RequiresPayoutMethodData
| api_enums::PayoutStatus::RequiresVendorAccountCreation
// Initiated by the underlying connector
| api_enums::PayoutStatus::Pending
| api_enums::PayoutStatus::Initiated
| api_enums::PayoutStatus::RequiresFulfillment
)
}
pub fn should_call_retrieve(status: api_enums::PayoutStatus) -> bool {
matches!(
status,
api_enums::PayoutStatus::Pending | api_enums::PayoutStatus::Initiated
)
}
pub fn is_payout_err_state(status: api_enums::PayoutStatus) -> bool {
matches!(
status,
api_enums::PayoutStatus::Cancelled
| api_enums::PayoutStatus::Failed
| api_enums::PayoutStatus::Ineligible
)
}
pub fn is_eligible_for_local_payout_cancellation(status: api_enums::PayoutStatus) -> bool {
matches!(
status,
api_enums::PayoutStatus::RequiresCreation
| api_enums::PayoutStatus::RequiresConfirmation
| api_enums::PayoutStatus::RequiresPayoutMethodData
| api_enums::PayoutStatus::RequiresVendorAccountCreation
)
}
#[cfg(feature = "olap")]
pub(super) async fn filter_by_constraints(
db: &dyn StorageInterface,
constraints: &api::PayoutListConstraints,
merchant_id: &id_type::MerchantId,
storage_scheme: storage::enums::MerchantStorageScheme,
) -> CustomResult<Vec<storage::Payouts>, errors::StorageError> {
let result = db
.filter_payouts_by_constraints(merchant_id, &constraints.clone().into(), storage_scheme)
.await?;
Ok(result)
}
#[cfg(feature = "v2")]
pub async fn update_payouts_and_payout_attempt(
_payout_data: &mut PayoutData,
_merchant_context: &domain::MerchantContext,
_req: &payouts::PayoutCreateRequest,
_state: &SessionState,
) -> CustomResult<(), errors::ApiErrorResponse> {
todo!()
}
#[cfg(feature = "v1")]
pub async fn update_payouts_and_payout_attempt(
payout_data: &mut PayoutData,
merchant_context: &domain::MerchantContext,
req: &payouts::PayoutCreateRequest,
state: &SessionState,
) -> CustomResult<(), errors::ApiErrorResponse> {
let payout_attempt = payout_data.payout_attempt.to_owned();
let status = payout_attempt.status;
let payout_id = payout_attempt.payout_id.clone();
// Verify update feasibility
if is_payout_terminal_state(status) || is_payout_initiated(status) {
return Err(report!(errors::ApiErrorResponse::InvalidRequestData {
message: format!(
"Payout {} cannot be updated for status {status}",
payout_id.get_string_repr()
),
}));
}
// Fetch customer details from request and create new or else use existing customer that was attached
let customer = get_customer_details_from_request(req);
let customer_id = if customer.customer_id.is_some()
|| customer.name.is_some()
|| customer.email.is_some()
|| customer.phone.is_some()
|| customer.phone_country_code.is_some()
{
payout_data.customer_details =
get_or_create_customer_details(state, &customer, merchant_context).await?;
payout_data
.customer_details
.as_ref()
.map(|customer| customer.customer_id.clone())
} else {
payout_data.payouts.customer_id.clone()
};
let (billing_address, address_id) = resolve_billing_address_for_payout(
state,
req.billing.as_ref(),
payout_data.payouts.address_id.as_ref(),
payout_data.payment_method.as_ref(),
merchant_context,
customer_id.as_ref(),
&payout_id,
)
.await?;
// Update payout state with resolved billing address
payout_data.billing_address = billing_address;
// Update DB with new data
let payouts = payout_data.payouts.to_owned();
let amount = MinorUnit::from(req.amount.unwrap_or(payouts.amount.into()));
let updated_payouts = storage::PayoutsUpdate::Update {
amount,
destination_currency: req
.currency
.to_owned()
.unwrap_or(payouts.destination_currency),
source_currency: req.currency.to_owned().unwrap_or(payouts.source_currency),
description: req
.description
.to_owned()
.clone()
.or(payouts.description.clone()),
recurring: req.recurring.to_owned().unwrap_or(payouts.recurring),
auto_fulfill: req.auto_fulfill.to_owned().unwrap_or(payouts.auto_fulfill),
return_url: req
.return_url
.to_owned()
.clone()
.or(payouts.return_url.clone()),
entity_type: req.entity_type.to_owned().unwrap_or(payouts.entity_type),
metadata: req.metadata.clone().or(payouts.metadata.clone()),
status: Some(status),
profile_id: Some(payout_attempt.profile_id.clone()),
confirm: req.confirm.to_owned(),
payout_type: req
.payout_type
.to_owned()
.or(payouts.payout_type.to_owned()),
address_id: address_id.clone(),
customer_id: customer_id.clone(),
};
let db = &*state.store;
payout_data.payouts = db
.update_payout(
&payouts,
updated_payouts,
&payout_attempt,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating payouts")?;
let updated_business_country =
payout_attempt
.business_country
.map_or(req.business_country.to_owned(), |c| {
req.business_country
.to_owned()
.and_then(|nc| if nc != c { Some(nc) } else { None })
});
let updated_business_label =
payout_attempt
.business_label
.map_or(req.business_label.to_owned(), |l| {
req.business_label
.to_owned()
.and_then(|nl| if nl != l { Some(nl) } else { None })
});
if updated_business_country.is_some()
|| updated_business_label.is_some()
|| customer_id.is_some()
|| address_id.is_some()
{
let payout_attempt = &payout_data.payout_attempt;
let updated_payout_attempt = storage::PayoutAttemptUpdate::BusinessUpdate {
business_country: updated_business_country,
business_label: updated_business_label,
address_id,
customer_id,
};
payout_data.payout_attempt = db
.update_payout_attempt(
payout_attempt,
updated_payout_attempt,
&payout_data.payouts,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating payout_attempt")?;
}
Ok(())
}
pub(super) fn get_customer_details_from_request(
request: &payouts::PayoutCreateRequest,
) -> CustomerDetails {
let customer_id = request.get_customer_id().map(ToOwned::to_owned);
let customer_name = request
.customer
.as_ref()
.and_then(|customer_details| customer_details.name.clone())
.or(request.name.clone());
let customer_email = request
.customer
.as_ref()
.and_then(|customer_details| customer_details.email.clone())
.or(request.email.clone());
let customer_phone = request
.customer
.as_ref()
.and_then(|customer_details| customer_details.phone.clone())
.or(request.phone.clone());
let customer_phone_code = request
.customer
.as_ref()
.and_then(|customer_details| customer_details.phone_country_code.clone())
.or(request.phone_country_code.clone());
let tax_registration_id = request
.customer
.as_ref()
.and_then(|customer_details| customer_details.tax_registration_id.clone());
CustomerDetails {
customer_id,
name: customer_name,
email: customer_email,
phone: customer_phone,
phone_country_code: customer_phone_code,
tax_registration_id,
}
}
pub async fn get_translated_unified_code_and_message(
state: &SessionState,
unified_code: Option<&UnifiedCode>,
unified_message: Option<&UnifiedMessage>,
locale: &str,
) -> CustomResult<Option<UnifiedMessage>, errors::ApiErrorResponse> {
Ok(unified_code
.zip(unified_message)
.async_and_then(|(code, message)| async {
payment_helpers::get_unified_translation(
state,
code.0.clone(),
message.0.clone(),
locale.to_string(),
)
.await
.map(UnifiedMessage::try_from)
})
.await
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "unified_message",
})?
.or_else(|| unified_message.cloned()))
}
pub async fn get_additional_payout_data(
pm_data: &api::PayoutMethodData,
db: &dyn StorageInterface,
profile_id: &id_type::ProfileId,
) -> Option<payout_additional::AdditionalPayoutMethodData> {
match pm_data {
api::PayoutMethodData::Card(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 last4 = Some(card_data.card_number.get_last4());
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| {
payout_additional::AdditionalPayoutMethodData::Card(Box::new(
payout_additional::CardAdditionalData {
card_issuer: card_info.card_issuer,
card_network: card_info.card_network.clone(),
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.expiry_month.clone()),
card_exp_year: Some(card_data.expiry_year.clone()),
card_holder_name: card_data.card_holder_name.clone(),
},
))
});
Some(card_info.unwrap_or_else(|| {
payout_additional::AdditionalPayoutMethodData::Card(Box::new(
payout_additional::CardAdditionalData {
card_issuer: None,
card_network: None,
bank_code: None,
card_type: None,
card_issuing_country: None,
last4,
card_isin,
card_extended_bin,
card_exp_month: Some(card_data.expiry_month.clone()),
card_exp_year: Some(card_data.expiry_year.clone()),
card_holder_name: card_data.card_holder_name.clone(),
},
))
}))
}
api::PayoutMethodData::Bank(bank_data) => {
Some(payout_additional::AdditionalPayoutMethodData::Bank(
Box::new(bank_data.to_owned().into()),
))
}
api::PayoutMethodData::Wallet(wallet_data) => {
Some(payout_additional::AdditionalPayoutMethodData::Wallet(
Box::new(wallet_data.to_owned().into()),
))
}
api::PayoutMethodData::BankRedirect(bank_redirect_data) => {
Some(payout_additional::AdditionalPayoutMethodData::BankRedirect(
Box::new(bank_redirect_data.to_owned().into()),
))
}
}
}
pub async fn resolve_billing_address_for_payout(
state: &SessionState,
req_billing: Option<&api_models::payments::Address>,
existing_address_id: Option<&String>,
payment_method: Option<&hyperswitch_domain_models::payment_methods::PaymentMethod>,
merchant_context: &domain::MerchantContext,
customer_id: Option<&id_type::CustomerId>,
payout_id: &id_type::PayoutId,
) -> RouterResult<(
Option<hyperswitch_domain_models::address::Address>,
Option<String>,
)> {
let payout_id_as_payment_id = id_type::PaymentId::try_from(std::borrow::Cow::Owned(
payout_id.get_string_repr().to_string(),
))
.change_context(errors::ApiErrorResponse::InvalidRequestData {
message: "payout_id contains invalid data for PaymentId conversion".to_string(),
})
.attach_printable("Error converting payout_id to PaymentId type")?;
match (req_billing, existing_address_id, payment_method) {
// Address in request
(Some(_), _, _) => {
let billing_address = payment_helpers::create_or_find_address_for_payment_by_request(
state,
req_billing,
None,
merchant_context.get_merchant_account().get_id(),
customer_id,
merchant_context.get_merchant_key_store(),
&payout_id_as_payment_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let address_id = billing_address.as_ref().map(|a| a.address_id.clone());
let hyperswitch_address = billing_address
.map(|addr| hyperswitch_domain_models::address::Address::from(&addr));
Ok((hyperswitch_address, address_id))
}
// Existing address using address_id
(None, Some(address_id), _) => {
let billing_address = payment_helpers::create_or_find_address_for_payment_by_request(
state,
None,
Some(address_id),
merchant_context.get_merchant_account().get_id(),
customer_id,
merchant_context.get_merchant_key_store(),
&payout_id_as_payment_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let hyperswitch_address = billing_address
.map(|addr| hyperswitch_domain_models::address::Address::from(&addr));
Ok((hyperswitch_address, Some(address_id.clone())))
}
// Existing address in stored payment method
(None, None, Some(pm)) => {
pm.payment_method_billing_address.as_ref().map_or_else(
|| {
logger::info!("No billing address found in payment method");
Ok((None, None))
},
|encrypted_billing_address| {
logger::info!("Found encrypted billing address data in payment method");
#[cfg(feature = "v1")]
{
encrypted_billing_address
.clone()
.into_inner()
.expose()
.parse_value::<hyperswitch_domain_models::address::Address>(
"payment_method_billing_address",
)
.map(|domain_address| {
logger::info!("Successfully parsed as hyperswitch_domain_models::address::Address");
(Some(domain_address), None)
})
.map_err(|e| {
logger::error!("Failed to parse billing address into (hyperswitch_domain_models::address::Address): {:?}", e);
errors::ApiErrorResponse::InternalServerError
})
.attach_printable("Failed to parse stored billing address")
}
#[cfg(feature = "v2")]
{
// TODO: Implement v2 logic when needed
logger::warn!("v2 billing address resolution not yet implemented");
Ok((None, None))
}
},
)
}
(None, None, None) => Ok((None, None)),
}
}
pub fn should_continue_payout<F: Clone + 'static>(
router_data: &router_types::PayoutsRouterData<F>,
) -> bool {
router_data.response.is_ok()
}
|
crates/router/src/core/payouts/helpers.rs
|
router::src::core::payouts::helpers
| 12,347
| true
|
// File: crates/router/src/core/payouts/retry.rs
// Module: router::src::core::payouts::retry
use std::vec::IntoIter;
use common_enums::PayoutRetryType;
use error_stack::ResultExt;
use router_env::{
logger,
tracing::{self, instrument},
};
use super::{call_connector_payout, PayoutData};
use crate::{
core::{
errors::{self, RouterResult, StorageErrorExt},
payouts,
},
db::StorageInterface,
routes::{self, app, metrics},
types::{api, domain, storage},
utils,
};
#[instrument(skip_all)]
#[allow(clippy::too_many_arguments)]
pub async fn do_gsm_multiple_connector_actions(
state: &app::SessionState,
mut connectors_routing_data: IntoIter<api::ConnectorRoutingData>,
original_connector_data: api::ConnectorData,
payout_data: &mut PayoutData,
merchant_context: &domain::MerchantContext,
) -> RouterResult<()> {
let mut retries = None;
metrics::AUTO_PAYOUT_RETRY_ELIGIBLE_REQUEST_COUNT.add(1, &[]);
let mut connector = original_connector_data;
loop {
let gsm = get_gsm(state, &connector, payout_data).await?;
match get_gsm_decision(gsm) {
common_enums::GsmDecision::Retry => {
retries = get_retries(
state,
retries,
merchant_context.get_merchant_account().get_id(),
PayoutRetryType::MultiConnector,
)
.await;
if retries.is_none() || retries == Some(0) {
metrics::AUTO_PAYOUT_RETRY_EXHAUSTED_COUNT.add(1, &[]);
logger::info!("retries exhausted for auto_retry payout");
break;
}
if connectors_routing_data.len() == 0 {
logger::info!("connectors exhausted for auto_retry payout");
metrics::AUTO_PAYOUT_RETRY_EXHAUSTED_COUNT.add(1, &[]);
break;
}
connector = super::get_next_connector(&mut connectors_routing_data)?.connector_data;
Box::pin(do_retry(
&state.clone(),
connector.to_owned(),
merchant_context,
payout_data,
))
.await?;
retries = retries.map(|i| i - 1);
}
common_enums::GsmDecision::DoDefault => break,
}
}
Ok(())
}
#[instrument(skip_all)]
#[allow(clippy::too_many_arguments)]
pub async fn do_gsm_single_connector_actions(
state: &app::SessionState,
original_connector_data: api::ConnectorData,
payout_data: &mut PayoutData,
merchant_context: &domain::MerchantContext,
) -> RouterResult<()> {
let mut retries = None;
metrics::AUTO_PAYOUT_RETRY_ELIGIBLE_REQUEST_COUNT.add(1, &[]);
let mut previous_gsm = None; // to compare previous status
loop {
let gsm = get_gsm(state, &original_connector_data, payout_data).await?;
// if the error config is same as previous, we break out of the loop
if gsm == previous_gsm {
break;
}
previous_gsm.clone_from(&gsm);
match get_gsm_decision(gsm) {
common_enums::GsmDecision::Retry => {
retries = get_retries(
state,
retries,
merchant_context.get_merchant_account().get_id(),
PayoutRetryType::SingleConnector,
)
.await;
if retries.is_none() || retries == Some(0) {
metrics::AUTO_PAYOUT_RETRY_EXHAUSTED_COUNT.add(1, &[]);
logger::info!("retries exhausted for auto_retry payment");
break;
}
Box::pin(do_retry(
&state.clone(),
original_connector_data.to_owned(),
merchant_context,
payout_data,
))
.await?;
retries = retries.map(|i| i - 1);
}
common_enums::GsmDecision::DoDefault => break,
}
}
Ok(())
}
#[instrument(skip_all)]
pub async fn get_retries(
state: &app::SessionState,
retries: Option<i32>,
merchant_id: &common_utils::id_type::MerchantId,
retry_type: PayoutRetryType,
) -> Option<i32> {
match retries {
Some(retries) => Some(retries),
None => {
let key = merchant_id.get_max_auto_single_connector_payout_retries_enabled(retry_type);
let db = &*state.store;
db.find_config_by_key(key.as_str())
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.and_then(|retries_config| {
retries_config
.config
.parse::<i32>()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Retries config parsing failed")
})
.map_err(|err| {
logger::error!(retries_error=?err);
None::<i32>
})
.ok()
}
}
}
#[instrument(skip_all)]
pub async fn get_gsm(
state: &app::SessionState,
original_connector_data: &api::ConnectorData,
payout_data: &PayoutData,
) -> RouterResult<Option<hyperswitch_domain_models::gsm::GatewayStatusMap>> {
let error_code = payout_data.payout_attempt.error_code.to_owned();
let error_message = payout_data.payout_attempt.error_message.to_owned();
let connector_name = Some(original_connector_data.connector_name.to_string());
Ok(payouts::helpers::get_gsm_record(
state,
error_code,
error_message,
connector_name,
common_utils::consts::PAYOUT_FLOW_STR,
)
.await)
}
#[instrument(skip_all)]
pub fn get_gsm_decision(
option_gsm: Option<hyperswitch_domain_models::gsm::GatewayStatusMap>,
) -> common_enums::GsmDecision {
let option_gsm_decision = option_gsm.map(|gsm| gsm.feature_data.get_decision());
if option_gsm_decision.is_some() {
metrics::AUTO_PAYOUT_RETRY_GSM_MATCH_COUNT.add(1, &[]);
}
option_gsm_decision.unwrap_or_default()
}
#[allow(clippy::too_many_arguments)]
#[instrument(skip_all)]
pub async fn do_retry(
state: &routes::SessionState,
connector: api::ConnectorData,
merchant_context: &domain::MerchantContext,
payout_data: &mut PayoutData,
) -> RouterResult<()> {
metrics::AUTO_RETRY_PAYOUT_COUNT.add(1, &[]);
modify_trackers(state, &connector, merchant_context, payout_data).await?;
Box::pin(call_connector_payout(
state,
merchant_context,
&connector,
payout_data,
))
.await
}
#[instrument(skip_all)]
pub async fn modify_trackers(
state: &routes::SessionState,
connector: &api::ConnectorData,
merchant_context: &domain::MerchantContext,
payout_data: &mut PayoutData,
) -> RouterResult<()> {
let new_attempt_count = payout_data.payouts.attempt_count + 1;
let db = &*state.store;
// update payout table's attempt count
let payouts = payout_data.payouts.to_owned();
let updated_payouts = storage::PayoutsUpdate::AttemptCountUpdate {
attempt_count: new_attempt_count,
};
let payout_id = payouts.payout_id.clone();
payout_data.payouts = db
.update_payout(
&payout_data.payouts,
updated_payouts,
&payout_data.payout_attempt,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating payouts")?;
let payout_attempt_id = utils::get_payout_attempt_id(
payout_id.get_string_repr(),
payout_data.payouts.attempt_count,
);
let payout_attempt_req = storage::PayoutAttemptNew {
payout_attempt_id: payout_attempt_id.to_string(),
payout_id: payout_id.to_owned(),
merchant_order_reference_id: payout_data
.payout_attempt
.merchant_order_reference_id
.clone(),
customer_id: payout_data.payout_attempt.customer_id.to_owned(),
connector: Some(connector.connector_name.to_string()),
merchant_id: payout_data.payout_attempt.merchant_id.to_owned(),
address_id: payout_data.payout_attempt.address_id.to_owned(),
business_country: payout_data.payout_attempt.business_country.to_owned(),
business_label: payout_data.payout_attempt.business_label.to_owned(),
payout_token: payout_data.payout_attempt.payout_token.to_owned(),
profile_id: payout_data.payout_attempt.profile_id.to_owned(),
connector_payout_id: None,
status: common_enums::PayoutStatus::default(),
is_eligible: None,
error_message: None,
error_code: None,
created_at: common_utils::date_time::now(),
last_modified_at: common_utils::date_time::now(),
merchant_connector_id: None,
routing_info: None,
unified_code: None,
unified_message: None,
additional_payout_method_data: payout_data
.payout_attempt
.additional_payout_method_data
.to_owned(),
payout_connector_metadata: None,
};
payout_data.payout_attempt = db
.insert_payout_attempt(
payout_attempt_req,
&payouts,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_duplicate_response(errors::ApiErrorResponse::DuplicatePayout { payout_id })
.attach_printable("Error inserting payouts in db")?;
payout_data.merchant_connector_account = None;
Ok(())
}
pub async fn config_should_call_gsm_payout(
db: &dyn StorageInterface,
merchant_id: &common_utils::id_type::MerchantId,
retry_type: PayoutRetryType,
) -> bool {
let key = merchant_id.get_should_call_gsm_payout_key(retry_type);
let config = db
.find_config_by_key_unwrap_or(key.as_str(), Some("false".to_string()))
.await;
match config {
Ok(conf) => conf.config == "true",
Err(error) => {
logger::error!(?error);
false
}
}
}
pub trait GsmValidation {
// TODO : move this function to appropriate place later.
fn should_call_gsm(&self) -> bool;
}
impl GsmValidation for PayoutData {
#[inline(always)]
fn should_call_gsm(&self) -> bool {
match self.payout_attempt.status {
common_enums::PayoutStatus::Success
| common_enums::PayoutStatus::RequiresConfirmation
| common_enums::PayoutStatus::Cancelled
| common_enums::PayoutStatus::Pending
| common_enums::PayoutStatus::Initiated
| common_enums::PayoutStatus::Reversed
| common_enums::PayoutStatus::Expired
| common_enums::PayoutStatus::Ineligible
| common_enums::PayoutStatus::RequiresCreation
| common_enums::PayoutStatus::RequiresPayoutMethodData
| common_enums::PayoutStatus::RequiresVendorAccountCreation
| common_enums::PayoutStatus::RequiresFulfillment => false,
common_enums::PayoutStatus::Failed => true,
}
}
}
|
crates/router/src/core/payouts/retry.rs
|
router::src::core::payouts::retry
| 2,486
| true
|
// File: crates/router/src/bin/router.rs
// Module: router::src::bin::router
use error_stack::ResultExt;
use router::{
configs::settings::{CmdLineConf, Settings},
core::errors::{ApplicationError, ApplicationResult},
logger,
routes::metrics,
};
#[tokio::main]
async fn main() -> ApplicationResult<()> {
// get commandline config before initializing config
let cmd_line = <CmdLineConf as clap::Parser>::parse();
#[allow(clippy::expect_used)]
let conf = Settings::with_config_path(cmd_line.config_path)
.expect("Unable to construct application configuration");
#[allow(clippy::expect_used)]
conf.validate()
.expect("Failed to validate router configuration");
#[allow(clippy::print_stdout)] // The logger has not yet been initialized
#[cfg(feature = "vergen")]
{
println!("Starting router (Version: {})", router_env::git_tag!());
}
let _guard = router_env::setup(
&conf.log,
router_env::service_name!(),
[router_env::service_name!(), "actix_server"],
)
.change_context(ApplicationError::ConfigurationError)?;
logger::info!("Application started [{:?}] [{:?}]", conf.server, conf.log);
// Spawn a thread for collecting metrics at fixed intervals
metrics::bg_metrics_collector::spawn_metrics_collector(
conf.log.telemetry.bg_metrics_collection_interval_in_secs,
);
#[allow(clippy::expect_used)]
let server = Box::pin(router::start_server(conf))
.await
.expect("Failed to create the server");
let _ = server.await;
Err(error_stack::Report::from(ApplicationError::from(
std::io::Error::other("Server shut down"),
)))
}
|
crates/router/src/bin/router.rs
|
router::src::bin::router
| 388
| true
|
// File: crates/router/src/bin/scheduler.rs
// Module: router::src::bin::scheduler
use std::{collections::HashMap, str::FromStr, sync::Arc};
use actix_web::{dev::Server, web, Scope};
use api_models::health_check::SchedulerHealthCheckResponse;
use common_utils::ext_traits::{OptionExt, StringExt};
use diesel_models::process_tracker::{self as storage, business_status};
use error_stack::ResultExt;
use router::{
configs::settings::{CmdLineConf, Settings},
core::{
errors::{self, CustomResult},
health_check::HealthCheckInterface,
},
logger, routes,
services::{self, api},
workflows,
};
use router_env::{
instrument,
tracing::{self, Instrument},
};
use scheduler::{
consumer::workflows::ProcessTrackerWorkflow, errors::ProcessTrackerError,
workflows::ProcessTrackerWorkflows, SchedulerSessionState,
};
use storage_impl::errors::ApplicationError;
use tokio::sync::{mpsc, oneshot};
const SCHEDULER_FLOW: &str = "SCHEDULER_FLOW";
#[tokio::main]
async fn main() -> CustomResult<(), ProcessTrackerError> {
let cmd_line = <CmdLineConf as clap::Parser>::parse();
#[allow(clippy::expect_used)]
let conf = Settings::with_config_path(cmd_line.config_path)
.expect("Unable to construct application configuration");
let api_client = Box::new(
services::ProxyClient::new(&conf.proxy)
.change_context(ProcessTrackerError::ConfigurationError)?,
);
// channel for listening to redis disconnect events
let (redis_shutdown_signal_tx, redis_shutdown_signal_rx) = oneshot::channel();
let state = Box::pin(routes::AppState::new(
conf,
redis_shutdown_signal_tx,
api_client,
))
.await;
// channel to shutdown scheduler gracefully
let (tx, rx) = mpsc::channel(1);
let _task_handle = tokio::spawn(
router::receiver_for_error(redis_shutdown_signal_rx, tx.clone()).in_current_span(),
);
#[allow(clippy::expect_used)]
let scheduler_flow_str =
std::env::var(SCHEDULER_FLOW).expect("SCHEDULER_FLOW environment variable not set");
#[allow(clippy::expect_used)]
let scheduler_flow = scheduler::SchedulerFlow::from_str(&scheduler_flow_str)
.expect("Unable to parse SchedulerFlow from environment variable");
#[allow(clippy::print_stdout)] // The logger has not yet been initialized
#[cfg(feature = "vergen")]
{
println!(
"Starting {scheduler_flow} (Version: {})",
router_env::git_tag!()
);
}
let _guard = router_env::setup(
&state.conf.log,
&scheduler_flow_str,
[router_env::service_name!()],
);
#[allow(clippy::expect_used)]
let web_server = Box::pin(start_web_server(
state.clone(),
scheduler_flow_str.to_string(),
))
.await
.expect("Failed to create the server");
let _task_handle = tokio::spawn(
async move {
let _ = web_server.await;
logger::error!("The health check probe stopped working!");
}
.in_current_span(),
);
logger::debug!(startup_config=?state.conf);
start_scheduler(&state, scheduler_flow, (tx, rx)).await?;
logger::error!("Scheduler shut down");
Ok(())
}
pub async fn start_web_server(
state: routes::AppState,
service: String,
) -> errors::ApplicationResult<Server> {
let server = state
.conf
.scheduler
.as_ref()
.ok_or(ApplicationError::InvalidConfigurationValueError(
"Scheduler server is invalidly configured".into(),
))?
.server
.clone();
let web_server = actix_web::HttpServer::new(move || {
actix_web::App::new().service(Health::server(state.clone(), service.clone()))
})
.bind((server.host.as_str(), server.port))
.change_context(ApplicationError::ConfigurationError)?
.workers(server.workers)
.run();
let _ = web_server.handle();
Ok(web_server)
}
pub struct Health;
impl Health {
pub fn server(state: routes::AppState, service: String) -> Scope {
web::scope("health")
.app_data(web::Data::new(state))
.app_data(web::Data::new(service))
.service(web::resource("").route(web::get().to(health)))
.service(web::resource("/ready").route(web::get().to(deep_health_check)))
}
}
#[instrument(skip_all)]
pub async fn health() -> impl actix_web::Responder {
logger::info!("Scheduler health was called");
actix_web::HttpResponse::Ok().body("Scheduler health is good")
}
#[instrument(skip_all)]
pub async fn deep_health_check(
state: web::Data<routes::AppState>,
service: web::Data<String>,
) -> impl actix_web::Responder {
let mut checks = HashMap::new();
let stores = state.stores.clone();
let app_state = Arc::clone(&state.into_inner());
let service_name = service.into_inner();
for (tenant, _) in stores {
let session_state_res = app_state.clone().get_session_state(&tenant, None, || {
errors::ApiErrorResponse::MissingRequiredField {
field_name: "tenant_id",
}
.into()
});
let session_state = match session_state_res {
Ok(state) => state,
Err(err) => {
return api::log_and_return_error_response(err);
}
};
let report = deep_health_check_func(session_state, &service_name).await;
match report {
Ok(response) => {
checks.insert(
tenant,
serde_json::to_string(&response)
.map_err(|err| {
logger::error!(serialization_error=?err);
})
.unwrap_or_default(),
);
}
Err(err) => {
return api::log_and_return_error_response(err);
}
}
}
services::http_response_json(
serde_json::to_string(&checks)
.map_err(|err| {
logger::error!(serialization_error=?err);
})
.unwrap_or_default(),
)
}
#[instrument(skip_all)]
pub async fn deep_health_check_func(
state: routes::SessionState,
service: &str,
) -> errors::RouterResult<SchedulerHealthCheckResponse> {
logger::info!("{} deep health check was called", service);
logger::debug!("Database health check begin");
let db_status = state
.health_check_db()
.await
.map(|_| true)
.map_err(|error| {
let message = error.to_string();
error.change_context(errors::ApiErrorResponse::HealthCheckError {
component: "Database",
message,
})
})?;
logger::debug!("Database health check end");
logger::debug!("Redis health check begin");
let redis_status = state
.health_check_redis()
.await
.map(|_| true)
.map_err(|error| {
let message = error.to_string();
error.change_context(errors::ApiErrorResponse::HealthCheckError {
component: "Redis",
message,
})
})?;
let outgoing_req_check =
state
.health_check_outgoing()
.await
.map(|_| true)
.map_err(|error| {
let message = error.to_string();
error.change_context(errors::ApiErrorResponse::HealthCheckError {
component: "Outgoing Request",
message,
})
})?;
logger::debug!("Redis health check end");
let response = SchedulerHealthCheckResponse {
database: db_status,
redis: redis_status,
outgoing_request: outgoing_req_check,
};
Ok(response)
}
#[derive(Debug, Copy, Clone)]
pub struct WorkflowRunner;
#[async_trait::async_trait]
impl ProcessTrackerWorkflows<routes::SessionState> for WorkflowRunner {
async fn trigger_workflow<'a>(
&'a self,
state: &'a routes::SessionState,
process: storage::ProcessTracker,
) -> CustomResult<(), ProcessTrackerError> {
let runner = process
.runner
.clone()
.get_required_value("runner")
.change_context(ProcessTrackerError::MissingRequiredField)
.attach_printable("Missing runner field in process information")?;
let runner: storage::ProcessTrackerRunner = runner
.parse_enum("ProcessTrackerRunner")
.change_context(ProcessTrackerError::UnexpectedFlow)
.attach_printable("Failed to parse workflow runner name")?;
let get_operation = |runner: storage::ProcessTrackerRunner| -> CustomResult<
Box<dyn ProcessTrackerWorkflow<routes::SessionState>>,
ProcessTrackerError,
> {
match runner {
storage::ProcessTrackerRunner::PaymentsSyncWorkflow => {
Ok(Box::new(workflows::payment_sync::PaymentsSyncWorkflow))
}
storage::ProcessTrackerRunner::RefundWorkflowRouter => {
Ok(Box::new(workflows::refund_router::RefundWorkflowRouter))
}
storage::ProcessTrackerRunner::ProcessDisputeWorkflow => {
Ok(Box::new(workflows::process_dispute::ProcessDisputeWorkflow))
}
storage::ProcessTrackerRunner::DisputeListWorkflow => {
Ok(Box::new(workflows::dispute_list::DisputeListWorkflow))
}
storage::ProcessTrackerRunner::InvoiceSyncflow => {
Ok(Box::new(workflows::invoice_sync::InvoiceSyncWorkflow))
}
storage::ProcessTrackerRunner::DeleteTokenizeDataWorkflow => Ok(Box::new(
workflows::tokenized_data::DeleteTokenizeDataWorkflow,
)),
storage::ProcessTrackerRunner::ApiKeyExpiryWorkflow => {
#[cfg(feature = "email")]
{
Ok(Box::new(workflows::api_key_expiry::ApiKeyExpiryWorkflow))
}
#[cfg(not(feature = "email"))]
{
Err(error_stack::report!(ProcessTrackerError::UnexpectedFlow))
.attach_printable(
"Cannot run API key expiry workflow when email feature is disabled",
)
}
}
storage::ProcessTrackerRunner::OutgoingWebhookRetryWorkflow => Ok(Box::new(
workflows::outgoing_webhook_retry::OutgoingWebhookRetryWorkflow,
)),
storage::ProcessTrackerRunner::AttachPayoutAccountWorkflow => {
#[cfg(feature = "payouts")]
{
Ok(Box::new(
workflows::attach_payout_account_workflow::AttachPayoutAccountWorkflow,
))
}
#[cfg(not(feature = "payouts"))]
{
Err(
error_stack::report!(ProcessTrackerError::UnexpectedFlow),
)
.attach_printable(
"Cannot run Stripe external account workflow when payouts feature is disabled",
)
}
}
storage::ProcessTrackerRunner::PaymentMethodStatusUpdateWorkflow => Ok(Box::new(
workflows::payment_method_status_update::PaymentMethodStatusUpdateWorkflow,
)),
storage::ProcessTrackerRunner::PassiveRecoveryWorkflow => {
Ok(Box::new(workflows::revenue_recovery::ExecutePcrWorkflow))
}
}
};
let operation = get_operation(runner)?;
let app_state = &state.clone();
let output = operation.execute_workflow(state, process.clone()).await;
match output {
Ok(_) => operation.success_handler(app_state, process).await,
Err(error) => match operation
.error_handler(app_state, process.clone(), error)
.await
{
Ok(_) => (),
Err(error) => {
logger::error!(?error, "Failed while handling error");
let status = state
.get_db()
.as_scheduler()
.finish_process_with_business_status(
process,
business_status::GLOBAL_FAILURE,
)
.await;
if let Err(error) = status {
logger::error!(
?error,
"Failed while performing database operation: {}",
business_status::GLOBAL_FAILURE
);
}
}
},
};
Ok(())
}
}
async fn start_scheduler(
state: &routes::AppState,
scheduler_flow: scheduler::SchedulerFlow,
channel: (mpsc::Sender<()>, mpsc::Receiver<()>),
) -> CustomResult<(), ProcessTrackerError> {
let scheduler_settings = state
.conf
.scheduler
.clone()
.ok_or(ProcessTrackerError::ConfigurationError)?;
scheduler::start_process_tracker(
state,
scheduler_flow,
Arc::new(scheduler_settings),
channel,
WorkflowRunner {},
|state, tenant| {
Arc::new(state.clone())
.get_session_state(tenant, None, || ProcessTrackerError::TenantNotFound.into())
},
)
.await
}
|
crates/router/src/bin/scheduler.rs
|
router::src::bin::scheduler
| 2,754
| true
|
// File: crates/router/src/workflows/tokenized_data.rs
// Module: router::src::workflows::tokenized_data
use scheduler::consumer::workflows::ProcessTrackerWorkflow;
#[cfg(feature = "v1")]
use crate::core::payment_methods::vault;
use crate::{errors, logger::error, routes::SessionState, types::storage};
pub struct DeleteTokenizeDataWorkflow;
#[async_trait::async_trait]
impl ProcessTrackerWorkflow<SessionState> for DeleteTokenizeDataWorkflow {
#[cfg(feature = "v1")]
async fn execute_workflow<'a>(
&'a self,
state: &'a SessionState,
process: storage::ProcessTracker,
) -> Result<(), errors::ProcessTrackerError> {
Ok(vault::start_tokenize_data_workflow(state, &process).await?)
}
#[cfg(feature = "v2")]
async fn execute_workflow<'a>(
&'a self,
_state: &'a SessionState,
_process: storage::ProcessTracker,
) -> Result<(), errors::ProcessTrackerError> {
todo!()
}
async fn error_handler<'a>(
&'a self,
_state: &'a SessionState,
process: storage::ProcessTracker,
_error: errors::ProcessTrackerError,
) -> errors::CustomResult<(), errors::ProcessTrackerError> {
error!(%process.id, "Failed while executing workflow");
Ok(())
}
}
|
crates/router/src/workflows/tokenized_data.rs
|
router::src::workflows::tokenized_data
| 305
| true
|
// File: crates/router/src/workflows/invoice_sync.rs
// Module: router::src::workflows::invoice_sync
use async_trait::async_trait;
use common_utils::{errors::CustomResult, ext_traits::ValueExt};
use router_env::logger;
use scheduler::{
consumer::{self, workflows::ProcessTrackerWorkflow},
errors,
};
use crate::{routes::SessionState, types::storage};
const INVOICE_SYNC_WORKFLOW: &str = "INVOICE_SYNC";
pub struct InvoiceSyncWorkflow;
#[async_trait]
impl ProcessTrackerWorkflow<SessionState> for InvoiceSyncWorkflow {
#[cfg(feature = "v1")]
async fn execute_workflow<'a>(
&'a self,
state: &'a SessionState,
process: storage::ProcessTracker,
) -> Result<(), errors::ProcessTrackerError> {
let tracking_data = process
.tracking_data
.clone()
.parse_value::<subscriptions::storage::invoice_sync::InvoiceSyncTrackingData>(
"InvoiceSyncTrackingData",
)?;
let subscription_state = state.clone().into();
match process.name.as_deref() {
Some(INVOICE_SYNC_WORKFLOW) => {
Box::pin(subscriptions::workflows::perform_subscription_invoice_sync(
&subscription_state,
process,
tracking_data,
))
.await
}
_ => Err(errors::ProcessTrackerError::JobNotFound),
}
}
async fn error_handler<'a>(
&'a self,
state: &'a SessionState,
process: storage::ProcessTracker,
error: errors::ProcessTrackerError,
) -> CustomResult<(), errors::ProcessTrackerError> {
logger::error!("Encountered error");
consumer::consumer_error_handler(state.store.as_scheduler(), process, error).await
}
#[cfg(feature = "v2")]
async fn execute_workflow<'a>(
&'a self,
state: &'a SessionState,
process: storage::ProcessTracker,
) -> Result<(), errors::ProcessTrackerError> {
Ok(())
}
}
|
crates/router/src/workflows/invoice_sync.rs
|
router::src::workflows::invoice_sync
| 432
| true
|
// File: crates/router/src/workflows/process_dispute.rs
// Module: router::src::workflows::process_dispute
use common_utils::ext_traits::{StringExt, ValueExt};
use diesel_models::process_tracker::business_status;
use error_stack::ResultExt;
use router_env::logger;
use scheduler::{
consumer::{self, types::process_data, workflows::ProcessTrackerWorkflow},
errors as sch_errors, utils as scheduler_utils,
};
#[cfg(feature = "v1")]
use crate::core::webhooks::incoming::get_payment_attempt_from_object_reference_id;
use crate::{
core::disputes,
db::StorageInterface,
errors,
routes::SessionState,
types::{api, domain, storage},
};
pub struct ProcessDisputeWorkflow;
/// This workflow inserts only new dispute records into the dispute table and triggers related outgoing webhook
#[async_trait::async_trait]
impl ProcessTrackerWorkflow<SessionState> for ProcessDisputeWorkflow {
#[cfg(feature = "v2")]
async fn execute_workflow<'a>(
&'a self,
_state: &'a SessionState,
_process: storage::ProcessTracker,
) -> Result<(), sch_errors::ProcessTrackerError> {
todo!()
}
#[cfg(feature = "v1")]
async fn execute_workflow<'a>(
&'a self,
state: &'a SessionState,
process: storage::ProcessTracker,
) -> Result<(), sch_errors::ProcessTrackerError> {
let db: &dyn StorageInterface = &*state.store;
let tracking_data: api::ProcessDisputePTData = process
.tracking_data
.clone()
.parse_value("ProcessDisputePTData")?;
let key_manager_state = &state.into();
let key_store = db
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&tracking_data.merchant_id,
&db.get_master_key().to_vec().into(),
)
.await?;
let merchant_account = db
.find_merchant_account_by_merchant_id(
key_manager_state,
&tracking_data.merchant_id,
&key_store,
)
.await?;
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(domain::Context(
merchant_account.clone(),
key_store.clone(),
)));
let payment_attempt = get_payment_attempt_from_object_reference_id(
state,
tracking_data.dispute_payload.object_reference_id.clone(),
&merchant_context,
)
.await?;
let business_profile = state
.store
.find_business_profile_by_profile_id(
&(state).into(),
merchant_context.get_merchant_key_store(),
&payment_attempt.profile_id,
)
.await?;
// Check if the dispute already exists
let dispute = state
.store
.find_by_merchant_id_payment_id_connector_dispute_id(
merchant_context.get_merchant_account().get_id(),
&payment_attempt.payment_id,
&tracking_data.dispute_payload.connector_dispute_id,
)
.await
.ok()
.flatten();
if dispute.is_some() {
// Dispute already exists — mark the process as complete
state
.store
.as_scheduler()
.finish_process_with_business_status(process, business_status::COMPLETED_BY_PT)
.await?;
} else {
// Update dispute data
let response = disputes::update_dispute_data(
state,
merchant_context,
business_profile,
dispute,
tracking_data.dispute_payload,
payment_attempt,
tracking_data.connector_name.as_str(),
)
.await
.map_err(|error| logger::error!("Dispute update failed: {error}"));
match response {
Ok(_) => {
state
.store
.as_scheduler()
.finish_process_with_business_status(
process,
business_status::COMPLETED_BY_PT,
)
.await?;
}
Err(_) => {
retry_sync_task(
db,
tracking_data.connector_name,
tracking_data.merchant_id,
process,
)
.await?;
}
}
}
Ok(())
}
async fn error_handler<'a>(
&'a self,
state: &'a SessionState,
process: storage::ProcessTracker,
error: sch_errors::ProcessTrackerError,
) -> errors::CustomResult<(), sch_errors::ProcessTrackerError> {
consumer::consumer_error_handler(state.store.as_scheduler(), process, error).await
}
}
pub async fn get_sync_process_schedule_time(
db: &dyn StorageInterface,
connector: &str,
merchant_id: &common_utils::id_type::MerchantId,
retry_count: i32,
) -> Result<Option<time::PrimitiveDateTime>, errors::ProcessTrackerError> {
let mapping: common_utils::errors::CustomResult<
process_data::ConnectorPTMapping,
errors::StorageError,
> = db
.find_config_by_key(&format!("pt_mapping_{connector}"))
.await
.map(|value| value.config)
.and_then(|config| {
config
.parse_struct("ConnectorPTMapping")
.change_context(errors::StorageError::DeserializationFailed)
});
let mapping = match mapping {
Ok(x) => x,
Err(error) => {
logger::info!(?error, "Redis Mapping Error");
process_data::ConnectorPTMapping::default()
}
};
let time_delta = scheduler_utils::get_schedule_time(mapping, merchant_id, retry_count);
Ok(scheduler_utils::get_time_from_delta(time_delta))
}
/// Schedule the task for retry
///
/// Returns bool which indicates whether this was the last retry or not
pub async fn retry_sync_task(
db: &dyn StorageInterface,
connector: String,
merchant_id: common_utils::id_type::MerchantId,
pt: storage::ProcessTracker,
) -> Result<bool, sch_errors::ProcessTrackerError> {
let schedule_time =
get_sync_process_schedule_time(db, &connector, &merchant_id, pt.retry_count + 1).await?;
match schedule_time {
Some(s_time) => {
db.as_scheduler().retry_process(pt, s_time).await?;
Ok(false)
}
None => {
db.as_scheduler()
.finish_process_with_business_status(pt, business_status::RETRIES_EXCEEDED)
.await?;
Ok(true)
}
}
}
|
crates/router/src/workflows/process_dispute.rs
|
router::src::workflows::process_dispute
| 1,373
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.