text stringlengths 70 351k | source stringclasses 4 values |
|---|---|
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/transformers.rs | crate: router
header_payload,
connector_mandate_request_reference_id,
authentication_id: None,
psd2_sca_exemption_type: None,
};
Ok(router_data)
}
#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
#[instrument(skip_all)]
#[allow(clippy::too_many_arguments)]
pub async fn construct_payment_router_data<'a, F, T>(
state: &'a SessionState,
payment_data: PaymentData<F>,
connector_id: &str,
merchant_account: &domain::MerchantAccount,
_key_store: &domain::MerchantKeyStore,
customer: &'a Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
) -> RouterResult<types::RouterData<F, T, types::PaymentsResponseData>>
where
T: TryFrom<PaymentAdditionalData<'a, F>>,
pub async fn construct_payment_router_data<'a, F, T>(
state: &'a SessionState,
payment_data: PaymentData<F>,
connector_id: &str,
merchant_account: &domain::MerchantAccount,
_key_store: &domain::MerchantKeyStore,
customer: &'a Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
) -> RouterResult<types::RouterData<F, T, types::PaymentsResponseData>>
where
T: TryFrom<PaymentAdditionalData<'a, F>>,
types::RouterData<F, T, types::PaymentsResponseData>: Feature<F, T>,
F: Clone,
error_stack::Report<errors::ApiErrorResponse>:
From<<T as TryFrom<PaymentAdditionalData<'a, F>>>::Error>,
{
{let (payment_method, router_data);<|fim_suffix|>
<|fim_middle|>
Ok(router_data)}}
| ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/transformers.rs | crate: router
header_payload,
connector_mandate_request_reference_id: None,
psd2_sca_exemption_type: None,
authentication_id: None,
};
Ok(router_data)
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
#[allow(clippy::too_many_arguments)]
pub async fn construct_payment_router_data_for_setup_mandate<'a>(
state: &'a SessionState,
payment_data: hyperswitch_domain_models::payments::PaymentConfirmData<api::SetupMandate>,
connector_id: &str,
merchant_account: &domain::MerchantAccount,
_key_store: &domain::MerchantKeyStore,
customer: &'a Option<domain::Customer>,
merchant_connector_account: &domain::MerchantConnectorAccount,
_merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
) -> RouterResult<types::SetupMandateRouterData> {
fp_utils::when(merchant_connector_account.is_disabled(), || {
Err(errors::ApiErrorResponse::MerchantConnectorAccountDisabled)
pub async fn construct_payment_router_data_for_setup_mandate<'a>(
state: &'a SessionState,
payment_data: hyperswitch_domain_models::payments::PaymentConfirmData<api::SetupMandate>,
connector_id: &str,
merchant_account: &domain::MerchantAccount,
_key_store: &domain::MerchantKeyStore,
customer: &'a Option<domain::Customer>,
merchant_connector_account: &domain::MerchantConnectorAccount,
_merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
) -> RouterResult<types::SetupMandateRouterData> {
<|fim_suffix|>
<|fim_middle|>
}
| ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/transformers.rs | crate: router
additional_merchant_data: None,
header_payload: None,
connector_mandate_request_reference_id,
authentication_id: None,
psd2_sca_exemption_type: None,
};
Ok(router_data)
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
#[allow(clippy::too_many_arguments)]
pub async fn construct_payment_router_data_for_authorize<'a>(
state: &'a SessionState,
payment_data: hyperswitch_domain_models::payments::PaymentConfirmData<api::Authorize>,
connector_id: &str,
merchant_account: &domain::MerchantAccount,
_key_store: &domain::MerchantKeyStore,
customer: &'a Option<domain::Customer>,
merchant_connector_account: &domain::MerchantConnectorAccount,
_merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
) -> RouterResult<types::PaymentsAuthorizeRouterData> {
use masking::ExposeOptionInterface;
pub async fn construct_payment_router_data_for_authorize<'a>(
state: &'a SessionState,
payment_data: hyperswitch_domain_models::payments::PaymentConfirmData<api::Authorize>,
connector_id: &str,
merchant_account: &domain::MerchantAccount,
_key_store: &domain::MerchantKeyStore,
customer: &'a Option<domain::Customer>,
merchant_connector_account: &domain::MerchantConnectorAccount,
_merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
) -> RouterResult<types::PaymentsAuthorizeRouterData> {
{use masking::ExposeOptionInterface;<|fim_suffix|>
<|fim_middle|>
Ok(router_data)}}
| ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
});
}
}
};
}
common_types::payments::XenditSplitRequest::SingleSplit(_) => (),
},
None => (),
}
Ok(())
}
pub async fn is_merchant_eligible_authentication_service(
merchant_id: &id_type::MerchantId,
state: &SessionState,
) -> RouterResult<bool> {
let merchants_eligible_for_authentication_service = state
.store
.as_ref()
.find_config_by_key_unwrap_or(
consts::AUTHENTICATION_SERVICE_ELIGIBLE_CONFIG,
Some("[]".to_string()),
)
.await;
pub async fn is_merchant_eligible_authentication_service(
merchant_id: &id_type::MerchantId,
state: &SessionState,
) -> RouterResult<bool> {
<|fim_suffix|>
<|fim_middle|>
}
| ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
if skip_saving_wallet_at_connector.contains(&payment_method_type) {
logger::debug!("Override setup_future_usage from off_session to on_session based on the merchant's skip_saving_wallet_at_connector configuration to avoid creating a connector mandate.");
payment_data
.set_setup_future_usage_in_payment_intent(enums::FutureUsage::OnSession);
}
}
};
};
Ok(())
}
#[cfg(feature = "v1")]
pub async fn validate_merchant_connector_ids_in_connector_mandate_details(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
connector_mandate_details: &api_models::payment_methods::CommonMandateReference,
merchant_id: &id_type::MerchantId,
card_network: Option<api_enums::CardNetwork>,
) -> CustomResult<(), errors::ApiErrorResponse> {
let db = &*state.store;
let merchant_connector_account_list = db
.find_merchant_connector_account_by_merchant_id_and_disabled_list(
&state.into(),
merchant_id,
true,
pub async fn validate_merchant_connector_ids_in_connector_mandate_details(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
connector_mandate_details: &api_models::payment_methods::CommonMandateReference,
merchant_id: &id_type::MerchantId,
card_network: Option<api_enums::CardNetwork>,
) -> CustomResult<(), errors::ApiErrorResponse> {
<|fim_suffix|>
<|fim_middle|>
}
| ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
serde_json::from_str::<Vec<storage_enums::PaymentMethodType>>(&conf.config)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("skip_save_wallet_at_connector config parsing failed")?,
),
Err(error) => {
logger::error!(?error);
None
}
})
}
#[cfg(feature = "v1")]
pub async fn override_setup_future_usage_to_on_session<F, D>(
db: &dyn StorageInterface,
payment_data: &mut D,
) -> CustomResult<(), errors::ApiErrorResponse>
where
F: Clone,
D: payments::OperationSessionGetters<F> + payments::OperationSessionSetters<F> + Send,
{
if payment_data.get_payment_intent().setup_future_usage == Some(enums::FutureUsage::OffSession)
{
let skip_saving_wallet_at_connector_optional = config_skip_saving_wallet_at_connector(
db,
&payment_data.get_payment_intent().merchant_id,
pub async fn override_setup_future_usage_to_on_session<F, D>(
db: &dyn StorageInterface,
payment_data: &mut D,
) -> CustomResult<(), errors::ApiErrorResponse>
where
F: Clone,
D: payments::OperationSessionGetters<F> + payments::OperationSessionSetters<F> + Send,
{
{<|fim_suffix|>
<|fim_middle|>
}}
| ast_fragments |
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
pub fn get_redis_key_for_extended_card_info(
merchant_id: &id_type::MerchantId,
payment_id: &id_type::PaymentId,
) -> String {
format!(
"{}_{}_extended_card_info",
merchant_id.get_string_repr(),
payment_id.get_string_repr()
)
}
pub fn check_integrity_based_on_flow<T, Request>(
request: &Request,
payment_response_data: &Result<PaymentsResponseData, ErrorResponse>,
) -> Result<(), common_utils::errors::IntegrityCheckError>
where
T: FlowIntegrity,
Request: GetIntegrityObject<T> + CheckIntegrity<Request, T>,
{
let connector_transaction_id = match payment_response_data {
Ok(resp_data) => match resp_data {
PaymentsResponseData::TransactionResponse {
connector_response_reference_id,
..
pub fn check_integrity_based_on_flow<T, Request>(
request: &Request,
payment_response_data: &Result<PaymentsResponseData, ErrorResponse>,
) -> Result<(), common_utils::errors::IntegrityCheckError>
where
T: FlowIntegrity,
Request: GetIntegrityObject<T> + CheckIntegrity<Request, T>,
{
let connector_transaction_id = match payment_response_data {
Ok(resp_data) => match resp_data {
PaymentsResponseData::TransactionResponse {
connector_response_reference_id,
..
} => connector_response_reference_id,
PaymentsResponseData::TransactionUnresolvedResponse {
connector_response_reference_id,
..
} => connector_response_reference_id,
PaymentsResponseData::PreProcessingResponse {
connector_response_reference_id,
..
} => connector_response_reference_id,
_ => &None,
},
Err(_) => &None,
};
request.check_integrity(request, connector_transaction_id.to_owned())
} | ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
ExternalAuthenticationInitiate {
acquirer_details: Option<authentication::types::AcquirerDetails>,
card: Box<hyperswitch_domain_models::payment_method_data::Card>,
token: String,
},
ExternalAuthenticationPostAuthenticate {
authentication_id: String,
},
ClickToPayConfirmation,
}
#[cfg(feature = "v1")]
pub async fn decide_action_for_unified_authentication_service<F: Clone>(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
business_profile: &domain::Profile,
payment_data: &mut PaymentData<F>,
connector_call_type: &api::ConnectorCallType,
mandate_type: Option<api_models::payments::MandateTransactionType>,
do_authorisation_confirmation: &bool,
) -> RouterResult<Option<UnifiedAuthenticationServiceFlow>> {
let external_authentication_flow = get_payment_external_authentication_flow_during_confirm(
state,
key_store,
business_profile,
pub async fn decide_action_for_unified_authentication_service<F: Clone>(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
business_profile: &domain::Profile,
payment_data: &mut PaymentData<F>,
connector_call_type: &api::ConnectorCallType,
mandate_type: Option<api_models::payments::MandateTransactionType>,
do_authorisation_confirmation: &bool,
) -> RouterResult<Option<UnifiedAuthenticationServiceFlow>> {
<|fim_suffix|>
<|fim_middle|>
}
| ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
api_models::payments::AdditionalPaymentData::PayLater { .. },
AdditionalPaymentMethodConnectorResponse::PayLater {
klarna_sdk: Some(KlarnaSdkResponse { payment_type }),
},
) => api_models::payments::AdditionalPaymentData::PayLater {
klarna_sdk: Some(api_models::payments::KlarnaSdkPaymentMethod { payment_type }),
},
_ => additional_payment_data,
}
}
pub fn update_additional_payment_data_with_connector_response_pm_data(
additional_payment_data: Option<serde_json::Value>,
connector_response_pm_data: Option<AdditionalPaymentMethodConnectorResponse>,
) -> RouterResult<Option<serde_json::Value>> {
let parsed_additional_payment_method_data = additional_payment_data
.as_ref()
.map(|payment_method_data| {
payment_method_data
.clone()
.parse_value::<api_models::payments::AdditionalPaymentData>(
"additional_payment_method_data",
)
})
pub fn update_additional_payment_data_with_connector_response_pm_data(
additional_payment_data: Option<serde_json::Value>,
connector_response_pm_data: Option<AdditionalPaymentMethodConnectorResponse>,
) -> RouterResult<Option<serde_json::Value>> {
<|fim_suffix|>
<|fim_middle|>
}
| ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
if !(consts::MIN_INTENT_FULFILLMENT_EXPIRY..=consts::MAX_INTENT_FULFILLMENT_EXPIRY)
.contains(&intent_fulfillment_time)
{
Err(errors::ApiErrorResponse::InvalidRequestData {
message: "intent_fulfillment_time should be between 60(1 min) to 1800(30 mins)."
.to_string(),
})
} else {
Ok(())
}
}
pub fn add_connector_response_to_additional_payment_data(
additional_payment_data: api_models::payments::AdditionalPaymentData,
connector_response_payment_method_data: AdditionalPaymentMethodConnectorResponse,
) -> api_models::payments::AdditionalPaymentData {
match (
&additional_payment_data,
connector_response_payment_method_data,
) {
(
api_models::payments::AdditionalPaymentData::Card(additional_card_data),
AdditionalPaymentMethodConnectorResponse::Card {
authentication_data,
payment_checks,
pub fn add_connector_response_to_additional_payment_data(
additional_payment_data: api_models::payments::AdditionalPaymentData,
connector_response_payment_method_data: AdditionalPaymentMethodConnectorResponse,
) -> api_models::payments::AdditionalPaymentData {
{<|fim_suffix|>
<|fim_middle|>
}}
| ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
use redis_interface::errors::RedisError;
use crate::{
configs::settings::{ConnectorRequestReferenceIdConfig, TempLockerEnableConfig},
connector,
consts::{self, BASE64_ENGINE},
core::{
authentication,
errors::{self, CustomResult, RouterResult, StorageErrorExt},
mandate::helpers::MandateGenericData,
payment_methods::{
self,
cards::{self},
network_tokenization, vault,
},
payments,
pm_auth::retrieve_payment_method_from_auth_service,
},
db::StorageInterface,
routes::{metrics, payment_methods as payment_methods_handler, SessionState},
services,
types::{
api::{self, admin, enums as api_enums, MandateValidationFieldsExt},
domain::{self, types},
storage::{self, enums as storage_enums, ephemeral_key, CardTokenData},
transformers::{ForeignFrom, ForeignTryFrom},
AdditionalMerchantData, AdditionalPaymentMethodConnectorResponse, ErrorResponse,
MandateReference, MerchantAccountData, MerchantRecipientData, PaymentsResponseData,
RecipientIdType, RecurringMandatePaymentData, RouterData,
},
utils::{
self,
crypto::{self, SignMessage},
OptionExt, StringExt,
},
};
pub fn get_recipient_id_for_open_banking(
merchant_data: &AdditionalMerchantData,
) -> Result<Option<String>, errors::ApiErrorResponse> {
<|fim_suffix|>
<|fim_middle|>
}
| ast_fragments |
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
use redis_interface::errors::RedisError;
use router_env::{instrument, logger, tracing};
use crate::{
configs::settings::{ConnectorRequestReferenceIdConfig, TempLockerEnableConfig},
connector,
consts::{self, BASE64_ENGINE},
core::{
authentication,
errors::{self, CustomResult, RouterResult, StorageErrorExt},
mandate::helpers::MandateGenericData,
payment_methods::{
self,
cards::{self},
network_tokenization, vault,
},
payments,
pm_auth::retrieve_payment_method_from_auth_service,
},
db::StorageInterface,
routes::{metrics, payment_methods as payment_methods_handler, SessionState},
services,
types::{
api::{self, admin, enums as api_enums, MandateValidationFieldsExt},
domain::{self, types},
storage::{self, enums as storage_enums, ephemeral_key, CardTokenData},
transformers::{ForeignFrom, ForeignTryFrom},
AdditionalMerchantData, AdditionalPaymentMethodConnectorResponse, ErrorResponse,
MandateReference, MerchantAccountData, MerchantRecipientData, PaymentsResponseData,
RecipientIdType, RecurringMandatePaymentData, RouterData,
},
utils::{
self,
crypto::{self, SignMessage},
OptionExt, StringExt,
},
};
pub async fn get_unified_translation(
state: &SessionState,
unified_code: String,
unified_message: String,
locale: String,
) -> Option<String> {
let get_unified_translation = || async {
state.store.find_translation(
unified_code.clone(),
unified_message.clone(),
locale.clone(),
)
.await
.map_err(|err| {
if err.current_context().is_db_not_found() {
logger::warn!(
"Translation missing for unified_code - {:?}, unified_message - {:?}, locale - {:?}",
unified_code,
unified_message,
locale
);
}
err.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed to fetch translation from unified_translations")
})
};
get_unified_translation()
.await
.inspect_err(|err| {
// warn log should suffice here because we are not propagating this error
logger::warn!(get_translation_error=?err, "error fetching unified translations");
})
.ok()
} | ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
use redis_interface::errors::RedisError;
use router_env::{instrument, logger, tracing};
use crate::{
configs::settings::{ConnectorRequestReferenceIdConfig, TempLockerEnableConfig},
connector,
consts::{self, BASE64_ENGINE},
core::{
authentication,
errors::{self, CustomResult, RouterResult, StorageErrorExt},
mandate::helpers::MandateGenericData,
payment_methods::{
self,
cards::{self},
network_tokenization, vault,
},
payments,
pm_auth::retrieve_payment_method_from_auth_service,
},
db::StorageInterface,
routes::{metrics, payment_methods as payment_methods_handler, SessionState},
services,
types::{
api::{self, admin, enums as api_enums, MandateValidationFieldsExt},
domain::{self, types},
storage::{self, enums as storage_enums, ephemeral_key, CardTokenData},
transformers::{ForeignFrom, ForeignTryFrom},
AdditionalMerchantData, AdditionalPaymentMethodConnectorResponse, ErrorResponse,
MandateReference, MerchantAccountData, MerchantRecipientData, PaymentsResponseData,
RecipientIdType, RecurringMandatePaymentData, RouterData,
},
utils::{
self,
crypto::{self, SignMessage},
OptionExt, StringExt,
},
};
use crate::{
core::payment_methods::cards::create_encrypted_data, types::storage::CustomerUpdate::Update,
};
pub async fn get_gsm_record(
state: &SessionState,
error_code: Option<String>,
error_message: Option<String>,
connector_name: String,
flow: String,
) -> Option<storage::gsm::GatewayStatusMap> {
<|fim_suffix|>
<|fim_middle|>
}
| ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
symmetric_key,
Some(&iv),
&[],
encrypted_message,
tag,
)
.change_context(errors::GooglePayDecryptionError::DecryptionFailed)?;
Ok(decrypted_data)
}
}
pub fn decrypt_paze_token(
paze_wallet_data: PazeWalletData,
paze_private_key: masking::Secret<String>,
paze_private_key_passphrase: masking::Secret<String>,
) -> CustomResult<serde_json::Value, errors::PazeDecryptionError> {
let decoded_paze_private_key = BASE64_ENGINE
.decode(paze_private_key.expose().as_bytes())
.change_context(errors::PazeDecryptionError::Base64DecodingFailed)?;
let decrypted_private_key = openssl::rsa::Rsa::private_key_from_pem_passphrase(
decoded_paze_private_key.as_slice(),
paze_private_key_passphrase.expose().as_bytes(),
)
.change_context(errors::PazeDecryptionError::CertificateParsingFailed)?;
pub fn decrypt_paze_token(
paze_wallet_data: PazeWalletData,
paze_private_key: masking::Secret<String>,
paze_private_key_passphrase: masking::Secret<String>,
) -> CustomResult<serde_json::Value, errors::PazeDecryptionError> {
<|fim_suffix|>
<|fim_middle|>
}
| ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
fn verify_hmac(
&self,
mac_key: &[u8],
tag: &[u8],
encrypted_message: &[u8],
) -> CustomResult<(), errors::GooglePayDecryptionError> {
let hmac_key = ring::hmac::Key::new(ring::hmac::HMAC_SHA256, mac_key);
ring::hmac::verify(&hmac_key, encrypted_message, tag)
.change_context(errors::GooglePayDecryptionError::HmacVerificationFailed)
}
// Method to decrypt the AES-GCM encrypted message
fn decrypt_message(
&self,
symmetric_key: &[u8],
encrypted_message: &[u8],
) -> CustomResult<Vec<u8>, errors::GooglePayDecryptionError> {
//initialization vector IV is typically used in AES-GCM (Galois/Counter Mode) encryption for randomizing the encryption process.
// zero iv is being passed as specified in Google Pay documentation
// https://developers.google.com/pay/api/android/guides/resources/payment-data-cryptography#decrypt-token
let iv = [0u8; 16];
// extract the tag from the end of the encrypted message
let tag = encrypted_message
.get(encrypted_message.len() - 16..)
fn decrypt_message(
&self,
symmetric_key: &[u8],
encrypted_message: &[u8],
) -> CustomResult<Vec<u8>, errors::GooglePayDecryptionError> {
{<|fim_suffix|>
<|fim_middle|>
}}
| ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
deriver
.set_peer(&ephemeral_pkey)
.change_context(errors::GooglePayDecryptionError::DerivingSharedSecretKeyFailed)?;
let shared_key = deriver
.derive_to_vec()
.change_context(errors::GooglePayDecryptionError::DerivingSharedSecretKeyFailed)?;
Ok(shared_key)
}
// Derive symmetric key and MAC key using HKDF
fn derive_key(
&self,
ephemeral_public_key_bytes: &[u8],
shared_key: &[u8],
) -> CustomResult<Vec<u8>, errors::GooglePayDecryptionError> {
// concatenate ephemeral public key and shared key
let input_key_material = [ephemeral_public_key_bytes, shared_key].concat();
// initialize HKDF with SHA-256 as the hash function
// Salt is not provided as per the Google Pay documentation
// https://developers.google.com/pay/api/android/guides/resources/payment-data-cryptography#encrypt-spec
let hkdf: ::hkdf::Hkdf<sha2::Sha256> = ::hkdf::Hkdf::new(None, &input_key_material);
fn derive_key(
&self,
ephemeral_public_key_bytes: &[u8],
shared_key: &[u8],
) -> CustomResult<Vec<u8>, errors::GooglePayDecryptionError> {
<|fim_suffix|>
<|fim_middle|>
}
| ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
signed_data.append(&mut sender_id.as_bytes().to_vec());
signed_data.append(&mut get_little_endian_format(length_of_recipient_id));
signed_data.append(&mut recipient_id.as_bytes().to_vec());
signed_data.append(&mut get_little_endian_format(length_of_protocol_version));
signed_data.append(&mut protocol_version.as_bytes().to_vec());
signed_data.append(&mut get_little_endian_format(length_of_signed_key));
signed_data.append(&mut signed_key.as_bytes().to_vec());
Ok(signed_data)
}
// Derive a shared key using ECDH
fn get_shared_key(
&self,
ephemeral_public_key_bytes: &[u8],
) -> CustomResult<Vec<u8>, errors::GooglePayDecryptionError> {
let group = openssl::ec::EcGroup::from_curve_name(openssl::nid::Nid::X9_62_PRIME256V1)
.change_context(errors::GooglePayDecryptionError::DerivingEcGroupFailed)?;
let mut big_num_context = openssl::bn::BigNumContext::new()
.change_context(errors::GooglePayDecryptionError::BigNumAllocationFailed)?;
let ec_key = openssl::ec::EcPoint::from_bytes(
&group,
ephemeral_public_key_bytes,
fn get_shared_key(
&self,
ephemeral_public_key_bytes: &[u8],
) -> CustomResult<Vec<u8>, errors::GooglePayDecryptionError> {
{<|fim_suffix|>
<|fim_middle|>
}}
| ast_fragments |
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
// parse the DER-encoded data as an EC public key
let ec_key = openssl::ec::EcKey::public_key_from_der(&der_data)
.change_context(errors::GooglePayDecryptionError::DerivingEcKeyFailed)?;
// wrap the EC key in a PKey (a more general-purpose public key type in OpenSSL)
let public_key = PKey::from_ec_key(ec_key)
.change_context(errors::GooglePayDecryptionError::DerivingPublicKeyFailed)?;
Ok(public_key)
}
// Construct signed data for signature verification
fn construct_signed_data_for_signature_verification(
&self,
sender_id: &str,
protocol_version: &str,
signed_key: &str,
) -> CustomResult<Vec<u8>, errors::GooglePayDecryptionError> {
let recipient_id = self.recipient_id.clone().expose();
let length_of_sender_id = u32::try_from(sender_id.len())
.change_context(errors::GooglePayDecryptionError::ParsingFailed)?;
let length_of_recipient_id = u32::try_from(recipient_id.len())
.change_context(errors::GooglePayDecryptionError::ParsingFailed)?;
let length_of_protocol_version = u32::try_from(protocol_version.len())
.change_context(errors::GooglePayDecryptionError::ParsingFailed)?;
fn construct_signed_data_for_signature_verification(
&self,
sender_id: &str,
protocol_version: &str,
signed_key: &str,
) -> CustomResult<Vec<u8>, errors::GooglePayDecryptionError> {
let recipient_id = self.recipient_id.clone().expose();
let length_of_sender_id = u32::try_from(sender_id.len())
.change_context(errors::GooglePayDecryptionError::ParsingFailed)?;
let length_of_recipient_id = u32::try_from(recipient_id.len())
.change_context(errors::GooglePayDecryptionError::ParsingFailed)?;
let length_of_protocol_version = u32::try_from(protocol_version.len())
.change_context(errors::GooglePayDecryptionError::ParsingFailed)?;
let length_of_signed_key = u32::try_from(signed_key.len())
.change_context(errors::GooglePayDecryptionError::ParsingFailed)?;
let mut signed_data: Vec<u8> = Vec::new();
signed_data.append(&mut get_little_endian_format(length_of_sender_id));
signed_data.append(&mut sender_id.as_bytes().to_vec());
signed_data.append(&mut get_little_endian_format(length_of_recipient_id));
signed_data.append(&mut recipient_id.as_bytes().to_vec());
signed_data.append(&mut get_little_endian_format(length_of_protocol_version));
signed_data.append(&mut protocol_version.as_bytes().to_vec());
signed_data.append(&mut get_little_endian_format(length_of_signed_key));
signed_data.append(&mut signed_key.as_bytes().to_vec());
Ok(signed_data)
} | ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
.parse_struct("GooglePaySignedKey")
.change_context(errors::GooglePayDecryptionError::SignedKeyParsingFailure)?;
if !matches!(
check_expiration_date_is_valid(&signed_key.key_expiration),
Ok(true)
) {
return Err(errors::GooglePayDecryptionError::SignedKeyExpired)?;
}
Ok(signed_key)
}
// Verify the signed message
fn verify_message_signature(
&self,
encrypted_data: &EncryptedData,
signed_key: &GooglePaySignedKey,
) -> CustomResult<(), errors::GooglePayDecryptionError> {
// create a public key from the intermediate signing key
let public_key = self.load_public_key(signed_key.key_value.peek())?;
// base64 decode the signature
let signature = BASE64_ENGINE
.decode(&encrypted_data.signature)
.change_context(errors::GooglePayDecryptionError::Base64DecodingFailed)?;
// parse the signature using ECDSA
fn verify_message_signature(
&self,
encrypted_data: &EncryptedData,
signed_key: &GooglePaySignedKey,
) -> CustomResult<(), errors::GooglePayDecryptionError> {
<|fim_suffix|>
<|fim_middle|>
}
| ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
return Err(errors::GooglePayDecryptionError::InvalidProtocolVersion.into());
}
// verify the intermediate signing key
self.verify_intermediate_signing_key(encrypted_data)?;
// validate and fetch the signed key
let signed_key = self.validate_signed_key(&encrypted_data.intermediate_signing_key)?;
// verify the signature of the token
self.verify_message_signature(encrypted_data, &signed_key)
}
// Verify the intermediate signing key
fn verify_intermediate_signing_key(
&self,
encrypted_data: &EncryptedData,
) -> CustomResult<(), errors::GooglePayDecryptionError> {
let mut signatrues: Vec<openssl::ecdsa::EcdsaSig> = Vec::new();
// decode and parse the signatures
for signature in encrypted_data.intermediate_signing_key.signatures.iter() {
let signature = BASE64_ENGINE
.decode(signature.peek())
.change_context(errors::GooglePayDecryptionError::Base64DecodingFailed)?;
let ecdsa_signature = openssl::ecdsa::EcdsaSig::from_der(&signature)
.change_context(errors::GooglePayDecryptionError::EcdsaSignatureParsingFailed)?;
fn verify_intermediate_signing_key(
&self,
encrypted_data: &EncryptedData,
) -> CustomResult<(), errors::GooglePayDecryptionError> {
<|fim_suffix|>
<|fim_middle|>
}
| ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
// parse and filter the root signing keys by protocol version
let filtered_root_signing_keys = filter_root_signing_keys(root_keys_vector)?;
Ok(Self {
root_signing_keys: filtered_root_signing_keys,
recipient_id,
private_key,
})
}
// Decrypt the Google pay token
pub fn decrypt_token(
&self,
data: String,
should_verify_signature: bool,
) -> CustomResult<
hyperswitch_domain_models::router_data::GooglePayDecryptedData,
errors::GooglePayDecryptionError,
> {
// parse the encrypted data
let encrypted_data: EncryptedData = data
.parse_struct("EncryptedData")
.change_context(errors::GooglePayDecryptionError::DeserializationFailed)?;
pub fn decrypt_token(
&self,
data: String,
should_verify_signature: bool,
) -> CustomResult<
hyperswitch_domain_models::router_data::GooglePayDecryptedData,
errors::GooglePayDecryptionError,
> {
<|fim_suffix|>
<|fim_middle|>
}
| ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
.collect::<Vec<GooglePayRootSigningKey>>();
logger::info!(
"Filtered {} out of {} root signing keys",
filtered_root_signing_keys.len(),
root_signing_keys.len()
);
Ok(filtered_root_signing_keys)
}
impl GooglePayTokenDecryptor {
pub fn new(
root_keys: masking::Secret<String>,
recipient_id: masking::Secret<String>,
private_key: masking::Secret<String>,
) -> CustomResult<Self, errors::GooglePayDecryptionError> {
// base64 decode the private key
let decoded_key = BASE64_ENGINE
.decode(private_key.expose())
.change_context(errors::GooglePayDecryptionError::Base64DecodingFailed)?;
// base64 decode the root signing keys
let decoded_root_signing_keys = BASE64_ENGINE
.decode(root_keys.expose())
.change_context(errors::GooglePayDecryptionError::Base64DecodingFailed)?;
pub fn new(
root_keys: masking::Secret<String>,
recipient_id: masking::Secret<String>,
private_key: masking::Secret<String>,
) -> CustomResult<Self, errors::GooglePayDecryptionError> {
{<|fim_suffix|>
<|fim_middle|>
}}
| ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
use redis_interface::errors::RedisError;
use router_env::{instrument, logger, tracing};
use crate::{
configs::settings::{ConnectorRequestReferenceIdConfig, TempLockerEnableConfig},
connector,
consts::{self, BASE64_ENGINE},
core::{
authentication,
errors::{self, CustomResult, RouterResult, StorageErrorExt},
mandate::helpers::MandateGenericData,
payment_methods::{
self,
cards::{self},
network_tokenization, vault,
},
payments,
pm_auth::retrieve_payment_method_from_auth_service,
},
db::StorageInterface,
routes::{metrics, payment_methods as payment_methods_handler, SessionState},
services,
types::{
api::{self, admin, enums as api_enums, MandateValidationFieldsExt},
domain::{self, types},
storage::{self, enums as storage_enums, ephemeral_key, CardTokenData},
transformers::{ForeignFrom, ForeignTryFrom},
AdditionalMerchantData, AdditionalPaymentMethodConnectorResponse, ErrorResponse,
MandateReference, MerchantAccountData, MerchantRecipientData, PaymentsResponseData,
RecipientIdType, RecurringMandatePaymentData, RouterData,
},
utils::{
self,
crypto::{self, SignMessage},
OptionExt, StringExt,
},
};
fn filter_root_signing_keys(
root_signing_keys: Vec<GooglePayRootSigningKey>,
) -> CustomResult<Vec<GooglePayRootSigningKey>, errors::GooglePayDecryptionError> {
<|fim_suffix|>
<|fim_middle|>
}
| ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
.trim()
.trim_start_matches('@')
.to_string();
merchant_id
})
.ok_or(errors::ApplePayDecryptionError::MissingMerchantId)
.attach_printable("Unable to find merchant ID extension in the certificate")?;
Ok(apple_pay_m_id)
}
pub fn shared_secret(
&self,
payment_processing_certificate_key: &masking::Secret<String>,
) -> CustomResult<Vec<u8>, errors::ApplePayDecryptionError> {
let public_ec_bytes = BASE64_ENGINE
.decode(self.header.ephemeral_public_key.peek().as_bytes())
.change_context(errors::ApplePayDecryptionError::Base64DecodingFailed)?;
let public_key = PKey::public_key_from_der(&public_ec_bytes)
.change_context(errors::ApplePayDecryptionError::KeyDeserializationFailed)
.attach_printable("Failed to deserialize the public key")?;
let decrypted_apple_pay_ppc_key = payment_processing_certificate_key.clone().expose();
pub fn shared_secret(
&self,
payment_processing_certificate_key: &masking::Secret<String>,
) -> CustomResult<Vec<u8>, errors::ApplePayDecryptionError> {
<|fim_suffix|>
<|fim_middle|>
}
| ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
payment_processing_certificate: &masking::Secret<String>,
payment_processing_certificate_key: &masking::Secret<String>,
) -> CustomResult<serde_json::Value, errors::ApplePayDecryptionError> {
let merchant_id = self.merchant_id(payment_processing_certificate)?;
let shared_secret = self.shared_secret(payment_processing_certificate_key)?;
let symmetric_key = self.symmetric_key(&merchant_id, &shared_secret)?;
let decrypted = self.decrypt_ciphertext(&symmetric_key)?;
let parsed_decrypted: serde_json::Value = serde_json::from_str(&decrypted)
.change_context(errors::ApplePayDecryptionError::DecryptionFailed)?;
Ok(parsed_decrypted)
}
pub fn merchant_id(
&self,
payment_processing_certificate: &masking::Secret<String>,
) -> CustomResult<String, errors::ApplePayDecryptionError> {
let cert_data = payment_processing_certificate.clone().expose();
let base64_decode_cert_data = BASE64_ENGINE
.decode(cert_data)
.change_context(errors::ApplePayDecryptionError::Base64DecodingFailed)?;
// Parsing the certificate using x509-parser
let (_, certificate) = parse_x509_certificate(&base64_decode_cert_data)
.change_context(errors::ApplePayDecryptionError::CertificateParsingFailed)
pub fn merchant_id(
&self,
payment_processing_certificate: &masking::Secret<String>,
) -> CustomResult<String, errors::ApplePayDecryptionError> {
<|fim_suffix|>
<|fim_middle|>
}
| ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
.and_then(|d| d.google_pay.clone()),
}
}
};
return Ok(Some(updated_wallet_details));
}
// Return connector_wallets_details if no Apple Pay metadata was found
Ok(connector_wallets_details_optional)
}
pub fn get_applepay_metadata(
connector_metadata: Option<pii::SecretSerdeValue>,
) -> RouterResult<api_models::payments::ApplepaySessionTokenMetadata> {
connector_metadata
.clone()
.parse_value::<api_models::payments::ApplepayCombinedSessionTokenData>(
"ApplepayCombinedSessionTokenData",
)
.map(|combined_metadata| {
api_models::payments::ApplepaySessionTokenMetadata::ApplePayCombined(
combined_metadata.apple_pay_combined,
)
})
pub fn get_applepay_metadata(
connector_metadata: Option<pii::SecretSerdeValue>,
) -> RouterResult<api_models::payments::ApplepaySessionTokenMetadata> {
<|fim_suffix|>
<|fim_middle|>
}
| ast_fragments |
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
// Otherwise, merge Apple Pay metadata
return get_and_merge_apple_pay_metadata(
connector_metadata.clone(),
Some(connector_wallets_details.clone()),
)
.await;
}
// If connector_wallets_details_optional is None, attempt to get Apple Pay metadata
get_and_merge_apple_pay_metadata(connector_metadata.clone(), None).await
}
async fn get_and_merge_apple_pay_metadata(
connector_metadata: Option<masking::Secret<tera::Value>>,
connector_wallets_details_optional: Option<api_models::admin::ConnectorWalletDetails>,
) -> RouterResult<Option<api_models::admin::ConnectorWalletDetails>> {
let apple_pay_metadata_optional = get_applepay_metadata(connector_metadata)
.map_err(|error| {
logger::error!(
"Apple Pay metadata parsing failed in get_encrypted_connector_wallets_details_with_apple_pay_certificates {:?}",
error
);
})
.ok();
async fn get_and_merge_apple_pay_metadata(
connector_metadata: Option<masking::Secret<tera::Value>>,
connector_wallets_details_optional: Option<api_models::admin::ConnectorWalletDetails>,
) -> RouterResult<Option<api_models::admin::ConnectorWalletDetails>> {
let apple_pay_metadata_optional = get_applepay_metadata(connector_metadata)
.map_err(|error| {
logger::error!(
"Apple Pay metadata parsing failed in get_encrypted_connector_wallets_details_with_apple_pay_certificates {:?}",
error
);
})
.ok();
if let Some(apple_pay_metadata) = apple_pay_metadata_optional {
let updated_wallet_details = match apple_pay_metadata {
api_models::payments::ApplepaySessionTokenMetadata::ApplePayCombined(
apple_pay_combined_metadata,
) => {
let combined_metadata_json = serde_json::to_value(apple_pay_combined_metadata)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to serialize Apple Pay combined metadata as JSON")?;
api_models::admin::ConnectorWalletDetails {
apple_pay_combined: Some(masking::Secret::new(combined_metadata_json)),
apple_pay: connector_wallets_details_optional
.as_ref()
.and_then(|d| d.apple_pay.clone()),
samsung_pay: connector_wallets_details_optional
.as_ref()
.and_then(|d| d.samsung_pay.clone()),
paze: connector_wallets_details_optional
.as_ref()
.and_then(|d| d.paze.clone()),
google_pay: connector_wallets_details_optional
.as_ref()
.and_then(|d| d.google_pay.clone()),
}
}
api_models::payments::ApplepaySessionTokenMetadata::ApplePay(apple_pay_metadata) => {
let metadata_json = serde_json::to_value(apple_pay_metadata)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to serialize Apple Pay metadata as JSON")?;
api_models::admin::ConnectorWalletDetails {
apple_pay: Some(masking::Secret::new(metadata_json)),
apple_pay_combined: connector_wallets_details_optional
.as_ref()
.and_then(|d| d.apple_pay_combined.clone()),
samsung_pay: connector_wallets_details_optional
.as_ref()
.and_then(|d| d.samsung_pay.clone()),
paze: connector_wallets_details_optional
.as_ref()
.and_then(|d| d.paze.clone()),
google_pay: connector_wallets_details_optional
.as_ref()
.and_then(|d| d.google_pay.clone()),
}
}
};
return Ok(Some(updated_wallet_details));
}
// Return connector_wallets_details if no Apple Pay metadata was found
Ok(connector_wallets_details_optional)
} | ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
api_models::payments::AdditionalPaymentData::MobilePayment {
details: Some(mobile_payment.to_owned().into()),
},
)),
domain::PaymentMethodData::NetworkToken(_) => Ok(None),
}
}
#[cfg(all(
any(feature = "v1", feature = "v2"),
not(feature = "payment_methods_v2")
))]
pub async fn populate_bin_details_for_payment_method_create(
card_details: api_models::payment_methods::CardDetail,
db: &dyn StorageInterface,
) -> api_models::payment_methods::CardDetail {
let card_isin: Option<_> = Some(card_details.card_number.get_card_isin());
if card_details.card_issuer.is_some()
&& card_details.card_network.is_some()
&& card_details.card_type.is_some()
&& card_details.card_issuing_country.is_some()
{
api::CardDetail {
card_issuer: card_details.card_issuer.to_owned(),
card_network: card_details.card_network.clone(),
pub async fn populate_bin_details_for_payment_method_create(
card_details: api_models::payment_methods::CardDetail,
db: &dyn StorageInterface,
) -> api_models::payment_methods::CardDetail {
{<|fim_suffix|>
<|fim_middle|>
}}
| ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
"manual_retry payment for {:?} with attempt_id {:?}",
updated_payment_intent.get_id(),
new_payment_attempt.get_id()
);
Ok((updated_payment_intent, new_payment_attempt))
}
}
}
}
#[inline(always)]
pub fn is_manual_retry_allowed(
intent_status: &storage_enums::IntentStatus,
attempt_status: &storage_enums::AttemptStatus,
connector_request_reference_id_config: &ConnectorRequestReferenceIdConfig,
merchant_id: &id_type::MerchantId,
) -> Option<bool> {
let is_payment_status_eligible_for_retry = match intent_status {
enums::IntentStatus::Failed => match attempt_status {
enums::AttemptStatus::Started
| enums::AttemptStatus::AuthenticationPending
| enums::AttemptStatus::AuthenticationSuccessful
| enums::AttemptStatus::Authorized
| enums::AttemptStatus::Charged
pub fn is_manual_retry_allowed(
intent_status: &storage_enums::IntentStatus,
attempt_status: &storage_enums::AttemptStatus,
connector_request_reference_id_config: &ConnectorRequestReferenceIdConfig,
merchant_id: &id_type::MerchantId,
) -> Option<bool> {
<|fim_suffix|>
<|fim_middle|>
}
| ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
// #[inline(always)]
// fn make_new_payment_attempt(
// _payment_method_data: Option<&api_models::payments::PaymentMethodData>,
// _old_payment_attempt: PaymentAttempt,
// _new_attempt_count: i16,
// _storage_scheme: enums::MerchantStorageScheme,
// ) -> PaymentAttempt {
// todo!()
// }
#[cfg(feature = "v1")]
#[instrument(skip_all)]
pub async fn modify_payment_intent_and_payment_attempt(
&self,
request: &api_models::payments::PaymentsRequest,
fetched_payment_intent: PaymentIntent,
fetched_payment_attempt: PaymentAttempt,
state: &SessionState,
key_store: &domain::MerchantKeyStore,
storage_scheme: storage::enums::MerchantStorageScheme,
) -> RouterResult<(PaymentIntent, PaymentAttempt)> {
match self {
Self::SameOld => Ok((fetched_payment_intent, fetched_payment_attempt)),
Self::New => {
let db = &*state.store;
pub async fn modify_payment_intent_and_payment_attempt(
&self,
request: &api_models::payments::PaymentsRequest,
fetched_payment_intent: PaymentIntent,
fetched_payment_attempt: PaymentAttempt,
state: &SessionState,
key_store: &domain::MerchantKeyStore,
storage_scheme: storage::enums::MerchantStorageScheme,
) -> RouterResult<(PaymentIntent, PaymentAttempt)> {
{<|fim_suffix|>
<|fim_middle|>
}}
| ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
mca.map(Box::new).map(MerchantConnectorAccountType::DbVal)
}
}
}
/// This function replaces the request and response type of routerdata with the
/// request and response type passed
/// # Arguments
///
/// * `router_data` - original router data
/// * `request` - new request core/helper
/// * `response` - new response
pub fn router_data_type_conversion<F1, F2, Req1, Req2, Res1, Res2>(
router_data: RouterData<F1, Req1, Res1>,
request: Req2,
response: Result<Res2, ErrorResponse>,
) -> RouterData<F2, Req2, Res2> {
RouterData {
flow: std::marker::PhantomData,
request,
response,
merchant_id: router_data.merchant_id,
tenant_id: router_data.tenant_id,
address: router_data.address,
amount_captured: router_data.amount_captured,
/// This function replaces the request and response type of routerdata with the
/// request and response type passed
/// # Arguments
///
/// * `router_data` - original router data
/// * `request` - new request core/helper
/// * `response` - new response
pub fn router_data_type_conversion<F1, F2, Req1, Req2, Res1, Res2>(
router_data: RouterData<F1, Req1, Res1>,
request: Req2,
response: Result<Res2, ErrorResponse>,
) -> RouterData<F2, Req2, Res2> {
<|fim_suffix|>
<|fim_middle|>
}
| ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
psd2_sca_exemption_type: None,
platform_merchant_id: None,
force_3ds_challenge: None,
force_3ds_challenge_trigger: None,
};
let req_cs = Some("1".to_string());
assert!(authenticate_client_secret(req_cs.as_ref(), &payment_intent).is_err())
}
}
// This function will be removed after moving this functionality to server_wrap and using cache instead of config
#[instrument(skip_all)]
pub async fn insert_merchant_connector_creds_to_config(
db: &dyn StorageInterface,
merchant_id: &id_type::MerchantId,
merchant_connector_details: admin::MerchantConnectorDetailsWrap,
) -> RouterResult<()> {
if let Some(encoded_data) = merchant_connector_details.encoded_data {
let redis = &db
.get_redis_conn()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get redis connection")?;
let key =
merchant_id.get_creds_identifier_key(&merchant_connector_details.creds_identifier);
pub async fn insert_merchant_connector_creds_to_config(
db: &dyn StorageInterface,
merchant_id: &id_type::MerchantId,
merchant_connector_details: admin::MerchantConnectorDetailsWrap,
) -> RouterResult<()> {
<|fim_suffix|>
<|fim_middle|>
}
| ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
skip_external_tax_calculation: None,
request_extended_authorization: None,
psd2_sca_exemption_type: None,
platform_merchant_id: None,
force_3ds_challenge: None,
force_3ds_challenge_trigger: None,
};
let req_cs = Some("1".to_string());
assert!(authenticate_client_secret(req_cs.as_ref(), &payment_intent,).is_err())
}
#[test]
fn test_authenticate_client_secret_expired() {
let payment_intent = PaymentIntent {
payment_id: id_type::PaymentId::try_from(Cow::Borrowed("23")).unwrap(),
merchant_id: id_type::MerchantId::default(),
status: storage_enums::IntentStatus::RequiresCapture,
amount: MinorUnit::new(200),
currency: None,
amount_captured: None,
customer_id: None,
description: None,
return_url: None,
metadata: None,
connector_id: None,
fn test_authenticate_client_secret_expired() {
{<|fim_suffix|>
<|fim_middle|>
}}
| ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
request_extended_authorization: None,
psd2_sca_exemption_type: None,
platform_merchant_id: None,
force_3ds_challenge: None,
force_3ds_challenge_trigger: None,
};
let req_cs = Some("1".to_string());
assert!(authenticate_client_secret(req_cs.as_ref(), &payment_intent).is_ok());
// Check if the result is an Ok variant
}
#[test]
fn test_authenticate_client_secret_session_expired() {
let created_at =
common_utils::date_time::now().saturating_sub(time::Duration::seconds(20 * 60));
let payment_intent = PaymentIntent {
payment_id: id_type::PaymentId::try_from(Cow::Borrowed("23")).unwrap(),
merchant_id: id_type::MerchantId::default(),
status: storage_enums::IntentStatus::RequiresCapture,
amount: MinorUnit::new(200),
currency: None,
amount_captured: None,
customer_id: None,
description: None,
return_url: None,
fn test_authenticate_client_secret_session_expired() {
<|fim_suffix|>
<|fim_middle|>
}
| ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
.ok_or(errors::ApiErrorResponse::ClientSecretInvalid)?;
Ok(payment_id.to_string())
}
#[cfg(feature = "v1")]
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used)]
use super::*;
#[test]
fn test_authenticate_client_secret_session_not_expired() {
let payment_intent = PaymentIntent {
payment_id: id_type::PaymentId::try_from(Cow::Borrowed("23")).unwrap(),
merchant_id: id_type::MerchantId::default(),
status: storage_enums::IntentStatus::RequiresCapture,
amount: MinorUnit::new(200),
currency: None,
amount_captured: None,
customer_id: None,
description: None,
return_url: None,
metadata: None,
connector_id: None,
fn test_authenticate_client_secret_session_not_expired() {
{<|fim_suffix|>
<|fim_middle|>
}}
| ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
.await
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
authenticate_client_secret(Some(&cs), &payment_intent)?;
Ok(payment_intent)
})
.await
.transpose()
}
#[cfg(feature = "v1")]
/// Check whether the business details are configured in the merchant account
pub fn validate_business_details(
business_country: Option<api_enums::CountryAlpha2>,
business_label: Option<&String>,
merchant_account: &domain::MerchantAccount,
) -> RouterResult<()> {
let primary_business_details = merchant_account
.primary_business_details
.clone()
.parse_value::<Vec<api_models::admin::PrimaryBusinessDetails>>("PrimaryBusinessDetails")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed to parse primary business details")?;
business_country
/// Check whether the business details are configured in the merchant account
pub fn validate_business_details(
business_country: Option<api_enums::CountryAlpha2>,
business_label: Option<&String>,
merchant_account: &domain::MerchantAccount,
) -> RouterResult<()> {
<|fim_suffix|>
<|fim_middle|>
}
| ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
// A function to perform database lookup and then verify the client secret
pub async fn verify_payment_intent_time_and_client_secret(
state: &SessionState,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
client_secret: Option<String>,
) -> error_stack::Result<Option<PaymentIntent>, errors::ApiErrorResponse> {
todo!()
}
#[cfg(feature = "v1")]
// A function to perform database lookup and then verify the client secret
pub async fn verify_payment_intent_time_and_client_secret(
state: &SessionState,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
client_secret: Option<String>,
) -> error_stack::Result<Option<PaymentIntent>, errors::ApiErrorResponse> {
let db = &*state.store;
client_secret
.async_map(|cs| async move {
let payment_id = get_payment_id_from_client_secret(&cs)?;
let payment_id = id_type::PaymentId::wrap(payment_id).change_context(
errors::ApiErrorResponse::InvalidDataValue {
pub async fn verify_payment_intent_time_and_client_secret(
state: &SessionState,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
client_secret: Option<String>,
) -> error_stack::Result<Option<PaymentIntent>, errors::ApiErrorResponse> {
{<|fim_suffix|>
<|fim_middle|>
}}
| ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
action: &'static str,
) -> Result<(), errors::ApiErrorResponse> {
fp_utils::when(not_allowed_statuses.contains(&intent_status), || {
Err(errors::ApiErrorResponse::PreconditionFailed {
message: format!(
"You cannot {action} this payment because it has status {intent_status}",
),
})
})
}
#[instrument(skip_all)]
pub(crate) fn validate_pm_or_token_given(
payment_method: &Option<api_enums::PaymentMethod>,
payment_method_data: &Option<api::PaymentMethodData>,
payment_method_type: &Option<api_enums::PaymentMethodType>,
mandate_type: &Option<api::MandateTransactionType>,
token: &Option<String>,
ctp_service_details: &Option<api_models::payments::CtpServiceDetails>,
) -> Result<(), errors::ApiErrorResponse> {
utils::when(
!matches!(
payment_method_type,
Some(api_enums::PaymentMethodType::Paypal)
) && !matches!(
pub(crate) fn validate_pm_or_token_given(
payment_method: &Option<api_enums::PaymentMethod>,
payment_method_data: &Option<api::PaymentMethodData>,
payment_method_type: &Option<api_enums::PaymentMethodType>,
mandate_type: &Option<api::MandateTransactionType>,
token: &Option<String>,
ctp_service_details: &Option<api_models::payments::CtpServiceDetails>,
) -> Result<(), errors::ApiErrorResponse> {
{<|fim_suffix|>
<|fim_middle|>
}}
| ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
.set_mandate_type(storage_enums::MandateType::MultiUse)
.to_owned()
}
},
))
}
(_, _) => Ok(None),
}
}
#[cfg(feature = "v1")]
// A function to manually authenticate the client secret with intent fulfillment time
pub fn authenticate_client_secret(
request_client_secret: Option<&String>,
payment_intent: &PaymentIntent,
) -> Result<(), errors::ApiErrorResponse> {
match (request_client_secret, &payment_intent.client_secret) {
(Some(req_cs), Some(pi_cs)) => {
if req_cs != pi_cs {
Err(errors::ApiErrorResponse::ClientSecretInvalid)
} else {
let current_timestamp = common_utils::date_time::now();
let session_expiry = payment_intent.session_expiry.unwrap_or(
payment_intent
pub fn authenticate_client_secret(
request_client_secret: Option<&String>,
payment_intent: &PaymentIntent,
) -> Result<(), errors::ApiErrorResponse> {
<|fim_suffix|>
<|fim_middle|>
}
| ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to sign the message")?;
Ok(hex::encode(signature))
}
pub fn check_if_operation_confirm<Op: std::fmt::Debug>(operations: Op) -> bool {
format!("{operations:?}") == "PaymentConfirm"
}
#[allow(clippy::too_many_arguments)]
pub fn generate_mandate(
merchant_id: id_type::MerchantId,
payment_id: id_type::PaymentId,
connector: String,
setup_mandate_details: Option<MandateData>,
customer_id: &Option<id_type::CustomerId>,
payment_method_id: String,
connector_mandate_id: Option<pii::SecretSerdeValue>,
network_txn_id: Option<String>,
payment_method_data_option: Option<domain::payments::PaymentMethodData>,
mandate_reference: Option<MandateReference>,
merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
) -> CustomResult<Option<storage::MandateNew>, errors::ApiErrorResponse> {
pub fn generate_mandate(
merchant_id: id_type::MerchantId,
payment_id: id_type::PaymentId,
connector: String,
setup_mandate_details: Option<MandateData>,
customer_id: &Option<id_type::CustomerId>,
payment_method_id: String,
connector_mandate_id: Option<pii::SecretSerdeValue>,
network_txn_id: Option<String>,
payment_method_data_option: Option<domain::payments::PaymentMethodData>,
mandate_reference: Option<MandateReference>,
merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
) -> CustomResult<Option<storage::MandateNew>, errors::ApiErrorResponse> {
<|fim_suffix|>
<|fim_middle|>
}
| ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
use std::{borrow::Cow, collections::HashSet, net::IpAddr, str::FromStr};
use redis_interface::errors::RedisError;
use crate::{
configs::settings::{ConnectorRequestReferenceIdConfig, TempLockerEnableConfig},
connector,
consts::{self, BASE64_ENGINE},
core::{
authentication,
errors::{self, CustomResult, RouterResult, StorageErrorExt},
mandate::helpers::MandateGenericData,
payment_methods::{
self,
cards::{self},
network_tokenization, vault,
},
payments,
pm_auth::retrieve_payment_method_from_auth_service,
},
db::StorageInterface,
routes::{metrics, payment_methods as payment_methods_handler, SessionState},
services,
types::{
api::{self, admin, enums as api_enums, MandateValidationFieldsExt},
domain::{self, types},
storage::{self, enums as storage_enums, ephemeral_key, CardTokenData},
transformers::{ForeignFrom, ForeignTryFrom},
AdditionalMerchantData, AdditionalPaymentMethodConnectorResponse, ErrorResponse,
MandateReference, MerchantAccountData, MerchantRecipientData, PaymentsResponseData,
RecipientIdType, RecurringMandatePaymentData, RouterData,
},
utils::{
self,
crypto::{self, SignMessage},
OptionExt, StringExt,
},
};
use crate::{core::admin as core_admin, headers};
pub fn make_url_with_signature(
redirect_url: &str,
business_profile: &domain::Profile,
) -> RouterResult<api::RedirectionResponse> {
{<|fim_suffix|>
<|fim_middle|>
}}
| ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
merchant_id: merchant_id.to_owned(),
secret,
};
let ek = store
.create_ephemeral_key(ek, state.conf.eph_key.validity)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to create ephemeral key")?;
Ok(services::ApplicationResponse::Json(ek))
}
#[cfg(feature = "v2")]
pub async fn make_client_secret(
state: SessionState,
resource_id: api_models::ephemeral_key::ResourceId,
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
headers: &actix_web::http::header::HeaderMap,
) -> errors::RouterResponse<ClientSecretResponse> {
let db = &state.store;
let key_manager_state = &((&state).into());
match &resource_id {
api_models::ephemeral_key::ResourceId::Customer(global_customer_id) => {
db.find_customer_by_global_id(
pub async fn make_client_secret(
state: SessionState,
resource_id: api_models::ephemeral_key::ResourceId,
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
headers: &actix_web::http::header::HeaderMap,
) -> errors::RouterResponse<ClientSecretResponse> {
<|fim_suffix|>
<|fim_middle|>
}
| ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
business_profile,
redirection_response,
payments_return_url,
response.client_secret.as_ref(),
response.manual_retry_allowed,
)
.attach_printable("Failed to make merchant url with response")?;
make_url_with_signature(&return_url, business_profile)
}
#[cfg(feature = "v1")]
pub fn make_merchant_url_with_response(
business_profile: &domain::Profile,
redirection_response: api::PgRedirectResponse,
request_return_url: Option<&String>,
client_secret: Option<&masking::Secret<String>>,
manual_retry_allowed: Option<bool>,
) -> RouterResult<String> {
// take return url if provided in the request else use merchant return url
let url = request_return_url
.or(business_profile.return_url.as_ref())
.get_required_value("return_url")?;
let status_check = redirection_response.status;
pub fn make_merchant_url_with_response(
business_profile: &domain::Profile,
redirection_response: api::PgRedirectResponse,
request_return_url: Option<&String>,
client_secret: Option<&masking::Secret<String>>,
manual_retry_allowed: Option<bool>,
) -> RouterResult<String> {
<|fim_suffix|>
<|fim_middle|>
}
| ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
|| {
Err(report!(errors::ApiErrorResponse::PaymentUnexpectedState {
field_name: "capture_method".to_string(),
current_flow: "captured".to_string(),
current_value: capture_method.to_string(),
states: "manual, manual_multiple, scheduled".to_string()
}))
},
)
}
#[instrument(skip_all)]
pub(crate) fn validate_status_with_capture_method(
status: storage_enums::IntentStatus,
capture_method: storage_enums::CaptureMethod,
) -> RouterResult<()> {
if status == storage_enums::IntentStatus::Processing
&& !(capture_method == storage_enums::CaptureMethod::ManualMultiple)
{
return Err(report!(errors::ApiErrorResponse::PaymentUnexpectedState {
field_name: "capture_method".to_string(),
current_flow: "captured".to_string(),
current_value: capture_method.to_string(),
states: "manual_multiple".to_string()
}));
pub(crate) fn validate_status_with_capture_method(
status: storage_enums::IntentStatus,
capture_method: storage_enums::CaptureMethod,
) -> RouterResult<()> {
<|fim_suffix|>
<|fim_middle|>
}
| ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
state: &SessionState,
payment_attempt: &PaymentAttempt,
payment_intent: &PaymentIntent,
payment_method: enums::PaymentMethod,
payment_method_data: &domain::PaymentMethodData,
merchant_key_store: &domain::MerchantKeyStore,
business_profile: Option<&domain::Profile>,
) -> RouterResult<Option<String>> {
todo!()
}
#[cfg(feature = "v1")]
pub async fn store_payment_method_data_in_vault(
state: &SessionState,
payment_attempt: &PaymentAttempt,
payment_intent: &PaymentIntent,
payment_method: enums::PaymentMethod,
payment_method_data: &domain::PaymentMethodData,
merchant_key_store: &domain::MerchantKeyStore,
business_profile: Option<&domain::Profile>,
) -> RouterResult<Option<String>> {
if should_store_payment_method_data_in_vault(
&state.conf.temp_locker_enable_config,
payment_attempt.connector.clone(),
payment_method,
pub async fn store_payment_method_data_in_vault(
state: &SessionState,
payment_attempt: &PaymentAttempt,
payment_intent: &PaymentIntent,
payment_method: enums::PaymentMethod,
payment_method_data: &domain::PaymentMethodData,
merchant_key_store: &domain::MerchantKeyStore,
business_profile: Option<&domain::Profile>,
) -> RouterResult<Option<String>> {
{<|fim_suffix|>
<|fim_middle|>
}}
| ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
payment_data.token = payment_token;
Ok((payment_method_data, None))
}
_ => Ok((None, None)),
}?;
Ok((operation, payment_method, pm_id))
}
#[cfg(feature = "v1")]
pub async fn store_in_vault_and_generate_ppmt(
state: &SessionState,
payment_method_data: &domain::PaymentMethodData,
payment_intent: &PaymentIntent,
payment_attempt: &PaymentAttempt,
payment_method: enums::PaymentMethod,
merchant_key_store: &domain::MerchantKeyStore,
business_profile: Option<&domain::Profile>,
) -> RouterResult<String> {
let router_token = vault::Vault::store_payment_method_data_in_locker(
state,
None,
payment_method_data,
pub async fn store_in_vault_and_generate_ppmt(
state: &SessionState,
payment_method_data: &domain::PaymentMethodData,
payment_intent: &PaymentIntent,
payment_attempt: &PaymentAttempt,
payment_method: enums::PaymentMethod,
merchant_key_store: &domain::MerchantKeyStore,
business_profile: Option<&domain::Profile>,
) -> RouterResult<String> {
<|fim_suffix|>
<|fim_middle|>
}
| ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
use error_stack::{report, ResultExt};
use redis_interface::errors::RedisError;
use crate::{
configs::settings::{ConnectorRequestReferenceIdConfig, TempLockerEnableConfig},
connector,
consts::{self, BASE64_ENGINE},
core::{
authentication,
errors::{self, CustomResult, RouterResult, StorageErrorExt},
mandate::helpers::MandateGenericData,
payment_methods::{
self,
cards::{self},
network_tokenization, vault,
},
payments,
pm_auth::retrieve_payment_method_from_auth_service,
},
db::StorageInterface,
routes::{metrics, payment_methods as payment_methods_handler, SessionState},
services,
types::{
api::{self, admin, enums as api_enums, MandateValidationFieldsExt},
domain::{self, types},
storage::{self, enums as storage_enums, ephemeral_key, CardTokenData},
transformers::{ForeignFrom, ForeignTryFrom},
AdditionalMerchantData, AdditionalPaymentMethodConnectorResponse, ErrorResponse,
MandateReference, MerchantAccountData, MerchantRecipientData, PaymentsResponseData,
RecipientIdType, RecurringMandatePaymentData, RouterData,
},
utils::{
self,
crypto::{self, SignMessage},
OptionExt, StringExt,
},
};
use crate::{
core::payment_methods::cards::create_encrypted_data, types::storage::CustomerUpdate::Update,
};
pub async fn retrieve_payment_token_data(
state: &SessionState,
token: String,
payment_method: Option<storage_enums::PaymentMethod>,
) -> RouterResult<storage::PaymentTokenData> {
<|fim_suffix|>
<|fim_middle|>
}
| ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
use diesel_models::enums;
use redis_interface::errors::RedisError;
use crate::{
configs::settings::{ConnectorRequestReferenceIdConfig, TempLockerEnableConfig},
connector,
consts::{self, BASE64_ENGINE},
core::{
authentication,
errors::{self, CustomResult, RouterResult, StorageErrorExt},
mandate::helpers::MandateGenericData,
payment_methods::{
self,
cards::{self},
network_tokenization, vault,
},
payments,
pm_auth::retrieve_payment_method_from_auth_service,
},
db::StorageInterface,
routes::{metrics, payment_methods as payment_methods_handler, SessionState},
services,
types::{
api::{self, admin, enums as api_enums, MandateValidationFieldsExt},
domain::{self, types},
storage::{self, enums as storage_enums, ephemeral_key, CardTokenData},
transformers::{ForeignFrom, ForeignTryFrom},
AdditionalMerchantData, AdditionalPaymentMethodConnectorResponse, ErrorResponse,
MandateReference, MerchantAccountData, MerchantRecipientData, PaymentsResponseData,
RecipientIdType, RecurringMandatePaymentData, RouterData,
},
utils::{
self,
crypto::{self, SignMessage},
OptionExt, StringExt,
},
};
use crate::{
core::payment_methods::cards::create_encrypted_data, types::storage::CustomerUpdate::Update,
};
pub async fn retrieve_payment_method_from_db_with_token_data(
state: &SessionState,
merchant_key_store: &domain::MerchantKeyStore,
token_data: &storage::PaymentTokenData,
storage_scheme: storage::enums::MerchantStorageScheme,
) -> RouterResult<Option<domain::PaymentMethod>> {
<|fim_suffix|>
<|fim_middle|>
}
| ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
card_type: None,
card_issuing_country: None,
bank_code: None,
eci: None,
};
Ok(network_token_data)
}
#[cfg(all(
any(feature = "v2", feature = "v1"),
not(feature = "payment_methods_v2")
))]
pub async fn fetch_card_details_for_network_transaction_flow_from_locker(
state: &SessionState,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
locker_id: &str,
) -> RouterResult<domain::PaymentMethodData> {
let card_details_from_locker =
cards::get_card_from_locker(state, customer_id, merchant_id, locker_id)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed to fetch card details from locker")?;
let card_network = card_details_from_locker
pub async fn fetch_card_details_for_network_transaction_flow_from_locker(
state: &SessionState,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
locker_id: &str,
) -> RouterResult<domain::PaymentMethodData> {
<|fim_suffix|>
<|fim_middle|>
}
| ast_fragments |
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
.flatten(),
card_type: None,
card_issuing_country: None,
bank_code: None,
};
Ok(api_card.into())
}
#[cfg(all(
any(feature = "v2", feature = "v1"),
not(feature = "payment_methods_v2")
))]
pub async fn fetch_network_token_details_from_locker(
state: &SessionState,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
network_token_locker_id: &str,
network_transaction_data: api_models::payments::NetworkTokenWithNTIRef,
) -> RouterResult<domain::NetworkTokenData> {
let mut token_data =
cards::get_card_from_locker(state, customer_id, merchant_id, network_token_locker_id)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"failed to fetch network token information from the permanent locker",
pub async fn fetch_network_token_details_from_locker(
state: &SessionState,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
network_token_locker_id: &str,
network_transaction_data: api_models::payments::NetworkTokenWithNTIRef,
) -> RouterResult<domain::NetworkTokenData> {
let mut token_data =
cards::get_card_from_locker(state, customer_id, merchant_id, network_token_locker_id)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"failed to fetch network token information from the permanent locker",
)?;
let expiry = network_transaction_data
.token_exp_month
.zip(network_transaction_data.token_exp_year);
if let Some((exp_month, exp_year)) = expiry {
token_data.card_exp_month = exp_month;
token_data.card_exp_year = exp_year;
}
let card_network = token_data
.card_brand
.map(|card_brand| enums::CardNetwork::from_str(&card_brand))
.transpose()
.map_err(|e| {
logger::error!("Failed to parse card network {e:?}");
})
.ok()
.flatten();
let network_token_data = domain::NetworkTokenData {
token_number: token_data.card_number,
token_cryptogram: None,
token_exp_month: token_data.card_exp_month,
token_exp_year: token_data.card_exp_year,
nick_name: token_data.nick_name.map(masking::Secret::new),
card_issuer: None,
card_network,
card_type: None,
card_issuing_country: None,
bank_code: None,
eci: None,
};
Ok(network_token_data)
} | ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
card_token_data,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed to fetch card information from the permanent locker")?,
))
}
#[cfg(all(
any(feature = "v2", feature = "v1"),
not(feature = "payment_methods_v2")
))]
pub async fn fetch_card_details_from_locker(
state: &SessionState,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
locker_id: &str,
card_token_data: Option<&domain::CardToken>,
) -> RouterResult<domain::Card> {
let card = cards::get_card_from_locker(state, customer_id, merchant_id, locker_id)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed to fetch card information from the permanent locker")?;
// The card_holder_name from locker retrieved card is considered if it is a non-empty string or else card_holder_name is picked
pub async fn fetch_card_details_from_locker(
state: &SessionState,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
locker_id: &str,
card_token_data: Option<&domain::CardToken>,
) -> RouterResult<domain::Card> {
<|fim_suffix|>
<|fim_middle|>
}
| ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
}
}
VaultFetchAction::NoFetchAction => Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Payment method data is not present"),
}
}
#[cfg(all(
any(feature = "v2", feature = "v1"),
not(feature = "payment_methods_v2")
))]
#[allow(clippy::too_many_arguments)]
pub async fn retrieve_card_with_permanent_token_for_external_authentication(
state: &SessionState,
locker_id: &str,
payment_intent: &PaymentIntent,
card_token_data: Option<&domain::CardToken>,
_merchant_key_store: &domain::MerchantKeyStore,
_storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<domain::PaymentMethodData> {
let customer_id = payment_intent
.customer_id
.as_ref()
.get_required_value("customer_id")
.change_context(errors::ApiErrorResponse::UnprocessableEntity {
pub async fn retrieve_card_with_permanent_token_for_external_authentication(
state: &SessionState,
locker_id: &str,
payment_intent: &PaymentIntent,
card_token_data: Option<&domain::CardToken>,
_merchant_key_store: &domain::MerchantKeyStore,
_storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<domain::PaymentMethodData> {
{<|fim_suffix|>
<|fim_middle|>
}}
| ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
mandate_id,
connector,
network_tokenization_supported_connectors,
network_token_requestor_ref_id,
)
};
should_retry_with_pan
.then_some(VaultFetchAction::FetchCardDetailsFromLocker)
.unwrap_or_else(standard_flow)
}
pub fn determine_standard_vault_action(
is_network_tokenization_enabled: bool,
mandate_id: Option<api_models::payments::MandateIds>,
connector: Option<api_enums::Connector>,
network_tokenization_supported_connectors: &HashSet<api_enums::Connector>,
network_token_requestor_ref_id: Option<String>,
) -> VaultFetchAction {
let is_network_transaction_id_flow = mandate_id
.as_ref()
.map(|mandate_ids| mandate_ids.is_network_transaction_id_flow())
.unwrap_or(false);
if !is_network_tokenization_enabled {
pub fn determine_standard_vault_action(
is_network_tokenization_enabled: bool,
mandate_id: Option<api_models::payments::MandateIds>,
connector: Option<api_enums::Connector>,
network_tokenization_supported_connectors: &HashSet<api_enums::Connector>,
network_token_requestor_ref_id: Option<String>,
) -> VaultFetchAction {
{<|fim_suffix|>
<|fim_middle|>
}}
| ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
Ok(cache_key)
}
}
Ok(None) => Ok(cache_key),
Err(error) => Err(errors::ApiErrorResponse::InternalServerError).attach_printable(error)?,
}
}
#[cfg(feature = "v1")]
/// Get the customer details from customer field if present
/// or from the individual fields in `PaymentsRequest`
#[instrument(skip_all)]
pub fn get_customer_details_from_request(
request: &api_models::payments::PaymentsRequest,
) -> 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
pub fn get_customer_details_from_request(
request: &api_models::payments::PaymentsRequest,
) -> CustomerDetails {
{<|fim_suffix|>
<|fim_middle|>
}}
| ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
confirm: Option<bool>,
) -> storage_enums::IntentStatus {
match payment_method_data {
Some(_) => match confirm {
Some(true) => storage_enums::IntentStatus::RequiresPaymentMethod,
_ => storage_enums::IntentStatus::RequiresConfirmation,
},
None => storage_enums::IntentStatus::RequiresPaymentMethod,
}
}
#[cfg(feature = "v1")]
pub async fn add_domain_task_to_pt<Op>(
operation: &Op,
state: &SessionState,
payment_attempt: &PaymentAttempt,
requeue: bool,
schedule_time: Option<time::PrimitiveDateTime>,
) -> CustomResult<(), errors::ApiErrorResponse>
where
Op: std::fmt::Debug,
{
if check_if_operation_confirm(operation) {
match schedule_time {
Some(stime) => {
pub async fn add_domain_task_to_pt<Op>(
operation: &Op,
state: &SessionState,
payment_attempt: &PaymentAttempt,
requeue: bool,
schedule_time: Option<time::PrimitiveDateTime>,
) -> CustomResult<(), errors::ApiErrorResponse>
where
Op: std::fmt::Debug,
{
{<|fim_suffix|>
<|fim_middle|>
}}
| ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
let off_session = req.off_session.get_required_value("off_session")?;
if !off_session {
Err(report!(errors::ApiErrorResponse::PreconditionFailed {
message: "`off_session` should be `true` for mandates".into()
}))?
}
Ok(())
}
}
}
pub fn verify_mandate_details(
request_amount: MinorUnit,
request_currency: api_enums::Currency,
mandate: storage::Mandate,
) -> RouterResult<()> {
match mandate.mandate_type {
storage_enums::MandateType::SingleUse => utils::when(
mandate
.mandate_amount
.map(|mandate_amount| request_amount.get_amount_as_i64() > mandate_amount)
.unwrap_or(true),
|| {
Err(report!(errors::ApiErrorResponse::MandateValidationFailed {
pub fn verify_mandate_details(
request_amount: MinorUnit,
request_currency: api_enums::Currency,
mandate: storage::Mandate,
) -> RouterResult<()> {
<|fim_suffix|>
<|fim_middle|>
}
| ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
format!("/{}", creds_identifier)
});
format!(
"{}/payments/{}/{}/redirect/complete/{}{}",
router_base_url,
payment_attempt.payment_id.get_string_repr(),
payment_attempt.merchant_id.get_string_repr(),
connector_name,
creds_identifier
)
}
fn validate_recurring_mandate(req: api::MandateValidationFields) -> RouterResult<()> {
let recurring_details = req
.recurring_details
.get_required_value("recurring_details")?;
match recurring_details {
RecurringDetails::ProcessorPaymentToken(_)
| RecurringDetails::NetworkTransactionIdAndCardDetails(_) => Ok(()),
_ => {
req.customer_id.check_value_present("customer_id")?;
let confirm = req.confirm.get_required_value("confirm")?;
if !confirm {
fn validate_recurring_mandate(req: api::MandateValidationFields) -> RouterResult<()> {
{<|fim_suffix|>
<|fim_middle|>
}}
| ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
},
)?;
utils::when(recurring_details.is_some() && mandate_id.is_some(), || {
Err(report!(errors::ApiErrorResponse::PreconditionFailed {
message: "Expected one out of recurring_details and mandate_id but got both".into()
}))
})?;
Ok(())
}
fn validate_new_mandate_request(
req: api::MandateValidationFields,
is_confirm_operation: bool,
) -> RouterResult<()> {
// We need not check for customer_id in the confirm request if it is already passed
// in create request
fp_utils::when(!is_confirm_operation && req.customer_id.is_none(), || {
Err(report!(errors::ApiErrorResponse::PreconditionFailed {
message: "`customer_id` is mandatory for mandates".into()
}))
})?;
fn validate_new_mandate_request(
req: api::MandateValidationFields,
is_confirm_operation: bool,
) -> RouterResult<()> {
<|fim_suffix|>
<|fim_middle|>
}
| ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
::cards::CardSecurityCode::try_from(card_cvc).change_context(
errors::ApiErrorResponse::PreconditionFailed {
message: "Invalid Card CVC".to_string(),
},
)?;
validate_card_expiry(&card.card_exp_month, &card.card_exp_year)?;
}
Ok(())
}
#[instrument(skip_all)]
pub fn validate_card_expiry(
card_exp_month: &masking::Secret<String>,
card_exp_year: &masking::Secret<String>,
) -> CustomResult<(), errors::ApiErrorResponse> {
let exp_month = card_exp_month
.peek()
.to_string()
.parse::<u8>()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "card_exp_month",
})?;
let month = ::cards::CardExpirationMonth::try_from(exp_month).change_context(
errors::ApiErrorResponse::PreconditionFailed {
pub fn validate_card_expiry(
card_exp_month: &masking::Secret<String>,
card_exp_year: &masking::Secret<String>,
) -> CustomResult<(), errors::ApiErrorResponse> {
<|fim_suffix|>
<|fim_middle|>
}
| ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
message: "amount_to_capture should not exist for when amount = 0"
.to_string()
}))
}
}
}
}
}
#[cfg(feature = "v1")]
/// if capture method = automatic, amount_to_capture(if provided) must be equal to amount
#[instrument(skip_all)]
pub fn validate_amount_to_capture_and_capture_method(
payment_attempt: Option<&PaymentAttempt>,
request: &api_models::payments::PaymentsRequest,
) -> CustomResult<(), errors::ApiErrorResponse> {
let option_net_amount = hyperswitch_domain_models::payments::payment_attempt::NetAmount::from_payments_request_and_payment_attempt(
request,
payment_attempt,
);
let capture_method = request
.capture_method
.or(payment_attempt
.map(|payment_attempt| payment_attempt.capture_method.unwrap_or_default()))
.unwrap_or_default();
pub fn validate_amount_to_capture_and_capture_method(
payment_attempt: Option<&PaymentAttempt>,
request: &api_models::payments::PaymentsRequest,
) -> CustomResult<(), errors::ApiErrorResponse> {
{<|fim_suffix|>
<|fim_middle|>
}}
| ast_fragments |
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
utils::when(merchant_id.ne(request_merchant_id), || {
Err(report!(errors::ApiErrorResponse::PreconditionFailed {
message: format!(
"Invalid `merchant_id`: {} not found in merchant account",
request_merchant_id.get_string_repr()
)
}))
})
}
#[instrument(skip_all)]
pub fn validate_request_amount_and_amount_to_capture(
op_amount: Option<api::Amount>,
op_amount_to_capture: Option<MinorUnit>,
surcharge_details: Option<RequestSurchargeDetails>,
) -> CustomResult<(), errors::ApiErrorResponse> {
match (op_amount, op_amount_to_capture) {
(None, _) => Ok(()),
(Some(_amount), None) => Ok(()),
(Some(amount), Some(amount_to_capture)) => {
match amount {
api::Amount::Value(amount_inner) => {
// If both amount and amount to capture is present
// then amount to be capture should be less than or equal to request amount
pub fn validate_request_amount_and_amount_to_capture(
op_amount: Option<api::Amount>,
op_amount_to_capture: Option<MinorUnit>,
surcharge_details: Option<RequestSurchargeDetails>,
) -> CustomResult<(), errors::ApiErrorResponse> {
match (op_amount, op_amount_to_capture) {
(None, _) => Ok(()),
(Some(_amount), None) => Ok(()),
(Some(amount), Some(amount_to_capture)) => {
match amount {
api::Amount::Value(amount_inner) => {
// If both amount and amount to capture is present
// then amount to be capture should be less than or equal to request amount
let total_capturable_amount = MinorUnit::new(amount_inner.get())
+ surcharge_details
.map(|surcharge_details| surcharge_details.get_total_surcharge_amount())
.unwrap_or_default();
utils::when(!amount_to_capture.le(&total_capturable_amount), || {
Err(report!(errors::ApiErrorResponse::PreconditionFailed {
message: format!(
"amount_to_capture is greater than amount capture_amount: {amount_to_capture:?} request_amount: {amount:?}"
)
}))
})
}
api::Amount::Zero => {
// If the amount is Null but still amount_to_capture is passed this is invalid and
Err(report!(errors::ApiErrorResponse::PreconditionFailed {
message: "amount_to_capture should not exist for when amount = 0"
.to_string()
}))
}
}
}
}
} | ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
let encryptable: Encryptable<masking::Secret<String, pii::EmailStrategy>> =
Encryptable::new(
email.clone().into_inner().switch_strategy(),
email.into_encrypted(),
);
encryptable
}),
})
}
.await
}
pub async fn get_address_by_id(
state: &SessionState,
address_id: Option<String>,
merchant_key_store: &domain::MerchantKeyStore,
payment_id: &id_type::PaymentId,
merchant_id: &id_type::MerchantId,
storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<Option<domain::Address>, errors::ApiErrorResponse> {
match address_id {
None => Ok(None),
Some(address_id) => {
let db = &*state.store;
Ok(db
pub async fn get_address_by_id(
state: &SessionState,
address_id: Option<String>,
merchant_key_store: &domain::MerchantKeyStore,
payment_id: &id_type::PaymentId,
merchant_id: &id_type::MerchantId,
storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<Option<domain::Address>, errors::ApiErrorResponse> {
{
None => Ok(None),<|fim_suffix|>
<|fim_middle|>
Some(address_id) => {
let db = &*state.store;
Ok(db
.find_address_by_merchant_id_payment_id_address_id(
&state.into(),
merchant_id,
payment_id,
&address_id,
merchant_key_store,
storage_scheme,
)
.await
.map(|payment_address| payment_address.address)
.ok())
}
}
} | ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
)
.await
.map(|payment_address| payment_address.address)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while inserting new address")?,
)
}
None => None,
},
})
}
pub async fn get_domain_address(
session_state: &SessionState,
address: &api_models::payments::Address,
merchant_id: &id_type::MerchantId,
key: &[u8],
storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<domain::Address, common_utils::errors::CryptoError> {
async {
let address_details = &address.address.as_ref();
let encrypted_data = types::crypto_operation(
&session_state.into(),
type_name!(domain::Address),
types::CryptoOperation::BatchEncrypt(
pub async fn get_domain_address(
session_state: &SessionState,
address: &api_models::payments::Address,
merchant_id: &id_type::MerchantId,
key: &[u8],
storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<domain::Address, common_utils::errors::CryptoError> {
{<|fim_suffix|>
<|fim_middle|>
}}
| ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while inserting new address")?,
)
}
None => None,
},
})
}
#[instrument(skip_all)]
#[allow(clippy::too_many_arguments)]
pub async fn create_or_find_address_for_payment_by_request(
state: &SessionState,
req_address: Option<&api::Address>,
address_id: Option<&str>,
merchant_id: &id_type::MerchantId,
customer_id: Option<&id_type::CustomerId>,
merchant_key_store: &domain::MerchantKeyStore,
payment_id: &id_type::PaymentId,
storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<Option<domain::Address>, errors::ApiErrorResponse> {
let key = merchant_key_store.key.get_inner().peek();
let db = &state.store;
let key_manager_state = &state.into();
pub async fn create_or_find_address_for_payment_by_request(
state: &SessionState,
req_address: Option<&api::Address>,
address_id: Option<&str>,
merchant_id: &id_type::MerchantId,
customer_id: Option<&id_type::CustomerId>,
merchant_key_store: &domain::MerchantKeyStore,
payment_id: &id_type::PaymentId,
storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<Option<domain::Address>, errors::ApiErrorResponse> {
<|fim_suffix|>
<|fim_middle|>
}
| ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
});
}
}
};
}
common_types::payments::XenditSplitRequest::SingleSplit(_) => (),
},
None => (),
}
Ok(())
}
pub async fn is_merchant_eligible_authentication_service(
merchant_id: &id_type::MerchantId,
state: &SessionState,
) -> RouterResult<bool> {
let merchants_eligible_for_authentication_service = state
.store
.as_ref()
.find_config_by_key_unwrap_or(
consts::AUTHENTICATION_SERVICE_ELIGIBLE_CONFIG,
Some("[]".to_string()),
)
.await;
pub async fn is_merchant_eligible_authentication_service(
merchant_id: &id_type::MerchantId,
state: &SessionState,
) -> RouterResult<bool> {
{
Ok(config) => serde_json::from_str(&config.config)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to parse authentication service config")?,<|fim_suffix|>
<|fim_middle|>
Err(err) => {
logger::error!(
"Error fetching authentication service enabled merchant config {:?}",
err
);
Vec::new()
}
}
} | ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
if !(consts::MIN_INTENT_FULFILLMENT_EXPIRY..=consts::MAX_INTENT_FULFILLMENT_EXPIRY)
.contains(&intent_fulfillment_time)
{
Err(errors::ApiErrorResponse::InvalidRequestData {
message: "intent_fulfillment_time should be between 60(1 min) to 1800(30 mins)."
.to_string(),
})
} else {
Ok(())
}
}
pub fn add_connector_response_to_additional_payment_data(
additional_payment_data: api_models::payments::AdditionalPaymentData,
connector_response_payment_method_data: AdditionalPaymentMethodConnectorResponse,
) -> api_models::payments::AdditionalPaymentData {
match (
&additional_payment_data,
connector_response_payment_method_data,
) {
(
api_models::payments::AdditionalPaymentData::Card(additional_card_data),
AdditionalPaymentMethodConnectorResponse::Card {
authentication_data,
payment_checks,
pub fn add_connector_response_to_additional_payment_data(
additional_payment_data: api_models::payments::AdditionalPaymentData,
connector_response_payment_method_data: AdditionalPaymentMethodConnectorResponse,
) -> api_models::payments::AdditionalPaymentData {
{
(
api_models::payments::AdditionalPaymentData::Card(additional_card_data),
AdditionalPaymentMethodConnectorResponse::Card {
authentication_data,
payment_checks,
..
},
) => api_models::payments::AdditionalPaymentData::Card(Box::new(
api_models::payments::AdditionalCardInfo {
payment_checks,
authentication_data,
..*additional_card_data.clone()
},
)),<|fim_suffix|>
<|fim_middle|>
_ => additional_payment_data,
}
} | ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
} => connector_response_reference_id,
PaymentsResponseData::PreProcessingResponse {
connector_response_reference_id,
..
} => connector_response_reference_id,
_ => &None,
},
Err(_) => &None,
};
request.check_integrity(request, connector_transaction_id.to_owned())
}
pub async fn config_skip_saving_wallet_at_connector(
db: &dyn StorageInterface,
merchant_id: &id_type::MerchantId,
) -> CustomResult<Option<Vec<storage_enums::PaymentMethodType>>, errors::ApiErrorResponse> {
let config = db
.find_config_by_key_unwrap_or(
&merchant_id.get_skip_saving_wallet_at_connector_key(),
Some("[]".to_string()),
)
.await;
Ok(match config {
Ok(conf) => Some(
serde_json::from_str::<Vec<storage_enums::PaymentMethodType>>(&conf.config)
pub async fn config_skip_saving_wallet_at_connector(
db: &dyn StorageInterface,
merchant_id: &id_type::MerchantId,
) -> CustomResult<Option<Vec<storage_enums::PaymentMethodType>>, errors::ApiErrorResponse> {
{<|fim_suffix|>
<|fim_middle|>
}}
| ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
use common_utils::id_type::GenerateId;
use common_utils::{
crypto::Encryptable,
ext_traits::{AsyncExt, ByteSliceExt, Encode, ValueExt},
fp_utils, generate_id,
id_type::{self},
new_type::{MaskedIban, MaskedSortCode},
pii, type_name,
types::{
keymanager::{Identifier, KeyManagerState, ToEncryptable},
MinorUnit,
},
};
pub fn get_redis_key_for_extended_card_info(
merchant_id: &id_type::MerchantId,
payment_id: &id_type::PaymentId,
) -> String {
<|fim_suffix|>
<|fim_middle|>
}
| ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
&auth_token,
payment_intent,
&None,
)
.await
}
storage::PaymentTokenData::WalletToken(_) => Ok(None),
}
}
// This function validates the mandate_data with its setup_future_usage
pub fn validate_mandate_data_and_future_usage(
setup_future_usages: Option<api_enums::FutureUsage>,
mandate_details_present: bool,
) -> Result<(), errors::ApiErrorResponse> {
if mandate_details_present
&& (Some(api_enums::FutureUsage::OnSession) == setup_future_usages
|| setup_future_usages.is_none())
{
Err(errors::ApiErrorResponse::PreconditionFailed {
message: "`setup_future_usage` must be `off_session` for mandates".into(),
})
} else {
Ok(())
pub fn validate_mandate_data_and_future_usage(
setup_future_usages: Option<api_enums::FutureUsage>,
mandate_details_present: bool,
) -> Result<(), errors::ApiErrorResponse> {
<|fim_suffix|>
<|fim_middle|>
}
| ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
)
});
additional_payment_method_data
.as_ref()
.map(Encode::encode_to_value)
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to encode additional pm data")
}
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
pub async fn get_payment_method_details_from_payment_token(
state: &SessionState,
payment_attempt: &PaymentAttempt,
payment_intent: &PaymentIntent,
key_store: &domain::MerchantKeyStore,
storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<Option<(domain::PaymentMethodData, enums::PaymentMethod)>> {
todo!()
}
#[cfg(all(
any(feature = "v1", feature = "v2"),
not(feature = "payment_methods_v2")
pub async fn get_payment_method_details_from_payment_token(
state: &SessionState,
payment_attempt: &PaymentAttempt,
payment_intent: &PaymentIntent,
key_store: &domain::MerchantKeyStore,
storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<Option<(domain::PaymentMethodData, enums::PaymentMethod)>> {
{<|fim_suffix|>
<|fim_middle|>
}}
| ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
use redis_interface::errors::RedisError;
use crate::{
configs::settings::{ConnectorRequestReferenceIdConfig, TempLockerEnableConfig},
connector,
consts::{self, BASE64_ENGINE},
core::{
authentication,
errors::{self, CustomResult, RouterResult, StorageErrorExt},
mandate::helpers::MandateGenericData,
payment_methods::{
self,
cards::{self},
network_tokenization, vault,
},
payments,
pm_auth::retrieve_payment_method_from_auth_service,
},
db::StorageInterface,
routes::{metrics, payment_methods as payment_methods_handler, SessionState},
services,
types::{
api::{self, admin, enums as api_enums, MandateValidationFieldsExt},
domain::{self, types},
storage::{self, enums as storage_enums, ephemeral_key, CardTokenData},
transformers::{ForeignFrom, ForeignTryFrom},
AdditionalMerchantData, AdditionalPaymentMethodConnectorResponse, ErrorResponse,
MandateReference, MerchantAccountData, MerchantRecipientData, PaymentsResponseData,
RecipientIdType, RecurringMandatePaymentData, RouterData,
},
utils::{
self,
crypto::{self, SignMessage},
OptionExt, StringExt,
},
};
pub fn validate_intent_fulfillment_expiry(
intent_fulfillment_time: u32,
) -> Result<(), errors::ApiErrorResponse> {
<|fim_suffix|>
<|fim_middle|>
}
| ast_fragments |
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
use redis_interface::errors::RedisError;
use crate::{
configs::settings::{ConnectorRequestReferenceIdConfig, TempLockerEnableConfig},
connector,
consts::{self, BASE64_ENGINE},
core::{
authentication,
errors::{self, CustomResult, RouterResult, StorageErrorExt},
mandate::helpers::MandateGenericData,
payment_methods::{
self,
cards::{self},
network_tokenization, vault,
},
payments,
pm_auth::retrieve_payment_method_from_auth_service,
},
db::StorageInterface,
routes::{metrics, payment_methods as payment_methods_handler, SessionState},
services,
types::{
api::{self, admin, enums as api_enums, MandateValidationFieldsExt},
domain::{self, types},
storage::{self, enums as storage_enums, ephemeral_key, CardTokenData},
transformers::{ForeignFrom, ForeignTryFrom},
AdditionalMerchantData, AdditionalPaymentMethodConnectorResponse, ErrorResponse,
MandateReference, MerchantAccountData, MerchantRecipientData, PaymentsResponseData,
RecipientIdType, RecurringMandatePaymentData, RouterData,
},
utils::{
self,
crypto::{self, SignMessage},
OptionExt, StringExt,
},
};
pub fn validate_session_expiry(session_expiry: u32) -> Result<(), errors::ApiErrorResponse> {
if !(consts::MIN_SESSION_EXPIRY..=consts::MAX_SESSION_EXPIRY).contains(&session_expiry) {
Err(errors::ApiErrorResponse::InvalidRequestData {
message: "session_expiry should be between 60(1 min) to 7890000(3 months).".to_string(),
})
} else {
Ok(())
}
} | ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
err.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed to fetch translation from unified_translations")
})
};
get_unified_translation()
.await
.inspect_err(|err| {
// warn log should suffice here because we are not propagating this error
logger::warn!(get_translation_error=?err, "error fetching unified translations");
})
.ok()
}
pub fn validate_order_details_amount(
order_details: Vec<api_models::payments::OrderDetailsWithAmount>,
amount: MinorUnit,
should_validate: bool,
) -> Result<(), errors::ApiErrorResponse> {
if should_validate {
let total_order_details_amount: MinorUnit = order_details
.iter()
.map(|order| order.amount * order.quantity)
.sum();
if total_order_details_amount != amount {
Err(errors::ApiErrorResponse::InvalidRequestData {
pub fn validate_order_details_amount(
order_details: Vec<api_models::payments::OrderDetailsWithAmount>,
amount: MinorUnit,
should_validate: bool,
) -> Result<(), errors::ApiErrorResponse> {
<|fim_suffix|>
<|fim_middle|>
}
| ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
use redis_interface::errors::RedisError;
use crate::{
configs::settings::{ConnectorRequestReferenceIdConfig, TempLockerEnableConfig},
connector,
consts::{self, BASE64_ENGINE},
core::{
authentication,
errors::{self, CustomResult, RouterResult, StorageErrorExt},
mandate::helpers::MandateGenericData,
payment_methods::{
self,
cards::{self},
network_tokenization, vault,
},
payments,
pm_auth::retrieve_payment_method_from_auth_service,
},
db::StorageInterface,
routes::{metrics, payment_methods as payment_methods_handler, SessionState},
services,
types::{
api::{self, admin, enums as api_enums, MandateValidationFieldsExt},
domain::{self, types},
storage::{self, enums as storage_enums, ephemeral_key, CardTokenData},
transformers::{ForeignFrom, ForeignTryFrom},
AdditionalMerchantData, AdditionalPaymentMethodConnectorResponse, ErrorResponse,
MandateReference, MerchantAccountData, MerchantRecipientData, PaymentsResponseData,
RecipientIdType, RecurringMandatePaymentData, RouterData,
},
utils::{
self,
crypto::{self, SignMessage},
OptionExt, StringExt,
},
};
pub fn validate_payment_link_request(
confirm: Option<bool>,
) -> Result<(), errors::ApiErrorResponse> {
{<|fim_suffix|>
<|fim_middle|>
}}
| ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
logger::error!(
"Failed to derive the shared ephemeral key for Google Pay decryption flow: {:?}",
err
);
report!(errors::GooglePayDecryptionError::DerivingSharedEphemeralKeyFailed)
})?;
Ok(output_key)
}
// Verify the Hmac key
// https://developers.google.com/pay/api/android/guides/resources/payment-data-cryptography#encrypt-spec
fn verify_hmac(
&self,
mac_key: &[u8],
tag: &[u8],
encrypted_message: &[u8],
) -> CustomResult<(), errors::GooglePayDecryptionError> {
let hmac_key = ring::hmac::Key::new(ring::hmac::HMAC_SHA256, mac_key);
ring::hmac::verify(&hmac_key, encrypted_message, tag)
.change_context(errors::GooglePayDecryptionError::HmacVerificationFailed)
}
// Method to decrypt the AES-GCM encrypted message
fn decrypt_message(
fn verify_hmac(
&self,
mac_key: &[u8],
tag: &[u8],
encrypted_message: &[u8],
) -> CustomResult<(), errors::GooglePayDecryptionError> {
<|fim_suffix|>
<|fim_middle|>
}
| ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
let result = ecdsa_signature
.verify(&message_hash, &ec_key)
.change_context(errors::GooglePayDecryptionError::SignatureVerificationFailed)?;
if result {
Ok(())
} else {
Err(errors::GooglePayDecryptionError::InvalidSignature)?
}
}
// Fetch the public key
fn load_public_key(
&self,
key: &str,
) -> CustomResult<PKey<openssl::pkey::Public>, errors::GooglePayDecryptionError> {
// decode the base64 string
let der_data = BASE64_ENGINE
.decode(key)
.change_context(errors::GooglePayDecryptionError::Base64DecodingFailed)?;
// parse the DER-encoded data as an EC public key
let ec_key = openssl::ec::EcKey::public_key_from_der(&der_data)
.change_context(errors::GooglePayDecryptionError::DerivingEcKeyFailed)?;
fn load_public_key(
&self,
key: &str,
) -> CustomResult<PKey<openssl::pkey::Public>, errors::GooglePayDecryptionError> {
{<|fim_suffix|>
<|fim_middle|>
}}
| ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
let mut signed_data: Vec<u8> = Vec::new();
signed_data.append(&mut get_little_endian_format(length_of_sender_id));
signed_data.append(&mut sender_id.as_bytes().to_vec());
signed_data.append(&mut get_little_endian_format(length_of_protocol_version));
signed_data.append(&mut protocol_version.as_bytes().to_vec());
signed_data.append(&mut get_little_endian_format(length_of_signed_key));
signed_data.append(&mut signed_key.as_bytes().to_vec());
Ok(signed_data)
}
// Validate and parse signed key
fn validate_signed_key(
&self,
intermediate_signing_key: &IntermediateSigningKey,
) -> CustomResult<GooglePaySignedKey, errors::GooglePayDecryptionError> {
let signed_key: GooglePaySignedKey = intermediate_signing_key
.signed_key
.clone()
.expose()
.parse_struct("GooglePaySignedKey")
.change_context(errors::GooglePayDecryptionError::SignedKeyParsingFailure)?;
if !matches!(
check_expiration_date_is_valid(&signed_key.key_expiration),
Ok(true)
fn validate_signed_key(
&self,
intermediate_signing_key: &IntermediateSigningKey,
) -> CustomResult<GooglePaySignedKey, errors::GooglePayDecryptionError> {
<|fim_suffix|>
<|fim_middle|>
}
| ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
)?;
if result {
return Ok(());
}
}
}
Err(errors::GooglePayDecryptionError::InvalidIntermediateSignature.into())
}
// Construct signed data for intermediate signing key verification
fn construct_signed_data_for_intermediate_signing_key_verification(
&self,
sender_id: &str,
protocol_version: &str,
signed_key: &str,
) -> CustomResult<Vec<u8>, errors::GooglePayDecryptionError> {
let length_of_sender_id = u32::try_from(sender_id.len())
.change_context(errors::GooglePayDecryptionError::ParsingFailed)?;
let length_of_protocol_version = u32::try_from(protocol_version.len())
.change_context(errors::GooglePayDecryptionError::ParsingFailed)?;
let length_of_signed_key = u32::try_from(signed_key.len())
.change_context(errors::GooglePayDecryptionError::ParsingFailed)?;
fn construct_signed_data_for_intermediate_signing_key_verification(
&self,
sender_id: &str,
protocol_version: &str,
signed_key: &str,
) -> CustomResult<Vec<u8>, errors::GooglePayDecryptionError> {
<|fim_suffix|>
<|fim_middle|>
}
| ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
// check the expiration date of the decrypted data
if matches!(
check_expiration_date_is_valid(&decrypted_data.message_expiration),
Ok(true)
) {
Ok(decrypted_data)
} else {
Err(errors::GooglePayDecryptionError::DecryptedTokenExpired.into())
}
}
// Verify the signature of the token
fn verify_signature(
&self,
encrypted_data: &EncryptedData,
) -> CustomResult<(), errors::GooglePayDecryptionError> {
// check the protocol version
if encrypted_data.protocol_version != GooglePayProtocolVersion::EcProtocolVersion2 {
return Err(errors::GooglePayDecryptionError::InvalidProtocolVersion.into());
}
// verify the intermediate signing key
self.verify_intermediate_signing_key(encrypted_data)?;
// validate and fetch the signed key
let signed_key = self.validate_signed_key(&encrypted_data.intermediate_signing_key)?;
fn verify_signature(
&self,
encrypted_data: &EncryptedData,
) -> CustomResult<(), errors::GooglePayDecryptionError> {
{<|fim_suffix|>
<|fim_middle|>
}}
| ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
fn get_little_endian_format(number: u32) -> Vec<u8> {
<|fim_suffix|>
<|fim_middle|>
}
| ast_fragments |
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
use std::{borrow::Cow, collections::HashSet, net::IpAddr, str::FromStr};
use redis_interface::errors::RedisError;
use crate::{
configs::settings::{ConnectorRequestReferenceIdConfig, TempLockerEnableConfig},
connector,
consts::{self, BASE64_ENGINE},
core::{
authentication,
errors::{self, CustomResult, RouterResult, StorageErrorExt},
mandate::helpers::MandateGenericData,
payment_methods::{
self,
cards::{self},
network_tokenization, vault,
},
payments,
pm_auth::retrieve_payment_method_from_auth_service,
},
db::StorageInterface,
routes::{metrics, payment_methods as payment_methods_handler, SessionState},
services,
types::{
api::{self, admin, enums as api_enums, MandateValidationFieldsExt},
domain::{self, types},
storage::{self, enums as storage_enums, ephemeral_key, CardTokenData},
transformers::{ForeignFrom, ForeignTryFrom},
AdditionalMerchantData, AdditionalPaymentMethodConnectorResponse, ErrorResponse,
MandateReference, MerchantAccountData, MerchantRecipientData, PaymentsResponseData,
RecipientIdType, RecurringMandatePaymentData, RouterData,
},
utils::{
self,
crypto::{self, SignMessage},
OptionExt, StringExt,
},
};
fn check_expiration_date_is_valid(
expiration: &str,
) -> CustomResult<bool, errors::GooglePayDecryptionError> {
let expiration_ms = expiration
.parse::<i128>()
.change_context(errors::GooglePayDecryptionError::InvalidExpirationTime)?;
// convert milliseconds to nanoseconds (1 millisecond = 1_000_000 nanoseconds) to create OffsetDateTime
let expiration_time =
time::OffsetDateTime::from_unix_timestamp_nanos(expiration_ms * 1_000_000)
.change_context(errors::GooglePayDecryptionError::InvalidExpirationTime)?;
let now = time::OffsetDateTime::now_utc();
Ok(expiration_time > now)
} | ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
let kdf_party_u = b"Apple";
let kdf_info = [&kdf_algorithm[..], kdf_party_u, &kdf_party_v[..]].concat();
let mut hash = openssl::sha::Sha256::new();
hash.update(b"\x00\x00\x00");
hash.update(b"\x01");
hash.update(shared_secret);
hash.update(&kdf_info[..]);
let symmetric_key = hash.finish();
Ok(symmetric_key.to_vec())
}
pub fn decrypt_ciphertext(
&self,
symmetric_key: &[u8],
) -> CustomResult<String, errors::ApplePayDecryptionError> {
logger::info!("Decrypt apple pay token");
let data = BASE64_ENGINE
.decode(self.data.peek().as_bytes())
.change_context(errors::ApplePayDecryptionError::Base64DecodingFailed)?;
let iv = [0u8; 16]; //Initialization vector IV is typically used in AES-GCM (Galois/Counter Mode) encryption for randomizing the encryption process.
let ciphertext = data
.get(..data.len() - 16)
.ok_or(errors::ApplePayDecryptionError::DecryptionFailed)?;
pub fn decrypt_ciphertext(
&self,
symmetric_key: &[u8],
) -> CustomResult<String, errors::ApplePayDecryptionError> {
<|fim_suffix|>
<|fim_middle|>
}
| ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
.set_peer(&public_key)
.change_context(errors::ApplePayDecryptionError::DerivingSharedSecretKeyFailed)
.attach_printable("Failed to set the peer key for the secret derivation")?;
// Compute the shared secret
let shared_secret = deriver
.derive_to_vec()
.change_context(errors::ApplePayDecryptionError::DerivingSharedSecretKeyFailed)
.attach_printable("Final key derivation failed")?;
Ok(shared_secret)
}
pub fn symmetric_key(
&self,
merchant_id: &str,
shared_secret: &[u8],
) -> CustomResult<Vec<u8>, errors::ApplePayDecryptionError> {
let kdf_algorithm = b"\x0did-aes256-GCM";
let kdf_party_v = hex::decode(merchant_id)
.change_context(errors::ApplePayDecryptionError::Base64DecodingFailed)?;
let kdf_party_u = b"Apple";
let kdf_info = [&kdf_algorithm[..], kdf_party_u, &kdf_party_v[..]].concat();
let mut hash = openssl::sha::Sha256::new();
hash.update(b"\x00\x00\x00");
pub fn symmetric_key(
&self,
merchant_id: &str,
shared_secret: &[u8],
) -> CustomResult<Vec<u8>, errors::ApplePayDecryptionError> {
{<|fim_suffix|>
<|fim_middle|>
}}
| ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
impl ApplePayData {
pub fn token_json(
wallet_data: domain::WalletData,
) -> CustomResult<Self, errors::ConnectorError> {
let json_wallet_data: Self = connector::utils::WalletData::get_wallet_token_as_json(
&wallet_data,
"Apple Pay".to_string(),
)?;
Ok(json_wallet_data)
}
pub async fn decrypt(
&self,
payment_processing_certificate: &masking::Secret<String>,
payment_processing_certificate_key: &masking::Secret<String>,
) -> CustomResult<serde_json::Value, errors::ApplePayDecryptionError> {
let merchant_id = self.merchant_id(payment_processing_certificate)?;
let shared_secret = self.shared_secret(payment_processing_certificate_key)?;
let symmetric_key = self.symmetric_key(&merchant_id, &shared_secret)?;
let decrypted = self.decrypt_ciphertext(&symmetric_key)?;
let parsed_decrypted: serde_json::Value = serde_json::from_str(&decrypted)
.change_context(errors::ApplePayDecryptionError::DecryptionFailed)?;
Ok(parsed_decrypted)
}
pub async fn decrypt(
&self,
payment_processing_certificate: &masking::Secret<String>,
payment_processing_certificate_key: &masking::Secret<String>,
) -> CustomResult<serde_json::Value, errors::ApplePayDecryptionError> {
{<|fim_suffix|>
<|fim_middle|>
}}
| ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
use redis_interface::errors::RedisError;
use crate::{
configs::settings::{ConnectorRequestReferenceIdConfig, TempLockerEnableConfig},
connector,
consts::{self, BASE64_ENGINE},
core::{
authentication,
errors::{self, CustomResult, RouterResult, StorageErrorExt},
mandate::helpers::MandateGenericData,
payment_methods::{
self,
cards::{self},
network_tokenization, vault,
},
payments,
pm_auth::retrieve_payment_method_from_auth_service,
},
db::StorageInterface,
routes::{metrics, payment_methods as payment_methods_handler, SessionState},
services,
types::{
api::{self, admin, enums as api_enums, MandateValidationFieldsExt},
domain::{self, types},
storage::{self, enums as storage_enums, ephemeral_key, CardTokenData},
transformers::{ForeignFrom, ForeignTryFrom},
AdditionalMerchantData, AdditionalPaymentMethodConnectorResponse, ErrorResponse,
MandateReference, MerchantAccountData, MerchantRecipientData, PaymentsResponseData,
RecipientIdType, RecurringMandatePaymentData, RouterData,
},
utils::{
self,
crypto::{self, SignMessage},
OptionExt, StringExt,
},
};
pub fn token_json(
wallet_data: domain::WalletData,
) -> CustomResult<Self, errors::ConnectorError> {
{<|fim_suffix|>
<|fim_middle|>
}}
| ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
let connector_wallets_details = connector_wallet_details_with_apple_pay_metadata_optional
.map(|details| {
serde_json::to_value(details)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to serialize Apple Pay metadata as JSON")
})
.transpose()?
.map(masking::Secret::new);
Ok(connector_wallets_details)
}
async fn get_apple_pay_metadata_if_needed(
connector_metadata: &Option<masking::Secret<tera::Value>>,
connector_wallets_details_optional: &Option<api_models::admin::ConnectorWalletDetails>,
) -> RouterResult<Option<api_models::admin::ConnectorWalletDetails>> {
if let Some(connector_wallets_details) = connector_wallets_details_optional {
if connector_wallets_details.apple_pay_combined.is_some()
|| connector_wallets_details.apple_pay.is_some()
{
return Ok(Some(connector_wallets_details.clone()));
}
// Otherwise, merge Apple Pay metadata
return get_and_merge_apple_pay_metadata(
connector_metadata.clone(),
async fn get_apple_pay_metadata_if_needed(
connector_metadata: &Option<masking::Secret<tera::Value>>,
connector_wallets_details_optional: &Option<api_models::admin::ConnectorWalletDetails>,
) -> RouterResult<Option<api_models::admin::ConnectorWalletDetails>> {
{<|fim_suffix|>
<|fim_middle|>
}}
| ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
api_models::payments::ApplePayCombinedMetadata::Simplified { .. }
)
)
))
}
// This function will return the encrypted connector wallets details with Apple Pay certificates
// Currently apple pay certifiactes are stored in the metadata which is not encrypted.
// In future we want those certificates to be encrypted and stored in the connector_wallets_details.
// As part of migration fallback this function checks apple pay details are present in connector_wallets_details
// If yes, it will encrypt connector_wallets_details and store it in the database.
// If no, it will check if apple pay details are present in metadata and merge it with connector_wallets_details, encrypt and store it.
pub async fn get_connector_wallets_details_with_apple_pay_certificates(
connector_metadata: &Option<masking::Secret<tera::Value>>,
connector_wallets_details_optional: &Option<api_models::admin::ConnectorWalletDetails>,
) -> RouterResult<Option<masking::Secret<serde_json::Value>>> {
let connector_wallet_details_with_apple_pay_metadata_optional =
get_apple_pay_metadata_if_needed(connector_metadata, connector_wallets_details_optional)
.await?;
let connector_wallets_details = connector_wallet_details_with_apple_pay_metadata_optional
.map(|details| {
serde_json::to_value(details)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to serialize Apple Pay metadata as JSON")
pub async fn get_connector_wallets_details_with_apple_pay_certificates(
connector_metadata: &Option<masking::Secret<tera::Value>>,
connector_wallets_details_optional: &Option<api_models::admin::ConnectorWalletDetails>,
) -> RouterResult<Option<masking::Secret<serde_json::Value>>> {
<|fim_suffix|>
<|fim_middle|>
}
| ast_fragments |
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
) -> Result<(), errors::ApiErrorResponse> {
if auth_flow == services::AuthFlow::Client && request.get_customer_id().is_some() {
let is_same_customer = request.get_customer_id() == payment_intent.customer_id.as_ref();
if !is_same_customer {
Err(errors::ApiErrorResponse::GenericUnauthorized {
message: "Unauthorised access to update customer".to_string(),
})?;
}
}
Ok(())
}
pub fn is_apple_pay_simplified_flow(
connector_metadata: Option<pii::SecretSerdeValue>,
connector_name: Option<&String>,
) -> CustomResult<bool, errors::ApiErrorResponse> {
let option_apple_pay_metadata = get_applepay_metadata(connector_metadata)
.map_err(|error| {
logger::info!(
"Apple pay metadata parsing for {:?} in is_apple_pay_simplified_flow {:?}",
connector_name,
error
)
})
.ok();
pub fn is_apple_pay_simplified_flow(
connector_metadata: Option<pii::SecretSerdeValue>,
connector_name: Option<&String>,
) -> CustomResult<bool, errors::ApiErrorResponse> {
let option_apple_pay_metadata = get_applepay_metadata(connector_metadata)
.map_err(|error| {
logger::info!(
"Apple pay metadata parsing for {:?} in is_apple_pay_simplified_flow {:?}",
connector_name,
error
)
})
.ok();
// return true only if the apple flow type is simplified
Ok(matches!(
option_apple_pay_metadata,
Some(
api_models::payments::ApplepaySessionTokenMetadata::ApplePayCombined(
api_models::payments::ApplePayCombinedMetadata::Simplified { .. }
)
)
))
} | ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
}
}
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
pub async fn populate_bin_details_for_payment_method_create(
_card_details: api_models::payment_methods::CardDetail,
_db: &dyn StorageInterface,
) -> api_models::payment_methods::CardDetail {
todo!()
}
#[cfg(feature = "v1")]
pub fn validate_customer_access(
payment_intent: &PaymentIntent,
auth_flow: services::AuthFlow,
request: &api::PaymentsRequest,
) -> Result<(), errors::ApiErrorResponse> {
if auth_flow == services::AuthFlow::Client && request.get_customer_id().is_some() {
let is_same_customer = request.get_customer_id() == payment_intent.customer_id.as_ref();
if !is_same_customer {
Err(errors::ApiErrorResponse::GenericUnauthorized {
message: "Unauthorised access to update customer".to_string(),
})?;
}
}
pub fn validate_customer_access(
payment_intent: &PaymentIntent,
auth_flow: services::AuthFlow,
request: &api::PaymentsRequest,
) -> Result<(), errors::ApiErrorResponse> {
<|fim_suffix|>
<|fim_middle|>
}
| ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
card_type: None,
card_issuing_country: None,
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(),
card_number: card_details.card_number.clone(),
nick_name: card_details.nick_name.clone(),
})
}
}
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
pub async fn populate_bin_details_for_payment_method_create(
_card_details: api_models::payment_methods::CardDetail,
_db: &dyn StorageInterface,
) -> api_models::payment_methods::CardDetail {
todo!()
}
#[cfg(feature = "v1")]
pub fn validate_customer_access(
payment_intent: &PaymentIntent,
auth_flow: services::AuthFlow,
request: &api::PaymentsRequest,
) -> Result<(), errors::ApiErrorResponse> {
pub async fn populate_bin_details_for_payment_method_create(
_card_details: api_models::payment_methods::CardDetail,
_db: &dyn StorageInterface,
) -> api_models::payment_methods::CardDetail {
{<|fim_suffix|>
<|fim_middle|>
}}
| ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
use super::{
operations::{BoxedOperation, Operation, PaymentResponse},
CustomerDetails, PaymentData,
};
fn test_client_secret_parse() {
{<|fim_suffix|>
<|fim_middle|>
}}
| ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
Self::DbVal(db_val) => Some(db_val.get_id()),
Self::CacheVal(_) => None,
}
}
pub fn get_connector_name(&self) -> Option<String> {
match self {
Self::DbVal(db_val) => Some(db_val.connector_name.to_string()),
Self::CacheVal(_) => None,
}
}
pub fn get_additional_merchant_data(
&self,
) -> Option<Encryptable<masking::Secret<serde_json::Value>>> {
match self {
Self::DbVal(db_val) => db_val.additional_merchant_data.clone(),
Self::CacheVal(_) => None,
}
}
}
/// Query for merchant connector account either by business label or profile id
/// If profile_id is passed use it, or use connector_label to query merchant connector account
#[instrument(skip_all)]
pub fn get_additional_merchant_data(
&self,
) -> Option<Encryptable<masking::Secret<serde_json::Value>>> {
<|fim_suffix|>
<|fim_middle|>
}
| ast_fragments |
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
#[cfg(feature = "v2")]
pub fn is_test_mode_on(&self) -> Option<bool> {
None
}
pub fn get_mca_id(&self) -> Option<id_type::MerchantConnectorAccountId> {
match self {
Self::DbVal(db_val) => Some(db_val.get_id()),
Self::CacheVal(_) => None,
}
}
pub fn get_connector_name(&self) -> Option<String> {
match self {
Self::DbVal(db_val) => Some(db_val.connector_name.to_string()),
Self::CacheVal(_) => None,
}
}
pub fn get_additional_merchant_data(
&self,
) -> Option<Encryptable<masking::Secret<serde_json::Value>>> {
match self {
Self::DbVal(db_val) => db_val.additional_merchant_data.clone(),
Self::CacheVal(_) => None,
pub fn get_connector_name(&self) -> Option<String> {
match self {
Self::DbVal(db_val) => Some(db_val.connector_name.to_string()),
Self::CacheVal(_) => None,
}
} | ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
pub fn is_test_mode_on(&self) -> Option<bool> {
match self {
Self::DbVal(val) => val.test_mode,
Self::CacheVal(_) => None,
}
}
#[cfg(feature = "v2")]
pub fn is_test_mode_on(&self) -> Option<bool> {
None
}
pub fn get_mca_id(&self) -> Option<id_type::MerchantConnectorAccountId> {
match self {
Self::DbVal(db_val) => Some(db_val.get_id()),
Self::CacheVal(_) => None,
}
}
pub fn get_connector_name(&self) -> Option<String> {
match self {
Self::DbVal(db_val) => Some(db_val.connector_name.to_string()),
Self::CacheVal(_) => None,
}
}
pub fn get_mca_id(&self) -> Option<id_type::MerchantConnectorAccountId> {
<|fim_suffix|>
<|fim_middle|>
}
| ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
}
}
#[cfg(feature = "v1")]
pub fn is_test_mode_on(&self) -> Option<bool> {
match self {
Self::DbVal(val) => val.test_mode,
Self::CacheVal(_) => None,
}
}
#[cfg(feature = "v2")]
pub fn is_test_mode_on(&self) -> Option<bool> {
None
}
pub fn get_mca_id(&self) -> Option<id_type::MerchantConnectorAccountId> {
match self {
Self::DbVal(db_val) => Some(db_val.get_id()),
Self::CacheVal(_) => None,
}
}
pub fn get_connector_name(&self) -> Option<String> {
match self {
pub fn is_test_mode_on(&self) -> Option<bool> {
<|fim_suffix|>
<|fim_middle|>
}
| ast_fragments |
// file: hyperswitch/crates/router/src/core/payments/helpers.rs | crate: router
Self::DbVal(val) => val.metadata.to_owned(),
Self::CacheVal(val) => val.metadata.to_owned(),
}
}
pub fn get_connector_account_details(&self) -> serde_json::Value {
match self {
Self::DbVal(val) => val.connector_account_details.peek().to_owned(),
Self::CacheVal(val) => val.connector_account_details.peek().to_owned(),
}
}
pub fn get_connector_wallets_details(&self) -> Option<masking::Secret<serde_json::Value>> {
match self {
Self::DbVal(val) => val.connector_wallets_details.as_deref().cloned(),
Self::CacheVal(_) => None,
}
}
pub fn is_disabled(&self) -> bool {
match self {
Self::DbVal(ref inner) => inner.disabled.unwrap_or(false),
// Cached merchant connector account, only contains the account details,
// the merchant connector account must only be cached if it's not disabled
Self::CacheVal(_) => false,
pub fn get_connector_wallets_details(&self) -> Option<masking::Secret<serde_json::Value>> {
match self {
Self::DbVal(val) => val.connector_wallets_details.as_deref().cloned(),
Self::CacheVal(_) => None,
}
} | ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/customers.rs | crate: router
use router_env::{instrument, tracing};
use crate::{
core::{
errors::{ConnectorErrorExt, RouterResult},
payments,
},
logger,
routes::{metrics, SessionState},
services,
types::{self, api, domain, storage},
};
pub async fn create_connector_customer<F: Clone, T: Clone>(
state: &SessionState,
connector: &api::ConnectorData,
router_data: &types::RouterData<F, T, types::PaymentsResponseData>,
customer_request_data: types::ConnectorCustomerData,
) -> RouterResult<Option<String>> {
{<|fim_suffix|>
<|fim_middle|>
}}
| ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/customers.rs | crate: router
use common_utils::pii;
use crate::{
core::{
errors::{ConnectorErrorExt, RouterResult},
payments,
},
logger,
routes::{metrics, SessionState},
services,
types::{self, api, domain, storage},
};
pub async fn update_connector_customer_in_customers(
connector_label: &str,
customer: Option<&domain::Customer>,
connector_customer_id: Option<String>,
) -> Option<storage::CustomerUpdate> {
{<|fim_suffix|>
<|fim_middle|>
}}
| ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/customers.rs | crate: router
use router_env::{instrument, tracing};
use crate::{
core::{
errors::{ConnectorErrorExt, RouterResult},
payments,
},
logger,
routes::{metrics, SessionState},
services,
types::{self, api, domain, storage},
};
pub async fn create_connector_customer<F: Clone, T: Clone>(
state: &SessionState,
connector: &api::ConnectorData,
router_data: &types::RouterData<F, T, types::PaymentsResponseData>,
customer_request_data: types::ConnectorCustomerData,
) -> RouterResult<Option<String>> {
{
types::PaymentsResponseData::ConnectorCustomerResponse {
connector_customer_id,
} => Some(connector_customer_id),<|fim_suffix|>
<|fim_middle|>
_ => None,
}
} | ast_fragments |
<|fim_prefix|>
// file: hyperswitch/crates/router/src/core/payments/customers.rs | crate: router
use common_utils::pii;
use crate::{
core::{
errors::{ConnectorErrorExt, RouterResult},
payments,
},
logger,
routes::{metrics, SessionState},
services,
types::{self, api, domain, storage},
};
pub async fn update_connector_customer_in_customers(
merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId,
customer: Option<&domain::Customer>,
connector_customer_id: Option<String>,
) -> Option<storage::CustomerUpdate> {
{<|fim_suffix|>
<|fim_middle|>
}}
| ast_fragments |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.