text
stringlengths
70
351k
source
stringclasses
4 values
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/webhooks/recovery_incoming.rs | crate: router }) } } pub struct BillingConnectorPaymentsSyncResponseData( revenue_recovery_response::BillingConnectorPaymentsSyncResponse, ); pub struct BillingConnectorPaymentsSyncFlowRouterData( router_types::BillingConnectorPaymentsSyncRouterData, ); impl BillingConnectorPaymentsSyncResponseData { async fn handle_billing_connector_payment_sync_call( state: &SessionState, merchant_account: &domain::MerchantAccount, merchant_connector_account: &hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount, connector_name: &str, id: &str, ) -> CustomResult<Self, errors::RevenueRecoveryError> { let connector_data = api::ConnectorData::get_connector_by_name( &state.conf.connectors, connector_name, api::GetToken::Connector, None, ) async fn handle_billing_connector_payment_sync_call( state: &SessionState, merchant_account: &domain::MerchantAccount, merchant_connector_account: &hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount, connector_name: &str, id: &str, ) -> CustomResult<Self, errors::RevenueRecoveryError> { { Ok(response) => Ok(response),<|fim_suffix|> <|fim_middle|> error @ Err(_) => { router_env::logger::error!(?error); Err(errors::RevenueRecoveryError::BillingConnectorPaymentsSyncFailed) .attach_printable("Failed while fetching billing connector payment details") } } }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/webhooks/recovery_incoming.rs | crate: router "Failed to get recovery attempt details from the billing connector", ) .map(RevenueRecoveryAttempt) }, |data| { Ok(Self(revenue_recovery::RevenueRecoveryAttemptData::from( data, ))) }, ) } async fn get_payment_attempt( &self, state: &SessionState, req_state: &ReqState, merchant_account: &domain::MerchantAccount, profile: &domain::Profile, key_store: &domain::MerchantKeyStore, payment_id: id_type::GlobalPaymentId, ) -> CustomResult<Option<revenue_recovery::RecoveryPaymentAttempt>, errors::RevenueRecoveryError> { let attempt_response = Box::pin(payments::payments_core::< router_flow_types::payments::PSync, api_payments::PaymentsResponse, async fn get_payment_attempt( &self, state: &SessionState, req_state: &ReqState, merchant_account: &domain::MerchantAccount, profile: &domain::Profile, key_store: &domain::MerchantKeyStore, payment_id: id_type::GlobalPaymentId, ) -> CustomResult<Option<revenue_recovery::RecoveryPaymentAttempt>, errors::RevenueRecoveryError> { {<|fim_suffix|> <|fim_middle|> }}
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/webhooks/recovery_incoming.rs | crate: router use hyperswitch_domain_models::{ errors::api_error_response, revenue_recovery, router_data_v2::flow_common_types, router_flow_types, router_request_types::revenue_recovery as revenue_recovery_request, router_response_types::revenue_recovery as revenue_recovery_response, types as router_types, }; use crate::{ core::{ errors::{self, CustomResult}, payments::{self, helpers}, }, db::{errors::RevenueRecoveryError, StorageInterface}, routes::{app::ReqState, metrics, SessionState}, services::{ self, connector_integration_interface::{self, RouterDataConversion}, }, types::{self, api, domain, storage::revenue_recovery as storage_churn_recovery}, workflows::revenue_recovery as revenue_recovery_flow, }; fn inner(self) -> router_types::BillingConnectorPaymentsSyncRouterData { {<|fim_suffix|> <|fim_middle|> }}
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/webhooks/recovery_incoming.rs | crate: router use hyperswitch_domain_models::{ errors::api_error_response, revenue_recovery, router_data_v2::flow_common_types, router_flow_types, router_request_types::revenue_recovery as revenue_recovery_request, router_response_types::revenue_recovery as revenue_recovery_response, types as router_types, }; use crate::{ core::{ errors::{self, CustomResult}, payments::{self, helpers}, }, db::{errors::RevenueRecoveryError, StorageInterface}, routes::{app::ReqState, metrics, SessionState}, services::{ self, connector_integration_interface::{self, RouterDataConversion}, }, types::{self, api, domain, storage::revenue_recovery as storage_churn_recovery}, workflows::revenue_recovery as revenue_recovery_flow, }; fn inner(self) -> revenue_recovery_response::BillingConnectorPaymentsSyncResponse { {<|fim_suffix|> <|fim_middle|> }}
ast_fragments
// file: hyperswitch/crates/router/src/core/webhooks/recovery_incoming.rs | crate: router use api_models::{payments as api_payments, webhooks}; use hyperswitch_domain_models::{ errors::api_error_response, revenue_recovery, router_data_v2::flow_common_types, router_flow_types, router_request_types::revenue_recovery as revenue_recovery_request, router_response_types::revenue_recovery as revenue_recovery_response, types as router_types, }; use hyperswitch_interfaces::webhooks as interface_webhooks; use crate::{ core::{ errors::{self, CustomResult}, payments::{self, helpers}, }, db::{errors::RevenueRecoveryError, StorageInterface}, routes::{app::ReqState, metrics, SessionState}, services::{ self, connector_integration_interface::{self, RouterDataConversion}, }, types::{self, api, domain, storage::revenue_recovery as storage_churn_recovery}, workflows::revenue_recovery as revenue_recovery_flow, }; fn get_recovery_invoice_details( connector_enum: &connector_integration_interface::ConnectorEnum, request_details: &hyperswitch_interfaces::webhooks::IncomingWebhookRequestDetails<'_>, billing_connector_payment_details: Option< &revenue_recovery_response::BillingConnectorPaymentsSyncResponse, >, ) -> CustomResult<Self, errors::RevenueRecoveryError> { billing_connector_payment_details.map_or_else( || { interface_webhooks::IncomingWebhook::get_revenue_recovery_invoice_details( connector_enum, request_details, ) .change_context(errors::RevenueRecoveryError::InvoiceWebhookProcessingFailed) .attach_printable("Failed while getting revenue recovery invoice details") .map(RevenueRecoveryInvoice) }, |data| { Ok(Self(revenue_recovery::RevenueRecoveryInvoiceData::from( data, ))) }, ) }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/webhooks/recovery_incoming.rs | crate: router use std::{marker::PhantomData, str::FromStr}; use api_models::{payments as api_payments, webhooks}; use common_utils::{ ext_traits::{AsyncExt, ValueExt}, id_type, }; use diesel_models::{process_tracker as storage, schema::process_tracker::retry_count}; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::{ errors::api_error_response, revenue_recovery, router_data_v2::flow_common_types, router_flow_types, router_request_types::revenue_recovery as revenue_recovery_request, router_response_types::revenue_recovery as revenue_recovery_response, types as router_types, }; use hyperswitch_interfaces::webhooks as interface_webhooks; use router_env::{instrument, tracing}; use serde_with::rust::unwrap_or_skip; use crate::{ core::{ errors::{self, CustomResult}, payments::{self, helpers}, }, db::{errors::RevenueRecoveryError, StorageInterface}, routes::{app::ReqState, metrics, SessionState}, services::{ self, connector_integration_interface::{self, RouterDataConversion}, }, types::{self, api, domain, storage::revenue_recovery as storage_churn_recovery}, workflows::revenue_recovery as revenue_recovery_flow, }; pub async fn recovery_incoming_webhook_flow( state: SessionState, merchant_account: domain::MerchantAccount, business_profile: domain::Profile, key_store: domain::MerchantKeyStore, _webhook_details: api::IncomingWebhookDetails, source_verified: bool, connector_enum: &connector_integration_interface::ConnectorEnum, billing_connector_account: hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount, connector_name: &str, request_details: &hyperswitch_interfaces::webhooks::IncomingWebhookRequestDetails<'_>, event_type: webhooks::IncomingWebhookEvent, req_state: ReqState, object_ref_id: &webhooks::ObjectReferenceId, ) -> CustomResult<webhooks::WebhookResponseTracker, errors::RevenueRecoveryError> { <|fim_suffix|> <|fim_middle|> }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/webhooks/incoming.rs | crate: router use common_utils::{errors::ReportSwitchExt, events::ApiEventsType}; use hyperswitch_domain_models::{ mandates::CommonMandateReference, payments::{payment_attempt::PaymentAttempt, HeaderPayload}, router_request_types::VerifyWebhookSourceRequestData, router_response_types::{VerifyWebhookSourceResponseData, VerifyWebhookStatus}, }; use crate::{ consts, core::{ api_locking, errors::{self, ConnectorErrorExt, CustomResult, RouterResponse, StorageErrorExt}, metrics, payments::{self, tokenization}, refunds, relay, utils as core_utils, webhooks::utils::construct_webhook_router_data, }, db::StorageInterface, events::api_logs::ApiEvent, logger, routes::{ app::{ReqState, SessionStateInfo}, lock_utils, SessionState, }, services::{ self, authentication as auth, connector_integration_interface::ConnectorEnum, ConnectorValidation, }, types::{ api::{ self, mandates::MandateResponseExt, ConnectorCommon, ConnectorData, GetToken, IncomingWebhook, }, domain, storage::{self, enums}, transformers::{ForeignFrom, ForeignInto, ForeignTryFrom}, }, utils::{self as helper_utils, ext_traits::OptionExt, generate_id}, }; fn insert_mandate_details( payment_attempt: &PaymentAttempt, webhook_mandate_details: &hyperswitch_domain_models::router_flow_types::ConnectorMandateDetails, payment_method_mandate_details: Option<CommonMandateReference>, ) -> CustomResult<Option<CommonMandateReference>, errors::ApiErrorResponse> { {<|fim_suffix|> <|fim_middle|> }}
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/webhooks/incoming.rs | crate: router use std::{str::FromStr, time::Instant}; use api_models::payouts as payout_models; use common_utils::{errors::ReportSwitchExt, events::ApiEventsType}; use crate::{ consts, core::{ api_locking, errors::{self, ConnectorErrorExt, CustomResult, RouterResponse, StorageErrorExt}, metrics, payments::{self, tokenization}, refunds, relay, utils as core_utils, webhooks::utils::construct_webhook_router_data, }, db::StorageInterface, events::api_logs::ApiEvent, logger, routes::{ app::{ReqState, SessionStateInfo}, lock_utils, SessionState, }, services::{ self, authentication as auth, connector_integration_interface::ConnectorEnum, ConnectorValidation, }, types::{ api::{ self, mandates::MandateResponseExt, ConnectorCommon, ConnectorData, GetToken, IncomingWebhook, }, domain, storage::{self, enums}, transformers::{ForeignFrom, ForeignInto, ForeignTryFrom}, }, utils::{self as helper_utils, ext_traits::OptionExt, generate_id}, }; /// This function fetches the merchant connector account ( if the url used is /{ <|fim_suffix|> <|fim_middle|> }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/webhooks/incoming.rs | crate: router )) .await?; } Ok(WebhookResponseTracker::Payment { payment_id, status }) } _ => Err(errors::ApiErrorResponse::WebhookProcessingFailure) .attach_printable("received non-json response from payments core")?, } } async fn get_payment_id( db: &dyn StorageInterface, payment_id: &api::PaymentIdType, merchant_id: &common_utils::id_type::MerchantId, storage_scheme: enums::MerchantStorageScheme, ) -> errors::RouterResult<common_utils::id_type::PaymentId> { let pay_id = || async { match payment_id { api_models::payments::PaymentIdType::PaymentIntentId(ref id) => Ok(id.to_owned()), api_models::payments::PaymentIdType::ConnectorTransactionId(ref id) => db .find_payment_attempt_by_merchant_id_connector_txn_id( merchant_id, id, async fn get_payment_id( db: &dyn StorageInterface, payment_id: &api::PaymentIdType, merchant_id: &common_utils::id_type::MerchantId, storage_scheme: enums::MerchantStorageScheme, ) -> errors::RouterResult<common_utils::id_type::PaymentId> { <|fim_suffix|> <|fim_middle|> }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/webhooks/incoming.rs | crate: router )?, } } else { logger::error!("Webhook source verification failed for frm webhooks flow"); Err(report!( errors::ApiErrorResponse::WebhookAuthenticationFailed )) } } #[allow(clippy::too_many_arguments)] #[instrument(skip_all)] async fn disputes_incoming_webhook_flow( state: SessionState, merchant_account: domain::MerchantAccount, business_profile: domain::Profile, key_store: domain::MerchantKeyStore, webhook_details: api::IncomingWebhookDetails, source_verified: bool, connector: &ConnectorEnum, request_details: &IncomingWebhookRequestDetails<'_>, event_type: webhooks::IncomingWebhookEvent, ) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> { metrics::INCOMING_DISPUTE_WEBHOOK_METRIC.add(1, &[]); if source_verified { async fn disputes_incoming_webhook_flow( state: SessionState, merchant_account: domain::MerchantAccount, business_profile: domain::Profile, key_store: domain::MerchantKeyStore, webhook_details: api::IncomingWebhookDetails, source_verified: bool, connector: &ConnectorEnum, request_details: &IncomingWebhookRequestDetails<'_>, event_type: webhooks::IncomingWebhookEvent, ) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> { <|fim_suffix|> <|fim_middle|> }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/webhooks/incoming.rs | crate: router id, merchant_account.get_id(), merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::WebhookResourceNotFound), _ => Err(errors::ApiErrorResponse::WebhookProcessingFailure) .attach_printable("received a non-payment id for retrieving payment")?, } } #[allow(clippy::too_many_arguments)] async fn get_or_update_dispute_object( state: SessionState, option_dispute: Option<diesel_models::dispute::Dispute>, dispute_details: api::disputes::DisputePayload, merchant_id: &common_utils::id_type::MerchantId, organization_id: &common_utils::id_type::OrganizationId, payment_attempt: &PaymentAttempt, event_type: webhooks::IncomingWebhookEvent, business_profile: &domain::Profile, connector_name: &str, ) -> CustomResult<diesel_models::dispute::Dispute, errors::ApiErrorResponse> { let db = &*state.store; match option_dispute { async fn get_or_update_dispute_object( state: SessionState, option_dispute: Option<diesel_models::dispute::Dispute>, dispute_details: api::disputes::DisputePayload, merchant_id: &common_utils::id_type::MerchantId, organization_id: &common_utils::id_type::OrganizationId, payment_attempt: &PaymentAttempt, event_type: webhooks::IncomingWebhookEvent, business_profile: &domain::Profile, connector_name: &str, ) -> CustomResult<diesel_models::dispute::Dispute, errors::ApiErrorResponse> { <|fim_suffix|> <|fim_middle|> }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/webhooks/incoming.rs | crate: router | webhooks::WebhookFlow::Subscription | webhooks::WebhookFlow::ReturnResponse | webhooks::WebhookFlow::BankTransfer | webhooks::WebhookFlow::Mandate | webhooks::WebhookFlow::ExternalAuthentication | webhooks::WebhookFlow::FraudCheck => Err(errors::ApiErrorResponse::NotSupported { message: "Relay webhook flow types not supported".to_string(), })?, }; Ok(result_response) } async fn get_payment_attempt_from_object_reference_id( state: &SessionState, object_reference_id: webhooks::ObjectReferenceId, merchant_account: &domain::MerchantAccount, ) -> CustomResult<PaymentAttempt, errors::ApiErrorResponse> { let db = &*state.store; match object_reference_id { api::ObjectReferenceId::PaymentId(api::PaymentIdType::ConnectorTransactionId(ref id)) => db .find_payment_attempt_by_merchant_id_connector_txn_id( merchant_account.get_id(), id, merchant_account.storage_scheme, ) async fn get_payment_attempt_from_object_reference_id( state: &SessionState, object_reference_id: webhooks::ObjectReferenceId, merchant_account: &domain::MerchantAccount, ) -> CustomResult<PaymentAttempt, errors::ApiErrorResponse> { { api::ObjectReferenceId::PaymentId(api::PaymentIdType::ConnectorTransactionId(ref id)) => db .find_payment_attempt_by_merchant_id_connector_txn_id( merchant_account.get_id(), id, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::WebhookResourceNotFound),<|fim_suffix|> <|fim_middle|> _ => Err(errors::ApiErrorResponse::WebhookProcessingFailure) .attach_printable("received a non-payment id for retrieving payment")?, } }
ast_fragments
// file: hyperswitch/crates/router/src/core/webhooks/incoming.rs | crate: router use api_models::webhooks::{self, WebhookResponseTracker}; use common_utils::{errors::ReportSwitchExt, events::ApiEventsType}; use hyperswitch_interfaces::webhooks::{IncomingWebhookFlowError, IncomingWebhookRequestDetails}; use super::{types, utils, MERCHANT_ID}; use crate::{ consts, core::{ api_locking, errors::{self, ConnectorErrorExt, CustomResult, RouterResponse, StorageErrorExt}, metrics, payments::{self, tokenization}, refunds, relay, utils as core_utils, webhooks::utils::construct_webhook_router_data, }, db::StorageInterface, events::api_logs::ApiEvent, logger, routes::{ app::{ReqState, SessionStateInfo}, lock_utils, SessionState, }, services::{ self, authentication as auth, connector_integration_interface::ConnectorEnum, ConnectorValidation, }, types::{ api::{ self, mandates::MandateResponseExt, ConnectorCommon, ConnectorData, GetToken, IncomingWebhook, }, domain, storage::{self, enums}, transformers::{ForeignFrom, ForeignInto, ForeignTryFrom}, }, utils::{self as helper_utils, ext_traits::OptionExt, generate_id}, }; use crate::{core::payouts, types::storage::PayoutAttemptUpdate}; async fn relay_incoming_webhook_flow( state: SessionState, merchant_account: domain::MerchantAccount, business_profile: domain::Profile, merchant_key_store: domain::MerchantKeyStore, webhook_details: api::IncomingWebhookDetails, event_type: webhooks::IncomingWebhookEvent, source_verified: bool, ) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> { let flow_type: api::WebhookFlow = event_type.into(); let result_response = match flow_type { webhooks::WebhookFlow::Refund => Box::pin(relay_refunds_incoming_webhook_flow( state, merchant_account, business_profile, merchant_key_store, webhook_details, event_type, source_verified, )) .await .attach_printable("Incoming webhook flow for relay refund failed")?, webhooks::WebhookFlow::Payment | webhooks::WebhookFlow::Payout | webhooks::WebhookFlow::Dispute | webhooks::WebhookFlow::Subscription | webhooks::WebhookFlow::ReturnResponse | webhooks::WebhookFlow::BankTransfer | webhooks::WebhookFlow::Mandate | webhooks::WebhookFlow::ExternalAuthentication | webhooks::WebhookFlow::FraudCheck => Err(errors::ApiErrorResponse::NotSupported { message: "Relay webhook flow types not supported".to_string(), })?, }; Ok(result_response) }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/webhooks/incoming.rs | crate: router use std::{str::FromStr, time::Instant}; use api_models::payouts as payout_models; use api_models::webhooks::{self, WebhookResponseTracker}; use common_utils::{errors::ReportSwitchExt, events::ApiEventsType}; use error_stack::{report, ResultExt}; use hyperswitch_interfaces::webhooks::{IncomingWebhookFlowError, IncomingWebhookRequestDetails}; use crate::{ consts, core::{ api_locking, errors::{self, ConnectorErrorExt, CustomResult, RouterResponse, StorageErrorExt}, metrics, payments::{self, tokenization}, refunds, relay, utils as core_utils, webhooks::utils::construct_webhook_router_data, }, db::StorageInterface, events::api_logs::ApiEvent, logger, routes::{ app::{ReqState, SessionStateInfo}, lock_utils, SessionState, }, services::{ self, authentication as auth, connector_integration_interface::ConnectorEnum, ConnectorValidation, }, types::{ api::{ self, mandates::MandateResponseExt, ConnectorCommon, ConnectorData, GetToken, IncomingWebhook, }, domain, storage::{self, enums}, transformers::{ForeignFrom, ForeignInto, ForeignTryFrom}, }, utils::{self as helper_utils, ext_traits::OptionExt, generate_id}, }; fn handle_incoming_webhook_error( error: error_stack::Report<errors::ApiErrorResponse>, connector: &ConnectorEnum, connector_name: &str, request_details: &IncomingWebhookRequestDetails<'_>, ) -> errors::RouterResult<( services::ApplicationResponse<serde_json::Value>, WebhookResponseTracker, serde_json::Value, )> { <|fim_suffix|> <|fim_middle|> }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/webhooks/incoming.rs | crate: router use std::{str::FromStr, time::Instant}; use actix_web::FromRequest; use common_utils::{errors::ReportSwitchExt, events::ApiEventsType}; use router_env::{instrument, tracing, tracing_actix_web::RequestId}; use super::{types, utils, MERCHANT_ID}; use crate::{ consts, core::{ api_locking, errors::{self, ConnectorErrorExt, CustomResult, RouterResponse, StorageErrorExt}, metrics, payments::{self, tokenization}, refunds, relay, utils as core_utils, webhooks::utils::construct_webhook_router_data, }, db::StorageInterface, events::api_logs::ApiEvent, logger, routes::{ app::{ReqState, SessionStateInfo}, lock_utils, SessionState, }, services::{ self, authentication as auth, connector_integration_interface::ConnectorEnum, ConnectorValidation, }, types::{ api::{ self, mandates::MandateResponseExt, ConnectorCommon, ConnectorData, GetToken, IncomingWebhook, }, domain, storage::{self, enums}, transformers::{ForeignFrom, ForeignInto, ForeignTryFrom}, }, utils::{self as helper_utils, ext_traits::OptionExt, generate_id}, }; use crate::{core::payouts, types::storage::PayoutAttemptUpdate}; pub async fn incoming_webhooks_wrapper<W: types::OutgoingWebhookType>( flow: &impl router_env::types::FlowMetric, state: SessionState, req_state: ReqState, req: &actix_web::HttpRequest, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, connector_name_or_mca_id: &str, body: actix_web::web::Bytes, is_relay_webhook: bool, ) -> RouterResponse<serde_json::Value> { {<|fim_suffix|> <|fim_middle|> }}
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/webhooks/incoming.rs | crate: router let (connector, connector_name) = get_connector_by_connector_name(state, &mca.connector_name, Some(mca.get_id()))?; Ok((Some(mca), connector, connector_name)) } else { // Merchant connector account is already being queried, it is safe to set connector id as None let (connector, connector_name) = get_connector_by_connector_name(state, connector_name_or_mca_id, None)?; Ok((None, connector, connector_name)) } } fn should_update_connector_mandate_details( source_verified: bool, event_type: webhooks::IncomingWebhookEvent, ) -> bool { source_verified && event_type == webhooks::IncomingWebhookEvent::PaymentIntentSuccess } async fn update_connector_mandate_details( state: &SessionState, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, object_ref_id: api::ObjectReferenceId, connector: &ConnectorEnum, fn should_update_connector_mandate_details( source_verified: bool, event_type: webhooks::IncomingWebhookEvent, ) -> bool { {<|fim_suffix|> <|fim_middle|> }}
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/webhooks/incoming.rs | crate: router } } else { logger::error!( "Webhook source verification failed for external authentication webhook flow" ); Err(report!( errors::ApiErrorResponse::WebhookAuthenticationFailed )) } } #[instrument(skip_all)] async fn mandates_incoming_webhook_flow( state: SessionState, merchant_account: domain::MerchantAccount, business_profile: domain::Profile, key_store: domain::MerchantKeyStore, webhook_details: api::IncomingWebhookDetails, source_verified: bool, event_type: webhooks::IncomingWebhookEvent, ) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> { if source_verified { let db = &*state.store; let mandate = match webhook_details.object_reference_id { webhooks::ObjectReferenceId::MandateId(webhooks::MandateIdType::MandateId( async fn mandates_incoming_webhook_flow( state: SessionState, merchant_account: domain::MerchantAccount, business_profile: domain::Profile, key_store: domain::MerchantKeyStore, webhook_details: api::IncomingWebhookDetails, source_verified: bool, event_type: webhooks::IncomingWebhookEvent, ) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> { {<|fim_suffix|> <|fim_middle|> }}
ast_fragments
// file: hyperswitch/crates/router/src/core/webhooks/incoming.rs | crate: router use api_models::webhooks::{self, WebhookResponseTracker}; use hyperswitch_interfaces::webhooks::{IncomingWebhookFlowError, IncomingWebhookRequestDetails}; use crate::{ consts, core::{ api_locking, errors::{self, ConnectorErrorExt, CustomResult, RouterResponse, StorageErrorExt}, metrics, payments::{self, tokenization}, refunds, relay, utils as core_utils, webhooks::utils::construct_webhook_router_data, }, db::StorageInterface, events::api_logs::ApiEvent, logger, routes::{ app::{ReqState, SessionStateInfo}, lock_utils, SessionState, }, services::{ self, authentication as auth, connector_integration_interface::ConnectorEnum, ConnectorValidation, }, types::{ api::{ self, mandates::MandateResponseExt, ConnectorCommon, ConnectorData, GetToken, IncomingWebhook, }, domain, storage::{self, enums}, transformers::{ForeignFrom, ForeignInto, ForeignTryFrom}, }, utils::{self as helper_utils, ext_traits::OptionExt, generate_id}, }; fn should_update_connector_mandate_details( source_verified: bool, event_type: webhooks::IncomingWebhookEvent, ) -> bool { source_verified && event_type == webhooks::IncomingWebhookEvent::PaymentIntentSuccess }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/webhooks/incoming.rs | crate: router get_connector_by_connector_name(state, connector_name_or_mca_id, None)?; Ok((None, connector, connector_name)) } } fn should_update_connector_mandate_details( source_verified: bool, event_type: webhooks::IncomingWebhookEvent, ) -> bool { source_verified && event_type == webhooks::IncomingWebhookEvent::PaymentIntentSuccess } async fn update_connector_mandate_details( state: &SessionState, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, object_ref_id: api::ObjectReferenceId, connector: &ConnectorEnum, request_details: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<(), errors::ApiErrorResponse> { let webhook_connector_mandate_details = connector .get_mandate_details(request_details) .switch() .attach_printable("Could not find connector mandate details in incoming webhook body")?; async fn update_connector_mandate_details( state: &SessionState, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, object_ref_id: api::ObjectReferenceId, connector: &ConnectorEnum, request_details: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<(), errors::ApiErrorResponse> { <|fim_suffix|> <|fim_middle|> }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/webhooks/incoming.rs | crate: router payment_id: dispute_object.payment_id, status: dispute_object.dispute_status, }) } else { metrics::INCOMING_DISPUTE_WEBHOOK_SIGNATURE_FAILURE_METRIC.add(1, &[]); Err(report!( errors::ApiErrorResponse::WebhookAuthenticationFailed )) } } #[instrument(skip_all)] async fn bank_transfer_webhook_flow( state: SessionState, req_state: ReqState, merchant_account: domain::MerchantAccount, business_profile: domain::Profile, key_store: domain::MerchantKeyStore, webhook_details: api::IncomingWebhookDetails, source_verified: bool, ) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> { let response = if source_verified { let payment_attempt = get_payment_attempt_from_object_reference_id( &state, webhook_details.object_reference_id, async fn bank_transfer_webhook_flow( state: SessionState, req_state: ReqState, merchant_account: domain::MerchantAccount, business_profile: domain::Profile, key_store: domain::MerchantKeyStore, webhook_details: api::IncomingWebhookDetails, source_verified: bool, ) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> { {<|fim_suffix|> <|fim_middle|> }}
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/webhooks/incoming.rs | crate: router status: updated_mandate.mandate_status, }) } else { logger::error!("Webhook source verification failed for mandates webhook flow"); Err(report!( errors::ApiErrorResponse::WebhookAuthenticationFailed )) } } #[allow(clippy::too_many_arguments)] #[instrument(skip_all)] async fn frm_incoming_webhook_flow( state: SessionState, req_state: ReqState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, source_verified: bool, event_type: webhooks::IncomingWebhookEvent, object_ref_id: api::ObjectReferenceId, business_profile: domain::Profile, ) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> { if source_verified { let payment_attempt = get_payment_attempt_from_object_reference_id(&state, object_ref_id, &merchant_account) async fn frm_incoming_webhook_flow( state: SessionState, req_state: ReqState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, source_verified: bool, event_type: webhooks::IncomingWebhookEvent, object_ref_id: api::ObjectReferenceId, business_profile: domain::Profile, ) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> { <|fim_suffix|> <|fim_middle|> }
ast_fragments
// file: hyperswitch/crates/router/src/core/webhooks/incoming.rs | crate: router } } else { logger::error!( "Webhook source verification failed for external authentication webhook flow" ); Err(report!( errors::ApiErrorResponse::WebhookAuthenticationFailed )) } } #[instrument(skip_all)] async fn mandates_incoming_webhook_flow( state: SessionState, merchant_account: domain::MerchantAccount, business_profile: domain::Profile, key_store: domain::MerchantKeyStore, webhook_details: api::IncomingWebhookDetails, source_verified: bool, event_type: webhooks::IncomingWebhookEvent, ) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> { if source_verified { let db = &*state.store; let mandate = match webhook_details.object_reference_id { webhooks::ObjectReferenceId::MandateId(webhooks::MandateIdType::MandateId( async fn mandates_incoming_webhook_flow( state: SessionState, merchant_account: domain::MerchantAccount, business_profile: domain::Profile, key_store: domain::MerchantKeyStore, webhook_details: api::IncomingWebhookDetails, source_verified: bool, event_type: webhooks::IncomingWebhookEvent, ) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> { if source_verified { let db = &*state.store; let mandate = match webhook_details.object_reference_id { webhooks::ObjectReferenceId::MandateId(webhooks::MandateIdType::MandateId( mandate_id, )) => db .find_mandate_by_merchant_id_mandate_id( merchant_account.get_id(), mandate_id.as_str(), merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?, webhooks::ObjectReferenceId::MandateId( webhooks::MandateIdType::ConnectorMandateId(connector_mandate_id), ) => db .find_mandate_by_merchant_id_connector_mandate_id( merchant_account.get_id(), connector_mandate_id.as_str(), merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?, _ => Err(errors::ApiErrorResponse::WebhookProcessingFailure) .attach_printable("received a non-mandate id for retrieving mandate")?, }; let mandate_status = common_enums::MandateStatus::foreign_try_from(event_type) .change_context(errors::ApiErrorResponse::WebhookProcessingFailure) .attach_printable("event type to mandate status mapping failed")?; let mandate_id = mandate.mandate_id.clone(); let updated_mandate = db .update_mandate_by_merchant_id_mandate_id( merchant_account.get_id(), &mandate_id, storage::MandateUpdate::StatusUpdate { mandate_status }, mandate, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?; let mandates_response = Box::new( api::mandates::MandateResponse::from_db_mandate( &state, key_store.clone(), updated_mandate.clone(), merchant_account.storage_scheme, ) .await?, ); let event_type: Option<enums::EventType> = updated_mandate.mandate_status.foreign_into(); if let Some(outgoing_event_type) = event_type { Box::pin(super::create_event_and_trigger_outgoing_webhook( state, merchant_account, business_profile, &key_store, outgoing_event_type, enums::EventClass::Mandates, updated_mandate.mandate_id.clone(), enums::EventObjectType::MandateDetails, api::OutgoingWebhookContent::MandateDetails(mandates_response), Some(updated_mandate.created_at), )) .await?; } Ok(WebhookResponseTracker::Mandate { mandate_id: updated_mandate.mandate_id, status: updated_mandate.mandate_status, }) } else { logger::error!("Webhook source verification failed for mandates webhook flow"); Err(report!( errors::ApiErrorResponse::WebhookAuthenticationFailed )) } }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/webhooks/incoming.rs | crate: router use std::{str::FromStr, time::Instant}; use api_models::payouts as payout_models; use api_models::webhooks::{self, WebhookResponseTracker}; use common_utils::{errors::ReportSwitchExt, events::ApiEventsType}; use hyperswitch_interfaces::webhooks::{IncomingWebhookFlowError, IncomingWebhookRequestDetails}; use super::{types, utils, MERCHANT_ID}; use crate::{ consts, core::{ api_locking, errors::{self, ConnectorErrorExt, CustomResult, RouterResponse, StorageErrorExt}, metrics, payments::{self, tokenization}, refunds, relay, utils as core_utils, webhooks::utils::construct_webhook_router_data, }, db::StorageInterface, events::api_logs::ApiEvent, logger, routes::{ app::{ReqState, SessionStateInfo}, lock_utils, SessionState, }, services::{ self, authentication as auth, connector_integration_interface::ConnectorEnum, ConnectorValidation, }, types::{ api::{ self, mandates::MandateResponseExt, ConnectorCommon, ConnectorData, GetToken, IncomingWebhook, }, domain, storage::{self, enums}, transformers::{ForeignFrom, ForeignInto, ForeignTryFrom}, }, utils::{self as helper_utils, ext_traits::OptionExt, generate_id}, }; use crate::{core::payouts, types::storage::PayoutAttemptUpdate}; async fn refunds_incoming_webhook_flow( state: SessionState, merchant_account: domain::MerchantAccount, business_profile: domain::Profile, key_store: domain::MerchantKeyStore, webhook_details: api::IncomingWebhookDetails, connector_name: &str, source_verified: bool, event_type: webhooks::IncomingWebhookEvent, ) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> { {<|fim_suffix|> <|fim_middle|> }}
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/webhooks/incoming.rs | crate: router Ok(WebhookResponseTracker::Payout { payout_id: updated_payout_attempt.payout_id, status: updated_payout_attempt.status, }) } else { metrics::INCOMING_PAYOUT_WEBHOOK_SIGNATURE_FAILURE_METRIC.add(1, &[]); Err(report!( errors::ApiErrorResponse::WebhookAuthenticationFailed )) } } async fn relay_refunds_incoming_webhook_flow( state: SessionState, merchant_account: domain::MerchantAccount, business_profile: domain::Profile, merchant_key_store: domain::MerchantKeyStore, webhook_details: api::IncomingWebhookDetails, event_type: webhooks::IncomingWebhookEvent, source_verified: bool, ) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> { let db = &*state.store; let key_manager_state = &(&state).into(); let relay_record = match webhook_details.object_reference_id { async fn relay_refunds_incoming_webhook_flow( state: SessionState, merchant_account: domain::MerchantAccount, business_profile: domain::Profile, merchant_key_store: domain::MerchantKeyStore, webhook_details: api::IncomingWebhookDetails, event_type: webhooks::IncomingWebhookEvent, source_verified: bool, ) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> { <|fim_suffix|> <|fim_middle|> }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/webhooks/incoming.rs | crate: router use api_models::payouts as payout_models; use api_models::webhooks::{self, WebhookResponseTracker}; use common_utils::{errors::ReportSwitchExt, events::ApiEventsType}; use error_stack::{report, ResultExt}; use hyperswitch_interfaces::webhooks::{IncomingWebhookFlowError, IncomingWebhookRequestDetails}; use super::{types, utils, MERCHANT_ID}; use crate::{ consts, core::{ api_locking, errors::{self, ConnectorErrorExt, CustomResult, RouterResponse, StorageErrorExt}, metrics, payments::{self, tokenization}, refunds, relay, utils as core_utils, webhooks::utils::construct_webhook_router_data, }, db::StorageInterface, events::api_logs::ApiEvent, logger, routes::{ app::{ReqState, SessionStateInfo}, lock_utils, SessionState, }, services::{ self, authentication as auth, connector_integration_interface::ConnectorEnum, ConnectorValidation, }, types::{ api::{ self, mandates::MandateResponseExt, ConnectorCommon, ConnectorData, GetToken, IncomingWebhook, }, domain, storage::{self, enums}, transformers::{ForeignFrom, ForeignInto, ForeignTryFrom}, }, utils::{self as helper_utils, ext_traits::OptionExt, generate_id}, }; use crate::{core::payouts, types::storage::PayoutAttemptUpdate}; async fn payouts_incoming_webhook_flow( state: SessionState, merchant_account: domain::MerchantAccount, business_profile: domain::Profile, key_store: domain::MerchantKeyStore, webhook_details: api::IncomingWebhookDetails, event_type: webhooks::IncomingWebhookEvent, source_verified: bool, ) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> { <|fim_suffix|> <|fim_middle|> }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/webhooks/incoming.rs | crate: router Ok(( response, WebhookResponseTracker::NoEffect, serde_json::Value::Null, )) } else { Err(error) } } #[allow(clippy::too_many_arguments)] #[instrument(skip_all)] async fn payments_incoming_webhook_flow( state: SessionState, req_state: ReqState, merchant_account: domain::MerchantAccount, business_profile: domain::Profile, key_store: domain::MerchantKeyStore, webhook_details: api::IncomingWebhookDetails, source_verified: bool, connector: &ConnectorEnum, request_details: &IncomingWebhookRequestDetails<'_>, event_type: webhooks::IncomingWebhookEvent, ) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> { let consume_or_trigger_flow = if source_verified { async fn payments_incoming_webhook_flow( state: SessionState, req_state: ReqState, merchant_account: domain::MerchantAccount, business_profile: domain::Profile, key_store: domain::MerchantKeyStore, webhook_details: api::IncomingWebhookDetails, source_verified: bool, connector: &ConnectorEnum, request_details: &IncomingWebhookRequestDetails<'_>, event_type: webhooks::IncomingWebhookEvent, ) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> { {<|fim_suffix|> <|fim_middle|> }}
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/webhooks/incoming.rs | crate: router challenge_required_by: dispute_details.challenge_required_by, connector_updated_at: dispute_details.updated_at, }; db.update_dispute(dispute, update_dispute) .await .to_not_found_response(errors::ApiErrorResponse::WebhookResourceNotFound) } } } #[allow(clippy::too_many_arguments)] #[instrument(skip_all)] async fn external_authentication_incoming_webhook_flow( state: SessionState, req_state: ReqState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, source_verified: bool, event_type: webhooks::IncomingWebhookEvent, request_details: &IncomingWebhookRequestDetails<'_>, connector: &ConnectorEnum, object_ref_id: api::ObjectReferenceId, business_profile: domain::Profile, merchant_connector_account: domain::MerchantConnectorAccount, ) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> { async fn external_authentication_incoming_webhook_flow( state: SessionState, req_state: ReqState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, source_verified: bool, event_type: webhooks::IncomingWebhookEvent, request_details: &IncomingWebhookRequestDetails<'_>, connector: &ConnectorEnum, object_ref_id: api::ObjectReferenceId, business_profile: domain::Profile, merchant_connector_account: domain::MerchantConnectorAccount, ) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> { {<|fim_suffix|> <|fim_middle|> }}
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/webhooks/incoming.rs | crate: router auth_type, None, api_event, req, req.method(), ); state.event_handler().log_event(&api_event); Ok(application_response) } #[allow(clippy::too_many_arguments)] #[instrument(skip_all)] async fn incoming_webhooks_core<W: types::OutgoingWebhookType>( state: SessionState, req_state: ReqState, req: &actix_web::HttpRequest, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, connector_name_or_mca_id: &str, body: actix_web::web::Bytes, is_relay_webhook: bool, ) -> errors::RouterResult<( services::ApplicationResponse<serde_json::Value>, WebhookResponseTracker, serde_json::Value, async fn incoming_webhooks_core<W: types::OutgoingWebhookType>( state: SessionState, req_state: ReqState, req: &actix_web::HttpRequest, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, connector_name_or_mca_id: &str, body: actix_web::web::Bytes, is_relay_webhook: bool, ) -> errors::RouterResult<( services::ApplicationResponse<serde_json::Value>, WebhookResponseTracker, serde_json::Value, )> { <|fim_suffix|> <|fim_middle|> }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/webhooks/webhook_events.rs | crate: router use common_utils::{self, fp_utils}; use crate::{ core::errors::{self, RouterResponse, StorageErrorExt}, routes::SessionState, services::ApplicationResponse, types::{api, domain, storage, transformers::ForeignTryFrom}, utils::{OptionExt, StringExt}, }; async fn get_account_and_key_store( state: SessionState, merchant_id: common_utils::id_type::MerchantId, profile_id: Option<common_utils::id_type::ProfileId>, ) -> errors::RouterResult<(MerchantAccountOrProfile, domain::MerchantKeyStore)> { <|fim_suffix|> <|fim_middle|> }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/webhooks/webhook_events.rs | crate: router use common_utils::{self, fp_utils}; use error_stack::ResultExt; use crate::{ core::errors::{self, RouterResponse, StorageErrorExt}, routes::SessionState, services::ApplicationResponse, types::{api, domain, storage, transformers::ForeignTryFrom}, utils::{OptionExt, StringExt}, }; pub async fn list_delivery_attempts( state: SessionState, merchant_id: common_utils::id_type::MerchantId, initial_attempt_id: String, ) -> RouterResponse<Vec<api::webhook_events::EventRetrieveResponse>> { <|fim_suffix|> <|fim_middle|> }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/webhooks/webhook_events.rs | crate: router use common_utils::{self, fp_utils}; use crate::{ core::errors::{self, RouterResponse, StorageErrorExt}, routes::SessionState, services::ApplicationResponse, types::{api, domain, storage, transformers::ForeignTryFrom}, utils::{OptionExt, StringExt}, }; pub async fn list_initial_delivery_attempts( state: SessionState, merchant_id: common_utils::id_type::MerchantId, api_constraints: api::webhook_events::EventListConstraints, ) -> RouterResponse<api::webhook_events::TotalEventsResponse> { { Some(offset) if offset > 0 => Some(offset),<|fim_suffix|> <|fim_middle|> _ => None, } }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/webhooks/webhook_events.rs | crate: router use common_utils::{self, fp_utils}; use crate::{ core::errors::{self, RouterResponse, StorageErrorExt}, routes::SessionState, services::ApplicationResponse, types::{api, domain, storage, transformers::ForeignTryFrom}, utils::{OptionExt, StringExt}, }; pub async fn retry_delivery_attempt( state: SessionState, merchant_id: common_utils::id_type::MerchantId, event_id: String, ) -> RouterResponse<api::webhook_events::EventRetrieveResponse> { {<|fim_suffix|> <|fim_middle|> }}
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/webhooks/webhook_events.rs | crate: router use common_utils::{self, fp_utils}; use crate::{ core::errors::{self, RouterResponse, StorageErrorExt}, routes::SessionState, services::ApplicationResponse, types::{api, domain, storage, transformers::ForeignTryFrom}, utils::{OptionExt, StringExt}, }; pub async fn list_initial_delivery_attempts( state: SessionState, merchant_id: common_utils::id_type::MerchantId, api_constraints: api::webhook_events::EventListConstraints, ) -> RouterResponse<api::webhook_events::TotalEventsResponse> { <|fim_suffix|> <|fim_middle|> }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/webhooks/utils.rs | crate: router use std::marker::PhantomData; use common_utils::{errors::CustomResult, ext_traits::ValueExt}; use crate::{ core::{ errors::{self}, payments::helpers, }, db::{get_and_deserialize_key, StorageInterface}, services::logger, types::{self, api, domain, PaymentAddress}, SessionState, }; pub async fn construct_webhook_router_data( state: &SessionState, connector_name: &str, merchant_connector_account: domain::MerchantConnectorAccount, merchant_account: &domain::MerchantAccount, connector_wh_secrets: &api_models::webhooks::ConnectorWebhookSecrets, request_details: &api::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<types::VerifyWebhookSourceRouterData, errors::ApiErrorResponse> { <|fim_suffix|> <|fim_middle|> }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/webhooks/utils.rs | crate: router use common_utils::{errors::CustomResult, ext_traits::ValueExt}; use crate::{ core::{ errors::{self}, payments::helpers, }, db::{get_and_deserialize_key, StorageInterface}, services::logger, types::{self, api, domain, PaymentAddress}, SessionState, }; /// Check whether the merchant has configured to disable the webhook `event` for the `connector` /// First check for the key "whconf_{ <|fim_suffix|> <|fim_middle|> }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/webhooks/utils.rs | crate: router use common_utils::{errors::CustomResult, ext_traits::ValueExt}; use crate::{ core::{ errors::{self}, payments::helpers, }, db::{get_and_deserialize_key, StorageInterface}, services::logger, types::{self, api, domain, PaymentAddress}, SessionState, }; /// Check whether the merchant has configured to disable the webhook `event` for the `connector` /// First check for the key "whconf_{ { Ok(set) => set.contains(event),<|fim_suffix|> <|fim_middle|> Err(err) => { logger::warn!(?err, "error while parsing merchant webhook config"); false } } }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/webhooks/utils.rs | crate: router use common_utils::{errors::CustomResult, ext_traits::ValueExt}; use crate::{ core::{ errors::{self}, payments::helpers, }, db::{get_and_deserialize_key, StorageInterface}, services::logger, types::{self, api, domain, PaymentAddress}, SessionState, }; pub(crate) fn generate_event_id() -> String { {<|fim_suffix|> <|fim_middle|> }}
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/webhooks/utils.rs | crate: router use std::marker::PhantomData; use common_utils::{errors::CustomResult, ext_traits::ValueExt}; use error_stack::ResultExt; use crate::{ core::{ errors::{self}, payments::helpers, }, db::{get_and_deserialize_key, StorageInterface}, services::logger, types::{self, api, domain, PaymentAddress}, SessionState, }; pub(crate) fn get_idempotent_event_id( primary_object_id: &str, event_type: types::storage::enums::EventType, delivery_attempt: types::storage::enums::WebhookDeliveryAttempt, ) -> String { <|fim_suffix|> <|fim_middle|> }
ast_fragments
// file: hyperswitch/crates/router/src/core/payment_methods/cards.rs | crate: router use diesel_models::payment_method; use hyperswitch_domain_models::customer::CustomerUpdate; use masking::Secret; use super::tokenize::NetworkTokenizationProcess; use crate::core::payment_methods::{ add_payment_method_status_update_task, tokenize, utils::{get_merchant_pm_filter_graph, make_pm_graph, refresh_pm_filters_cache}, }; use crate::types::domain::types::AsyncLift; use crate::{ configs::{ defaults::{get_billing_required_fields, get_shipping_required_fields}, settings, }, consts as router_consts, core::{ errors::{self, StorageErrorExt}, payment_methods::{network_tokenization, transformers as payment_methods, vault}, payments::{ helpers, routing::{self, SessionFlowRoutingInput}, }, utils as core_utils, }, db, logger, pii::prelude::*, routes::{self, metrics, payment_methods::ParentPaymentMethodToken}, services, types::{ api::{self, routing as routing_types, PaymentMethodCreateExt}, domain::{self, Profile}, storage::{self, enums, PaymentMethodListContext, PaymentTokenData}, transformers::{ForeignFrom, ForeignTryFrom}, }, utils, utils::OptionExt, }; pub async fn execute_payment_method_tokenization( executor: tokenize::CardNetworkTokenizeExecutor<'_, domain::TokenizePaymentMethodRequest>, builder: tokenize::NetworkTokenizationBuilder<'_, tokenize::TokenizeWithPmId>, req: &domain::TokenizePaymentMethodRequest, ) -> errors::RouterResult<api::CardNetworkTokenizeResponse> { // Fetch payment method let payment_method = executor .fetch_payment_method(&req.payment_method_id) .await?; let builder = builder.set_payment_method(&payment_method); // Validate payment method and customer let (locker_id, customer) = executor .validate_request_and_locker_reference_and_customer(&payment_method) .await?; let builder = builder.set_validate_result(&customer); // Fetch card from locker let card_details = get_card_from_locker( executor.state, &customer.id, executor.merchant_account.get_id(), &locker_id, ) .await?; // Perform BIN lookup and validate card network let optional_card_info = executor .fetch_bin_details_and_validate_card_network( card_details.card_number.clone(), None, None, None, None, ) .await?; let builder = builder.set_card_details(&card_details, optional_card_info, req.card_cvc.clone()); // Tokenize card let (optional_card, optional_cvc) = builder.get_optional_card_and_cvc(); let domain_card = optional_card.get_required_value("card")?; let network_token_details = executor .tokenize_card(&customer.id, &domain_card, optional_cvc) .await?; let builder = builder.set_token_details(&network_token_details); // Store token in locker let store_token_resp = executor .store_network_token_in_locker( &network_token_details, &customer.id, card_details.name_on_card.clone(), card_details.nick_name.clone().map(Secret::new), ) .await?; let builder = builder.set_stored_token_response(&store_token_resp); // Update payment method let updated_payment_method = executor .update_payment_method( &store_token_resp, payment_method, &network_token_details, &domain_card, ) .await?; let builder = builder.set_payment_method(&updated_payment_method); Ok(builder.build()) }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/payment_methods/cards.rs | crate: router ); let builder = tokenize::NetworkTokenizationBuilder::<tokenize::TokenizeWithPmId>::default(); execute_payment_method_tokenization(executor, builder, payment_method).await } } } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] pub async fn execute_card_tokenization( executor: tokenize::CardNetworkTokenizeExecutor<'_, domain::TokenizeCardRequest>, builder: tokenize::NetworkTokenizationBuilder<'_, tokenize::TokenizeWithCard>, req: &domain::TokenizeCardRequest, ) -> errors::RouterResult<api::CardNetworkTokenizeResponse> { // Validate request and get optional customer let optional_customer = executor .validate_request_and_fetch_optional_customer() .await?; let builder = builder.set_validate_result(); // Perform BIN lookup and validate card network let optional_card_info = executor pub async fn execute_card_tokenization( executor: tokenize::CardNetworkTokenizeExecutor<'_, domain::TokenizeCardRequest>, builder: tokenize::NetworkTokenizationBuilder<'_, tokenize::TokenizeWithCard>, req: &domain::TokenizeCardRequest, ) -> errors::RouterResult<api::CardNetworkTokenizeResponse> { {// Validate request and get optional customer<|fim_suffix|> <|fim_middle|> Ok(builder.build())}}
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/payment_methods/cards.rs | crate: router .map(|country_code| CountryCodeWithName { code: country_code, name: common_enums::Country::from_alpha2(country_code), }) .collect(), } } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] pub async fn tokenize_card_flow( state: &routes::SessionState, req: domain::CardNetworkTokenizeRequest, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, ) -> errors::RouterResult<api::CardNetworkTokenizeResponse> { match req.data { domain::TokenizeDataRequest::Card(ref card_req) => { let executor = tokenize::CardNetworkTokenizeExecutor::new( state, key_store, merchant_account, card_req, pub async fn tokenize_card_flow( state: &routes::SessionState, req: domain::CardNetworkTokenizeRequest, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, ) -> errors::RouterResult<api::CardNetworkTokenizeResponse> { {<|fim_suffix|> <|fim_middle|> }}
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/payment_methods/cards.rs | crate: router Ok(services::ApplicationResponse::Json( list_countries_currencies_for_connector_payment_method_util( state.conf.pm_filters.clone(), req.connector, req.payment_method_type, ) .await, )) } // This feature will be more efficient as a WASM function rather than as an API. // So extracting this logic to a separate function so that it can be used in WASM as well. pub async fn list_countries_currencies_for_connector_payment_method_util( connector_filters: settings::ConnectorFilters, connector: api_enums::Connector, payment_method_type: api_enums::PaymentMethodType, ) -> ListCountriesCurrenciesResponse { let payment_method_type = settings::PaymentMethodFilterKey::PaymentMethodType(payment_method_type); let (currencies, country_codes) = connector_filters .0 .get(&connector.to_string()) .and_then(|filter| filter.0.get(&payment_method_type)) .map(|filter| (filter.currency.clone(), filter.country.clone())) pub async fn list_countries_currencies_for_connector_payment_method_util( connector_filters: settings::ConnectorFilters, connector: api_enums::Connector, payment_method_type: api_enums::PaymentMethodType, ) -> ListCountriesCurrenciesResponse { <|fim_suffix|> <|fim_middle|> }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/payment_methods/cards.rs | crate: router .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update the default payment method id for the customer")?; }; Ok(services::ApplicationResponse::Json( api::PaymentMethodDeleteResponse { payment_method_id: key.payment_method_id.clone(), deleted: true, }, )) } pub async fn create_encrypted_data<T>( key_manager_state: &KeyManagerState, key_store: &domain::MerchantKeyStore, data: T, ) -> Result<Encryptable<Secret<serde_json::Value>>, error_stack::Report<errors::StorageError>> where T: Debug + serde::Serialize, { let key = key_store.key.get_inner().peek(); let identifier = Identifier::Merchant(key_store.merchant_id.clone()); let encoded_data = Encode::encode_to_value(&data) .change_context(errors::StorageError::SerializationFailed) pub async fn create_encrypted_data<T>( key_manager_state: &KeyManagerState, key_store: &domain::MerchantKeyStore, data: T, ) -> Result<Encryptable<Secret<serde_json::Value>>, error_stack::Report<errors::StorageError>> where T: Debug + serde::Serialize, { {<|fim_suffix|> <|fim_middle|> }}
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/payment_methods/cards.rs | crate: router 1, router_env::metric_attributes!(("flow", "DeleteTokenizeData")), ); Ok(card) } } #[cfg(all( any(feature = "v2", feature = "v1"), not(feature = "payment_methods_v2") ))] #[instrument(skip_all)] pub async fn retrieve_payment_method( state: routes::SessionState, pm: api::PaymentMethodId, key_store: domain::MerchantKeyStore, merchant_account: domain::MerchantAccount, ) -> errors::RouterResponse<api::PaymentMethodResponse> { let db = state.store.as_ref(); let pm = db .find_payment_method( &((&state).into()), &key_store, &pm.payment_method_id, merchant_account.storage_scheme, pub async fn retrieve_payment_method( state: routes::SessionState, pm: api::PaymentMethodId, key_store: domain::MerchantKeyStore, merchant_account: domain::MerchantAccount, ) -> errors::RouterResponse<api::PaymentMethodResponse> { {<|fim_suffix|> <|fim_middle|> }}
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/payment_methods/cards.rs | crate: router #[cfg(all( any(feature = "v2", feature = "v1"), not(feature = "payment_methods_v2") ))] pub struct TempLockerCardSupport; #[cfg(all( any(feature = "v2", feature = "v1"), not(feature = "payment_methods_v2") ))] impl TempLockerCardSupport { #[instrument(skip_all)] async fn create_payment_method_data_in_temp_locker( state: &routes::SessionState, payment_token: &str, card: api::CardDetailFromLocker, pm: &domain::PaymentMethod, merchant_key_store: &domain::MerchantKeyStore, ) -> errors::RouterResult<api::CardDetailFromLocker> { let card_number = card.card_number.clone().get_required_value("card_number")?; let card_exp_month = card .expiry_month .clone() .expose_option() .get_required_value("expiry_month")?; async fn create_payment_method_data_in_temp_locker( state: &routes::SessionState, payment_token: &str, card: api::CardDetailFromLocker, pm: &domain::PaymentMethod, merchant_key_store: &domain::MerchantKeyStore, ) -> errors::RouterResult<api::CardDetailFromLocker> { {<|fim_suffix|> <|fim_middle|> }}
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/payment_methods/cards.rs | crate: router key_store, payment_method.clone(), update_last_used, storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update the last_used_at in db")?; Ok(()) } #[cfg(feature = "payouts")] pub async fn get_bank_from_hs_locker( state: &routes::SessionState, key_store: &domain::MerchantKeyStore, temp_token: Option<&String>, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, token_ref: &str, ) -> errors::RouterResult<api::BankPayout> { let payment_method = get_payment_method_from_hs_locker( state, key_store, customer_id, merchant_id, pub async fn get_bank_from_hs_locker( state: &routes::SessionState, key_store: &domain::MerchantKeyStore, temp_token: Option<&String>, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, token_ref: &str, ) -> errors::RouterResult<api::BankPayout> { <|fim_suffix|> <|fim_middle|> }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/payment_methods/cards.rs | crate: router })), PaymentMethodsData::WalletDetails(_) => Ok(None), }, None => Err(report!(errors::ApiErrorResponse::InternalServerError)) .attach_printable("Unable to fetch payment method data"), } } #[cfg(all( any(feature = "v2", feature = "v1"), not(feature = "payment_methods_v2") ))] pub async fn get_bank_account_connector_details( pm: &domain::PaymentMethod, ) -> errors::RouterResult<Option<BankAccountTokenData>> { let payment_method_data = pm .payment_method_data .clone() .map(|x| x.into_inner().expose()) .map( |v| -> Result<PaymentMethodsData, error_stack::Report<errors::ApiErrorResponse>> { v.parse_value::<PaymentMethodsData>("PaymentMethodsData") .change_context(errors::StorageError::DeserializationFailed) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to deserialize Payment Method Auth config") pub async fn get_bank_account_connector_details( pm: &domain::PaymentMethod, ) -> errors::RouterResult<Option<BankAccountTokenData>> { <|fim_suffix|> <|fim_middle|> }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/payment_methods/cards.rs | crate: router let resp = TempLockerCardSupport::create_payment_method_data_in_temp_locker( state, payment_token, card, pm, merchant_key_store, ) .await?; Ok(resp) } pub async fn get_masked_bank_details( pm: &domain::PaymentMethod, ) -> errors::RouterResult<Option<MaskedBankDetails>> { #[cfg(all( any(feature = "v2", feature = "v1"), not(feature = "payment_methods_v2") ))] let payment_method_data = pm .payment_method_data .clone() .map(|x| x.into_inner().expose()) .map( |v| -> Result<PaymentMethodsData, error_stack::Report<errors::ApiErrorResponse>> { pub async fn get_masked_bank_details( pm: &domain::PaymentMethod, ) -> errors::RouterResult<Option<MaskedBankDetails>> { <|fim_suffix|> <|fim_middle|> }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/payment_methods/cards.rs | crate: router return true; } match connector_mandate_details { Some(connector_mandate_details) => merchant_connector_accounts .is_merchant_connector_account_id_in_connector_mandate_details( profile_id.as_ref(), connector_mandate_details, ), None => false, } } pub async fn decrypt_generic_data<T>( state: &routes::SessionState, data: Option<Encryption>, key_store: &domain::MerchantKeyStore, ) -> errors::RouterResult<Option<T>> where T: serde::de::DeserializeOwned, { let key = key_store.key.get_inner().peek(); let identifier = Identifier::Merchant(key_store.merchant_id.clone()); let decrypted_data = domain::types::crypto_operation::<serde_json::Value, masking::WithType>( &state.into(), type_name!(T), pub async fn decrypt_generic_data<T>( state: &routes::SessionState, data: Option<Encryption>, key_store: &domain::MerchantKeyStore, ) -> errors::RouterResult<Option<T>> where T: serde::de::DeserializeOwned, { <|fim_suffix|> <|fim_middle|> }
ast_fragments
// file: hyperswitch/crates/router/src/core/payment_methods/cards.rs | crate: router pub async fn perform_surcharge_ops( _payment_intent: Option<storage::PaymentIntent>, _state: &routes::SessionState, _merchant_account: &domain::MerchantAccount, _key_store: domain::MerchantKeyStore, _business_profile: Option<Profile>, _response: &mut api::CustomerPaymentMethodsListResponse, ) -> Result<(), error_stack::Report<errors::ApiErrorResponse>> { todo!() } #[cfg(feature = "v1")] pub async fn get_mca_status( state: &routes::SessionState, key_store: &domain::MerchantKeyStore, profile_id: Option<id_type::ProfileId>, merchant_id: &id_type::MerchantId, is_connector_agnostic_mit_enabled: bool, connector_mandate_details: Option<CommonMandateReference>, network_transaction_id: Option<&String>, ) -> errors::RouterResult<bool> { if is_connector_agnostic_mit_enabled && network_transaction_id.is_some() { return Ok(true); } if let Some(connector_mandate_details) = connector_mandate_details { pub async fn get_mca_status( state: &routes::SessionState, key_store: &domain::MerchantKeyStore, profile_id: Option<id_type::ProfileId>, merchant_id: &id_type::MerchantId, is_connector_agnostic_mit_enabled: bool, connector_mandate_details: Option<CommonMandateReference>, network_transaction_id: Option<&String>, ) -> errors::RouterResult<bool> { if is_connector_agnostic_mit_enabled && network_transaction_id.is_some() { return Ok(true); } if let Some(connector_mandate_details) = connector_mandate_details { let mcas = state .store .find_merchant_connector_account_by_merchant_id_and_disabled_list( &state.into(), merchant_id, true, key_store, ) .await .change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: merchant_id.get_string_repr().to_owned(), })?; return Ok( mcas.is_merchant_connector_account_id_in_connector_mandate_details( profile_id.as_ref(), &connector_mandate_details, ), ); } Ok(false) }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/payment_methods/cards.rs | crate: router use error_stack::{report, ResultExt}; use crate::routes::app::SessionStateInfo; use crate::types::domain::types::AsyncLift; use crate::{ configs::{ defaults::{get_billing_required_fields, get_shipping_required_fields}, settings, }, consts as router_consts, core::{ errors::{self, StorageErrorExt}, payment_methods::{network_tokenization, transformers as payment_methods, vault}, payments::{ helpers, routing::{self, SessionFlowRoutingInput}, }, utils as core_utils, }, db, logger, pii::prelude::*, routes::{self, metrics, payment_methods::ParentPaymentMethodToken}, services, types::{ api::{self, routing as routing_types, PaymentMethodCreateExt}, domain::{self, Profile}, storage::{self, enums, PaymentMethodListContext, PaymentTokenData}, transformers::{ForeignFrom, ForeignTryFrom}, }, utils, utils::OptionExt, }; async fn perform_surcharge_ops( payment_intent: Option<storage::PaymentIntent>, state: &routes::SessionState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, business_profile: Option<Profile>, response: &mut api::CustomerPaymentMethodsListResponse, ) -> Result<(), error_stack::Report<errors::ApiErrorResponse>> { <|fim_suffix|> <|fim_middle|> }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/payment_methods/cards.rs | crate: router fn filter_recurring_based( payment_method: &RequestPaymentMethodTypes, recurring_enabled: Option<bool>, ) -> bool { recurring_enabled.map_or(true, |enabled| payment_method.recurring_enabled == enabled) } #[cfg(all( any(feature = "v2", feature = "v1"), not(feature = "payment_methods_v2"), not(feature = "customer_v2") ))] pub async fn do_list_customer_pm_fetch_customer_if_not_passed( state: routes::SessionState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, req: Option<api::PaymentMethodListRequest>, customer_id: Option<&id_type::CustomerId>, ephemeral_api_key: Option<&str>, ) -> errors::RouterResponse<api::CustomerPaymentMethodsListResponse> { let limit = req.clone().and_then(|pml_req| pml_req.limit); let auth_cust = if let Some(key) = ephemeral_api_key { let key = state .store() pub async fn do_list_customer_pm_fetch_customer_if_not_passed( state: routes::SessionState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, req: Option<api::PaymentMethodListRequest>, customer_id: Option<&id_type::CustomerId>, ephemeral_api_key: Option<&str>, ) -> errors::RouterResponse<api::CustomerPaymentMethodsListResponse> { <|fim_suffix|> <|fim_middle|> }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/payment_methods/cards.rs | crate: router use super::surcharge_decision_configs::{ perform_surcharge_decision_management_for_payment_method_list, perform_surcharge_decision_management_for_saved_cards, }; use crate::routes::app::SessionStateInfo; use crate::types::domain::types::AsyncLift; use crate::{ configs::{ defaults::{get_billing_required_fields, get_shipping_required_fields}, settings, }, consts as router_consts, core::{ errors::{self, StorageErrorExt}, payment_methods::{network_tokenization, transformers as payment_methods, vault}, payments::{ helpers, routing::{self, SessionFlowRoutingInput}, }, utils as core_utils, }, db, logger, pii::prelude::*, routes::{self, metrics, payment_methods::ParentPaymentMethodToken}, services, types::{ api::{self, routing as routing_types, PaymentMethodCreateExt}, domain::{self, Profile}, storage::{self, enums, PaymentMethodListContext, PaymentTokenData}, transformers::{ForeignFrom, ForeignTryFrom}, }, utils, utils::OptionExt, }; pub async fn call_surcharge_decision_management_for_saved_card( state: &routes::SessionState, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, business_profile: &Profile, payment_attempt: &storage::PaymentAttempt, payment_intent: storage::PaymentIntent, customer_payment_method_response: &mut api::CustomerPaymentMethodsListResponse, ) -> errors::RouterResult<()> { <|fim_suffix|> <|fim_middle|> }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/payment_methods/cards.rs | crate: router let client_secret_expired = authenticate_pm_client_secret_and_check_expiry(cs, &payment_method)?; if client_secret_expired { return Err::<(), error_stack::Report<errors::ApiErrorResponse>>( (errors::ApiErrorResponse::ClientSecretExpired).into(), ); } Ok(()) } #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] pub async fn call_surcharge_decision_management( state: routes::SessionState, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, business_profile: &Profile, payment_attempt: &storage::PaymentAttempt, payment_intent: storage::PaymentIntent, billing_address: Option<domain::Address>, response_payment_method_types: &mut [ResponsePaymentMethodsEnabled], ) -> errors::RouterResult<api_surcharge_decision_configs::MerchantSurchargeConfigs> { #[cfg(feature = "v1")] let algorithm_ref: routing_types::RoutingAlgorithmRef = merchant_account .routing_algorithm pub async fn call_surcharge_decision_management( state: routes::SessionState, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, business_profile: &Profile, payment_attempt: &storage::PaymentAttempt, payment_intent: storage::PaymentIntent, billing_address: Option<domain::Address>, response_payment_method_types: &mut [ResponsePaymentMethodsEnabled], ) -> errors::RouterResult<api_surcharge_decision_configs::MerchantSurchargeConfigs> { {<|fim_suffix|> <|fim_middle|> }}
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/payment_methods/cards.rs | crate: router use std::{ collections::{HashMap, HashSet}, fmt::Debug, str::FromStr, }; use diesel_models::payment_method; use error_stack::{report, ResultExt}; use crate::routes::app::SessionStateInfo; use crate::types::domain::types::AsyncLift; use crate::{ configs::{ defaults::{get_billing_required_fields, get_shipping_required_fields}, settings, }, consts as router_consts, core::{ errors::{self, StorageErrorExt}, payment_methods::{network_tokenization, transformers as payment_methods, vault}, payments::{ helpers, routing::{self, SessionFlowRoutingInput}, }, utils as core_utils, }, db, logger, pii::prelude::*, routes::{self, metrics, payment_methods::ParentPaymentMethodToken}, services, types::{ api::{self, routing as routing_types, PaymentMethodCreateExt}, domain::{self, Profile}, storage::{self, enums, PaymentMethodListContext, PaymentTokenData}, transformers::{ForeignFrom, ForeignTryFrom}, }, utils, utils::OptionExt, }; async fn validate_payment_method_and_client_secret( state: &routes::SessionState, cs: &String, db: &dyn db::StorageInterface, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, ) -> Result<(), error_stack::Report<errors::ApiErrorResponse>> { {<|fim_suffix|> <|fim_middle|> }}
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/payment_methods/cards.rs | crate: router collect_shipping_details_from_wallets, collect_billing_details_from_wallets, is_tax_calculation_enabled: is_tax_connector_enabled && !skip_external_tax_calculation, }, )) } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "customer_v2"), not(feature = "payment_methods_v2") ))] fn should_collect_shipping_or_billing_details_from_wallet_connector( payment_method: api_enums::PaymentMethod, payment_experience_optional: Option<&api_enums::PaymentExperience>, business_profile: &Profile, mut required_fields_hs: HashMap<String, RequiredFieldInfo>, ) -> HashMap<String, RequiredFieldInfo> { match (payment_method, payment_experience_optional) { (api_enums::PaymentMethod::Wallet, Some(api_enums::PaymentExperience::InvokeSdkClient)) | ( api_enums::PaymentMethod::PayLater, Some(api_enums::PaymentExperience::InvokeSdkClient), ) => { let always_send_billing_details = fn should_collect_shipping_or_billing_details_from_wallet_connector( payment_method: api_enums::PaymentMethod, payment_experience_optional: Option<&api_enums::PaymentExperience>, business_profile: &Profile, mut required_fields_hs: HashMap<String, RequiredFieldInfo>, ) -> HashMap<String, RequiredFieldInfo> { <|fim_suffix|> <|fim_middle|> }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/payment_methods/cards.rs | crate: router let locker_mock_up = db .delete_locker_mock_up(card_id) .await .change_context(errors::VaultError::FetchCardFailed)?; Ok(payment_methods::DeleteCardResponse { card_id: Some(locker_mock_up.card_id), external_id: Some(locker_mock_up.external_id), card_isin: None, status: "Ok".to_string(), }) } //------------------------------------------------------------------------------ pub fn get_banks( state: &routes::SessionState, pm_type: common_enums::enums::PaymentMethodType, connectors: Vec<String>, ) -> Result<Vec<BankCodeResponse>, errors::ApiErrorResponse> { let mut bank_names_hm: HashMap<String, HashSet<common_enums::enums::BankNames>> = HashMap::new(); if matches!( pm_type, api_enums::PaymentMethodType::Giropay | api_enums::PaymentMethodType::Sofort ) { Ok(vec![BankCodeResponse { pub fn get_banks( state: &routes::SessionState, pm_type: common_enums::enums::PaymentMethodType, connectors: Vec<String>, ) -> Result<Vec<BankCodeResponse>, errors::ApiErrorResponse> { <|fim_suffix|> <|fim_middle|> }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/payment_methods/cards.rs | crate: router customer_id: locker_mock_up.customer_id, duplicate: locker_mock_up.duplicate, }; Ok(( payment_methods::GetCardResponse { card: add_card_response, }, locker_mock_up.card_cvc, )) } #[instrument(skip_all)] pub async fn mock_get_payment_method<'a>( state: &routes::SessionState, key_store: &domain::MerchantKeyStore, card_id: &'a str, ) -> errors::CustomResult<payment_methods::GetPaymentMethodResponse, errors::VaultError> { let db = &*state.store; let locker_mock_up = db .find_locker_by_card_id(card_id) .await .change_context(errors::VaultError::FetchPaymentMethodFailed)?; let dec_data = if let Some(e) = locker_mock_up.enc_card_data { decode_and_decrypt_locker_data(state, key_store, e).await } else { pub async fn mock_get_payment_method<'a>( state: &routes::SessionState, key_store: &domain::MerchantKeyStore, card_id: &'a str, ) -> errors::CustomResult<payment_methods::GetPaymentMethodResponse, errors::VaultError> { {<|fim_suffix|> <|fim_middle|> }}
ast_fragments
// file: hyperswitch/crates/router/src/core/payment_methods/cards.rs | crate: router card_reference: response.card_id, duplication_check: None, }; Ok(payment_methods::StoreCardResp { status: "Ok".to_string(), error_code: None, error_message: None, payload: Some(payload), }) } #[instrument(skip_all)] pub async fn mock_get_card<'a>( db: &dyn db::StorageInterface, card_id: &'a str, ) -> errors::CustomResult<(payment_methods::GetCardResponse, Option<String>), errors::VaultError> { let locker_mock_up = db .find_locker_by_card_id(card_id) .await .change_context(errors::VaultError::FetchCardFailed)?; let add_card_response = payment_methods::AddCardResponse { card_id: locker_mock_up .payment_method_id .unwrap_or(locker_mock_up.card_id), external_id: locker_mock_up.external_id, pub async fn mock_get_card<'a>( db: &dyn db::StorageInterface, card_id: &'a str, ) -> errors::CustomResult<(payment_methods::GetCardResponse, Option<String>), errors::VaultError> { let locker_mock_up = db .find_locker_by_card_id(card_id) .await .change_context(errors::VaultError::FetchCardFailed)?; let add_card_response = payment_methods::AddCardResponse { card_id: locker_mock_up .payment_method_id .unwrap_or(locker_mock_up.card_id), external_id: locker_mock_up.external_id, card_fingerprint: locker_mock_up.card_fingerprint.into(), card_global_fingerprint: locker_mock_up.card_global_fingerprint.into(), merchant_id: Some(locker_mock_up.merchant_id), card_number: cards::CardNumber::try_from(locker_mock_up.card_number) .change_context(errors::VaultError::ResponseDeserializationFailed) .attach_printable("Invalid card number format from the mock locker") .map(Some)?, card_exp_year: Some(locker_mock_up.card_exp_year.into()), card_exp_month: Some(locker_mock_up.card_exp_month.into()), name_on_card: locker_mock_up.name_on_card.map(|card| card.into()), nickname: locker_mock_up.nickname, customer_id: locker_mock_up.customer_id, duplicate: locker_mock_up.duplicate, }; Ok(( payment_methods::GetCardResponse { card: add_card_response, }, locker_mock_up.card_cvc, )) }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/payment_methods/cards.rs | crate: router #[cfg(all(feature = "v2", feature = "customer_v2"))] #[instrument(skip_all)] pub async fn delete_card_from_hs_locker_by_global_id<'a>( state: &routes::SessionState, id: &str, merchant_id: &id_type::MerchantId, card_reference: &'a str, ) -> errors::RouterResult<payment_methods::DeleteCardResp> { todo!() } ///Mock api for local testing pub async fn mock_call_to_locker_hs( db: &dyn db::StorageInterface, card_id: &str, payload: &payment_methods::StoreLockerReq, card_cvc: Option<String>, payment_method_id: Option<String>, customer_id: Option<&id_type::CustomerId>, ) -> errors::CustomResult<payment_methods::StoreCardResp, errors::VaultError> { let mut locker_mock_up = storage::LockerMockUpNew { card_id: card_id.to_string(), external_id: uuid::Uuid::new_v4().to_string(), card_fingerprint: uuid::Uuid::new_v4().to_string(), card_global_fingerprint: uuid::Uuid::new_v4().to_string(), ///Mock api for local testing pub async fn mock_call_to_locker_hs( db: &dyn db::StorageInterface, card_id: &str, payload: &payment_methods::StoreLockerReq, card_cvc: Option<String>, payment_method_id: Option<String>, customer_id: Option<&id_type::CustomerId>, ) -> errors::CustomResult<payment_methods::StoreCardResp, errors::VaultError> { {<|fim_suffix|> <|fim_middle|> }}
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/payment_methods/cards.rs | crate: router retrieve_card_resp .card .get_required_value("Card") .change_context(errors::VaultError::FetchCardFailed) } else { let (get_card_resp, _) = mock_get_card(&*state.store, card_reference).await?; payment_methods::mk_get_card_response(get_card_resp) .change_context(errors::VaultError::ResponseDeserializationFailed) } } #[instrument(skip_all)] pub async fn delete_card_from_hs_locker<'a>( state: &routes::SessionState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, card_reference: &'a str, ) -> errors::CustomResult<payment_methods::DeleteCardResp, errors::VaultError> { let locker = &state.conf.locker; let jwekey = &state.conf.jwekey.get_inner(); let request = payment_methods::mk_delete_card_request_hs( jwekey, locker, customer_id, pub async fn delete_card_from_hs_locker<'a>( state: &routes::SessionState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, card_reference: &'a str, ) -> errors::CustomResult<payment_methods::DeleteCardResp, errors::VaultError> { <|fim_suffix|> <|fim_middle|> }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/payment_methods/cards.rs | crate: router .transpose()?; let pm_update = payment_method::PaymentMethodUpdate::ConnectorMandateDetailsUpdate { connector_mandate_details: connector_mandate_details_value, }; db.update_payment_method(&(state.into()), key_store, pm, pm_update, storage_scheme) .await .change_context(errors::VaultError::UpdateInPaymentMethodDataTableFailed)?; Ok(()) } #[instrument(skip_all)] pub async fn get_card_from_hs_locker<'a>( state: &'a routes::SessionState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, card_reference: &'a str, locker_choice: api_enums::LockerChoice, ) -> errors::CustomResult<Card, errors::VaultError> { let locker = &state.conf.locker; let jwekey = &state.conf.jwekey.get_inner(); if !locker.mock_locker { let request = payment_methods::mk_get_card_request_hs( jwekey, pub async fn get_card_from_hs_locker<'a>( state: &'a routes::SessionState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, card_reference: &'a str, locker_choice: api_enums::LockerChoice, ) -> errors::CustomResult<Card, errors::VaultError> { <|fim_suffix|> <|fim_middle|> }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/payment_methods/cards.rs | crate: router use common_enums::{enums::MerchantStorageScheme, ConnectorType}; use diesel_models::payment_method; use hyperswitch_domain_models::mandates::CommonMandateReference; use router_env::{instrument, tracing}; use crate::routes::app::SessionStateInfo; use crate::types::domain::types::AsyncLift; use crate::{ configs::{ defaults::{get_billing_required_fields, get_shipping_required_fields}, settings, }, consts as router_consts, core::{ errors::{self, StorageErrorExt}, payment_methods::{network_tokenization, transformers as payment_methods, vault}, payments::{ helpers, routing::{self, SessionFlowRoutingInput}, }, utils as core_utils, }, db, logger, pii::prelude::*, routes::{self, metrics, payment_methods::ParentPaymentMethodToken}, services, types::{ api::{self, routing as routing_types, PaymentMethodCreateExt}, domain::{self, Profile}, storage::{self, enums, PaymentMethodListContext, PaymentTokenData}, transformers::{ForeignFrom, ForeignTryFrom}, }, utils, utils::OptionExt, }; pub async fn update_payment_method_connector_mandate_details( state: &routes::SessionState, key_store: &domain::MerchantKeyStore, db: &dyn db::StorageInterface, pm: domain::PaymentMethod, connector_mandate_details: Option<CommonMandateReference>, storage_scheme: MerchantStorageScheme, ) -> errors::CustomResult<(), errors::VaultError> { <|fim_suffix|> <|fim_middle|> }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/payment_methods/cards.rs | crate: router let card_id = generate_id(consts::ID_LENGTH, "card"); mock_call_to_locker_hs(db, &card_id, payload, None, None, Some(customer_id)).await? }; let stored_card = stored_card_response .payload .get_required_value("StoreCardRespPayload") .change_context(errors::VaultError::SaveCardFailed)?; Ok(stored_card) } #[instrument(skip_all)] pub async fn call_locker_api<T>( state: &routes::SessionState, request: Request, flow_name: &str, locker_choice: Option<api_enums::LockerChoice>, ) -> errors::CustomResult<T, errors::VaultError> where T: serde::de::DeserializeOwned, { let locker = &state.conf.locker; let jwekey = state.conf.jwekey.get_inner(); let response_type_name = type_name!(T); pub async fn call_locker_api<T>( state: &routes::SessionState, request: Request, flow_name: &str, locker_choice: Option<api_enums::LockerChoice>, ) -> errors::CustomResult<T, errors::VaultError> where T: serde::de::DeserializeOwned, { <|fim_suffix|> <|fim_middle|> }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/payment_methods/cards.rs | crate: router )?; decode_and_decrypt_locker_data(state, key_store, enc_card_data.peek().to_string()).await? } else { mock_get_payment_method(state, key_store, payment_method_reference) .await? .payment_method .payment_method_data }; Ok(payment_method_data) } #[instrument(skip_all)] pub async fn add_card_to_hs_locker( state: &routes::SessionState, payload: &payment_methods::StoreLockerReq, customer_id: &id_type::CustomerId, locker_choice: api_enums::LockerChoice, ) -> errors::CustomResult<payment_methods::StoreCardRespPayload, errors::VaultError> { let locker = &state.conf.locker; let jwekey = state.conf.jwekey.get_inner(); let db = &*state.store; let stored_card_response = if !locker.mock_locker { let request = payment_methods::mk_add_locker_request_hs( jwekey, locker, pub async fn add_card_to_hs_locker( state: &routes::SessionState, payload: &payment_methods::StoreLockerReq, customer_id: &id_type::CustomerId, locker_choice: api_enums::LockerChoice, ) -> errors::CustomResult<payment_methods::StoreCardRespPayload, errors::VaultError> { <|fim_suffix|> <|fim_middle|> }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/payment_methods/cards.rs | crate: router key, ) .await .and_then(|val| val.try_into_optionaloperation()) .change_context(errors::VaultError::FetchPaymentMethodFailed)? .map_or( Err(report!(errors::VaultError::FetchPaymentMethodFailed)), |d| Ok(d.into_inner()), ) } #[instrument(skip_all)] pub async fn get_payment_method_from_hs_locker<'a>( state: &'a routes::SessionState, key_store: &domain::MerchantKeyStore, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, payment_method_reference: &'a str, locker_choice: Option<api_enums::LockerChoice>, ) -> errors::CustomResult<Secret<String>, errors::VaultError> { let locker = &state.conf.locker; let jwekey = state.conf.jwekey.get_inner(); let payment_method_data = if !locker.mock_locker { let request = payment_methods::mk_get_card_request_hs( pub async fn get_payment_method_from_hs_locker<'a>( state: &'a routes::SessionState, key_store: &domain::MerchantKeyStore, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, payment_method_reference: &'a str, locker_choice: Option<api_enums::LockerChoice>, ) -> errors::CustomResult<Secret<String>, errors::VaultError> { {<|fim_suffix|> <|fim_middle|> }}
ast_fragments
// file: hyperswitch/crates/router/src/core/payment_methods/cards.rs | crate: router add_card_to_hs_locker(state, &payload, customer_id, locker_choice).await?; let payment_method_resp = payment_methods::mk_add_card_response_hs( card.clone(), store_card_payload.card_reference, req, merchant_account.get_id(), ); Ok((payment_method_resp, store_card_payload.duplication_check)) } #[instrument(skip_all)] pub async fn decode_and_decrypt_locker_data( state: &routes::SessionState, key_store: &domain::MerchantKeyStore, enc_card_data: String, ) -> errors::CustomResult<Secret<String>, errors::VaultError> { // Fetch key let key = key_store.key.get_inner().peek(); // Decode let decoded_bytes = hex::decode(&enc_card_data) .change_context(errors::VaultError::ResponseDeserializationFailed) .attach_printable("Failed to decode hex string into bytes")?; // Decrypt domain::types::crypto_operation( pub async fn decode_and_decrypt_locker_data( state: &routes::SessionState, key_store: &domain::MerchantKeyStore, enc_card_data: String, ) -> errors::CustomResult<Secret<String>, errors::VaultError> { // Fetch key let key = key_store.key.get_inner().peek(); // Decode let decoded_bytes = hex::decode(&enc_card_data) .change_context(errors::VaultError::ResponseDeserializationFailed) .attach_printable("Failed to decode hex string into bytes")?; // Decrypt domain::types::crypto_operation( &state.into(), type_name!(payment_method::PaymentMethod), domain::types::CryptoOperation::DecryptOptional(Some(Encryption::new( decoded_bytes.into(), ))), Identifier::Merchant(key_store.merchant_id.clone()), key, ) .await .and_then(|val| val.try_into_optionaloperation()) .change_context(errors::VaultError::FetchPaymentMethodFailed)? .map_or( Err(report!(errors::VaultError::FetchPaymentMethodFailed)), |d| Ok(d.into_inner()), ) }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/payment_methods/cards.rs | crate: router } #[cfg(all(feature = "v2", feature = "customer_v2"))] pub async fn delete_card_by_locker_id( state: &routes::SessionState, id: &id_type::GlobalCustomerId, merchant_id: &id_type::MerchantId, ) -> errors::RouterResult<payment_methods::DeleteCardResp> { todo!() } #[instrument(skip_all)] pub async fn add_card_hs( state: &routes::SessionState, req: api::PaymentMethodCreate, card: &api::CardDetail, customer_id: &id_type::CustomerId, merchant_account: &domain::MerchantAccount, locker_choice: api_enums::LockerChoice, card_reference: Option<&str>, ) -> errors::CustomResult< ( api::PaymentMethodResponse, Option<payment_methods::DataDuplicationCheck>, ), pub async fn add_card_hs( state: &routes::SessionState, req: api::PaymentMethodCreate, card: &api::CardDetail, customer_id: &id_type::CustomerId, merchant_account: &domain::MerchantAccount, locker_choice: api_enums::LockerChoice, card_reference: Option<&str>, ) -> errors::CustomResult< ( api::PaymentMethodResponse, Option<payment_methods::DataDuplicationCheck>, ), errors::VaultError, > { <|fim_suffix|> <|fim_middle|> }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/payment_methods/cards.rs | crate: router ); }) }, &metrics::CARD_GET_TIME, router_env::metric_attributes!(("locker", "rust")), ) .await?; logger::debug!("card retrieved from rust locker"); Ok(get_card_from_rs_locker_resp) } pub async fn delete_card_from_locker( state: &routes::SessionState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, card_reference: &str, ) -> errors::RouterResult<payment_methods::DeleteCardResp> { metrics::DELETE_FROM_LOCKER.add(1, &[]); common_utils::metrics::utils::record_operation_time( async move { delete_card_from_hs_locker(state, customer_id, merchant_id, card_reference) .await .inspect_err(|_| { pub async fn delete_card_from_locker( state: &routes::SessionState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, card_reference: &str, ) -> errors::RouterResult<payment_methods::DeleteCardResp> { {<|fim_suffix|> <|fim_middle|> }}
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/payment_methods/cards.rs | crate: router ); }) }, &metrics::CARD_ADD_TIME, router_env::metric_attributes!(("locker", "rust")), )) .await?; logger::debug!("card added to hyperswitch-card-vault"); Ok(add_card_to_hs_resp) } pub async fn get_card_from_locker( state: &routes::SessionState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, card_reference: &str, ) -> errors::RouterResult<Card> { metrics::GET_FROM_LOCKER.add(1, &[]); let get_card_from_rs_locker_resp = common_utils::metrics::utils::record_operation_time( async { get_card_from_hs_locker( state, customer_id, pub async fn get_card_from_locker( state: &routes::SessionState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, card_reference: &str, ) -> errors::RouterResult<Card> { {<|fim_suffix|> <|fim_middle|> }}
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/payment_methods/cards.rs | crate: router ) .await?; let payment_method_resp = payment_methods::mk_add_bank_response_hs( bank.clone(), store_resp.card_reference, req, merchant_account.get_id(), ); Ok((payment_method_resp, store_resp.duplication_check)) } /// The response will be the tuple of PaymentMethodResponse and the duplication check of payment_method pub async fn add_card_to_locker( state: &routes::SessionState, req: api::PaymentMethodCreate, card: &api::CardDetail, customer_id: &id_type::CustomerId, merchant_account: &domain::MerchantAccount, card_reference: Option<&str>, ) -> errors::CustomResult< ( api::PaymentMethodResponse, Option<payment_methods::DataDuplicationCheck>, ), errors::VaultError, /// The response will be the tuple of PaymentMethodResponse and the duplication check of payment_method pub async fn add_card_to_locker( state: &routes::SessionState, req: api::PaymentMethodCreate, card: &api::CardDetail, customer_id: &id_type::CustomerId, merchant_account: &domain::MerchantAccount, card_reference: Option<&str>, ) -> errors::CustomResult< ( api::PaymentMethodResponse, Option<payment_methods::DataDuplicationCheck>, ), errors::VaultError, > { <|fim_suffix|> <|fim_middle|> }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/payment_methods/cards.rs | crate: router #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] pub fn validate_payment_method_update( _card_updation_obj: CardDetailUpdate, _existing_card_data: api::CardDetailFromLocker, ) -> bool { todo!() } // Wrapper function to switch lockers #[cfg(feature = "payouts")] pub async fn add_bank_to_locker( state: &routes::SessionState, req: api::PaymentMethodCreate, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, bank: &api::BankPayout, customer_id: &id_type::CustomerId, ) -> errors::CustomResult< ( api::PaymentMethodResponse, Option<payment_methods::DataDuplicationCheck>, ), errors::VaultError, pub async fn add_bank_to_locker( state: &routes::SessionState, req: api::PaymentMethodCreate, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, bank: &api::BankPayout, customer_id: &id_type::CustomerId, ) -> errors::CustomResult< ( api::PaymentMethodResponse, Option<payment_methods::DataDuplicationCheck>, ), errors::VaultError, > { {<|fim_suffix|> <|fim_middle|> }}
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/payment_methods/cards.rs | crate: router Ok(services::ApplicationResponse::Json(response)) } else { Err(report!(errors::ApiErrorResponse::NotSupported { message: "Payment method update for the given payment method is not supported".into() })) } } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] pub fn validate_payment_method_update( card_updation_obj: CardDetailUpdate, existing_card_data: api::CardDetailFromLocker, ) -> bool { // Return true If any one of the below condition returns true, // If a field is not passed in the update request, return false. // If the field is present, it depends on the existing field data: // - If existing field data is not present, or if it is present and doesn't match // the update request data, then return true. // - Or else return false card_updation_obj .card_exp_month .map(|exp_month| exp_month.expose()) pub fn validate_payment_method_update( card_updation_obj: CardDetailUpdate, existing_card_data: api::CardDetailFromLocker, ) -> bool { {<|fim_suffix|> <|fim_middle|> }}
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/payment_methods/cards.rs | crate: router .and_then(|val| (!val.0.is_empty()).then_some(false)) }), ); Ok(services::ApplicationResponse::Json(resp)) } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] #[allow(clippy::too_many_arguments)] pub async fn insert_payment_method( state: &routes::SessionState, resp: &api::PaymentMethodResponse, req: &api::PaymentMethodCreate, key_store: &domain::MerchantKeyStore, merchant_id: &id_type::MerchantId, customer_id: &id_type::CustomerId, pm_metadata: Option<serde_json::Value>, customer_acceptance: Option<serde_json::Value>, locker_id: Option<String>, connector_mandate_details: Option<serde_json::Value>, network_transaction_id: Option<String>, storage_scheme: MerchantStorageScheme, pub async fn insert_payment_method( state: &routes::SessionState, resp: &api::PaymentMethodResponse, req: &api::PaymentMethodCreate, key_store: &domain::MerchantKeyStore, merchant_id: &id_type::MerchantId, customer_id: &id_type::CustomerId, pm_metadata: Option<serde_json::Value>, customer_acceptance: Option<serde_json::Value>, locker_id: Option<String>, connector_mandate_details: Option<serde_json::Value>, network_transaction_id: Option<String>, storage_scheme: MerchantStorageScheme, payment_method_billing_address: crypto::OptionalEncryptableValue, network_token_requestor_reference_id: Option<String>, network_token_locker_id: Option<String>, network_token_payment_method_data: crypto::OptionalEncryptableValue, ) -> errors::RouterResult<domain::PaymentMethod> { {<|fim_suffix|> <|fim_middle|> }}
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/payment_methods/cards.rs | crate: router .attach_printable( "Failed to add payment method status update task in process tracker", )?; } Ok(services::api::ApplicationResponse::Json( api::PaymentMethodResponse::foreign_from((None, res)), )) } } #[instrument(skip_all)] pub fn authenticate_pm_client_secret_and_check_expiry( req_client_secret: &String, payment_method: &domain::PaymentMethod, ) -> errors::CustomResult<bool, errors::ApiErrorResponse> { let stored_client_secret = payment_method .client_secret .clone() .get_required_value("client_secret") .change_context(errors::ApiErrorResponse::MissingRequiredField { field_name: "client_secret", }) .attach_printable("client secret not found in db")?; pub fn authenticate_pm_client_secret_and_check_expiry( req_client_secret: &String, payment_method: &domain::PaymentMethod, ) -> errors::CustomResult<bool, errors::ApiErrorResponse> { {<|fim_suffix|> <|fim_middle|> }}
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/payment_methods/cards.rs | crate: router cards::validate::validate_card_number_chars(&card_isin) .and_then(|_| cards::validate::validate_card_number_chars(&last4_digits))?; Ok((card_isin, last4_digits)) } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] #[instrument(skip_all)] pub async fn get_client_secret_or_add_payment_method( state: &routes::SessionState, req: api::PaymentMethodCreate, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, ) -> errors::RouterResponse<api::PaymentMethodResponse> { let merchant_id = merchant_account.get_id(); let customer_id = req.customer_id.clone().get_required_value("customer_id")?; #[cfg(not(feature = "payouts"))] let condition = req.card.is_some(); #[cfg(feature = "payouts")] let condition = req.card.is_some() || req.bank_transfer.is_some() || req.wallet.is_some(); pub async fn get_client_secret_or_add_payment_method( state: &routes::SessionState, req: api::PaymentMethodCreate, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, ) -> errors::RouterResponse<api::PaymentMethodResponse> { {<|fim_suffix|> <|fim_middle|> }}
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/payment_methods/cards.rs | crate: router #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] impl ForeignTryFrom<( &api_models::payment_methods::MigrateCardDetail, Option<diesel_models::CardInfo>, )> for api_models::payment_methods::CardDetailFromLocker { type Error = error_stack::Report<errors::ApiErrorResponse>; fn foreign_try_from( (card_details, card_info): ( &api_models::payment_methods::MigrateCardDetail, Option<diesel_models::CardInfo>, ), ) -> Result<Self, Self::Error> { let (card_isin, last4_digits) = get_card_bin_and_last4_digits_for_masked_card(card_details.card_number.peek()) .change_context(errors::ApiErrorResponse::InvalidRequestData { message: "Invalid card number".to_string(), })?; if let Some(card_bin_info) = card_info { Ok(Self { fn foreign_try_from( (card_details, card_info): ( &api_models::payment_methods::MigrateCardDetail, Option<diesel_models::CardInfo>, ), ) -> Result<Self, Self::Error> { <|fim_suffix|> <|fim_middle|> }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/payment_methods/cards.rs | crate: router _req: api::PaymentMethodMigrate, _merchant_id: &id_type::MerchantId, _merchant_account: &domain::MerchantAccount, _key_store: &domain::MerchantKeyStore, ) -> errors::RouterResponse<api::PaymentMethodMigrateResponse> { todo!() } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] pub async fn populate_bin_details_for_masked_card( card_details: &api_models::payment_methods::MigrateCardDetail, db: &dyn db::StorageInterface, ) -> errors::CustomResult<api::CardDetailFromLocker, errors::ApiErrorResponse> { migration::validate_card_expiry(&card_details.card_exp_month, &card_details.card_exp_year)?; let card_number = card_details.card_number.clone(); let (card_isin, _last4_digits) = get_card_bin_and_last4_digits_for_masked_card( card_number.peek(), ) .change_context(errors::ApiErrorResponse::InvalidRequestData { message: "Invalid card number".to_string(), })?; pub async fn populate_bin_details_for_masked_card( card_details: &api_models::payment_methods::MigrateCardDetail, db: &dyn db::StorageInterface, ) -> errors::CustomResult<api::CardDetailFromLocker, errors::ApiErrorResponse> { {<|fim_suffix|> <|fim_middle|> }}
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/payment_methods/cards.rs | crate: router _merchant_id: &id_type::MerchantId, ) -> ( api::PaymentMethodResponse, Option<payment_methods::DataDuplicationCheck>, ) { todo!() } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] #[instrument(skip_all)] pub async fn get_or_insert_payment_method( state: &routes::SessionState, req: api::PaymentMethodCreate, resp: &mut api::PaymentMethodResponse, merchant_account: &domain::MerchantAccount, customer_id: &id_type::CustomerId, key_store: &domain::MerchantKeyStore, ) -> errors::RouterResult<domain::PaymentMethod> { let mut payment_method_id = resp.payment_method_id.clone(); let mut locker_id = None; let db = &*state.store; let key_manager_state = &(state.into()); let payment_method = { pub async fn get_or_insert_payment_method( state: &routes::SessionState, req: api::PaymentMethodCreate, resp: &mut api::PaymentMethodResponse, merchant_account: &domain::MerchantAccount, customer_id: &id_type::CustomerId, key_store: &domain::MerchantKeyStore, ) -> errors::RouterResult<domain::PaymentMethod> { <|fim_suffix|> <|fim_middle|> }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/payment_methods/cards.rs | crate: router storage_scheme, ) .await .map_err(|error| logger::error!(?error, "Failed to set the payment method as default")); } Ok(response) } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] pub fn store_default_payment_method( req: &api::PaymentMethodCreate, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, ) -> ( api::PaymentMethodResponse, Option<payment_methods::DataDuplicationCheck>, ) { let pm_id = generate_id(consts::ID_LENGTH, "pm"); let payment_method_response = api::PaymentMethodResponse { merchant_id: merchant_id.to_owned(), customer_id: Some(customer_id.to_owned()), payment_method_id: pm_id, pub fn store_default_payment_method( req: &api::PaymentMethodCreate, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, ) -> ( api::PaymentMethodResponse, Option<payment_methods::DataDuplicationCheck>, ) { {<|fim_suffix|> <|fim_middle|> }}
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/payment_methods/cards.rs | crate: router &customer.id, ) .await?; let builder = builder.set_payment_method_response(&payment_method); Ok(builder.build()) } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] pub async fn execute_payment_method_tokenization( executor: tokenize::CardNetworkTokenizeExecutor<'_, domain::TokenizePaymentMethodRequest>, builder: tokenize::NetworkTokenizationBuilder<'_, tokenize::TokenizeWithPmId>, req: &domain::TokenizePaymentMethodRequest, ) -> errors::RouterResult<api::CardNetworkTokenizeResponse> { // Fetch payment method let payment_method = executor .fetch_payment_method(&req.payment_method_id) .await?; let builder = builder.set_payment_method(&payment_method); // Validate payment method and customer let (locker_id, customer) = executor pub async fn execute_payment_method_tokenization( executor: tokenize::CardNetworkTokenizeExecutor<'_, domain::TokenizePaymentMethodRequest>, builder: tokenize::NetworkTokenizationBuilder<'_, tokenize::TokenizeWithPmId>, req: &domain::TokenizePaymentMethodRequest, ) -> errors::RouterResult<api::CardNetworkTokenizeResponse> { {// Fetch payment method<|fim_suffix|> <|fim_middle|> Ok(builder.build())}}
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/payment_methods/cards.rs | crate: router ); let builder = tokenize::NetworkTokenizationBuilder::<tokenize::TokenizeWithPmId>::default(); execute_payment_method_tokenization(executor, builder, payment_method).await } } } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] pub async fn execute_card_tokenization( executor: tokenize::CardNetworkTokenizeExecutor<'_, domain::TokenizeCardRequest>, builder: tokenize::NetworkTokenizationBuilder<'_, tokenize::TokenizeWithCard>, req: &domain::TokenizeCardRequest, ) -> errors::RouterResult<api::CardNetworkTokenizeResponse> { // Validate request and get optional customer let optional_customer = executor .validate_request_and_fetch_optional_customer() .await?; let builder = builder.set_validate_result(); // Perform BIN lookup and validate card network let optional_card_info = executor pub async fn execute_card_tokenization( executor: tokenize::CardNetworkTokenizeExecutor<'_, domain::TokenizeCardRequest>, builder: tokenize::NetworkTokenizationBuilder<'_, tokenize::TokenizeWithCard>, req: &domain::TokenizeCardRequest, ) -> errors::RouterResult<api::CardNetworkTokenizeResponse> { { Some(customer) => customer,<|fim_suffix|> <|fim_middle|> None => executor.create_customer().await?, } }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/payment_methods/cards.rs | crate: router domain::types::CryptoOperation::Encrypt(secret_data), identifier.clone(), key, ) .await .and_then(|val| val.try_into_operation()) .change_context(errors::StorageError::EncryptionError) .attach_printable("Unable to encrypt data")?; Ok(encrypted_data) } pub async fn list_countries_currencies_for_connector_payment_method( state: routes::SessionState, req: ListCountriesCurrenciesRequest, _profile_id: Option<id_type::ProfileId>, ) -> errors::RouterResponse<ListCountriesCurrenciesResponse> { Ok(services::ApplicationResponse::Json( list_countries_currencies_for_connector_payment_method_util( state.conf.pm_filters.clone(), req.connector, req.payment_method_type, ) .await, )) pub async fn list_countries_currencies_for_connector_payment_method( state: routes::SessionState, req: ListCountriesCurrenciesRequest, _profile_id: Option<id_type::ProfileId>, ) -> errors::RouterResponse<ListCountriesCurrenciesResponse> { <|fim_suffix|> <|fim_middle|> }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/payment_methods/cards.rs | crate: router .attach_printable("Failed to update the default payment method id for the customer")?; let resp = api_models::payment_methods::CustomerDefaultPaymentMethodResponse { default_payment_method_id: updated_customer_details.default_payment_method_id, customer_id, payment_method_type: payment_method.get_payment_method_subtype(), payment_method: pm, }; Ok(services::ApplicationResponse::Json(resp)) } pub async fn update_last_used_at( payment_method: &domain::PaymentMethod, state: &routes::SessionState, storage_scheme: MerchantStorageScheme, key_store: &domain::MerchantKeyStore, ) -> errors::RouterResult<()> { let update_last_used = storage::PaymentMethodUpdate::LastUsedUpdate { last_used_at: common_utils::date_time::now(), }; state .store .update_payment_method( pub async fn update_last_used_at( payment_method: &domain::PaymentMethod, state: &routes::SessionState, storage_scheme: MerchantStorageScheme, key_store: &domain::MerchantKeyStore, ) -> errors::RouterResult<()> { <|fim_suffix|> <|fim_middle|> }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/payment_methods/cards.rs | crate: router use std::{ collections::{HashMap, HashSet}, fmt::Debug, str::FromStr, }; use crate::routes::app::SessionStateInfo; use crate::types::domain::types::AsyncLift; use crate::{ configs::{ defaults::{get_billing_required_fields, get_shipping_required_fields}, settings, }, consts as router_consts, core::{ errors::{self, StorageErrorExt}, payment_methods::{network_tokenization, transformers as payment_methods, vault}, payments::{ helpers, routing::{self, SessionFlowRoutingInput}, }, utils as core_utils, }, db, logger, pii::prelude::*, routes::{self, metrics, payment_methods::ParentPaymentMethodToken}, services, types::{ api::{self, routing as routing_types, PaymentMethodCreateExt}, domain::{self, Profile}, storage::{self, enums, PaymentMethodListContext, PaymentTokenData}, transformers::{ForeignFrom, ForeignTryFrom}, }, utils, utils::OptionExt, }; pub async fn get_lookup_key_from_locker( state: &routes::SessionState, payment_token: &str, pm: &domain::PaymentMethod, merchant_key_store: &domain::MerchantKeyStore, ) -> errors::RouterResult<api::CardDetailFromLocker> { {<|fim_suffix|> <|fim_middle|> }}
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/payment_methods/cards.rs | crate: router } else { logger::debug!( "Getting card details from locker as it is not found in payment methods table" ); get_card_details_from_locker(state, pm).await? }) } #[cfg(all( any(feature = "v2", feature = "v1"), not(feature = "payment_methods_v2") ))] pub async fn get_card_details_from_locker( state: &routes::SessionState, pm: &domain::PaymentMethod, ) -> errors::RouterResult<api::CardDetailFromLocker> { let card = get_card_from_locker( state, &pm.customer_id, &pm.merchant_id, pm.locker_id.as_ref().unwrap_or(pm.get_id()), ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error getting card from card vault")?; pub async fn get_card_details_from_locker( state: &routes::SessionState, pm: &domain::PaymentMethod, ) -> errors::RouterResult<api::CardDetailFromLocker> { <|fim_suffix|> <|fim_middle|> }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/payment_methods/cards.rs | crate: router } else { logger::debug!( "Getting card details from locker as it is not found in payment methods table" ); Some(get_card_details_from_locker(state, pm).await?) }) } #[cfg(all( any(feature = "v2", feature = "v1"), not(feature = "payment_methods_v2") ))] pub async fn get_card_details_without_locker_fallback( pm: &domain::PaymentMethod, state: &routes::SessionState, ) -> errors::RouterResult<api::CardDetailFromLocker> { let card_decrypted = pm .payment_method_data .clone() .map(|x| x.into_inner().expose()) .and_then(|v| serde_json::from_value::<PaymentMethodsData>(v).ok()) .and_then(|pmd| match pmd { PaymentMethodsData::Card(crd) => Some(api::CardDetailFromLocker::from(crd)), _ => None, }); pub async fn get_card_details_without_locker_fallback( pm: &domain::PaymentMethod, state: &routes::SessionState, ) -> errors::RouterResult<api::CardDetailFromLocker> { {<|fim_suffix|> <|fim_middle|> }}
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/payment_methods/cards.rs | crate: router decrypted_data .map(|decrypted_data| decrypted_data.into_inner().expose()) .map(|decrypted_value| decrypted_value.parse_value("generic_data")) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("unable to parse generic data value") } #[cfg(all( any(feature = "v2", feature = "v1"), not(feature = "payment_methods_v2") ))] pub async fn get_card_details_with_locker_fallback( pm: &domain::PaymentMethod, state: &routes::SessionState, ) -> errors::RouterResult<Option<api::CardDetailFromLocker>> { let card_decrypted = pm .payment_method_data .clone() .map(|x| x.into_inner().expose()) .and_then(|v| serde_json::from_value::<PaymentMethodsData>(v).ok()) .and_then(|pmd| match pmd { PaymentMethodsData::Card(crd) => Some(api::CardDetailFromLocker::from(crd)), _ => None, }); pub async fn get_card_details_with_locker_fallback( pm: &domain::PaymentMethod, state: &routes::SessionState, ) -> errors::RouterResult<Option<api::CardDetailFromLocker>> { <|fim_suffix|> <|fim_middle|> }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/payment_methods/cards.rs | crate: router return Ok( mcas.is_merchant_connector_account_id_in_connector_mandate_details( profile_id.as_ref(), &connector_mandate_details, ), ); } Ok(false) } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[allow(clippy::too_many_arguments)] pub async fn get_mca_status( state: &routes::SessionState, key_store: &domain::MerchantKeyStore, profile_id: Option<id_type::ProfileId>, merchant_id: &id_type::MerchantId, is_connector_agnostic_mit_enabled: bool, connector_mandate_details: Option<&CommonMandateReference>, network_transaction_id: Option<&String>, merchant_connector_accounts: &domain::MerchantConnectorAccounts, ) -> bool { if is_connector_agnostic_mit_enabled && network_transaction_id.is_some() { return true; } pub async fn get_mca_status( state: &routes::SessionState, key_store: &domain::MerchantKeyStore, profile_id: Option<id_type::ProfileId>, merchant_id: &id_type::MerchantId, is_connector_agnostic_mit_enabled: bool, connector_mandate_details: Option<&CommonMandateReference>, network_transaction_id: Option<&String>, merchant_connector_accounts: &domain::MerchantConnectorAccounts, ) -> bool { { Some(connector_mandate_details) => merchant_connector_accounts .is_merchant_connector_account_id_in_connector_mandate_details( profile_id.as_ref(), connector_mandate_details, ),<|fim_suffix|> <|fim_middle|> None => false, } }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/payment_methods/cards.rs | crate: router use error_stack::{report, ResultExt}; use crate::routes::app::SessionStateInfo; use crate::types::domain::types::AsyncLift; use crate::{ configs::{ defaults::{get_billing_required_fields, get_shipping_required_fields}, settings, }, consts as router_consts, core::{ errors::{self, StorageErrorExt}, payment_methods::{network_tokenization, transformers as payment_methods, vault}, payments::{ helpers, routing::{self, SessionFlowRoutingInput}, }, utils as core_utils, }, db, logger, pii::prelude::*, routes::{self, metrics, payment_methods::ParentPaymentMethodToken}, services, types::{ api::{self, routing as routing_types, PaymentMethodCreateExt}, domain::{self, Profile}, storage::{self, enums, PaymentMethodListContext, PaymentTokenData}, transformers::{ForeignFrom, ForeignTryFrom}, }, utils, utils::OptionExt, }; pub async fn perform_surcharge_ops( _payment_intent: Option<storage::PaymentIntent>, _state: &routes::SessionState, _merchant_account: &domain::MerchantAccount, _key_store: domain::MerchantKeyStore, _business_profile: Option<Profile>, _response: &mut api::CustomerPaymentMethodsListResponse, ) -> Result<(), error_stack::Report<errors::ApiErrorResponse>> { {<|fim_suffix|> <|fim_middle|> }}
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/payment_methods/cards.rs | crate: router use api_models::{ enums as api_enums, payment_methods::{ BankAccountTokenData, Card, CardDetailUpdate, CardDetailsPaymentMethod, CardNetworkTypes, CountryCodeWithName, ListCountriesCurrenciesRequest, ListCountriesCurrenciesResponse, MaskedBankDetails, PaymentExperienceTypes, PaymentMethodsData, RequestPaymentMethodTypes, RequiredFieldInfo, ResponsePaymentMethodIntermediate, ResponsePaymentMethodTypes, ResponsePaymentMethodsEnabled, }, payments::BankCodeResponse, pm_auth::PaymentMethodAuthConfig, surcharge_decision_configs as api_surcharge_decision_configs, }; use diesel_models::payment_method; fn filter_recurring_based( payment_method: &RequestPaymentMethodTypes, recurring_enabled: Option<bool>, ) -> bool { {<|fim_suffix|> <|fim_middle|> }}
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/payment_methods/cards.rs | crate: router use api_models::{ enums as api_enums, payment_methods::{ BankAccountTokenData, Card, CardDetailUpdate, CardDetailsPaymentMethod, CardNetworkTypes, CountryCodeWithName, ListCountriesCurrenciesRequest, ListCountriesCurrenciesResponse, MaskedBankDetails, PaymentExperienceTypes, PaymentMethodsData, RequestPaymentMethodTypes, RequiredFieldInfo, ResponsePaymentMethodIntermediate, ResponsePaymentMethodTypes, ResponsePaymentMethodsEnabled, }, payments::BankCodeResponse, pm_auth::PaymentMethodAuthConfig, surcharge_decision_configs as api_surcharge_decision_configs, }; fn filter_pm_based_on_allowed_types( allowed_types: Option<&Vec<api_enums::PaymentMethodType>>, payment_method_type: api_enums::PaymentMethodType, ) -> bool { <|fim_suffix|> <|fim_middle|> }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/payment_methods/cards.rs | crate: router use api_models::{ enums as api_enums, payment_methods::{ BankAccountTokenData, Card, CardDetailUpdate, CardDetailsPaymentMethod, CardNetworkTypes, CountryCodeWithName, ListCountriesCurrenciesRequest, ListCountriesCurrenciesResponse, MaskedBankDetails, PaymentExperienceTypes, PaymentMethodsData, RequestPaymentMethodTypes, RequiredFieldInfo, ResponsePaymentMethodIntermediate, ResponsePaymentMethodTypes, ResponsePaymentMethodsEnabled, }, payments::BankCodeResponse, pm_auth::PaymentMethodAuthConfig, surcharge_decision_configs as api_surcharge_decision_configs, }; fn filter_pm_card_network_based( pm_card_networks: Option<&Vec<api_enums::CardNetwork>>, request_card_networks: Option<&Vec<api_enums::CardNetwork>>, pm_type: api_enums::PaymentMethodType, ) -> bool { <|fim_suffix|> <|fim_middle|> }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/payment_methods/cards.rs | crate: router use api_models::{ enums as api_enums, payment_methods::{ BankAccountTokenData, Card, CardDetailUpdate, CardDetailsPaymentMethod, CardNetworkTypes, CountryCodeWithName, ListCountriesCurrenciesRequest, ListCountriesCurrenciesResponse, MaskedBankDetails, PaymentExperienceTypes, PaymentMethodsData, RequestPaymentMethodTypes, RequiredFieldInfo, ResponsePaymentMethodIntermediate, ResponsePaymentMethodTypes, ResponsePaymentMethodsEnabled, }, payments::BankCodeResponse, pm_auth::PaymentMethodAuthConfig, surcharge_decision_configs as api_surcharge_decision_configs, }; use diesel_models::payment_method; fn filter_installment_based( payment_method: &RequestPaymentMethodTypes, installment_payment_enabled: Option<bool>, ) -> bool { {<|fim_suffix|> <|fim_middle|> }}
ast_fragments
// file: hyperswitch/crates/router/src/core/payment_methods/cards.rs | crate: router use api_models::{ enums as api_enums, payment_methods::{ BankAccountTokenData, Card, CardDetailUpdate, CardDetailsPaymentMethod, CardNetworkTypes, CountryCodeWithName, ListCountriesCurrenciesRequest, ListCountriesCurrenciesResponse, MaskedBankDetails, PaymentExperienceTypes, PaymentMethodsData, RequestPaymentMethodTypes, RequiredFieldInfo, ResponsePaymentMethodIntermediate, ResponsePaymentMethodTypes, ResponsePaymentMethodsEnabled, }, payments::BankCodeResponse, pm_auth::PaymentMethodAuthConfig, surcharge_decision_configs as api_surcharge_decision_configs, }; use common_utils::{ consts, crypto::{self, Encryptable}, encryption::Encryption, ext_traits::{AsyncExt, BytesExt, ConfigExt, Encode, StringExt, ValueExt}, generate_id, id_type, request::Request, type_name, types::{ keymanager::{Identifier, KeyManagerState}, MinorUnit, }, }; use diesel_models::payment_method; fn filter_amount_based( payment_method: &RequestPaymentMethodTypes, amount: Option<MinorUnit>, ) -> bool { let min_check = amount .and_then(|amt| payment_method.minimum_amount.map(|min_amt| amt >= min_amt)) .unwrap_or(true); let max_check = amount .and_then(|amt| payment_method.maximum_amount.map(|max_amt| amt <= max_amt)) .unwrap_or(true); (min_check && max_check) || amount == Some(MinorUnit::zero()) }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/payment_methods/cards.rs | crate: router } } } } } Ok(()) } // v2 type for PaymentMethodListRequest will not have the installment_payment_enabled field, // need to re-evaluate filter logic #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[allow(clippy::too_many_arguments)] pub async fn filter_payment_methods( _graph: &cgraph::ConstraintGraph<dir::DirValue>, _mca_id: String, _payment_methods: &[Secret<serde_json::Value>], _req: &mut api::PaymentMethodListRequest, _resp: &mut [ResponsePaymentMethodIntermediate], _payment_intent: Option<&storage::PaymentIntent>, _payment_attempt: Option<&storage::PaymentAttempt>, _address: Option<&domain::Address>, _connector: String, _saved_payment_methods: &settings::EligiblePaymentMethods, ) -> errors::CustomResult<(), errors::ApiErrorResponse> { todo!() pub async fn filter_payment_methods( _graph: &cgraph::ConstraintGraph<dir::DirValue>, _mca_id: String, _payment_methods: &[Secret<serde_json::Value>], _req: &mut api::PaymentMethodListRequest, _resp: &mut [ResponsePaymentMethodIntermediate], _payment_intent: Option<&storage::PaymentIntent>, _payment_attempt: Option<&storage::PaymentAttempt>, _address: Option<&domain::Address>, _connector: String, _saved_payment_methods: &settings::EligiblePaymentMethods, ) -> errors::CustomResult<(), errors::ApiErrorResponse> { <|fim_suffix|> <|fim_middle|> }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/payment_methods/cards.rs | crate: router use std::{ collections::{HashMap, HashSet}, fmt::Debug, str::FromStr, }; use serde_json::json; fn get_val(str: String, val: &serde_json::Value) -> Option<String> { <|fim_suffix|> <|fim_middle|> }
ast_fragments
// file: hyperswitch/crates/router/src/core/payment_methods/cards.rs | crate: router ) -> errors::CustomResult<payment_methods::DeleteCardResp, errors::VaultError> { db.delete_locker_mock_up(card_id) .await .change_context(errors::VaultError::FetchCardFailed)?; Ok(payment_methods::DeleteCardResp { status: "Ok".to_string(), error_code: None, error_message: None, }) } #[instrument(skip_all)] pub async fn mock_delete_card<'a>( db: &dyn db::StorageInterface, card_id: &'a str, ) -> errors::CustomResult<payment_methods::DeleteCardResponse, errors::VaultError> { let locker_mock_up = db .delete_locker_mock_up(card_id) .await .change_context(errors::VaultError::FetchCardFailed)?; Ok(payment_methods::DeleteCardResponse { card_id: Some(locker_mock_up.card_id), external_id: Some(locker_mock_up.external_id), card_isin: None, status: "Ok".to_string(), pub async fn mock_delete_card<'a>( db: &dyn db::StorageInterface, card_id: &'a str, ) -> errors::CustomResult<payment_methods::DeleteCardResponse, errors::VaultError> { let locker_mock_up = db .delete_locker_mock_up(card_id) .await .change_context(errors::VaultError::FetchCardFailed)?; Ok(payment_methods::DeleteCardResponse { card_id: Some(locker_mock_up.card_id), external_id: Some(locker_mock_up.external_id), card_isin: None, status: "Ok".to_string(), }) }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/payment_methods/cards.rs | crate: router merchant_id: Some(locker_mock_up.merchant_id.to_owned()), nickname: locker_mock_up.nickname, customer_id: locker_mock_up.customer_id, duplicate: locker_mock_up.duplicate, payment_method_data: dec_data, }; Ok(payment_methods::GetPaymentMethodResponse { payment_method: payment_method_response, }) } #[instrument(skip_all)] pub async fn mock_delete_card_hs<'a>( db: &dyn db::StorageInterface, card_id: &'a str, ) -> errors::CustomResult<payment_methods::DeleteCardResp, errors::VaultError> { db.delete_locker_mock_up(card_id) .await .change_context(errors::VaultError::FetchCardFailed)?; Ok(payment_methods::DeleteCardResp { status: "Ok".to_string(), error_code: None, error_message: None, }) } pub async fn mock_delete_card_hs<'a>( db: &dyn db::StorageInterface, card_id: &'a str, ) -> errors::CustomResult<payment_methods::DeleteCardResp, errors::VaultError> { <|fim_suffix|> <|fim_middle|> }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/core/payment_methods/cards.rs | crate: router .await .change_context(errors::VaultError::DeleteCardFailed) } else { Ok(mock_delete_card_hs(&*state.store, card_reference) .await .change_context(errors::VaultError::DeleteCardFailed)?) } } // Need to fix this function while completing v2 #[cfg(all(feature = "v2", feature = "customer_v2"))] #[instrument(skip_all)] pub async fn delete_card_from_hs_locker_by_global_id<'a>( state: &routes::SessionState, id: &str, merchant_id: &id_type::MerchantId, card_reference: &'a str, ) -> errors::RouterResult<payment_methods::DeleteCardResp> { todo!() } ///Mock api for local testing pub async fn mock_call_to_locker_hs( db: &dyn db::StorageInterface, card_id: &str, pub async fn delete_card_from_hs_locker_by_global_id<'a>( state: &routes::SessionState, id: &str, merchant_id: &id_type::MerchantId, card_reference: &'a str, ) -> errors::RouterResult<payment_methods::DeleteCardResp> { {<|fim_suffix|> <|fim_middle|> }}
ast_fragments