text
stringlengths
70
351k
source
stringclasses
4 values
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/wellsfargopayout.rs<|crate|> router anchor=build_request kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/connector/wellsfargopayout.rs" role="context" start="280" end="293"> fn build_request( &self, req: &types::PaymentsSyncRouterData, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { Ok(Some( services::RequestBuilder::new() .method(services::Method::Get) .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?) .build(), )) } <file_sep path="hyperswitch/crates/router/src/connector/wellsfargopayout.rs" role="context" start="279" end="279"> use common_utils::types::{AmountConvertor, StringMinorUnit, StringMinorUnitForConnector}; use self::transformers as wellsfargopayout; use crate::{ configs::settings, core::errors::{self, CustomResult}, events::connector_api_logs::ConnectorEvent, headers, services::{ self, request::{self, Mask}, ConnectorIntegration, ConnectorSpecifications, ConnectorValidation, }, types::{ self, api::{self, ConnectorCommon, ConnectorCommonExt}, ErrorResponse, RequestContent, Response, }, utils::BytesExt, }; <file_sep path="hyperswitch/crates/router/src/connector/wellsfargopayout.rs" role="context" start="314" end="320"> fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } <file_sep path="hyperswitch/crates/router/src/connector/wellsfargopayout.rs" role="context" start="295" end="312"> fn handle_response( &self, data: &types::PaymentsSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { let response: wellsfargopayout::WellsfargopayoutPaymentsResponse = res .response .parse_struct("wellsfargopayout PaymentsSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } <file_sep path="hyperswitch/crates/router/src/connector/wellsfargopayout.rs" role="context" start="272" end="278"> fn get_url( &self, _req: &types::PaymentsSyncRouterData, _connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) } <file_sep path="hyperswitch/crates/router/src/connector/wellsfargopayout.rs" role="context" start="268" end="270"> fn get_content_type(&self) -> &'static str { self.common_get_content_type() } <file_sep path="hyperswitch/crates/router/src/connector/wellsfargopayout.rs" role="context" start="498" end="504"> fn get_headers( &self, req: &types::RefundSyncRouterData, connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } <file_sep path="hyperswitch/crates/router/src/connector/wellsfargopayout.rs" role="context" start="33" end="37"> pub fn new() -> &'static Self { &Self { amount_converter: &StringMinorUnitForConnector, } } <file_sep path="hyperswitch/crates/router/src/core/relay.rs" role="context" start="97" end="97"> type Request = relay_api_models::RelayRefundRequestData; <file_sep path="hyperswitch/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/event.test.js" role="context" start="61" end="78"> "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.", ); } // Response body should have value "succeeded" for "status" if (jsonData?.status) { pm.test( "[POST]::/payments - Content check if value for 'status' matches 'succeeded'", function () { pm.expect(jsonData.status).to.eql("succeeded"); }, ); }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/stripe.rs<|crate|> router anchor=build_request kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="688" end="701"> fn build_request( &self, req: &types::PaymentsSyncRouterData, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { Ok(Some( services::RequestBuilder::new() .method(services::Method::Get) .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?) .build(), )) } <file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="687" end="687"> use common_utils::{ request::RequestContent, types::{AmountConvertor, MinorUnit, MinorUnitForConnector}, }; use self::transformers as stripe; use super::utils::{self as connector_utils, PaymentMethodDataType, RefundsRequestData}; use crate::{ configs::settings, consts, core::{ errors::{self, CustomResult}, payments, }, events::connector_api_logs::ConnectorEvent, headers, services::{ self, request::{self, Mask}, ConnectorSpecifications, ConnectorValidation, }, types::{ self, api::{self, ConnectorCommon, ConnectorCommonExt}, domain, }, utils::{crypto, ByteSliceExt, BytesExt, OptionExt}, }; type Verify = dyn services::ConnectorIntegration< api::SetupMandate, types::SetupMandateRequestData, types::PaymentsResponseData, >; <file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="760" end="798"> fn get_error_response( &self, res: types::Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { let response: stripe::ErrorResponse = res .response .parse_struct("ErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_error_response_body(&response)); router_env::logger::info!(connector_response=?response); Ok(types::ErrorResponse { status_code: res.status_code, code: response .error .code .clone() .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()), message: response .error .code .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), reason: response.error.message.map(|message| { response .error .decline_code .map(|decline_code| { format!("message - {}, decline_code - {}", message, decline_code) }) .unwrap_or(message) }), attempt_status: None, connector_transaction_id: response.error.payment_intent.map(|pi| pi.id), network_advice_code: None, network_decline_code: None, network_error_message: None, }) } <file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="703" end="758"> fn handle_response( &self, data: &types::PaymentsSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> where types::PaymentsResponseData: Clone, { let id = data.request.connector_transaction_id.clone(); match id.get_connector_transaction_id() { Ok(x) if x.starts_with("set") => { let response: stripe::SetupIntentResponse = res .response .parse_struct("SetupIntentSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } Ok(_) => { let response: stripe::PaymentIntentSyncResponse = res .response .parse_struct("PaymentIntentSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; let response_integrity_object = connector_utils::get_sync_integrity_object( self.amount_converter, response.amount, response.currency.clone(), )?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); let new_router_data = types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }); new_router_data.map(|mut router_data| { router_data.request.integrity_object = Some(response_integrity_object); router_data }) } Err(err) => { Err(err).change_context(errors::ConnectorError::MissingConnectorTransactionID) } } } <file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="663" end="686"> fn get_url( &self, req: &types::PaymentsSyncRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { let id = req.request.connector_transaction_id.clone(); match id.get_connector_transaction_id() { Ok(x) if x.starts_with("set") => Ok(format!( "{}{}/{}?expand[0]=latest_attempt", // expand latest attempt to extract payment checks and three_d_secure data self.base_url(connectors), "v1/setup_intents", x, )), Ok(x) => Ok(format!( "{}{}/{}{}", self.base_url(connectors), "v1/payment_intents", x, "?expand[0]=latest_charge" //updated payment_id(if present) reside inside latest_charge field )), x => x.change_context(errors::ConnectorError::MissingConnectorTransactionID), } } <file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="659" end="661"> fn get_content_type(&self) -> &'static str { self.common_get_content_type() } <file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="48" end="52"> pub const fn new() -> &'static Self { &Self { amount_converter: &MinorUnitForConnector, } } <file_sep path="hyperswitch/crates/router/src/connector/stripe.rs" role="context" start="2663" end="2673"> fn get_url( &self, req: &types::PayoutsRouterData<api::PoRecipientAccount>, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { let connector_customer_id = req.get_connector_customer_id()?; Ok(format!( "{}v1/accounts/{}/external_accounts", connectors.stripe.base_url, connector_customer_id )) } <file_sep path="hyperswitch/crates/router/src/core/relay.rs" role="context" start="97" end="97"> type Request = relay_api_models::RelayRefundRequestData;
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/db/merchant_connector_account.rs<|crate|> router anchor=update_call kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/db/merchant_connector_account.rs" role="context" start="618" end="632"> async fn update_call( connection: &diesel_models::PgPooledConn, (merchant_connector_account, mca_update): ( domain::MerchantConnectorAccount, storage::MerchantConnectorAccountUpdateInternal, ), ) -> Result<(), error_stack::Report<storage_impl::errors::StorageError>> { Conversion::convert(merchant_connector_account) .await .change_context(errors::StorageError::EncryptionError)? .update(connection, mca_update) .await .map_err(|error| report!(errors::StorageError::from(error)))?; Ok(()) } <file_sep path="hyperswitch/crates/router/src/db/merchant_connector_account.rs" role="context" start="617" end="617"> use error_stack::{report, ResultExt}; use storage_impl::redis::cache; use storage_impl::redis::kv_store::RedisConnInterface; use crate::{ connection, core::errors::{self, CustomResult}, types::{ self, domain::{ self, behaviour::{Conversion, ReverseConversion}, }, storage, }, }; <file_sep path="hyperswitch/crates/router/src/db/merchant_connector_account.rs" role="context" start="720" end="796"> async fn update_merchant_connector_account( &self, state: &KeyManagerState, this: domain::MerchantConnectorAccount, merchant_connector_account: storage::MerchantConnectorAccountUpdateInternal, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> { let _connector_name = this.connector_name.clone(); let _profile_id = this.profile_id.clone(); let _merchant_id = this.merchant_id.clone(); let _merchant_connector_id = this.merchant_connector_id.clone(); let update_call = || async { let conn = connection::pg_accounts_connection_write(self).await?; Conversion::convert(this) .await .change_context(errors::StorageError::EncryptionError)? .update(&conn, merchant_connector_account) .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|item| async { item.convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) }) .await }; #[cfg(feature = "accounts_cache")] { // Redact all caches as any of might be used because of backwards compatibility cache::publish_and_redact_multiple( self, [ cache::CacheKind::Accounts( format!("{}_{}", _profile_id.get_string_repr(), _connector_name).into(), ), cache::CacheKind::Accounts( format!( "{}_{}", _merchant_id.get_string_repr(), _merchant_connector_id.get_string_repr() ) .into(), ), cache::CacheKind::CGraph( format!( "cgraph_{}_{}", _merchant_id.get_string_repr(), _profile_id.get_string_repr() ) .into(), ), cache::CacheKind::PmFiltersCGraph( format!( "pm_filters_cgraph_{}_{}", _merchant_id.get_string_repr(), _profile_id.get_string_repr(), ) .into(), ), ], update_call, ) .await } #[cfg(not(feature = "accounts_cache"))] { update_call().await } } <file_sep path="hyperswitch/crates/router/src/db/merchant_connector_account.rs" role="context" start="609" end="716"> async fn update_multiple_merchant_connector_accounts( &self, merchant_connector_accounts: Vec<( domain::MerchantConnectorAccount, storage::MerchantConnectorAccountUpdateInternal, )>, ) -> CustomResult<(), errors::StorageError> { let conn = connection::pg_accounts_connection_write(self).await?; async fn update_call( connection: &diesel_models::PgPooledConn, (merchant_connector_account, mca_update): ( domain::MerchantConnectorAccount, storage::MerchantConnectorAccountUpdateInternal, ), ) -> Result<(), error_stack::Report<storage_impl::errors::StorageError>> { Conversion::convert(merchant_connector_account) .await .change_context(errors::StorageError::EncryptionError)? .update(connection, mca_update) .await .map_err(|error| report!(errors::StorageError::from(error)))?; Ok(()) } conn.transaction_async(|connection_pool| async move { for (merchant_connector_account, update_merchant_connector_account) in merchant_connector_accounts { #[cfg(feature = "v1")] let _connector_name = merchant_connector_account.connector_name.clone(); #[cfg(feature = "v2")] let _connector_name = merchant_connector_account.connector_name.to_string(); let _profile_id = merchant_connector_account.profile_id.clone(); let _merchant_id = merchant_connector_account.merchant_id.clone(); let _merchant_connector_id = merchant_connector_account.get_id().clone(); let update = update_call( &connection_pool, ( merchant_connector_account, update_merchant_connector_account, ), ); #[cfg(feature = "accounts_cache")] // Redact all caches as any of might be used because of backwards compatibility Box::pin(cache::publish_and_redact_multiple( self, [ cache::CacheKind::Accounts( format!("{}_{}", _profile_id.get_string_repr(), _connector_name).into(), ), cache::CacheKind::Accounts( format!( "{}_{}", _merchant_id.get_string_repr(), _merchant_connector_id.get_string_repr() ) .into(), ), cache::CacheKind::CGraph( format!( "cgraph_{}_{}", _merchant_id.get_string_repr(), _profile_id.get_string_repr() ) .into(), ), ], || update, )) .await .map_err(|error| { // Returning `DatabaseConnectionError` after logging the actual error because // -> it is not possible to get the underlying from `error_stack::Report<C>` // -> it is not possible to write a `From` impl to convert the `diesel::result::Error` to `error_stack::Report<StorageError>` // because of Rust's orphan rules router_env::logger::error!( ?error, "DB transaction for updating multiple merchant connector account failed" ); errors::StorageError::DatabaseConnectionError })?; #[cfg(not(feature = "accounts_cache"))] { update.await.map_err(|error| { // Returning `DatabaseConnectionError` after logging the actual error because // -> it is not possible to get the underlying from `error_stack::Report<C>` // -> it is not possible to write a `From` impl to convert the `diesel::result::Error` to `error_stack::Report<StorageError>` // because of Rust's orphan rules router_env::logger::error!( ?error, "DB transaction for updating multiple merchant connector account failed" ); errors::StorageError::DatabaseConnectionError })?; } } Ok::<_, errors::StorageError>(()) }) .await?; Ok(()) } <file_sep path="hyperswitch/crates/router/src/db/merchant_connector_account.rs" role="context" start="580" end="606"> async fn list_connector_account_by_profile_id( &self, state: &KeyManagerState, profile_id: &common_utils::id_type::ProfileId, key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::MerchantConnectorAccount>, errors::StorageError> { let conn = connection::pg_accounts_connection_read(self).await?; storage::MerchantConnectorAccount::list_by_profile_id(&conn, profile_id) .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|items| async { let mut output = Vec::with_capacity(items.len()); for item in items.into_iter() { output.push( item.convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError)?, ) } Ok(output) }) .await } <file_sep path="hyperswitch/crates/router/src/db/merchant_connector_account.rs" role="context" start="541" end="576"> async fn find_merchant_connector_account_by_merchant_id_and_disabled_list( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, get_disabled: bool, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccounts, errors::StorageError> { let conn = connection::pg_accounts_connection_read(self).await?; let merchant_connector_account_vec = storage::MerchantConnectorAccount::find_by_merchant_id( &conn, merchant_id, get_disabled, ) .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|items| async { let mut output = Vec::with_capacity(items.len()); for item in items.into_iter() { output.push( item.convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError)?, ) } Ok(output) }) .await?; Ok(domain::MerchantConnectorAccounts::new( merchant_connector_account_vec, )) } <file_sep path="hyperswitch/v2_compatible_migrations/2024-08-28-081721_add_v2_columns/up.sql" role="context" start="51" end="67"> ADD COLUMN external_reference_id VARCHAR(128), ADD COLUMN tax_on_surcharge BIGINT, ADD COLUMN payment_method_billing_address BYTEA, ADD COLUMN redirection_data JSONB, ADD COLUMN connector_payment_data TEXT, ADD COLUMN connector_token_details JSONB; -- Change the type of the column from JSON to JSONB ALTER TABLE merchant_connector_account ADD COLUMN IF NOT EXISTS feature_metadata JSONB; ALTER TABLE payment_methods ADD COLUMN IF NOT EXISTS locker_fingerprint_id VARCHAR(64), ADD COLUMN IF NOT EXISTS payment_method_type_v2 VARCHAR(64), ADD COLUMN IF NOT EXISTS payment_method_subtype VARCHAR(64); ALTER TABLE refund
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/wise.rs<|crate|> router anchor=build_request kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/connector/wise.rs" role="context" start="286" end="299"> fn build_request( &self, req: &types::PayoutsRouterData<api::PoCancel>, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { let request = services::RequestBuilder::new() .method(services::Method::Put) .url(&types::PayoutCancelType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PayoutCancelType::get_headers(self, req, connectors)?) .build(); Ok(Some(request)) } <file_sep path="hyperswitch/crates/router/src/connector/wise.rs" role="context" start="285" end="285"> use common_utils::request::RequestContent; use common_utils::types::{AmountConvertor, MinorUnit, MinorUnitForConnector}; use self::transformers as wise; use crate::{ configs::settings, core::errors::{self, CustomResult}, events::connector_api_logs::ConnectorEvent, headers, services::{ self, request::{self, Mask}, ConnectorSpecifications, ConnectorValidation, }, types::{ self, api::{self, ConnectorCommon, ConnectorCommonExt}, }, utils::BytesExt, }; <file_sep path="hyperswitch/crates/router/src/connector/wise.rs" role="context" start="323" end="354"> fn get_error_response( &self, res: types::Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { let response: wise::ErrorResponse = res .response .parse_struct("ErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_error_response_body(&response)); router_env::logger::info!(connector_response=?response); let def_res = response.status.unwrap_or_default().to_string(); let errors = response.errors.unwrap_or_default(); let (code, message) = if let Some(e) = errors.first() { (e.code.clone(), e.message.clone()) } else { (def_res, response.message.unwrap_or_default()) }; Ok(types::ErrorResponse { status_code: res.status_code, code, message, reason: None, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, }) } <file_sep path="hyperswitch/crates/router/src/connector/wise.rs" role="context" start="302" end="321"> fn handle_response( &self, data: &types::PayoutsRouterData<api::PoCancel>, event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PayoutsRouterData<api::PoCancel>, errors::ConnectorError> { let response: wise::WisePayoutResponse = res .response .parse_struct("WisePayoutResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } <file_sep path="hyperswitch/crates/router/src/connector/wise.rs" role="context" start="278" end="284"> fn get_headers( &self, req: &types::PayoutsRouterData<api::PoCancel>, _connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, _connectors) } <file_sep path="hyperswitch/crates/router/src/connector/wise.rs" role="context" start="262" end="276"> fn get_url( &self, req: &types::PayoutsRouterData<api::PoCancel>, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { let transfer_id = req.request.connector_payout_id.clone().ok_or( errors::ConnectorError::MissingRequiredField { field_name: "transfer_id", }, )?; Ok(format!( "{}v1/transfers/{}/cancel", connectors.wise.base_url, transfer_id )) } <file_sep path="hyperswitch/crates/router/src/connector/wise.rs" role="context" start="37" end="41"> pub fn new() -> &'static Self { &Self { amount_converter: &MinorUnitForConnector, } } <file_sep path="hyperswitch/crates/router/src/connector/wise.rs" role="context" start="638" end="656"> fn get_url( &self, req: &types::PayoutsRouterData<api::PoFulfill>, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { let auth = wise::WiseAuthType::try_from(&req.connector_auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; let transfer_id = req.request.connector_payout_id.to_owned().ok_or( errors::ConnectorError::MissingRequiredField { field_name: "transfer_id", }, )?; Ok(format!( "{}v3/profiles/{}/transfers/{}/payments", connectors.wise.base_url, auth.profile_id.peek(), transfer_id )) } <file_sep path="hyperswitch/crates/router/src/core/relay.rs" role="context" start="97" end="97"> type Request = relay_api_models::RelayRefundRequestData;
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/square.rs<|crate|> router<|connector|> square anchor=should_fail_for_refund_amount_higher_than_payment_amount kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="571" end="591"> async fn should_fail_for_refund_amount_higher_than_payment_amount() { let response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 150, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(create_token().await), ) .await .unwrap(); assert_eq!( response .response .unwrap_err() .reason .unwrap_or("".to_string()), "The requested refund amount exceeds the amount available to refund.", ); } <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="570" end="570"> use router::types::{self, storage::enums, PaymentsResponseData}; <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="550" end="567"> async fn should_fail_capture_for_invalid_payment() { let capture_response = CONNECTOR .capture_payment( "123456789".to_string(), None, get_default_payment_info(create_token().await), ) .await .unwrap(); assert_eq!( capture_response .response .unwrap_err() .reason .unwrap_or("".to_string()), String::from("Could not find payment with id: 123456789") ); } <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="522" end="546"> async fn should_fail_void_payment_for_auto_capture() { let authorize_response = CONNECTOR .make_payment( payment_method_details(), get_default_payment_info(create_token().await), ) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let void_response = CONNECTOR .void_payment( txn_id.clone().unwrap(), None, get_default_payment_info(None), ) .await .unwrap(); let connector_transaction_id = txn_id.unwrap(); assert_eq!( void_response.response.unwrap_err().reason.unwrap_or("".to_string()), format!("Payment {connector_transaction_id} is in inflight state COMPLETED, which is invalid for the requested operation") ); } <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="54" end="56"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="39" end="52"> fn get_default_payment_info(payment_method_token: Option<String>) -> Option<utils::PaymentInfo> { Some(utils::PaymentInfo { address: None, auth_type: None, access_token: None, connector_meta_data: None, connector_customer: None, payment_method_token, #[cfg(feature = "payouts")] payout_method_data: None, #[cfg(feature = "payouts")] currency: None, }) } <file_sep path="hyperswitch/crates/router/tests/connectors/utils.rs" role="context" start="923" end="923"> pub struct PaymentRefundType(pub types::RefundsData);
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/square.rs<|crate|> router<|connector|> square anchor=should_sync_refund kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="402" end="424"> async fn should_sync_refund() { let refund_response = CONNECTOR .make_payment_and_refund( payment_method_details(), None, get_default_payment_info(create_token().await), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(None), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="401" end="401"> use router::types::{self, storage::enums, PaymentsResponseData}; <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="460" end="487"> async fn should_fail_payment_for_invalid_exp_month() { let token_response = CONNECTOR .create_connector_pm_token( Some(types::PaymentMethodTokenizationData { payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card { card_number: cards::CardNumber::from_str("4111111111111111").unwrap(), card_exp_month: Secret::new("20".to_string()), card_exp_year: Secret::new("2027".to_string()), card_cvc: Secret::new("123".to_string()), ..utils::CCardType::default().0 }), browser_info: None, amount: None, currency: enums::Currency::USD, }), get_default_payment_info(None), ) .await .expect("Authorize payment response"); assert_eq!( token_response .response .unwrap_err() .reason .unwrap_or("".to_string()), "Invalid card expiration date.".to_string(), ); } <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="429" end="456"> async fn should_fail_payment_for_incorrect_cvc() { let token_response = CONNECTOR .create_connector_pm_token( Some(types::PaymentMethodTokenizationData { payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card { card_number: cards::CardNumber::from_str("4111111111111111").unwrap(), card_exp_month: Secret::new("11".to_string()), card_exp_year: Secret::new("2027".to_string()), card_cvc: Secret::new("".to_string()), ..utils::CCardType::default().0 }), browser_info: None, amount: None, currency: enums::Currency::USD, }), get_default_payment_info(None), ) .await .expect("Authorize payment response"); assert_eq!( token_response .response .unwrap_err() .reason .unwrap_or("".to_string()), "Missing required parameter.".to_string(), ); } <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="359" end="398"> async fn should_refund_succeeded_payment_multiple_times() { //make a successful payment let response = CONNECTOR .make_payment( payment_method_details(), get_default_payment_info(create_token().await), ) .await .unwrap(); let refund_data = Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }); //try refund for previous payment let transaction_id = get_connector_transaction_id(response.response).unwrap(); for _x in 0..2 { tokio::time::sleep(Duration::from_secs(CONNECTOR.get_request_interval())).await; // to avoid 404 error let refund_response = CONNECTOR .refund_payment( transaction_id.clone(), refund_data.clone(), get_default_payment_info(None), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(None), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } } <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="330" end="355"> async fn should_partially_refund_succeeded_payment() { let refund_response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(create_token().await), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(None), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="39" end="52"> fn get_default_payment_info(payment_method_token: Option<String>) -> Option<utils::PaymentInfo> { Some(utils::PaymentInfo { address: None, auth_type: None, access_token: None, connector_meta_data: None, connector_customer: None, payment_method_token, #[cfg(feature = "payouts")] payout_method_data: None, #[cfg(feature = "payouts")] currency: None, }) } <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="54" end="56"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } <file_sep path="hyperswitch/crates/router/src/connector/dummyconnector/transformers.rs" role="context" start="304" end="309"> pub enum RefundStatus { Succeeded, Failed, #[default] Processing, } <file_sep path="hyperswitch/crates/api_models/src/refunds.rs" role="context" start="378" end="384"> pub enum RefundStatus { Succeeded, Failed, #[default] Pending, Review, }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/services/authentication/blacklist.rs<|crate|> router anchor=check_role_in_blacklist kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/services/authentication/blacklist.rs" role="context" start="85" end="98"> pub async fn check_role_in_blacklist<A: SessionStateInfo>( state: &A, role_id: &str, token_expiry: u64, ) -> RouterResult<bool> { let token = format!("{}{}", ROLE_BLACKLIST_PREFIX, role_id); let token_issued_at = expiry_to_i64(token_expiry - JWT_TOKEN_TIME_IN_SECS)?; let redis_conn = get_redis_connection(state)?; redis_conn .get_key::<Option<i64>>(&token.as_str().into()) .await .change_context(ApiErrorResponse::InternalServerError) .map(|timestamp| timestamp > Some(token_issued_at)) } <file_sep path="hyperswitch/crates/router/src/services/authentication/blacklist.rs" role="context" start="84" end="84"> use crate::{ consts::{JWT_TOKEN_TIME_IN_SECS, ROLE_BLACKLIST_PREFIX, USER_BLACKLIST_PREFIX}, core::errors::{ApiErrorResponse, RouterResult}, routes::app::SessionStateInfo, }; <file_sep path="hyperswitch/crates/router/src/services/authentication/blacklist.rs" role="context" start="113" end="125"> pub async fn check_email_token_in_blacklist(state: &SessionState, token: &str) -> UserResult<()> { let redis_conn = get_redis_connection(state).change_context(UserErrors::InternalServerError)?; let blacklist_key = format!("{}{token}", EMAIL_TOKEN_BLACKLIST_PREFIX); let key_exists = redis_conn .exists::<()>(&blacklist_key.as_str().into()) .await .change_context(UserErrors::InternalServerError)?; if key_exists { return Err(UserErrors::LinkInvalid.into()); } Ok(()) } <file_sep path="hyperswitch/crates/router/src/services/authentication/blacklist.rs" role="context" start="101" end="110"> pub async fn insert_email_token_in_blacklist(state: &SessionState, token: &str) -> UserResult<()> { let redis_conn = get_redis_connection(state).change_context(UserErrors::InternalServerError)?; let blacklist_key = format!("{}{token}", EMAIL_TOKEN_BLACKLIST_PREFIX); let expiry = expiry_to_i64(EMAIL_TOKEN_TIME_IN_SECS).change_context(UserErrors::InternalServerError)?; redis_conn .set_key_with_expiry(&blacklist_key.as_str().into(), true, expiry) .await .change_context(UserErrors::InternalServerError) } <file_sep path="hyperswitch/crates/router/src/services/authentication/blacklist.rs" role="context" start="70" end="83"> pub async fn check_user_in_blacklist<A: SessionStateInfo>( state: &A, user_id: &str, token_expiry: u64, ) -> RouterResult<bool> { let token = format!("{}{}", USER_BLACKLIST_PREFIX, user_id); let token_issued_at = expiry_to_i64(token_expiry - JWT_TOKEN_TIME_IN_SECS)?; let redis_conn = get_redis_connection(state)?; redis_conn .get_key::<Option<i64>>(&token.as_str().into()) .await .change_context(ApiErrorResponse::InternalServerError) .map(|timestamp| timestamp > Some(token_issued_at)) } <file_sep path="hyperswitch/crates/router/src/services/authentication/blacklist.rs" role="context" start="61" end="68"> async fn invalidate_role_cache(state: &SessionState, role_id: &str) -> RouterResult<()> { let redis_conn = get_redis_connection(state)?; redis_conn .delete_key(&authz::get_cache_key_from_role_id(role_id).as_str().into()) .await .map(|_| ()) .change_context(ApiErrorResponse::InternalServerError) } <file_sep path="hyperswitch/crates/router/src/services/authentication/blacklist.rs" role="context" start="148" end="156"> async fn check_in_blacklist<A>(&self, state: &A) -> RouterResult<bool> where A: SessionStateInfo + Sync, { Ok( check_user_in_blacklist(state, &self.user_id, self.exp).await? || check_role_in_blacklist(state, &self.role_id, self.exp).await?, ) } <file_sep path="hyperswitch/crates/router/src/services/authentication/blacklist.rs" role="context" start="127" end="133"> fn get_redis_connection<A: SessionStateInfo>(state: &A) -> RouterResult<Arc<RedisConnectionPool>> { state .store() .get_redis_conn() .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Failed to get redis connection") } <file_sep path="hyperswitch/crates/router/src/services/authentication/blacklist.rs" role="context" start="135" end="137"> fn expiry_to_i64(expiry: u64) -> RouterResult<i64> { i64::try_from(expiry).change_context(ApiErrorResponse::InternalServerError) } <file_sep path="hyperswitch/crates/router/src/core/errors.rs" role="context" start="31" end="31"> pub type RouterResult<T> = CustomResult<T, ApiErrorResponse>; <file_sep path="hyperswitch/crates/api_models/src/errors/types.rs" role="context" start="86" end="100"> pub enum ApiErrorResponse { Unauthorized(ApiError), ForbiddenCommonResource(ApiError), ForbiddenPrivateResource(ApiError), Conflict(ApiError), Gone(ApiError), Unprocessable(ApiError), InternalServerError(ApiError), NotImplemented(ApiError), ConnectorError(ApiError, #[serde(skip_serializing)] StatusCode), NotFound(ApiError), MethodNotAllowed(ApiError), BadRequest(ApiError), DomainError(ApiError), }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/stax.rs<|crate|> router<|connector|> stax anchor=should_sync_refund kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="433" end="455"> async fn should_sync_refund() { let refund_response = CONNECTOR .make_payment_and_refund( payment_method_details(), None, get_default_payment_info(None, create_customer_and_get_token().await), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(None, None), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="432" end="432"> use router::types::{self, domain, storage::enums, PaymentsResponseData}; <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="498" end="532"> async fn should_fail_payment_for_invalid_exp_month() { let customer_response = CONNECTOR .create_connector_customer(customer_details(), get_default_payment_info(None, None)) .await .expect("Authorize payment response"); let connector_customer_id = match customer_response.response.unwrap() { PaymentsResponseData::ConnectorCustomerResponse { connector_customer_id, } => Some(connector_customer_id), _ => None, }; let token_response = CONNECTOR .create_connector_pm_token( Some(types::PaymentMethodTokenizationData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("4111111111111111").unwrap(), card_exp_month: Secret::new("20".to_string()), card_exp_year: Secret::new("2027".to_string()), card_cvc: Secret::new("123".to_string()), ..utils::CCardType::default().0 }), browser_info: None, amount: None, currency: enums::Currency::USD, }), get_default_payment_info(connector_customer_id, None), ) .await .expect("Authorize payment response"); assert_eq!( token_response.response.unwrap_err().reason, Some(r#"{"validation":["Tokenization Validation Errors: Month is invalid"]}"#.to_string()), ); } <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="460" end="494"> async fn should_fail_payment_for_incorrect_cvc() { let customer_response = CONNECTOR .create_connector_customer(customer_details(), get_default_payment_info(None, None)) .await .expect("Authorize payment response"); let connector_customer_id = match customer_response.response.unwrap() { PaymentsResponseData::ConnectorCustomerResponse { connector_customer_id, } => Some(connector_customer_id), _ => None, }; let token_response = CONNECTOR .create_connector_pm_token( Some(types::PaymentMethodTokenizationData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("4111111111111111").unwrap(), card_exp_month: Secret::new("11".to_string()), card_exp_year: Secret::new("2027".to_string()), card_cvc: Secret::new("123456".to_string()), ..utils::CCardType::default().0 }), browser_info: None, amount: None, currency: enums::Currency::USD, }), get_default_payment_info(connector_customer_id, None), ) .await .expect("Authorize payment response"); assert_eq!( token_response.response.unwrap_err().reason, Some(r#"{"card_cvv":["The card cvv may not be greater than 99999."]}"#.to_string()), ); } <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="398" end="429"> async fn should_refund_succeeded_payment_multiple_times() { let payment_method_token = create_customer_and_get_token().await; let response = CONNECTOR .make_payment( payment_method_details(), get_default_payment_info(None, payment_method_token.clone()), ) .await .unwrap(); //try refund for previous payment let transaction_id = utils::get_connector_transaction_id(response.response).unwrap(); for _x in 0..2 { tokio::time::sleep(Duration::from_secs(60)).await; // to avoid 404 error let refund_response = CONNECTOR .refund_payment( transaction_id.clone(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(None, payment_method_token.clone()), ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } } <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="378" end="394"> async fn should_partially_refund_succeeded_payment() { let refund_response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(None, create_customer_and_get_token().await), ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="84" end="107"> async fn create_customer_and_get_token() -> Option<String> { let customer_response = CONNECTOR .create_connector_customer(customer_details(), get_default_payment_info(None, None)) .await .expect("Authorize payment response"); let connector_customer_id = match customer_response.response.unwrap() { PaymentsResponseData::ConnectorCustomerResponse { connector_customer_id, } => Some(connector_customer_id), _ => None, }; let token_response = CONNECTOR .create_connector_pm_token( token_details(), get_default_payment_info(connector_customer_id, None), ) .await .expect("Authorize payment response"); match token_response.response.unwrap() { PaymentsResponseData::TokenizationResponse { token } => Some(token), _ => None, } } <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="78" end="82"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { ..utils::PaymentAuthorizeType::default().0 }) } <file_sep path="hyperswitch/crates/router/src/connector/dummyconnector/transformers.rs" role="context" start="304" end="309"> pub enum RefundStatus { Succeeded, Failed, #[default] Processing, } <file_sep path="hyperswitch/crates/api_models/src/refunds.rs" role="context" start="378" end="384"> pub enum RefundStatus { Succeeded, Failed, #[default] Pending, Review, }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/square.rs<|crate|> router<|connector|> square anchor=should_sync_manually_captured_refund kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="234" end="257"> async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(create_token().await), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(None), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="233" end="233"> use router::types::{self, storage::enums, PaymentsResponseData}; <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="274" end="300"> async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment( payment_method_details(), get_default_payment_info(create_token().await), ) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), get_default_payment_info(None), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="261" end="270"> async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment( payment_method_details(), get_default_payment_info(create_token().await), ) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="204" end="230"> async fn should_partially_refund_manually_captured_payment() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(create_token().await), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(None), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="177" end="200"> async fn should_refund_manually_captured_payment() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(create_token().await), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(None), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="39" end="52"> fn get_default_payment_info(payment_method_token: Option<String>) -> Option<utils::PaymentInfo> { Some(utils::PaymentInfo { address: None, auth_type: None, access_token: None, connector_meta_data: None, connector_customer: None, payment_method_token, #[cfg(feature = "payouts")] payout_method_data: None, #[cfg(feature = "payouts")] currency: None, }) } <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="54" end="56"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } <file_sep path="hyperswitch/crates/router/src/connector/dummyconnector/transformers.rs" role="context" start="304" end="309"> pub enum RefundStatus { Succeeded, Failed, #[default] Processing, } <file_sep path="hyperswitch/crates/api_models/src/refunds.rs" role="context" start="378" end="384"> pub enum RefundStatus { Succeeded, Failed, #[default] Pending, Review, }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/square.rs<|crate|> router<|connector|> square anchor=should_refund_manually_captured_payment kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="177" end="200"> async fn should_refund_manually_captured_payment() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(create_token().await), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(None), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="176" end="176"> use router::types::{self, storage::enums, PaymentsResponseData}; <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="234" end="257"> async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(create_token().await), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(None), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="204" end="230"> async fn should_partially_refund_manually_captured_payment() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(create_token().await), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(None), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="159" end="173"> async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_and_void_payment( payment_method_details(), Some(types::PaymentsCancelData { connector_transaction_id: String::from(""), cancellation_reason: Some("requested_by_customer".to_string()), ..Default::default() }), get_default_payment_info(create_token().await), ) .await .expect("Void payment response"); assert_eq!(response.status, enums::AttemptStatus::Voided); } <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="132" end="155"> async fn should_sync_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment( payment_method_details(), get_default_payment_info(create_token().await), ) .await .expect("Authorize payment response"); let txn_id = get_connector_transaction_id(authorize_response.response); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() }), get_default_payment_info(None), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Authorized,); } <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="54" end="56"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="39" end="52"> fn get_default_payment_info(payment_method_token: Option<String>) -> Option<utils::PaymentInfo> { Some(utils::PaymentInfo { address: None, auth_type: None, access_token: None, connector_meta_data: None, connector_customer: None, payment_method_token, #[cfg(feature = "payouts")] payout_method_data: None, #[cfg(feature = "payouts")] currency: None, }) } <file_sep path="hyperswitch/crates/router/src/connector/dummyconnector/transformers.rs" role="context" start="304" end="309"> pub enum RefundStatus { Succeeded, Failed, #[default] Processing, } <file_sep path="hyperswitch/crates/api_models/src/refunds.rs" role="context" start="378" end="384"> pub enum RefundStatus { Succeeded, Failed, #[default] Pending, Review, }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/trustpay.rs<|crate|> router<|connector|> trustpay anchor=get_default_browser_info kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/trustpay.rs" role="context" start="40" end="57"> fn get_default_browser_info() -> BrowserInformation { BrowserInformation { color_depth: Some(24), java_enabled: Some(false), java_script_enabled: Some(true), language: Some("en-US".to_string()), screen_height: Some(1080), screen_width: Some(1920), time_zone: Some(3600), accept_header: Some("*".to_string()), user_agent: Some("none".to_string()), ip_address: None, os_type: None, os_version: None, device_model: None, accept_language: Some("en".to_string()), } } <file_sep path="hyperswitch/crates/router/tests/connectors/trustpay.rs" role="context" start="39" end="39"> use router::types::{self, api, domain, storage::enums, BrowserInformation}; <file_sep path="hyperswitch/crates/router/tests/connectors/trustpay.rs" role="context" start="73" end="96"> fn get_default_payment_info() -> Option<utils::PaymentInfo> { Some(utils::PaymentInfo { address: Some(types::PaymentAddress::new( None, Some(Address { address: Some(AddressDetails { first_name: Some(Secret::new("first".to_string())), last_name: Some(Secret::new("last".to_string())), line1: Some(Secret::new("line1".to_string())), line2: Some(Secret::new("line2".to_string())), city: Some("city".to_string()), zip: Some(Secret::new("zip".to_string())), country: Some(api_models::enums::CountryAlpha2::IN), ..Default::default() }), phone: None, email: None, }), None, None, )), ..Default::default() }) } <file_sep path="hyperswitch/crates/router/tests/connectors/trustpay.rs" role="context" start="59" end="71"> fn get_default_payment_authorize_data() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("4200000000000000").unwrap(), card_exp_year: Secret::new("25".to_string()), card_cvc: Secret::new("123".to_string()), ..utils::CCardType::default().0 }), browser_info: Some(get_default_browser_info()), router_return_url: Some(String::from("http://localhost:8080")), ..utils::PaymentAuthorizeType::default().0 }) } <file_sep path="hyperswitch/crates/router/tests/connectors/trustpay.rs" role="context" start="35" end="37"> fn get_name(&self) -> String { "trustpay".to_string() } <file_sep path="hyperswitch/crates/router/tests/connectors/trustpay.rs" role="context" start="26" end="33"> fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .trustpay .expect("Missing connector authentication configuration") .into(), ) } <file_sep path="hyperswitch/crates/router/tests/connectors/trustpay.rs" role="context" start="212" end="232"> async fn should_fail_payment_for_incorrect_expiry_year() { let payment_authorize_data = Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("4200000000000000").unwrap(), card_exp_year: Secret::new("22".to_string()), card_cvc: Secret::new("123".to_string()), ..utils::CCardType::default().0 }), browser_info: Some(get_default_browser_info()), ..utils::PaymentAuthorizeType::default().0 }); let response = CONNECTOR .make_payment(payment_authorize_data, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Errors { code: 15, description: \"the provided expiration year is not valid\" }" .to_string(), ); }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/trustpay.rs<|crate|> router<|connector|> trustpay anchor=get_default_browser_info kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/trustpay.rs" role="context" start="40" end="57"> fn get_default_browser_info() -> BrowserInformation { BrowserInformation { color_depth: Some(24), java_enabled: Some(false), java_script_enabled: Some(true), language: Some("en-US".to_string()), screen_height: Some(1080), screen_width: Some(1920), time_zone: Some(3600), accept_header: Some("*".to_string()), user_agent: Some("none".to_string()), ip_address: None, os_type: None, os_version: None, device_model: None, accept_language: Some("en".to_string()), } } <file_sep path="hyperswitch/crates/router/tests/connectors/trustpay.rs" role="context" start="39" end="39"> use router::types::{self, api, domain, storage::enums, BrowserInformation}; <file_sep path="hyperswitch/crates/router/tests/connectors/trustpay.rs" role="context" start="73" end="96"> fn get_default_payment_info() -> Option<utils::PaymentInfo> { Some(utils::PaymentInfo { address: Some(types::PaymentAddress::new( None, Some(Address { address: Some(AddressDetails { first_name: Some(Secret::new("first".to_string())), last_name: Some(Secret::new("last".to_string())), line1: Some(Secret::new("line1".to_string())), line2: Some(Secret::new("line2".to_string())), city: Some("city".to_string()), zip: Some(Secret::new("zip".to_string())), country: Some(api_models::enums::CountryAlpha2::IN), ..Default::default() }), phone: None, email: None, }), None, None, )), ..Default::default() }) } <file_sep path="hyperswitch/crates/router/tests/connectors/trustpay.rs" role="context" start="59" end="71"> fn get_default_payment_authorize_data() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("4200000000000000").unwrap(), card_exp_year: Secret::new("25".to_string()), card_cvc: Secret::new("123".to_string()), ..utils::CCardType::default().0 }), browser_info: Some(get_default_browser_info()), router_return_url: Some(String::from("http://localhost:8080")), ..utils::PaymentAuthorizeType::default().0 }) } <file_sep path="hyperswitch/crates/router/tests/connectors/trustpay.rs" role="context" start="35" end="37"> fn get_name(&self) -> String { "trustpay".to_string() } <file_sep path="hyperswitch/crates/router/tests/connectors/trustpay.rs" role="context" start="26" end="33"> fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .trustpay .expect("Missing connector authentication configuration") .into(), ) } <file_sep path="hyperswitch/crates/router/tests/connectors/trustpay.rs" role="context" start="212" end="232"> async fn should_fail_payment_for_incorrect_expiry_year() { let payment_authorize_data = Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("4200000000000000").unwrap(), card_exp_year: Secret::new("22".to_string()), card_cvc: Secret::new("123".to_string()), ..utils::CCardType::default().0 }), browser_info: Some(get_default_browser_info()), ..utils::PaymentAuthorizeType::default().0 }); let response = CONNECTOR .make_payment(payment_authorize_data, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Errors { code: 15, description: \"the provided expiration year is not valid\" }" .to_string(), ); } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="1398" end="1441"> pub struct BrowserInformation { /// Color depth supported by the browser pub color_depth: Option<u8>, /// Whether java is enabled in the browser pub java_enabled: Option<bool>, /// Whether javascript is enabled in the browser pub java_script_enabled: Option<bool>, /// Language supported pub language: Option<String>, /// The screen height in pixels pub screen_height: Option<u32>, /// The screen width in pixels pub screen_width: Option<u32>, /// Time zone of the client pub time_zone: Option<i32>, /// Ip address of the client #[schema(value_type = Option<String>)] pub ip_address: Option<std::net::IpAddr>, /// List of headers that are accepted #[schema( example = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8" )] pub accept_header: Option<String>, /// User-agent of the browser pub user_agent: Option<String>, /// The os type of the client device pub os_type: Option<String>, /// The os version of the client device pub os_version: Option<String>, /// The device model of the client pub device_model: Option<String>, }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/dummyconnector.rs<|crate|> router anchor=build_request kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/connector/dummyconnector.rs" role="context" start="231" end="251"> fn build_request( &self, req: &types::PaymentsAuthorizeRouterData, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { Ok(Some( services::RequestBuilder::new() .method(services::Method::Post) .url(&types::PaymentsAuthorizeType::get_url( self, req, connectors, )?) .attach_default_headers() .headers(types::PaymentsAuthorizeType::get_headers( self, req, connectors, )?) .set_body(types::PaymentsAuthorizeType::get_request_body( self, req, connectors, )?) .build(), )) } <file_sep path="hyperswitch/crates/router/src/connector/dummyconnector.rs" role="context" start="230" end="230"> use crate::{ configs::settings, connector::utils as connector_utils, core::errors::{self, CustomResult}, events::connector_api_logs::ConnectorEvent, headers, services::{ self, request::{self, Mask}, ConnectorIntegration, ConnectorSpecifications, ConnectorValidation, }, types::{ self, api::{self, ConnectorCommon, ConnectorCommonExt}, ErrorResponse, Response, }, utils::BytesExt, }; <file_sep path="hyperswitch/crates/router/src/connector/dummyconnector.rs" role="context" start="273" end="279"> fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } <file_sep path="hyperswitch/crates/router/src/connector/dummyconnector.rs" role="context" start="253" end="271"> fn handle_response( &self, data: &types::PaymentsAuthorizeRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: transformers::PaymentsResponse = res .response .parse_struct("DummyConnector PaymentsResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) .change_context(errors::ConnectorError::ResponseHandlingFailed) } <file_sep path="hyperswitch/crates/router/src/connector/dummyconnector.rs" role="context" start="222" end="229"> fn get_request_body( &self, req: &types::PaymentsAuthorizeRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = transformers::DummyConnectorPaymentsRequest::<T>::try_from(req)?; Ok(RequestContent::Json(Box::new(connector_req))) } <file_sep path="hyperswitch/crates/router/src/connector/dummyconnector.rs" role="context" start="206" end="220"> fn get_url( &self, req: &types::PaymentsAuthorizeRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { match req.payment_method { enums::PaymentMethod::Card => Ok(format!("{}/payment", self.base_url(connectors))), enums::PaymentMethod::Wallet => Ok(format!("{}/payment", self.base_url(connectors))), enums::PaymentMethod::PayLater => Ok(format!("{}/payment", self.base_url(connectors))), _ => Err(error_stack::report!(errors::ConnectorError::NotSupported { message: format!("The payment method {} is not supported", req.payment_method), connector: Into::<transformers::DummyConnectors>::into(T).get_dummy_connector_id(), })), } } <file_sep path="hyperswitch/crates/router/src/connector/dummyconnector.rs" role="context" start="534" end="540"> fn get_headers( &self, req: &types::RefundSyncRouterData, connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } <file_sep path="hyperswitch/crates/router/src/connector/dummyconnector.rs" role="context" start="474" end="481"> fn get_request_body( &self, req: &types::RefundsRouterData<api::Execute>, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = transformers::DummyConnectorRefundRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(connector_req))) } <file_sep path="hyperswitch/crates/router/src/core/relay.rs" role="context" start="97" end="97"> type Request = relay_api_models::RelayRefundRequestData;
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/services/openidconnect.rs<|crate|> router anchor=get_nonce_from_redis kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/services/openidconnect.rs" role="context" start="137" end="152"> async fn get_nonce_from_redis( state: &SessionState, redirect_state: &Secret<String>, ) -> UserResult<oidc::Nonce> { let redis_connection = get_redis_connection(state)?; let redirect_state = redirect_state.clone().expose(); let key = get_oidc_redis_key(&redirect_state); redis_connection .get_key::<Option<String>>(&key.into()) .await .change_context(UserErrors::InternalServerError) .attach_printable("Error Fetching CSRF from redis")? .map(oidc::Nonce::new) .ok_or(UserErrors::SSOFailed) .attach_printable("Cannot find csrf in redis. Csrf invalid or expired") } <file_sep path="hyperswitch/crates/router/src/services/openidconnect.rs" role="context" start="136" end="136"> use masking::{ExposeInterface, Secret}; use oidc::TokenResponse; use openidconnect::{self as oidc, core as oidc_core}; use crate::{ consts, core::errors::{UserErrors, UserResult}, routes::SessionState, services::api::client, types::domain::user::UserEmail, }; <file_sep path="hyperswitch/crates/router/src/services/openidconnect.rs" role="context" start="187" end="189"> fn get_oidc_redis_key(csrf: &str) -> String { format!("{}OIDC_{}", consts::user::REDIS_SSO_PREFIX, csrf) } <file_sep path="hyperswitch/crates/router/src/services/openidconnect.rs" role="context" start="154" end="185"> async fn get_oidc_reqwest_client( state: &SessionState, request: oidc::HttpRequest, ) -> Result<oidc::HttpResponse, ApiClientError> { let client = client::create_client(&state.conf.proxy, None, None) .map_err(|e| e.current_context().to_owned())?; let mut request_builder = client .request(request.method, request.url) .body(request.body); for (name, value) in &request.headers { request_builder = request_builder.header(name.as_str(), value.as_bytes()); } let request = request_builder .build() .map_err(|_| ApiClientError::ClientConstructionFailed)?; let response = client .execute(request) .await .map_err(|_| ApiClientError::RequestNotSent("OpenIDConnect".to_string()))?; Ok(oidc::HttpResponse { status_code: response.status(), headers: response.headers().to_owned(), body: response .bytes() .await .map_err(|_| ApiClientError::ResponseDecodingFailed)? .to_vec(), }) } <file_sep path="hyperswitch/crates/router/src/services/openidconnect.rs" role="context" start="119" end="135"> fn get_oidc_core_client( discovery_document: oidc_core::CoreProviderMetadata, client_id: Secret<String>, client_secret: Option<Secret<String>>, redirect_url: String, ) -> UserResult<oidc_core::CoreClient> { let client_id = oidc::ClientId::new(client_id.expose()); let client_secret = client_secret.map(|secret| oidc::ClientSecret::new(secret.expose())); let redirect_url = oidc::RedirectUrl::new(redirect_url) .change_context(UserErrors::InternalServerError) .attach_printable("Error creating redirect URL type")?; Ok( oidc_core::CoreClient::from_provider_metadata(discovery_document, client_id, client_secret) .set_redirect_uri(redirect_url), ) } <file_sep path="hyperswitch/crates/router/src/services/openidconnect.rs" role="context" start="106" end="117"> async fn get_discovery_document( base_url: Secret<String>, state: &SessionState, ) -> UserResult<oidc_core::CoreProviderMetadata> { let issuer_url = oidc::IssuerUrl::new(base_url.expose()).change_context(UserErrors::InternalServerError)?; oidc_core::CoreProviderMetadata::discover_async(issuer_url, |req| { get_oidc_reqwest_client(state, req) }) .await .change_context(UserErrors::InternalServerError) } <file_sep path="hyperswitch/crates/router/src/services/openidconnect.rs" role="context" start="46" end="103"> pub async fn get_user_email_from_oidc_provider( state: &SessionState, redirect_url: String, redirect_state: Secret<String>, base_url: Secret<String>, client_id: Secret<String>, authorization_code: Secret<String>, client_secret: Secret<String>, ) -> UserResult<UserEmail> { let nonce = get_nonce_from_redis(state, &redirect_state).await?; let discovery_document = get_discovery_document(base_url, state).await?; let client = get_oidc_core_client( discovery_document, client_id, Some(client_secret), redirect_url, )?; let nonce_clone = nonce.clone(); client .authorize_url( oidc_core::CoreAuthenticationFlow::AuthorizationCode, || oidc::CsrfToken::new(redirect_state.expose()), || nonce_clone, ) .add_scope(oidc::Scope::new("email".to_string())); // Send request to OpenId provider with authorization code let token_response = client .exchange_code(oidc::AuthorizationCode::new(authorization_code.expose())) .request_async(|req| get_oidc_reqwest_client(state, req)) .await .change_context(UserErrors::InternalServerError) .attach_printable("Failed to exchange code and fetch oidc token")?; // Fetch id token from response let id_token = token_response .id_token() .ok_or(UserErrors::InternalServerError) .attach_printable("Id Token not provided in token response")?; // Verify id token let id_token_claims = id_token .claims(&client.id_token_verifier(), &nonce) .change_context(UserErrors::InternalServerError) .attach_printable("Failed to verify id token")?; // Get email from token let email_from_token = id_token_claims .email() .map(|email| email.to_string()) .ok_or(UserErrors::InternalServerError) .attach_printable("OpenID Provider Didnt provide email")?; UserEmail::new(Secret::new(email_from_token)) .change_context(UserErrors::InternalServerError) .attach_printable("Failed to create email type") } <file_sep path="hyperswitch/crates/router/src/services/openidconnect.rs" role="context" start="191" end="197"> fn get_redis_connection(state: &SessionState) -> UserResult<std::sync::Arc<RedisConnectionPool>> { state .store .get_redis_conn() .change_context(UserErrors::InternalServerError) .attach_printable("Failed to get redis connection") } <file_sep path="hyperswitch/crates/router/tests/utils.rs" role="context" start="399" end="401"> pub struct Error { pub message: Message, } <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="2478" end="2478"> type Error = error_stack::Report<errors::ValidationError>;
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/signifyd.rs<|crate|> router anchor=build_request kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/connector/signifyd.rs" role="context" start="256" end="272"> fn build_request( &self, req: &frm_types::FrmSaleRouterData, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { Ok(Some( services::RequestBuilder::new() .method(services::Method::Post) .url(&frm_types::FrmSaleType::get_url(self, req, connectors)?) .attach_default_headers() .headers(frm_types::FrmSaleType::get_headers(self, req, connectors)?) .set_body(frm_types::FrmSaleType::get_request_body( self, req, connectors, )?) .build(), )) } <file_sep path="hyperswitch/crates/router/src/connector/signifyd.rs" role="context" start="255" end="255"> use crate::{ configs::settings, core::errors::{self, CustomResult}, headers, services::{self, request, ConnectorIntegration, ConnectorSpecifications, ConnectorValidation}, types::{ self, api::{self, ConnectorCommon, ConnectorCommonExt}, }, }; use crate::{ consts, events::connector_api_logs::ConnectorEvent, types::{api::fraud_check as frm_api, fraud_check as frm_types, ErrorResponse, Response}, utils::BytesExt, }; <file_sep path="hyperswitch/crates/router/src/connector/signifyd.rs" role="context" start="294" end="300"> fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } <file_sep path="hyperswitch/crates/router/src/connector/signifyd.rs" role="context" start="274" end="293"> fn handle_response( &self, data: &frm_types::FrmSaleRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<frm_types::FrmSaleRouterData, errors::ConnectorError> { let response: signifyd::SignifydPaymentsResponse = res .response .parse_struct("SignifydPaymentsResponse Sale") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); <frm_types::FrmSaleRouterData>::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } <file_sep path="hyperswitch/crates/router/src/connector/signifyd.rs" role="context" start="247" end="254"> fn get_request_body( &self, req: &frm_types::FrmSaleRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let req_obj = signifyd::SignifydPaymentsSaleRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(req_obj))) } <file_sep path="hyperswitch/crates/router/src/connector/signifyd.rs" role="context" start="235" end="245"> fn get_url( &self, _req: &frm_types::FrmSaleRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}{}", self.base_url(connectors), "v3/orders/events/sales" )) } <file_sep path="hyperswitch/crates/router/src/connector/signifyd.rs" role="context" start="579" end="585"> fn get_headers( &self, req: &frm_types::FrmRecordReturnRouterData, connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } <file_sep path="hyperswitch/crates/router/src/connector/signifyd.rs" role="context" start="591" end="601"> fn get_url( &self, _req: &frm_types::FrmRecordReturnRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}{}", self.base_url(connectors), "v3/orders/events/returns/records" )) } <file_sep path="hyperswitch/crates/router/src/core/relay.rs" role="context" start="97" end="97"> type Request = relay_api_models::RelayRefundRequestData;
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/dummyconnector.rs<|crate|> router anchor=build_request kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/connector/dummyconnector.rs" role="context" start="483" end="500"> fn build_request( &self, req: &types::RefundsRouterData<api::Execute>, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { let request = services::RequestBuilder::new() .method(services::Method::Post) .url(&types::RefundExecuteType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::RefundExecuteType::get_headers( self, req, connectors, )?) .set_body(types::RefundExecuteType::get_request_body( self, req, connectors, )?) .build(); Ok(Some(request)) } <file_sep path="hyperswitch/crates/router/src/connector/dummyconnector.rs" role="context" start="482" end="482"> use common_utils::{consts as common_consts, request::RequestContent}; use crate::{ configs::settings, connector::utils as connector_utils, core::errors::{self, CustomResult}, events::connector_api_logs::ConnectorEvent, headers, services::{ self, request::{self, Mask}, ConnectorIntegration, ConnectorSpecifications, ConnectorValidation, }, types::{ self, api::{self, ConnectorCommon, ConnectorCommonExt}, ErrorResponse, Response, }, utils::BytesExt, }; <file_sep path="hyperswitch/crates/router/src/connector/dummyconnector.rs" role="context" start="522" end="528"> fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } <file_sep path="hyperswitch/crates/router/src/connector/dummyconnector.rs" role="context" start="502" end="520"> fn handle_response( &self, data: &types::RefundsRouterData<api::Execute>, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> { let response: transformers::RefundResponse = res .response .parse_struct("transformers RefundResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) .change_context(errors::ConnectorError::ResponseHandlingFailed) } <file_sep path="hyperswitch/crates/router/src/connector/dummyconnector.rs" role="context" start="474" end="481"> fn get_request_body( &self, req: &types::RefundsRouterData<api::Execute>, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = transformers::DummyConnectorRefundRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(connector_req))) } <file_sep path="hyperswitch/crates/router/src/connector/dummyconnector.rs" role="context" start="462" end="472"> fn get_url( &self, req: &types::RefundsRouterData<api::Execute>, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}/{}/refund", self.base_url(connectors), req.request.connector_transaction_id )) } <file_sep path="hyperswitch/crates/router/src/connector/dummyconnector.rs" role="context" start="534" end="540"> fn get_headers( &self, req: &types::RefundSyncRouterData, connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } <file_sep path="hyperswitch/crates/router/src/connector/dummyconnector.rs" role="context" start="546" end="557"> fn get_url( &self, req: &types::RefundSyncRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { let refund_id = req.request.get_connector_refund_id()?; Ok(format!( "{}/refunds/{}", self.base_url(connectors), refund_id )) } <file_sep path="hyperswitch/crates/router/src/core/relay.rs" role="context" start="97" end="97"> type Request = relay_api_models::RelayRefundRequestData;
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/signifyd.rs<|crate|> router anchor=build_request kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/connector/signifyd.rs" role="context" start="344" end="362"> fn build_request( &self, req: &frm_types::FrmCheckoutRouterData, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { Ok(Some( services::RequestBuilder::new() .method(services::Method::Post) .url(&frm_types::FrmCheckoutType::get_url(self, req, connectors)?) .attach_default_headers() .headers(frm_types::FrmCheckoutType::get_headers( self, req, connectors, )?) .set_body(frm_types::FrmCheckoutType::get_request_body( self, req, connectors, )?) .build(), )) } <file_sep path="hyperswitch/crates/router/src/connector/signifyd.rs" role="context" start="343" end="343"> use crate::{ configs::settings, core::errors::{self, CustomResult}, headers, services::{self, request, ConnectorIntegration, ConnectorSpecifications, ConnectorValidation}, types::{ self, api::{self, ConnectorCommon, ConnectorCommonExt}, }, }; use crate::{ consts, events::connector_api_logs::ConnectorEvent, types::{api::fraud_check as frm_api, fraud_check as frm_types, ErrorResponse, Response}, utils::BytesExt, }; <file_sep path="hyperswitch/crates/router/src/connector/signifyd.rs" role="context" start="382" end="388"> fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } <file_sep path="hyperswitch/crates/router/src/connector/signifyd.rs" role="context" start="364" end="381"> fn handle_response( &self, data: &frm_types::FrmCheckoutRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<frm_types::FrmCheckoutRouterData, errors::ConnectorError> { let response: signifyd::SignifydPaymentsResponse = res .response .parse_struct("SignifydPaymentsResponse Checkout") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); <frm_types::FrmCheckoutRouterData>::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } <file_sep path="hyperswitch/crates/router/src/connector/signifyd.rs" role="context" start="335" end="342"> fn get_request_body( &self, req: &frm_types::FrmCheckoutRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let req_obj = signifyd::SignifydPaymentsCheckoutRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(req_obj))) } <file_sep path="hyperswitch/crates/router/src/connector/signifyd.rs" role="context" start="323" end="333"> fn get_url( &self, _req: &frm_types::FrmCheckoutRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}{}", self.base_url(connectors), "v3/orders/events/checkouts" )) } <file_sep path="hyperswitch/crates/router/src/connector/signifyd.rs" role="context" start="603" end="610"> fn get_request_body( &self, req: &frm_types::FrmRecordReturnRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let req_obj = signifyd::SignifydPaymentsRecordReturnRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(req_obj))) } <file_sep path="hyperswitch/crates/router/src/connector/signifyd.rs" role="context" start="579" end="585"> fn get_headers( &self, req: &frm_types::FrmRecordReturnRouterData, connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } <file_sep path="hyperswitch/crates/router/src/core/relay.rs" role="context" start="97" end="97"> type Request = relay_api_models::RelayRefundRequestData;
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/services/authentication/blacklist.rs<|crate|> router anchor=insert_role_in_blacklist kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/services/authentication/blacklist.rs" role="context" start="42" end="58"> pub async fn insert_role_in_blacklist(state: &SessionState, role_id: &str) -> UserResult<()> { let role_blacklist_key = format!("{}{}", ROLE_BLACKLIST_PREFIX, role_id); let expiry = expiry_to_i64(JWT_TOKEN_TIME_IN_SECS).change_context(UserErrors::InternalServerError)?; let redis_conn = get_redis_connection(state).change_context(UserErrors::InternalServerError)?; redis_conn .set_key_with_expiry( &role_blacklist_key.as_str().into(), date_time::now_unix_timestamp(), expiry, ) .await .change_context(UserErrors::InternalServerError)?; invalidate_role_cache(state, role_id) .await .change_context(UserErrors::InternalServerError) } <file_sep path="hyperswitch/crates/router/src/services/authentication/blacklist.rs" role="context" start="41" end="41"> use common_utils::date_time; use crate::{ consts::{JWT_TOKEN_TIME_IN_SECS, ROLE_BLACKLIST_PREFIX, USER_BLACKLIST_PREFIX}, core::errors::{ApiErrorResponse, RouterResult}, routes::app::SessionStateInfo, }; use crate::{ core::errors::{UserErrors, UserResult}, routes::SessionState, services::authorization as authz, }; <file_sep path="hyperswitch/crates/router/src/services/authentication/blacklist.rs" role="context" start="70" end="83"> pub async fn check_user_in_blacklist<A: SessionStateInfo>( state: &A, user_id: &str, token_expiry: u64, ) -> RouterResult<bool> { let token = format!("{}{}", USER_BLACKLIST_PREFIX, user_id); let token_issued_at = expiry_to_i64(token_expiry - JWT_TOKEN_TIME_IN_SECS)?; let redis_conn = get_redis_connection(state)?; redis_conn .get_key::<Option<i64>>(&token.as_str().into()) .await .change_context(ApiErrorResponse::InternalServerError) .map(|timestamp| timestamp > Some(token_issued_at)) } <file_sep path="hyperswitch/crates/router/src/services/authentication/blacklist.rs" role="context" start="61" end="68"> async fn invalidate_role_cache(state: &SessionState, role_id: &str) -> RouterResult<()> { let redis_conn = get_redis_connection(state)?; redis_conn .delete_key(&authz::get_cache_key_from_role_id(role_id).as_str().into()) .await .map(|_| ()) .change_context(ApiErrorResponse::InternalServerError) } <file_sep path="hyperswitch/crates/router/src/services/authentication/blacklist.rs" role="context" start="26" end="39"> pub async fn insert_user_in_blacklist(state: &SessionState, user_id: &str) -> UserResult<()> { let user_blacklist_key = format!("{}{}", USER_BLACKLIST_PREFIX, user_id); let expiry = expiry_to_i64(JWT_TOKEN_TIME_IN_SECS).change_context(UserErrors::InternalServerError)?; let redis_conn = get_redis_connection(state).change_context(UserErrors::InternalServerError)?; redis_conn .set_key_with_expiry( &user_blacklist_key.as_str().into(), date_time::now_unix_timestamp(), expiry, ) .await .change_context(UserErrors::InternalServerError) } <file_sep path="hyperswitch/crates/router/src/services/authentication/blacklist.rs" role="context" start="127" end="133"> fn get_redis_connection<A: SessionStateInfo>(state: &A) -> RouterResult<Arc<RedisConnectionPool>> { state .store() .get_redis_conn() .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Failed to get redis connection") } <file_sep path="hyperswitch/crates/router/src/core/errors/user.rs" role="context" start="10" end="113"> pub enum UserErrors { #[error("User InternalServerError")] InternalServerError, #[error("InvalidCredentials")] InvalidCredentials, #[error("UserNotFound")] UserNotFound, #[error("UserExists")] UserExists, #[error("LinkInvalid")] LinkInvalid, #[error("UnverifiedUser")] UnverifiedUser, #[error("InvalidOldPassword")] InvalidOldPassword, #[error("EmailParsingError")] EmailParsingError, #[error("NameParsingError")] NameParsingError, #[error("PasswordParsingError")] PasswordParsingError, #[error("UserAlreadyVerified")] UserAlreadyVerified, #[error("CompanyNameParsingError")] CompanyNameParsingError, #[error("MerchantAccountCreationError: {0}")] MerchantAccountCreationError(String), #[error("InvalidEmailError")] InvalidEmailError, #[error("DuplicateOrganizationId")] DuplicateOrganizationId, #[error("MerchantIdNotFound")] MerchantIdNotFound, #[error("MetadataAlreadySet")] MetadataAlreadySet, #[error("InvalidRoleId")] InvalidRoleId, #[error("InvalidRoleOperation")] InvalidRoleOperation, #[error("IpAddressParsingFailed")] IpAddressParsingFailed, #[error("InvalidMetadataRequest")] InvalidMetadataRequest, #[error("MerchantIdParsingError")] MerchantIdParsingError, #[error("ChangePasswordError")] ChangePasswordError, #[error("InvalidDeleteOperation")] InvalidDeleteOperation, #[error("MaxInvitationsError")] MaxInvitationsError, #[error("RoleNotFound")] RoleNotFound, #[error("InvalidRoleOperationWithMessage")] InvalidRoleOperationWithMessage(String), #[error("RoleNameParsingError")] RoleNameParsingError, #[error("RoleNameAlreadyExists")] RoleNameAlreadyExists, #[error("TotpNotSetup")] TotpNotSetup, #[error("InvalidTotp")] InvalidTotp, #[error("TotpRequired")] TotpRequired, #[error("InvalidRecoveryCode")] InvalidRecoveryCode, #[error("TwoFactorAuthRequired")] TwoFactorAuthRequired, #[error("TwoFactorAuthNotSetup")] TwoFactorAuthNotSetup, #[error("TOTP secret not found")] TotpSecretNotFound, #[error("User auth method already exists")] UserAuthMethodAlreadyExists, #[error("Invalid user auth method operation")] InvalidUserAuthMethodOperation, #[error("Auth config parsing error")] AuthConfigParsingError, #[error("Invalid SSO request")] SSOFailed, #[error("profile_id missing in JWT")] JwtProfileIdMissing, #[error("Maximum attempts reached for TOTP")] MaxTotpAttemptsReached, #[error("Maximum attempts reached for Recovery Code")] MaxRecoveryCodeAttemptsReached, #[error("Forbidden tenant id")] ForbiddenTenantId, #[error("Error Uploading file to Theme Storage")] ErrorUploadingFile, #[error("Error Retrieving file from Theme Storage")] ErrorRetrievingFile, #[error("Theme not found")] ThemeNotFound, #[error("Theme with lineage already exists")] ThemeAlreadyExists, #[error("Invalid field: {0} in lineage")] InvalidThemeLineage(String), #[error("Missing required field: email_config")] MissingEmailConfig, #[error("Invalid Auth Method Operation: {0}")] InvalidAuthMethodOperationWithMessage(String), }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/signifyd.rs<|crate|> router anchor=build_request kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/connector/signifyd.rs" role="context" start="432" end="452"> fn build_request( &self, req: &frm_types::FrmTransactionRouterData, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { Ok(Some( services::RequestBuilder::new() .method(services::Method::Post) .url(&frm_types::FrmTransactionType::get_url( self, req, connectors, )?) .attach_default_headers() .headers(frm_types::FrmTransactionType::get_headers( self, req, connectors, )?) .set_body(frm_types::FrmTransactionType::get_request_body( self, req, connectors, )?) .build(), )) } <file_sep path="hyperswitch/crates/router/src/connector/signifyd.rs" role="context" start="431" end="431"> use crate::{ configs::settings, core::errors::{self, CustomResult}, headers, services::{self, request, ConnectorIntegration, ConnectorSpecifications, ConnectorValidation}, types::{ self, api::{self, ConnectorCommon, ConnectorCommonExt}, }, }; use crate::{ consts, events::connector_api_logs::ConnectorEvent, types::{api::fraud_check as frm_api, fraud_check as frm_types, ErrorResponse, Response}, utils::BytesExt, }; <file_sep path="hyperswitch/crates/router/src/connector/signifyd.rs" role="context" start="472" end="478"> fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } <file_sep path="hyperswitch/crates/router/src/connector/signifyd.rs" role="context" start="454" end="471"> fn handle_response( &self, data: &frm_types::FrmTransactionRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<frm_types::FrmTransactionRouterData, errors::ConnectorError> { let response: signifyd::SignifydPaymentsResponse = res .response .parse_struct("SignifydPaymentsResponse Transaction") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); <frm_types::FrmTransactionRouterData>::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } <file_sep path="hyperswitch/crates/router/src/connector/signifyd.rs" role="context" start="423" end="430"> fn get_request_body( &self, req: &frm_types::FrmTransactionRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let req_obj = signifyd::SignifydPaymentsTransactionRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(req_obj))) } <file_sep path="hyperswitch/crates/router/src/connector/signifyd.rs" role="context" start="411" end="421"> fn get_url( &self, _req: &frm_types::FrmTransactionRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}{}", self.base_url(connectors), "v3/orders/events/transactions" )) } <file_sep path="hyperswitch/crates/router/src/connector/signifyd.rs" role="context" start="591" end="601"> fn get_url( &self, _req: &frm_types::FrmRecordReturnRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}{}", self.base_url(connectors), "v3/orders/events/returns/records" )) } <file_sep path="hyperswitch/crates/router/src/connector/signifyd.rs" role="context" start="603" end="610"> fn get_request_body( &self, req: &frm_types::FrmRecordReturnRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let req_obj = signifyd::SignifydPaymentsRecordReturnRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(req_obj))) } <file_sep path="hyperswitch/crates/router/src/core/relay.rs" role="context" start="97" end="97"> type Request = relay_api_models::RelayRefundRequestData; <file_sep path="hyperswitch/crates/api_models/src/analytics/frm.rs" role="context" start="22" end="26"> pub enum FrmTransactionType { #[default] PreFrm, PostFrm, }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/signifyd.rs<|crate|> router anchor=build_request kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/connector/signifyd.rs" role="context" start="612" end="632"> fn build_request( &self, req: &frm_types::FrmRecordReturnRouterData, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { Ok(Some( services::RequestBuilder::new() .method(services::Method::Post) .url(&frm_types::FrmRecordReturnType::get_url( self, req, connectors, )?) .attach_default_headers() .headers(frm_types::FrmRecordReturnType::get_headers( self, req, connectors, )?) .set_body(frm_types::FrmRecordReturnType::get_request_body( self, req, connectors, )?) .build(), )) } <file_sep path="hyperswitch/crates/router/src/connector/signifyd.rs" role="context" start="611" end="611"> use crate::{ configs::settings, core::errors::{self, CustomResult}, headers, services::{self, request, ConnectorIntegration, ConnectorSpecifications, ConnectorValidation}, types::{ self, api::{self, ConnectorCommon, ConnectorCommonExt}, }, }; use crate::{ consts, events::connector_api_logs::ConnectorEvent, types::{api::fraud_check as frm_api, fraud_check as frm_types, ErrorResponse, Response}, utils::BytesExt, }; <file_sep path="hyperswitch/crates/router/src/connector/signifyd.rs" role="context" start="652" end="658"> fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } <file_sep path="hyperswitch/crates/router/src/connector/signifyd.rs" role="context" start="634" end="651"> fn handle_response( &self, data: &frm_types::FrmRecordReturnRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<frm_types::FrmRecordReturnRouterData, errors::ConnectorError> { let response: signifyd::SignifydPaymentsRecordReturnResponse = res .response .parse_struct("SignifydPaymentsResponse Transaction") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); <frm_types::FrmRecordReturnRouterData>::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } <file_sep path="hyperswitch/crates/router/src/connector/signifyd.rs" role="context" start="603" end="610"> fn get_request_body( &self, req: &frm_types::FrmRecordReturnRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let req_obj = signifyd::SignifydPaymentsRecordReturnRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(req_obj))) } <file_sep path="hyperswitch/crates/router/src/connector/signifyd.rs" role="context" start="591" end="601"> fn get_url( &self, _req: &frm_types::FrmRecordReturnRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}{}", self.base_url(connectors), "v3/orders/events/returns/records" )) } <file_sep path="hyperswitch/crates/router/src/connector/signifyd.rs" role="context" start="579" end="585"> fn get_headers( &self, req: &frm_types::FrmRecordReturnRouterData, connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } <file_sep path="hyperswitch/crates/router/src/core/relay.rs" role="context" start="97" end="97"> type Request = relay_api_models::RelayRefundRequestData;
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/utils/currency.rs<|crate|> router anchor=acquire_redis_lock kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/utils/currency.rs" role="context" start="449" end="465"> async fn acquire_redis_lock(state: &SessionState) -> CustomResult<bool, ForexError> { let forex_api = state.conf.forex_api.get_inner(); logger::debug!("forex_log: Acquiring redis lock"); state .store .get_redis_conn() .change_context(ForexError::RedisConnectionError)? .set_key_if_not_exists_with_expiry( &REDIX_FOREX_CACHE_KEY.into(), "", Some(i64::from(forex_api.redis_lock_timeout_in_seconds)), ) .await .map(|val| matches!(val, redis_interface::SetnxReply::KeySet)) .change_context(ForexError::CouldNotAcquireLock) .attach_printable("Unable to acquire redis lock") } <file_sep path="hyperswitch/crates/router/src/utils/currency.rs" role="context" start="448" end="448"> use common_utils::{date_time, errors::CustomResult, events::ApiEventMetric, ext_traits::AsyncExt}; use redis_interface::DelReply; use crate::{ logger, routes::app::settings::{Conversion, DefaultExchangeRates}, services, SessionState, }; <file_sep path="hyperswitch/crates/router/src/utils/currency.rs" role="context" start="487" end="499"> async fn retrieve_forex_data_from_redis( app_state: &SessionState, ) -> CustomResult<Option<FxExchangeRatesCacheEntry>, ForexError> { logger::debug!("forex_log: Retrieving forex from redis"); app_state .store .get_redis_conn() .change_context(ForexError::RedisConnectionError)? .get_and_deserialize_key(&REDIX_FOREX_CACHE_DATA.into(), "FxExchangeRatesCache") .await .change_context(ForexError::EntryNotFound) .attach_printable("Forex entry not found in redis") } <file_sep path="hyperswitch/crates/router/src/utils/currency.rs" role="context" start="467" end="485"> async fn save_forex_data_to_redis( app_state: &SessionState, forex_exchange_cache_entry: &FxExchangeRatesCacheEntry, ) -> CustomResult<(), ForexError> { let forex_api = app_state.conf.forex_api.get_inner(); logger::debug!("forex_log: Saving forex to redis"); app_state .store .get_redis_conn() .change_context(ForexError::RedisConnectionError)? .serialize_and_set_key_with_expiry( &REDIX_FOREX_CACHE_DATA.into(), forex_exchange_cache_entry, i64::from(forex_api.redis_ttl_in_seconds), ) .await .change_context(ForexError::RedisWriteError) .attach_printable("Unable to save forex data to redis") } <file_sep path="hyperswitch/crates/router/src/utils/currency.rs" role="context" start="435" end="447"> async fn release_redis_lock( state: &SessionState, ) -> Result<DelReply, error_stack::Report<ForexError>> { logger::debug!("forex_log: Releasing redis lock"); state .store .get_redis_conn() .change_context(ForexError::RedisConnectionError)? .delete_key(&REDIX_FOREX_CACHE_KEY.into()) .await .change_context(ForexError::RedisLockReleaseFailed) .attach_printable("Unable to release redis lock") } <file_sep path="hyperswitch/crates/router/src/utils/currency.rs" role="context" start="350" end="433"> pub async fn fetch_forex_rates_from_fallback_api( state: &SessionState, ) -> CustomResult<FxExchangeRatesCacheEntry, ForexError> { let fallback_forex_api_key = state.conf.forex_api.get_inner().fallback_api_key.peek(); let fallback_forex_url: String = format!("{}{}", FALLBACK_FOREX_BASE_URL, fallback_forex_api_key,); let fallback_forex_request = services::RequestBuilder::new() .method(services::Method::Get) .url(&fallback_forex_url) .build(); logger::info!(fallback_forex_request=?fallback_forex_request,"forex_log: Fallback api call for forex fetch"); let response = state .api_client .send_request( &state.clone(), fallback_forex_request, Some(FOREX_API_TIMEOUT), false, ) .await .change_context(ForexError::ApiUnresponsive) .attach_printable("Fallback forex fetch api unresponsive")?; let fallback_forex_response = response .json::<FallbackForexResponse>() .await .change_context(ForexError::ParsingError) .attach_printable( "Unable to parse response received from falback api into ForexResponse", )?; logger::info!(fallback_forex_response=?fallback_forex_response,"forex_log"); let mut conversions: HashMap<enums::Currency, CurrencyFactors> = HashMap::new(); for enum_curr in enums::Currency::iter() { match fallback_forex_response.quotes.get( format!( "{}{}", FALLBACK_FOREX_API_CURRENCY_PREFIX, &enum_curr.to_string() ) .as_str(), ) { Some(rate) => { let from_factor = match Decimal::new(1, 0).checked_div(**rate) { Some(rate) => rate, None => { logger::error!( "forex_error: Rates for {} not received from API", &enum_curr ); continue; } }; let currency_factors = CurrencyFactors::new(**rate, from_factor); conversions.insert(enum_curr, currency_factors); } None => { if enum_curr == enums::Currency::USD { let currency_factors = CurrencyFactors::new(Decimal::new(1, 0), Decimal::new(1, 0)); conversions.insert(enum_curr, currency_factors); } else { logger::error!( "forex_error: Rates for {} not received from API", &enum_curr ); } } }; } let rates = FxExchangeRatesCacheEntry::new(ExchangeRates::new(enums::Currency::USD, conversions)); match acquire_redis_lock(state).await { Ok(_) => { save_forex_data_to_cache_and_redis(state, rates.clone()).await?; Ok(rates) } Err(e) => Err(e), } } <file_sep path="hyperswitch/crates/router/src/utils/currency.rs" role="context" start="225" end="250"> async fn acquire_redis_lock_and_call_forex_api( state: &SessionState, ) -> CustomResult<(), ForexError> { let lock_acquired = acquire_redis_lock(state).await?; if !lock_acquired { Err(ForexError::CouldNotAcquireLock.into()) } else { logger::debug!("forex_log: redis lock acquired"); let api_rates = fetch_forex_rates_from_primary_api(state).await; match api_rates { Ok(rates) => save_forex_data_to_cache_and_redis(state, rates).await, Err(error) => { logger::error!(forex_error=?error,"primary_forex_error"); // API not able to fetch data call secondary service let secondary_api_rates = fetch_forex_rates_from_fallback_api(state).await; match secondary_api_rates { Ok(rates) => save_forex_data_to_cache_and_redis(state, rates).await, Err(error) => { release_redis_lock(state).await?; Err(error) } } } } } } <file_sep path="hyperswitch/crates/router/src/utils/currency.rs" role="context" start="149" end="154"> fn from(value: Conversion) -> Self { Self { to_factor: value.to_factor, from_factor: value.from_factor, } } <file_sep path="hyperswitch/crates/router/src/utils/currency.rs" role="context" start="41" end="80"> pub enum ForexError { #[error("API error")] ApiError, #[error("API timeout")] ApiTimeout, #[error("API unresponsive")] ApiUnresponsive, #[error("Conversion error")] ConversionError, #[error("Could not acquire the lock for cache entry")] CouldNotAcquireLock, #[error("Provided currency not acceptable")] CurrencyNotAcceptable, #[error("Forex configuration error: {0}")] ConfigurationError(String), #[error("Incorrect entries in default Currency response")] DefaultCurrencyParsingError, #[error("Entry not found in cache")] EntryNotFound, #[error("Forex data unavailable")] ForexDataUnavailable, #[error("Expiration time invalid")] InvalidLogExpiry, #[error("Error reading local")] LocalReadError, #[error("Error writing to local cache")] LocalWriteError, #[error("Json Parsing error")] ParsingError, #[error("Aws Kms decryption error")] AwsKmsDecryptionFailed, #[error("Error connecting to redis")] RedisConnectionError, #[error("Not able to release write lock")] RedisLockReleaseFailed, #[error("Error writing to redis")] RedisWriteError, #[error("Not able to acquire write lock")] WriteLockNotAcquired, } <file_sep path="hyperswitch/crates/router/src/routes/app.rs" role="context" start="104" end="125"> pub struct SessionState { pub store: Box<dyn StorageInterface>, /// Global store is used for global schema operations in tables like Users and Tenants pub global_store: Box<dyn GlobalStorageInterface>, pub accounts_store: Box<dyn AccountsStorageInterface>, pub conf: Arc<settings::Settings<RawSecret>>, pub api_client: Box<dyn crate::services::ApiClient>, pub event_handler: EventsHandler, #[cfg(feature = "email")] pub email_client: Arc<Box<dyn EmailService>>, #[cfg(feature = "olap")] pub pool: AnalyticsProvider, pub file_storage_client: Arc<dyn FileStorageInterface>, pub request_id: Option<RequestId>, pub base_url: String, pub tenant: Tenant, #[cfg(feature = "olap")] pub opensearch_client: Option<Arc<OpenSearchClient>>, pub grpc_client: Arc<GrpcClients>, pub theme_storage_client: Arc<dyn FileStorageInterface>, pub locale: String, }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/stax.rs<|crate|> router<|connector|> stax anchor=should_fail_void_payment_for_auto_capture kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="575" end="594"> async fn should_fail_void_payment_for_auto_capture() { let authorize_response = CONNECTOR .make_payment( payment_method_details(), get_default_payment_info(None, create_customer_and_get_token().await), ) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let void_response = CONNECTOR .void_payment(txn_id.unwrap(), None, get_default_payment_info(None, None)) .await .unwrap(); assert_eq!( void_response.response.unwrap_err().message, "You cannot cancel this PaymentIntent because it has a status of succeeded." ); } <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="574" end="574"> use router::types::{self, domain, storage::enums, PaymentsResponseData}; <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="615" end="631"> async fn should_fail_for_refund_amount_higher_than_payment_amount() { let response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 150, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(None, create_customer_and_get_token().await), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().reason, Some(r#"{"total":["The total may not be greater than 1."]}"#.to_string()), ); } <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="598" end="611"> async fn should_fail_capture_for_invalid_payment() { let capture_response = CONNECTOR .capture_payment( "123456789".to_string(), None, get_default_payment_info(None, create_customer_and_get_token().await), ) .await .unwrap(); assert_eq!( capture_response.response.unwrap_err().reason, Some(r#"{"id":["The selected id is invalid."]}"#.to_string()), ); } <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="536" end="570"> async fn should_fail_payment_for_incorrect_expiry_year() { let customer_response = CONNECTOR .create_connector_customer(customer_details(), get_default_payment_info(None, None)) .await .expect("Authorize payment response"); let connector_customer_id = match customer_response.response.unwrap() { PaymentsResponseData::ConnectorCustomerResponse { connector_customer_id, } => Some(connector_customer_id), _ => None, }; let token_response = CONNECTOR .create_connector_pm_token( Some(types::PaymentMethodTokenizationData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("4111111111111111").unwrap(), card_exp_month: Secret::new("04".to_string()), card_exp_year: Secret::new("2000".to_string()), card_cvc: Secret::new("123".to_string()), ..utils::CCardType::default().0 }), browser_info: None, amount: None, currency: enums::Currency::USD, }), get_default_payment_info(connector_customer_id, None), ) .await .expect("Authorize payment response"); assert_eq!( token_response.response.unwrap_err().reason, Some(r#"{"validation":["Tokenization Validation Errors: Year is invalid"]}"#.to_string()), ); } <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="498" end="532"> async fn should_fail_payment_for_invalid_exp_month() { let customer_response = CONNECTOR .create_connector_customer(customer_details(), get_default_payment_info(None, None)) .await .expect("Authorize payment response"); let connector_customer_id = match customer_response.response.unwrap() { PaymentsResponseData::ConnectorCustomerResponse { connector_customer_id, } => Some(connector_customer_id), _ => None, }; let token_response = CONNECTOR .create_connector_pm_token( Some(types::PaymentMethodTokenizationData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("4111111111111111").unwrap(), card_exp_month: Secret::new("20".to_string()), card_exp_year: Secret::new("2027".to_string()), card_cvc: Secret::new("123".to_string()), ..utils::CCardType::default().0 }), browser_info: None, amount: None, currency: enums::Currency::USD, }), get_default_payment_info(connector_customer_id, None), ) .await .expect("Authorize payment response"); assert_eq!( token_response.response.unwrap_err().reason, Some(r#"{"validation":["Tokenization Validation Errors: Month is invalid"]}"#.to_string()), ); } <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="78" end="82"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { ..utils::PaymentAuthorizeType::default().0 }) } <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="39" end="55"> fn get_default_payment_info( connector_customer: Option<String>, payment_method_token: Option<String>, ) -> Option<utils::PaymentInfo> { Some(utils::PaymentInfo { address: None, auth_type: None, access_token: None, connector_meta_data: None, connector_customer, payment_method_token, #[cfg(feature = "payouts")] payout_method_data: None, #[cfg(feature = "payouts")] currency: None, }) } <file_sep path="hyperswitch/v2_compatible_migrations/2024-08-28-081721_add_v2_columns/up.sql" role="context" start="19" end="35"> -- Intentionally not adding a default value here since we would have to -- check if any merchants have enabled this from configs table, -- before filling data for this column. -- If no merchants have enabled this, then we can use `false` as the default value -- when adding the column, later we can drop the default added for the column -- so that we ensure new records inserted always have a value for the column. ADD COLUMN should_collect_cvv_during_payment BOOLEAN; ALTER TABLE payment_intent ADD COLUMN merchant_reference_id VARCHAR(64), ADD COLUMN billing_address BYTEA DEFAULT NULL, ADD COLUMN shipping_address BYTEA DEFAULT NULL, ADD COLUMN capture_method "CaptureMethod", ADD COLUMN authentication_type "AuthenticationType", ADD COLUMN amount_to_capture bigint, ADD COLUMN prerouting_algorithm JSONB, ADD COLUMN surcharge_amount bigint,
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/signifyd.rs<|crate|> router anchor=build_request kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/connector/signifyd.rs" role="context" start="522" end="542"> fn build_request( &self, req: &frm_types::FrmFulfillmentRouterData, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { Ok(Some( services::RequestBuilder::new() .method(services::Method::Post) .url(&frm_types::FrmFulfillmentType::get_url( self, req, connectors, )?) .attach_default_headers() .headers(frm_types::FrmFulfillmentType::get_headers( self, req, connectors, )?) .set_body(frm_types::FrmFulfillmentType::get_request_body( self, req, connectors, )?) .build(), )) } <file_sep path="hyperswitch/crates/router/src/connector/signifyd.rs" role="context" start="521" end="521"> use crate::{ configs::settings, core::errors::{self, CustomResult}, headers, services::{self, request, ConnectorIntegration, ConnectorSpecifications, ConnectorValidation}, types::{ self, api::{self, ConnectorCommon, ConnectorCommonExt}, }, }; use crate::{ consts, events::connector_api_logs::ConnectorEvent, types::{api::fraud_check as frm_api, fraud_check as frm_types, ErrorResponse, Response}, utils::BytesExt, }; <file_sep path="hyperswitch/crates/router/src/connector/signifyd.rs" role="context" start="562" end="568"> fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } <file_sep path="hyperswitch/crates/router/src/connector/signifyd.rs" role="context" start="544" end="561"> fn handle_response( &self, data: &frm_types::FrmFulfillmentRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<frm_types::FrmFulfillmentRouterData, errors::ConnectorError> { let response: signifyd::FrmFulfillmentSignifydApiResponse = res .response .parse_struct("FrmFulfillmentSignifydApiResponse Sale") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); frm_types::FrmFulfillmentRouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } <file_sep path="hyperswitch/crates/router/src/connector/signifyd.rs" role="context" start="513" end="520"> fn get_request_body( &self, req: &frm_types::FrmFulfillmentRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let req_obj = signifyd::FrmFulfillmentSignifydRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(req_obj.clone()))) } <file_sep path="hyperswitch/crates/router/src/connector/signifyd.rs" role="context" start="501" end="511"> fn get_url( &self, _req: &frm_types::FrmFulfillmentRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}{}", self.base_url(connectors), "v3/orders/events/fulfillments" )) } <file_sep path="hyperswitch/crates/router/src/connector/signifyd.rs" role="context" start="603" end="610"> fn get_request_body( &self, req: &frm_types::FrmRecordReturnRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let req_obj = signifyd::SignifydPaymentsRecordReturnRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(req_obj))) } <file_sep path="hyperswitch/crates/router/src/connector/signifyd.rs" role="context" start="579" end="585"> fn get_headers( &self, req: &frm_types::FrmRecordReturnRouterData, connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } <file_sep path="hyperswitch/crates/router/src/core/relay.rs" role="context" start="97" end="97"> type Request = relay_api_models::RelayRefundRequestData;
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/square.rs<|crate|> router<|connector|> square anchor=should_partially_refund_manually_captured_payment kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="204" end="230"> async fn should_partially_refund_manually_captured_payment() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(create_token().await), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(None), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="203" end="203"> use router::types::{self, storage::enums, PaymentsResponseData}; <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="261" end="270"> async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment( payment_method_details(), get_default_payment_info(create_token().await), ) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="234" end="257"> async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(create_token().await), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(None), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="177" end="200"> async fn should_refund_manually_captured_payment() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(create_token().await), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(None), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="159" end="173"> async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_and_void_payment( payment_method_details(), Some(types::PaymentsCancelData { connector_transaction_id: String::from(""), cancellation_reason: Some("requested_by_customer".to_string()), ..Default::default() }), get_default_payment_info(create_token().await), ) .await .expect("Void payment response"); assert_eq!(response.status, enums::AttemptStatus::Voided); } <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="54" end="56"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="39" end="52"> fn get_default_payment_info(payment_method_token: Option<String>) -> Option<utils::PaymentInfo> { Some(utils::PaymentInfo { address: None, auth_type: None, access_token: None, connector_meta_data: None, connector_customer: None, payment_method_token, #[cfg(feature = "payouts")] payout_method_data: None, #[cfg(feature = "payouts")] currency: None, }) } <file_sep path="hyperswitch/crates/router/src/connector/dummyconnector/transformers.rs" role="context" start="304" end="309"> pub enum RefundStatus { Succeeded, Failed, #[default] Processing, } <file_sep path="hyperswitch/crates/api_models/src/refunds.rs" role="context" start="378" end="384"> pub enum RefundStatus { Succeeded, Failed, #[default] Pending, Review, }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/threedsecureio.rs<|crate|> router anchor=build_request kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/connector/threedsecureio.rs" role="context" start="270" end="296"> fn build_request( &self, req: &types::authentication::ConnectorAuthenticationRouterData, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { Ok(Some( services::RequestBuilder::new() .method(services::Method::Post) .url( &types::authentication::ConnectorAuthenticationType::get_url( self, req, connectors, )?, ) .attach_default_headers() .headers( types::authentication::ConnectorAuthenticationType::get_headers( self, req, connectors, )?, ) .set_body( types::authentication::ConnectorAuthenticationType::get_request_body( self, req, connectors, )?, ) .build(), )) } <file_sep path="hyperswitch/crates/router/src/connector/threedsecureio.rs" role="context" start="269" end="269"> use crate::{ configs::settings, core::errors::{self, CustomResult}, events::connector_api_logs::ConnectorEvent, headers, services::{ self, request::{self, Mask}, ConnectorIntegration, ConnectorSpecifications, ConnectorValidation, }, types::{ self, api::{self, ConnectorCommon, ConnectorCommonExt}, ErrorResponse, RequestContent, Response, }, utils::{self, BytesExt}, }; <file_sep path="hyperswitch/crates/router/src/connector/threedsecureio.rs" role="context" start="320" end="326"> fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } <file_sep path="hyperswitch/crates/router/src/connector/threedsecureio.rs" role="context" start="298" end="318"> fn handle_response( &self, data: &types::authentication::ConnectorAuthenticationRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult< types::authentication::ConnectorAuthenticationRouterData, errors::ConnectorError, > { let response: threedsecureio::ThreedsecureioAuthenticationResponse = res .response .parse_struct("ThreedsecureioAuthenticationResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } <file_sep path="hyperswitch/crates/router/src/connector/threedsecureio.rs" role="context" start="246" end="268"> fn get_request_body( &self, req: &types::authentication::ConnectorAuthenticationRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_router_data = threedsecureio::ThreedsecureioRouterData::try_from(( &self.get_currency_unit(), req.request .currency .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "currency", })?, req.request .amount .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "amount", })?, req, ))?; let req_obj = threedsecureio::ThreedsecureioAuthenticationRequest::try_from(&connector_router_data); Ok(RequestContent::Json(Box::new(req_obj?))) } <file_sep path="hyperswitch/crates/router/src/connector/threedsecureio.rs" role="context" start="238" end="244"> fn get_url( &self, _req: &types::authentication::ConnectorAuthenticationRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}/auth", self.base_url(connectors),)) } <file_sep path="hyperswitch/crates/router/src/connector/threedsecureio.rs" role="context" start="451" end="460"> fn get_request_body( &self, req: &types::authentication::ConnectorPostAuthenticationRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let req_obj = threedsecureio::ThreedsecureioPostAuthenticationRequest { three_ds_server_trans_id: req.request.threeds_server_transaction_id.clone(), }; Ok(RequestContent::Json(Box::new(req_obj))) } <file_sep path="hyperswitch/crates/router/src/connector/threedsecureio.rs" role="context" start="443" end="449"> fn get_url( &self, _req: &types::authentication::ConnectorPostAuthenticationRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}/postauth", self.base_url(connectors),)) } <file_sep path="hyperswitch/crates/router/src/core/relay.rs" role="context" start="97" end="97"> type Request = relay_api_models::RelayRefundRequestData;
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/types/domain/user.rs<|crate|> router anchor=try_from kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/types/domain/user.rs" role="context" start="700" end="719"> fn try_from(value: UserMerchantCreateRequestWithToken) -> UserResult<Self> { let merchant_id = if matches!(env::which(), env::Env::Production) { id_type::MerchantId::try_from(MerchantId::new(value.1.company_name.clone())?)? } else { id_type::MerchantId::new_from_unix_timestamp() }; let (user_from_storage, user_merchant_create, user_from_token) = value; Ok(Self { merchant_id, company_name: Some(UserCompanyName::new( user_merchant_create.company_name.clone(), )?), product_type: user_merchant_create.product_type, new_organization: NewUserOrganization::from(( user_from_storage, user_merchant_create, user_from_token, )), }) } <file_sep path="hyperswitch/crates/router/src/types/domain/user.rs" role="context" start="699" end="699"> use common_utils::{ crypto::Encryptable, id_type, new_type::MerchantName, pii, type_name, types::keymanager::Identifier, }; use router_env::env; use crate::{ consts, core::{ admin, errors::{UserErrors, UserResult}, }, db::GlobalStorageInterface, routes::SessionState, services::{self, authentication::UserFromToken}, types::{domain, transformers::ForeignFrom}, utils::user::password, }; type UserMerchantCreateRequestWithToken = (UserFromStorage, user_api::UserMerchantCreate, UserFromToken); <file_sep path="hyperswitch/crates/router/src/types/domain/user.rs" role="context" start="752" end="754"> pub fn get_user_id(&self) -> String { self.user_id.clone() } <file_sep path="hyperswitch/crates/router/src/types/domain/user.rs" role="context" start="746" end="748"> fn deref(&self) -> &Self::Target { &self.password } <file_sep path="hyperswitch/crates/router/src/types/domain/user.rs" role="context" start="682" end="691"> fn from(value: (user_api::CreateTenantUserRequest, MerchantAccountIdentifier)) -> Self { let merchant_id = value.1.merchant_id.clone(); let new_organization = NewUserOrganization::from(value); Self { company_name: None, merchant_id, new_organization, product_type: None, } } <file_sep path="hyperswitch/crates/router/src/types/domain/user.rs" role="context" start="669" end="678"> fn try_from(value: InviteeUserRequestWithInvitedUserToken) -> UserResult<Self> { let merchant_id = value.clone().1.merchant_id; let new_organization = NewUserOrganization::from(value); Ok(Self { company_name: None, merchant_id, new_organization, product_type: None, }) } <file_sep path="hyperswitch/crates/router/src/types/domain/user.rs" role="context" start="1414" end="1423"> fn from(value: ProfileLevel) -> Self { Self { entity_id: value.profile_id.get_string_repr().to_owned(), entity_type: EntityType::Profile, tenant_id: value.tenant_id, org_id: Some(value.org_id), merchant_id: Some(value.merchant_id), profile_id: Some(value.profile_id), } } <file_sep path="hyperswitch/crates/router/src/types/domain/user.rs" role="context" start="1256" end="1265"> pub fn new(name: String) -> UserResult<Self> { let is_empty_or_whitespace = name.trim().is_empty(); let is_too_long = name.graphemes(true).count() > consts::user_role::MAX_ROLE_NAME_LENGTH; if is_empty_or_whitespace || is_too_long || name.contains(' ') { Err(UserErrors::RoleNameParsingError.into()) } else { Ok(Self(name.to_lowercase())) } } <file_sep path="hyperswitch/crates/router/src/types/domain/user.rs" role="context" start="694" end="695"> type UserMerchantCreateRequestWithToken = (UserFromStorage, user_api::UserMerchantCreate, UserFromToken); <file_sep path="hyperswitch/crates/router/src/types/domain/user.rs" role="context" start="360" end="360"> pub struct MerchantId(String); <file_sep path="hyperswitch/crates/router/src/core/errors/user.rs" role="context" start="5" end="5"> pub type UserResult<T> = CustomResult<T, UserErrors>; <file_sep path="hyperswitch/crates/api_models/src/admin.rs" role="context" start="698" end="700"> pub struct MerchantId { pub merchant_id: id_type::MerchantId, }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/stax.rs<|crate|> router<|connector|> stax anchor=should_sync_authorized_payment kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="156" end="179"> async fn should_sync_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment( payment_method_details(), get_default_payment_info(None, create_customer_and_get_token().await), ) .await .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() }), get_default_payment_info(None, None), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Authorized,); } <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="155" end="155"> use router::types::{self, domain, storage::enums, PaymentsResponseData}; <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="201" end="233"> async fn should_refund_manually_captured_payment() { let capture_response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), Some(types::PaymentsCaptureData { ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(None, create_customer_and_get_token().await), ) .await .expect("Capture payment response"); let refund_txn_id = utils::get_connector_transaction_id(capture_response.response.clone()).unwrap(); let refund_connector_meta = utils::get_connector_metadata(capture_response.response); let response = CONNECTOR .refund_payment( refund_txn_id, Some(types::RefundsData { connector_metadata: refund_connector_meta, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(None, None), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="183" end="197"> async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_and_void_payment( payment_method_details(), Some(types::PaymentsCancelData { connector_transaction_id: String::from(""), cancellation_reason: Some("requested_by_customer".to_string()), ..Default::default() }), get_default_payment_info(None, create_customer_and_get_token().await), ) .await .expect("Void payment response"); assert_eq!(response.status, enums::AttemptStatus::Voided); } <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="139" end="152"> async fn should_partially_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), Some(types::PaymentsCaptureData { amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(None, create_customer_and_get_token().await), ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="125" end="135"> async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), None, get_default_payment_info(None, create_customer_and_get_token().await), ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="84" end="107"> async fn create_customer_and_get_token() -> Option<String> { let customer_response = CONNECTOR .create_connector_customer(customer_details(), get_default_payment_info(None, None)) .await .expect("Authorize payment response"); let connector_customer_id = match customer_response.response.unwrap() { PaymentsResponseData::ConnectorCustomerResponse { connector_customer_id, } => Some(connector_customer_id), _ => None, }; let token_response = CONNECTOR .create_connector_pm_token( token_details(), get_default_payment_info(connector_customer_id, None), ) .await .expect("Authorize payment response"); match token_response.response.unwrap() { PaymentsResponseData::TokenizationResponse { token } => Some(token), _ => None, } } <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="78" end="82"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { ..utils::PaymentAuthorizeType::default().0 }) }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/threedsecureio.rs<|crate|> router anchor=build_request kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/connector/threedsecureio.rs" role="context" start="462" end="488"> fn build_request( &self, req: &types::authentication::ConnectorPostAuthenticationRouterData, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { Ok(Some( services::RequestBuilder::new() .method(services::Method::Post) .url( &types::authentication::ConnectorPostAuthenticationType::get_url( self, req, connectors, )?, ) .attach_default_headers() .headers( types::authentication::ConnectorPostAuthenticationType::get_headers( self, req, connectors, )?, ) .set_body( types::authentication::ConnectorPostAuthenticationType::get_request_body( self, req, connectors, )?, ) .build(), )) } <file_sep path="hyperswitch/crates/router/src/connector/threedsecureio.rs" role="context" start="461" end="461"> use crate::{ configs::settings, core::errors::{self, CustomResult}, events::connector_api_logs::ConnectorEvent, headers, services::{ self, request::{self, Mask}, ConnectorIntegration, ConnectorSpecifications, ConnectorValidation, }, types::{ self, api::{self, ConnectorCommon, ConnectorCommonExt}, ErrorResponse, RequestContent, Response, }, utils::{self, BytesExt}, }; <file_sep path="hyperswitch/crates/router/src/connector/threedsecureio.rs" role="context" start="519" end="525"> fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } <file_sep path="hyperswitch/crates/router/src/connector/threedsecureio.rs" role="context" start="490" end="517"> fn handle_response( &self, data: &types::authentication::ConnectorPostAuthenticationRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult< types::authentication::ConnectorPostAuthenticationRouterData, errors::ConnectorError, > { let response: threedsecureio::ThreedsecureioPostAuthenticationResponse = res .response .parse_struct("threedsecureio PaymentsSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); Ok( types::authentication::ConnectorPostAuthenticationRouterData { response: Ok( types::authentication::AuthenticationResponseData::PostAuthNResponse { trans_status: response.trans_status.into(), authentication_value: response.authentication_value, eci: response.eci, }, ), ..data.clone() }, ) } <file_sep path="hyperswitch/crates/router/src/connector/threedsecureio.rs" role="context" start="451" end="460"> fn get_request_body( &self, req: &types::authentication::ConnectorPostAuthenticationRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let req_obj = threedsecureio::ThreedsecureioPostAuthenticationRequest { three_ds_server_trans_id: req.request.threeds_server_transaction_id.clone(), }; Ok(RequestContent::Json(Box::new(req_obj))) } <file_sep path="hyperswitch/crates/router/src/connector/threedsecureio.rs" role="context" start="443" end="449"> fn get_url( &self, _req: &types::authentication::ConnectorPostAuthenticationRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}/postauth", self.base_url(connectors),)) } <file_sep path="hyperswitch/crates/router/src/core/relay.rs" role="context" start="97" end="97"> type Request = relay_api_models::RelayRefundRequestData;
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/routes/disputes.rs<|crate|> router anchor=retrieve_disputes_list kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/routes/disputes.rs" role="context" start="86" end="111"> pub async fn retrieve_disputes_list( state: web::Data<AppState>, req: HttpRequest, query: web::Query<dispute_models::DisputeListGetConstraints>, ) -> HttpResponse { let flow = Flow::DisputesList; let payload = query.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, req, _| { disputes::retrieve_disputes_list(state, auth.merchant_account, None, req) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { permission: Permission::MerchantDisputeRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } <file_sep path="hyperswitch/crates/router/src/routes/disputes.rs" role="context" start="85" end="85"> use actix_web::{web, HttpRequest, HttpResponse}; use api_models::disputes as dispute_models; use router_env::{instrument, tracing, Flow}; use crate::{core::api_locking, services::authorization::permissions::Permission}; use super::app::AppState; use crate::{ core::disputes, services::{api, authentication as auth}, types::api::disputes as dispute_types, }; <file_sep path="hyperswitch/crates/router/src/routes/disputes.rs" role="context" start="184" end="204"> pub async fn get_disputes_filters(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse { let flow = Flow::DisputesFilters; Box::pin(api::server_wrap( flow, state, &req, (), |state, auth: auth::AuthenticationData, _, _| { disputes::get_filters_for_disputes(state, auth.merchant_account, None) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { permission: Permission::MerchantDisputeRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } <file_sep path="hyperswitch/crates/router/src/routes/disputes.rs" role="context" start="139" end="169"> pub async fn retrieve_disputes_list_profile( state: web::Data<AppState>, req: HttpRequest, payload: web::Query<dispute_models::DisputeListGetConstraints>, ) -> HttpResponse { let flow = Flow::DisputesList; let payload = payload.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, req, _| { disputes::retrieve_disputes_list( state, auth.merchant_account, auth.profile_id.map(|profile_id| vec![profile_id]), req, ) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { permission: Permission::ProfileDisputeRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } <file_sep path="hyperswitch/crates/router/src/routes/disputes.rs" role="context" start="33" end="60"> pub async fn retrieve_dispute( state: web::Data<AppState>, req: HttpRequest, path: web::Path<String>, ) -> HttpResponse { let flow = Flow::DisputesRetrieve; let dispute_id = dispute_types::DisputeId { dispute_id: path.into_inner(), }; Box::pin(api::server_wrap( flow, state, &req, dispute_id, |state, auth: auth::AuthenticationData, req, _| { disputes::retrieve_dispute(state, auth.merchant_account, auth.profile_id, req) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { permission: Permission::ProfileDisputeRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } <file_sep path="hyperswitch/crates/api_models/src/disputes.rs" role="context" start="116" end="147"> pub struct DisputeListGetConstraints { /// The identifier for dispute pub dispute_id: Option<String>, /// The payment_id against which dispute is raised pub payment_id: Option<common_utils::id_type::PaymentId>, /// Limit on the number of objects to return pub limit: Option<u32>, /// The starting point within a list of object pub offset: Option<u32>, /// The identifier for business profile #[schema(value_type = Option<String>)] pub profile_id: Option<common_utils::id_type::ProfileId>, /// The comma separated list of status of the disputes #[serde(default, deserialize_with = "parse_comma_separated")] pub dispute_status: Option<Vec<DisputeStatus>>, /// The comma separated list of stages of the disputes #[serde(default, deserialize_with = "parse_comma_separated")] pub dispute_stage: Option<Vec<DisputeStage>>, /// Reason for the dispute pub reason: Option<String>, /// The comma separated list of connectors linked to disputes #[serde(default, deserialize_with = "parse_comma_separated")] pub connector: Option<Vec<String>>, /// The comma separated list of currencies of the disputes #[serde(default, deserialize_with = "parse_comma_separated")] pub currency: Option<Vec<Currency>>, /// The merchant connector id to filter the disputes list pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, /// The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc). #[serde(flatten)] pub time_range: Option<TimeRange>, }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/square.rs<|crate|> router<|connector|> square anchor=should_fail_void_payment_for_auto_capture kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="522" end="546"> async fn should_fail_void_payment_for_auto_capture() { let authorize_response = CONNECTOR .make_payment( payment_method_details(), get_default_payment_info(create_token().await), ) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let void_response = CONNECTOR .void_payment( txn_id.clone().unwrap(), None, get_default_payment_info(None), ) .await .unwrap(); let connector_transaction_id = txn_id.unwrap(); assert_eq!( void_response.response.unwrap_err().reason.unwrap_or("".to_string()), format!("Payment {connector_transaction_id} is in inflight state COMPLETED, which is invalid for the requested operation") ); } <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="521" end="521"> use router::types::{self, storage::enums, PaymentsResponseData}; <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="571" end="591"> async fn should_fail_for_refund_amount_higher_than_payment_amount() { let response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 150, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(create_token().await), ) .await .unwrap(); assert_eq!( response .response .unwrap_err() .reason .unwrap_or("".to_string()), "The requested refund amount exceeds the amount available to refund.", ); } <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="550" end="567"> async fn should_fail_capture_for_invalid_payment() { let capture_response = CONNECTOR .capture_payment( "123456789".to_string(), None, get_default_payment_info(create_token().await), ) .await .unwrap(); assert_eq!( capture_response .response .unwrap_err() .reason .unwrap_or("".to_string()), String::from("Could not find payment with id: 123456789") ); } <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="491" end="518"> async fn should_fail_payment_for_incorrect_expiry_year() { let token_response = CONNECTOR .create_connector_pm_token( Some(types::PaymentMethodTokenizationData { payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card { card_number: cards::CardNumber::from_str("4111111111111111").unwrap(), card_exp_month: Secret::new("11".to_string()), card_exp_year: Secret::new("2000".to_string()), card_cvc: Secret::new("123".to_string()), ..utils::CCardType::default().0 }), browser_info: None, amount: None, currency: enums::Currency::USD, }), get_default_payment_info(None), ) .await .expect("Authorize payment response"); assert_eq!( token_response .response .unwrap_err() .reason .unwrap_or("".to_string()), "Invalid card expiration date.".to_string(), ); } <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="460" end="487"> async fn should_fail_payment_for_invalid_exp_month() { let token_response = CONNECTOR .create_connector_pm_token( Some(types::PaymentMethodTokenizationData { payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card { card_number: cards::CardNumber::from_str("4111111111111111").unwrap(), card_exp_month: Secret::new("20".to_string()), card_exp_year: Secret::new("2027".to_string()), card_cvc: Secret::new("123".to_string()), ..utils::CCardType::default().0 }), browser_info: None, amount: None, currency: enums::Currency::USD, }), get_default_payment_info(None), ) .await .expect("Authorize payment response"); assert_eq!( token_response .response .unwrap_err() .reason .unwrap_or("".to_string()), "Invalid card expiration date.".to_string(), ); } <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="39" end="52"> fn get_default_payment_info(payment_method_token: Option<String>) -> Option<utils::PaymentInfo> { Some(utils::PaymentInfo { address: None, auth_type: None, access_token: None, connector_meta_data: None, connector_customer: None, payment_method_token, #[cfg(feature = "payouts")] payout_method_data: None, #[cfg(feature = "payouts")] currency: None, }) } <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="54" end="56"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/gpayments.rs<|crate|> router anchor=build_request kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/connector/gpayments.rs" role="context" start="360" end="384"> fn build_request( &self, req: &types::authentication::ConnectorPostAuthenticationRouterData, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { let gpayments_auth_type = gpayments::GpaymentsAuthType::try_from(&req.connector_auth_type)?; Ok(Some( services::RequestBuilder::new() .method(services::Method::Get) .url( &types::authentication::ConnectorPostAuthenticationType::get_url( self, req, connectors, )?, ) .attach_default_headers() .headers( types::authentication::ConnectorPostAuthenticationType::get_headers( self, req, connectors, )?, ) .add_certificate(Some(gpayments_auth_type.certificate)) .add_certificate_key(Some(gpayments_auth_type.private_key)) .build(), )) } <file_sep path="hyperswitch/crates/router/src/connector/gpayments.rs" role="context" start="359" end="359"> use common_utils::{ request::RequestContent, types::{AmountConvertor, MinorUnit, MinorUnitForConnector}, }; use transformers as gpayments; use crate::{ configs::settings, connector::{gpayments::gpayments_types::GpaymentsConnectorMetaData, utils::to_connector_meta}, core::errors::{self, CustomResult}, events::connector_api_logs::ConnectorEvent, headers, services, services::{request, ConnectorIntegration, ConnectorSpecifications, ConnectorValidation}, types::{ self, api::{self, ConnectorCommon, ConnectorCommonExt}, ErrorResponse, Response, }, utils::BytesExt, }; <file_sep path="hyperswitch/crates/router/src/connector/gpayments.rs" role="context" start="415" end="421"> fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } <file_sep path="hyperswitch/crates/router/src/connector/gpayments.rs" role="context" start="386" end="413"> fn handle_response( &self, data: &types::authentication::ConnectorPostAuthenticationRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult< types::authentication::ConnectorPostAuthenticationRouterData, errors::ConnectorError, > { let response: gpayments_types::GpaymentsPostAuthenticationResponse = res .response .parse_struct("gpayments PaymentsSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); Ok( types::authentication::ConnectorPostAuthenticationRouterData { response: Ok( types::authentication::AuthenticationResponseData::PostAuthNResponse { trans_status: response.trans_status.into(), authentication_value: response.authentication_value, eci: response.eci, }, ), ..data.clone() }, ) } <file_sep path="hyperswitch/crates/router/src/connector/gpayments.rs" role="context" start="348" end="358"> fn get_url( &self, req: &types::authentication::ConnectorPostAuthenticationRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { let base_url = build_endpoint(self.base_url(connectors), &req.connector_meta_data)?; Ok(format!( "{}/api/v2/auth/brw/result?threeDSServerTransID={}", base_url, req.request.threeds_server_transaction_id, )) } <file_sep path="hyperswitch/crates/router/src/connector/gpayments.rs" role="context" start="344" end="346"> fn get_content_type(&self) -> &'static str { self.common_get_content_type() } <file_sep path="hyperswitch/crates/router/src/connector/gpayments.rs" role="context" start="32" end="36"> pub fn new() -> &'static Self { &Self { _amount_converter: &MinorUnitForConnector, } } <file_sep path="hyperswitch/crates/router/src/connector/gpayments.rs" role="context" start="528" end="534"> fn get_headers( &self, req: &types::authentication::PreAuthNVersionCallRouterData, connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } <file_sep path="hyperswitch/crates/router/src/core/relay.rs" role="context" start="97" end="97"> type Request = relay_api_models::RelayRefundRequestData; <file_sep path="hyperswitch/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/event.test.js" role="context" start="61" end="78"> "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.", ); } // Response body should have value "succeeded" for "status" if (jsonData?.status) { pm.test( "[POST]::/payments - Content check if value for 'status' matches 'succeeded'", function () { pm.expect(jsonData.status).to.eql("succeeded"); }, ); }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/services/authentication/decision.rs<|crate|> router anchor=call_decision_service kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/src/services/authentication/decision.rs" role="context" start="132" end="161"> async fn call_decision_service<T: ErasedMaskSerialize + Send + 'static>( state: &SessionState, decision_config: &DecisionConfig, rule: T, method: common_utils::request::Method, ) -> CustomResult<(), ApiClientError> { let mut request = common_utils::request::Request::new( method, &(decision_config.base_url.clone() + DECISION_ENDPOINT), ); request.set_body(RequestContent::Json(Box::new(rule))); request.add_default_headers(); let response = state .api_client .send_request(state, request, None, false) .await; match response { Err(error) => { router_env::error!("Failed while calling the decision service: {:?}", error); Err(error) } Ok(response) => { router_env::info!("Decision service response: {:?}", response); Ok(()) } } } <file_sep path="hyperswitch/crates/router/src/services/authentication/decision.rs" role="context" start="131" end="131"> use common_utils::{errors::CustomResult, request::RequestContent}; use masking::{ErasedMaskSerialize, Secret}; use storage_impl::errors::ApiClientError; use crate::{ core::metrics, routes::{app::settings::DecisionConfig, SessionState}, }; <file_sep path="hyperswitch/crates/router/src/services/authentication/decision.rs" role="context" start="183" end="192"> pub fn convert_expiry(expiry: time::PrimitiveDateTime) -> u64 { let now = common_utils::date_time::now(); let duration = expiry - now; let output = duration.whole_seconds(); match output { i64::MIN..=0 => 0, _ => output as u64, } } <file_sep path="hyperswitch/crates/router/src/services/authentication/decision.rs" role="context" start="163" end="179"> pub async fn revoke_api_key( state: &SessionState, api_key: Secret<String>, ) -> CustomResult<(), ApiClientError> { let decision_config = if let Some(config) = &state.conf.decision { config } else { return Ok(()); }; let rule = RuleDeleteRequest { tag: state.tenant.schema.clone(), variant: AuthType::ApiKey { api_key }, }; call_decision_service(state, decision_config, rule, RULE_DELETE_METHOD).await } <file_sep path="hyperswitch/crates/router/src/services/authentication/decision.rs" role="context" start="106" end="130"> pub async fn add_publishable_key( state: &SessionState, api_key: Secret<String>, merchant_id: common_utils::id_type::MerchantId, expiry: Option<u64>, ) -> CustomResult<(), ApiClientError> { let decision_config = if let Some(config) = &state.conf.decision { config } else { return Ok(()); }; let rule = RuleRequest { tag: state.tenant.schema.clone(), expiry, variant: AuthRuleType::ApiKey { api_key, identifiers: Identifiers::PublishableKey { merchant_id: merchant_id.get_string_repr().to_owned(), }, }, }; call_decision_service(state, decision_config, rule, RULE_ADD_METHOD).await } <file_sep path="hyperswitch/crates/router/src/services/authentication/decision.rs" role="context" start="78" end="104"> pub async fn add_api_key( state: &SessionState, api_key: Secret<String>, merchant_id: common_utils::id_type::MerchantId, key_id: common_utils::id_type::ApiKeyId, expiry: Option<u64>, ) -> CustomResult<(), ApiClientError> { let decision_config = if let Some(config) = &state.conf.decision { config } else { return Ok(()); }; let rule = RuleRequest { tag: state.tenant.schema.clone(), expiry, variant: AuthRuleType::ApiKey { api_key, identifiers: Identifiers::ApiKey { merchant_id, key_id, }, }, }; call_decision_service(state, decision_config, rule, RULE_ADD_METHOD).await }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/types/storage/payment_attempt.rs<|crate|> router anchor=create_single_connection_test_transaction_pool kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/types/storage/payment_attempt.rs" role="context" start="139" end="156"> async fn create_single_connection_test_transaction_pool() -> routes::AppState { // Set pool size to 1 and minimum idle connection size to 0 std::env::set_var("ROUTER__MASTER_DATABASE__POOL_SIZE", "1"); std::env::set_var("ROUTER__MASTER_DATABASE__MIN_IDLE", "0"); std::env::set_var("ROUTER__REPLICA_DATABASE__POOL_SIZE", "1"); std::env::set_var("ROUTER__REPLICA_DATABASE__MIN_IDLE", "0"); let conf = Settings::new().expect("invalid settings"); let tx: oneshot::Sender<()> = oneshot::channel().0; let api_client = Box::new(services::MockApiClient); Box::pin(routes::AppState::with_storage( conf, StorageImpl::PostgresqlTest, tx, api_client, )) .await } <file_sep path="hyperswitch/crates/router/src/types/storage/payment_attempt.rs" role="context" start="243" end="335"> async fn test_find_payment_attempt() { let state = create_single_connection_test_transaction_pool().await; let current_time = common_utils::date_time::now(); let payment_id = common_utils::id_type::PaymentId::generate_test_payment_id_for_sample_data(); let attempt_id = Uuid::new_v4().to_string(); let merchant_id = common_utils::id_type::MerchantId::new_from_unix_timestamp(); let connector = types::Connector::DummyConnector1.to_string(); let payment_attempt = PaymentAttemptNew { payment_id: payment_id.clone(), merchant_id: merchant_id.clone(), connector: Some(connector), created_at: current_time.into(), modified_at: current_time.into(), attempt_id: attempt_id.clone(), status: Default::default(), net_amount: Default::default(), currency: Default::default(), save_to_locker: Default::default(), error_message: Default::default(), offer_amount: Default::default(), payment_method_id: Default::default(), payment_method: Default::default(), capture_method: Default::default(), capture_on: Default::default(), confirm: Default::default(), authentication_type: Default::default(), last_synced: Default::default(), cancellation_reason: Default::default(), amount_to_capture: Default::default(), mandate_id: Default::default(), browser_info: Default::default(), payment_token: Default::default(), error_code: Default::default(), connector_metadata: Default::default(), payment_experience: Default::default(), payment_method_type: Default::default(), payment_method_data: Default::default(), business_sub_label: Default::default(), straight_through_algorithm: Default::default(), preprocessing_step_id: Default::default(), mandate_details: Default::default(), error_reason: Default::default(), connector_response_reference_id: Default::default(), multiple_capture_count: Default::default(), amount_capturable: Default::default(), updated_by: Default::default(), authentication_data: Default::default(), encoded_data: Default::default(), merchant_connector_id: Default::default(), unified_code: Default::default(), unified_message: Default::default(), external_three_ds_authentication_attempted: Default::default(), authentication_connector: Default::default(), authentication_id: Default::default(), mandate_data: Default::default(), payment_method_billing_address_id: Default::default(), fingerprint_id: Default::default(), client_source: Default::default(), client_version: Default::default(), customer_acceptance: Default::default(), profile_id: common_utils::generate_profile_id_of_default_length(), organization_id: Default::default(), connector_mandate_detail: Default::default(), request_extended_authorization: Default::default(), extended_authorization_applied: Default::default(), capture_before: Default::default(), card_discovery: Default::default(), }; let store = state .stores .get(state.conf.multitenancy.get_tenant_ids().first().unwrap()) .unwrap(); store .insert_payment_attempt(payment_attempt, enums::MerchantStorageScheme::PostgresOnly) .await .unwrap(); let response = store .find_payment_attempt_by_payment_id_merchant_id_attempt_id( &payment_id, &merchant_id, &attempt_id, enums::MerchantStorageScheme::PostgresOnly, ) .await .unwrap(); eprintln!("{response:?}"); assert_eq!(response.payment_id, payment_id); } <file_sep path="hyperswitch/crates/router/src/types/storage/payment_attempt.rs" role="context" start="159" end="238"> async fn test_payment_attempt_insert() { let state = create_single_connection_test_transaction_pool().await; let payment_id = common_utils::id_type::PaymentId::generate_test_payment_id_for_sample_data(); let current_time = common_utils::date_time::now(); let connector = types::Connector::DummyConnector1.to_string(); let payment_attempt = PaymentAttemptNew { payment_id: payment_id.clone(), connector: Some(connector), created_at: current_time.into(), modified_at: current_time.into(), merchant_id: Default::default(), attempt_id: Default::default(), status: Default::default(), net_amount: Default::default(), currency: Default::default(), save_to_locker: Default::default(), error_message: Default::default(), offer_amount: Default::default(), payment_method_id: Default::default(), payment_method: Default::default(), capture_method: Default::default(), capture_on: Default::default(), confirm: Default::default(), authentication_type: Default::default(), last_synced: Default::default(), cancellation_reason: Default::default(), amount_to_capture: Default::default(), mandate_id: Default::default(), browser_info: Default::default(), payment_token: Default::default(), error_code: Default::default(), connector_metadata: Default::default(), payment_experience: Default::default(), payment_method_type: Default::default(), payment_method_data: Default::default(), business_sub_label: Default::default(), straight_through_algorithm: Default::default(), preprocessing_step_id: Default::default(), mandate_details: Default::default(), error_reason: Default::default(), connector_response_reference_id: Default::default(), multiple_capture_count: Default::default(), amount_capturable: Default::default(), updated_by: Default::default(), authentication_data: Default::default(), encoded_data: Default::default(), merchant_connector_id: Default::default(), unified_code: Default::default(), unified_message: Default::default(), external_three_ds_authentication_attempted: Default::default(), authentication_connector: Default::default(), authentication_id: Default::default(), mandate_data: Default::default(), payment_method_billing_address_id: Default::default(), fingerprint_id: Default::default(), client_source: Default::default(), client_version: Default::default(), customer_acceptance: Default::default(), profile_id: common_utils::generate_profile_id_of_default_length(), organization_id: Default::default(), connector_mandate_detail: Default::default(), request_extended_authorization: Default::default(), extended_authorization_applied: Default::default(), capture_before: Default::default(), card_discovery: Default::default(), }; let store = state .stores .get(state.conf.multitenancy.get_tenant_ids().first().unwrap()) .unwrap(); let response = store .insert_payment_attempt(payment_attempt, enums::MerchantStorageScheme::PostgresOnly) .await .unwrap(); eprintln!("{response:?}"); assert_eq!(response.payment_id, payment_id.clone()); } <file_sep path="hyperswitch/crates/router/src/types/storage/payment_attempt.rs" role="context" start="116" end="118"> fn maps_to_intent_status(self, intent_status: enums::IntentStatus) -> bool { enums::IntentStatus::foreign_from(self) == intent_status } <file_sep path="hyperswitch/crates/router/src/types/storage/payment_attempt.rs" role="context" start="106" end="108"> fn get_total_amount(&self) -> MinorUnit { todo!() } <file_sep path="hyperswitch/crates/router/src/routes/app.rs" role="context" start="212" end="232"> pub struct AppState { pub flow_name: String, pub global_store: Box<dyn GlobalStorageInterface>, // TODO: use a separate schema for accounts_store pub accounts_store: HashMap<id_type::TenantId, Box<dyn AccountsStorageInterface>>, pub stores: HashMap<id_type::TenantId, Box<dyn StorageInterface>>, pub conf: Arc<settings::Settings<RawSecret>>, pub event_handler: EventsHandler, #[cfg(feature = "email")] pub email_client: Arc<Box<dyn EmailService>>, pub api_client: Box<dyn crate::services::ApiClient>, #[cfg(feature = "olap")] pub pools: HashMap<id_type::TenantId, AnalyticsProvider>, #[cfg(feature = "olap")] pub opensearch_client: Option<Arc<OpenSearchClient>>, pub request_id: Option<RequestId>, pub file_storage_client: Arc<dyn FileStorageInterface>, pub encryption_client: Arc<dyn EncryptionManagementInterface>, pub grpc_client: Arc<GrpcClients>, pub theme_storage_client: Arc<dyn FileStorageInterface>, } <file_sep path="hyperswitch/crates/api_models/src/user/theme.rs" role="context" start="63" end="70"> struct Settings { colors: Colors, sidebar: Option<Sidebar>, typography: Option<Typography>, buttons: Buttons, borders: Option<Borders>, spacing: Option<Spacing>, }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/square.rs<|crate|> router<|connector|> square anchor=should_sync_auto_captured_payment kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="274" end="300"> async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment( payment_method_details(), get_default_payment_info(create_token().await), ) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), get_default_payment_info(None), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="273" end="273"> use router::types::{self, storage::enums, PaymentsResponseData}; <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="330" end="355"> async fn should_partially_refund_succeeded_payment() { let refund_response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(create_token().await), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(None), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="304" end="326"> async fn should_refund_auto_captured_payment() { let refund_response = CONNECTOR .make_payment_and_refund( payment_method_details(), None, get_default_payment_info(create_token().await), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(None), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="261" end="270"> async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment( payment_method_details(), get_default_payment_info(create_token().await), ) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="234" end="257"> async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(create_token().await), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(None), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="73" end="82"> async fn create_token() -> Option<String> { let token_response = CONNECTOR .create_connector_pm_token(token_details(), get_default_payment_info(None)) .await .expect("Authorize payment response"); match token_response.response.unwrap() { PaymentsResponseData::TokenizationResponse { token } => Some(token), _ => None, } } <file_sep path="hyperswitch/crates/router/tests/connectors/square.rs" role="context" start="39" end="52"> fn get_default_payment_info(payment_method_token: Option<String>) -> Option<utils::PaymentInfo> { Some(utils::PaymentInfo { address: None, auth_type: None, access_token: None, connector_meta_data: None, connector_customer: None, payment_method_token, #[cfg(feature = "payouts")] payout_method_data: None, #[cfg(feature = "payouts")] currency: None, }) }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/stax.rs<|crate|> router<|connector|> stax anchor=should_refund_manually_captured_payment kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="201" end="233"> async fn should_refund_manually_captured_payment() { let capture_response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), Some(types::PaymentsCaptureData { ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(None, create_customer_and_get_token().await), ) .await .expect("Capture payment response"); let refund_txn_id = utils::get_connector_transaction_id(capture_response.response.clone()).unwrap(); let refund_connector_meta = utils::get_connector_metadata(capture_response.response); let response = CONNECTOR .refund_payment( refund_txn_id, Some(types::RefundsData { connector_metadata: refund_connector_meta, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(None, None), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="200" end="200"> use router::types::{self, domain, storage::enums, PaymentsResponseData}; <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="273" end="314"> async fn should_sync_manually_captured_refund() { let capture_response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), Some(types::PaymentsCaptureData { ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(None, create_customer_and_get_token().await), ) .await .expect("Capture payment response"); let refund_txn_id = utils::get_connector_transaction_id(capture_response.response.clone()).unwrap(); let refund_connector_meta = utils::get_connector_metadata(capture_response.response); let refund_response = CONNECTOR .refund_payment( refund_txn_id, Some(types::RefundsData { connector_metadata: refund_connector_meta, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(None, None), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(None, None), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="237" end="269"> async fn should_partially_refund_manually_captured_payment() { let capture_response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), Some(types::PaymentsCaptureData { ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(None, create_customer_and_get_token().await), ) .await .expect("Capture payment response"); let refund_txn_id = utils::get_connector_transaction_id(capture_response.response.clone()).unwrap(); let refund_connector_meta = utils::get_connector_metadata(capture_response.response); let response = CONNECTOR .refund_payment( refund_txn_id, Some(types::RefundsData { refund_amount: 50, connector_metadata: refund_connector_meta, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(None, None), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="183" end="197"> async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_and_void_payment( payment_method_details(), Some(types::PaymentsCancelData { connector_transaction_id: String::from(""), cancellation_reason: Some("requested_by_customer".to_string()), ..Default::default() }), get_default_payment_info(None, create_customer_and_get_token().await), ) .await .expect("Void payment response"); assert_eq!(response.status, enums::AttemptStatus::Voided); } <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="156" end="179"> async fn should_sync_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment( payment_method_details(), get_default_payment_info(None, create_customer_and_get_token().await), ) .await .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() }), get_default_payment_info(None, None), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Authorized,); } <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="84" end="107"> async fn create_customer_and_get_token() -> Option<String> { let customer_response = CONNECTOR .create_connector_customer(customer_details(), get_default_payment_info(None, None)) .await .expect("Authorize payment response"); let connector_customer_id = match customer_response.response.unwrap() { PaymentsResponseData::ConnectorCustomerResponse { connector_customer_id, } => Some(connector_customer_id), _ => None, }; let token_response = CONNECTOR .create_connector_pm_token( token_details(), get_default_payment_info(connector_customer_id, None), ) .await .expect("Authorize payment response"); match token_response.response.unwrap() { PaymentsResponseData::TokenizationResponse { token } => Some(token), _ => None, } } <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="78" end="82"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { ..utils::PaymentAuthorizeType::default().0 }) } <file_sep path="hyperswitch/crates/router/src/connector/dummyconnector/transformers.rs" role="context" start="304" end="309"> pub enum RefundStatus { Succeeded, Failed, #[default] Processing, } <file_sep path="hyperswitch/migrations/2023-07-07-091223_create_captures_table/up.sql" role="context" start="1" end="17"> CREATE TYPE "CaptureStatus" AS ENUM ( 'started', 'charged', 'pending', 'failed' ); ALTER TYPE "IntentStatus" ADD VALUE If NOT EXISTS 'partially_captured' AFTER 'requires_capture'; CREATE TABLE captures( capture_id VARCHAR(64) NOT NULL PRIMARY KEY, payment_id VARCHAR(64) NOT NULL, merchant_id VARCHAR(64) NOT NULL, status "CaptureStatus" NOT NULL, amount BIGINT NOT NULL, currency "Currency", connector VARCHAR(255), error_message VARCHAR(255), <file_sep path="hyperswitch/crates/api_models/src/refunds.rs" role="context" start="378" end="384"> pub enum RefundStatus { Succeeded, Failed, #[default] Pending, Review, }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/stax.rs<|crate|> router<|connector|> stax anchor=should_sync_auto_captured_payment kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="331" end="357"> async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment( payment_method_details(), get_default_payment_info(None, create_customer_and_get_token().await), ) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), get_default_payment_info(None, None), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="330" end="330"> use router::types::{self, domain, storage::enums, PaymentsResponseData}; <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="378" end="394"> async fn should_partially_refund_succeeded_payment() { let refund_response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(None, create_customer_and_get_token().await), ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="361" end="374"> async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund( payment_method_details(), None, get_default_payment_info(None, create_customer_and_get_token().await), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="318" end="327"> async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment( payment_method_details(), get_default_payment_info(None, create_customer_and_get_token().await), ) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="273" end="314"> async fn should_sync_manually_captured_refund() { let capture_response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), Some(types::PaymentsCaptureData { ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(None, create_customer_and_get_token().await), ) .await .expect("Capture payment response"); let refund_txn_id = utils::get_connector_transaction_id(capture_response.response.clone()).unwrap(); let refund_connector_meta = utils::get_connector_metadata(capture_response.response); let refund_response = CONNECTOR .refund_payment( refund_txn_id, Some(types::RefundsData { connector_metadata: refund_connector_meta, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(None, None), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(None, None), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="84" end="107"> async fn create_customer_and_get_token() -> Option<String> { let customer_response = CONNECTOR .create_connector_customer(customer_details(), get_default_payment_info(None, None)) .await .expect("Authorize payment response"); let connector_customer_id = match customer_response.response.unwrap() { PaymentsResponseData::ConnectorCustomerResponse { connector_customer_id, } => Some(connector_customer_id), _ => None, }; let token_response = CONNECTOR .create_connector_pm_token( token_details(), get_default_payment_info(connector_customer_id, None), ) .await .expect("Authorize payment response"); match token_response.response.unwrap() { PaymentsResponseData::TokenizationResponse { token } => Some(token), _ => None, } } <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="78" end="82"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { ..utils::PaymentAuthorizeType::default().0 }) }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/db/locker_mock_up.rs<|crate|> router anchor=create_locker_mock_up_new kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/src/db/locker_mock_up.rs" role="context" start="146" end="163"> fn create_locker_mock_up_new(locker_ids: LockerMockUpIds) -> storage::LockerMockUpNew { storage::LockerMockUpNew { card_id: locker_ids.card_id, external_id: locker_ids.external_id, card_fingerprint: "card_fingerprint".into(), card_global_fingerprint: "card_global_fingerprint".into(), merchant_id: locker_ids.merchant_id, card_number: "1234123412341234".into(), card_exp_year: "2023".into(), card_exp_month: "06".into(), name_on_card: Some("name_on_card".into()), card_cvc: Some("123".into()), payment_method_id: Some("payment_method_id".into()), customer_id: Some(locker_ids.customer_id), nickname: Some("card_holder_nickname".into()), enc_card_data: Some("enc_card_data".into()), } } <file_sep path="hyperswitch/crates/router/src/db/locker_mock_up.rs" role="context" start="145" end="145"> use crate::{ connection, core::errors::{self, CustomResult}, types::storage, }; <file_sep path="hyperswitch/crates/router/src/db/locker_mock_up.rs" role="context" start="197" end="224"> async fn insert_locker_mock_up() { #[allow(clippy::expect_used)] let mockdb = MockDb::new(&redis_interface::RedisSettings::default()) .await .expect("Failed to create Mock store"); let created_locker = mockdb .insert_locker_mock_up(create_locker_mock_up_new(LockerMockUpIds { card_id: "card_1".into(), external_id: "external_1".into(), merchant_id: id_type::MerchantId::default(), customer_id: generate_customer_id_of_default_length(), })) .await .unwrap(); let found_locker = mockdb .lockers .lock() .await .iter() .find(|l| l.card_id == "card_1") .cloned(); assert!(found_locker.is_some()); assert_eq!(created_locker, found_locker.unwrap()) } <file_sep path="hyperswitch/crates/router/src/db/locker_mock_up.rs" role="context" start="166" end="194"> async fn find_locker_by_card_id() { #[allow(clippy::expect_used)] let mockdb = MockDb::new(&redis_interface::RedisSettings::default()) .await .expect("Failed to create Mock store"); let created_locker = mockdb .insert_locker_mock_up(create_locker_mock_up_new(LockerMockUpIds { card_id: "card_1".into(), external_id: "external_1".into(), merchant_id: id_type::MerchantId::default(), customer_id: generate_customer_id_of_default_length(), })) .await .unwrap(); let _ = mockdb .insert_locker_mock_up(create_locker_mock_up_new(LockerMockUpIds { card_id: "card_2".into(), external_id: "external_1".into(), merchant_id: id_type::MerchantId::default(), customer_id: generate_customer_id_of_default_length(), })) .await; let found_locker = mockdb.find_locker_by_card_id("card_1").await.unwrap(); assert_eq!(created_locker, found_locker) } <file_sep path="hyperswitch/crates/router/src/db/locker_mock_up.rs" role="context" start="113" end="125"> async fn delete_locker_mock_up( &self, card_id: &str, ) -> CustomResult<storage::LockerMockUp, errors::StorageError> { let mut locked_lockers = self.lockers.lock().await; let position = locked_lockers .iter() .position(|l| l.card_id == card_id) .ok_or(errors::StorageError::MockDbError)?; Ok(locked_lockers.remove(position)) } <file_sep path="hyperswitch/crates/router/src/db/locker_mock_up.rs" role="context" start="80" end="111"> async fn insert_locker_mock_up( &self, new: storage::LockerMockUpNew, ) -> CustomResult<storage::LockerMockUp, errors::StorageError> { let mut locked_lockers = self.lockers.lock().await; if locked_lockers.iter().any(|l| l.card_id == new.card_id) { Err(errors::StorageError::MockDbError)?; } let created_locker = storage::LockerMockUp { card_id: new.card_id, external_id: new.external_id, card_fingerprint: new.card_fingerprint, card_global_fingerprint: new.card_global_fingerprint, merchant_id: new.merchant_id, card_number: new.card_number, card_exp_year: new.card_exp_year, card_exp_month: new.card_exp_month, name_on_card: new.name_on_card, nickname: None, customer_id: new.customer_id, duplicate: None, card_cvc: new.card_cvc, payment_method_id: new.payment_method_id, enc_card_data: new.enc_card_data, }; locked_lockers.push(created_locker.clone()); Ok(created_locker) } <file_sep path="hyperswitch/crates/router/src/db/locker_mock_up.rs" role="context" start="227" end="255"> async fn delete_locker_mock_up() { #[allow(clippy::expect_used)] let mockdb = MockDb::new(&redis_interface::RedisSettings::default()) .await .expect("Failed to create Mock store"); let created_locker = mockdb .insert_locker_mock_up(create_locker_mock_up_new(LockerMockUpIds { card_id: "card_1".into(), external_id: "external_1".into(), merchant_id: id_type::MerchantId::default(), customer_id: generate_customer_id_of_default_length(), })) .await .unwrap(); let deleted_locker = mockdb.delete_locker_mock_up("card_1").await.unwrap(); assert_eq!(created_locker, deleted_locker); let exist = mockdb .lockers .lock() .await .iter() .any(|l| l.card_id == "card_1"); assert!(!exist) } <file_sep path="hyperswitch/crates/router/src/db/locker_mock_up.rs" role="context" start="139" end="144"> pub struct LockerMockUpIds { card_id: String, external_id: String, merchant_id: id_type::MerchantId, customer_id: id_type::CustomerId, }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/stax.rs<|crate|> router<|connector|> stax anchor=should_partially_refund_manually_captured_payment kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="237" end="269"> async fn should_partially_refund_manually_captured_payment() { let capture_response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), Some(types::PaymentsCaptureData { ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(None, create_customer_and_get_token().await), ) .await .expect("Capture payment response"); let refund_txn_id = utils::get_connector_transaction_id(capture_response.response.clone()).unwrap(); let refund_connector_meta = utils::get_connector_metadata(capture_response.response); let response = CONNECTOR .refund_payment( refund_txn_id, Some(types::RefundsData { refund_amount: 50, connector_metadata: refund_connector_meta, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(None, None), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="236" end="236"> use router::types::{self, domain, storage::enums, PaymentsResponseData}; <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="318" end="327"> async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment( payment_method_details(), get_default_payment_info(None, create_customer_and_get_token().await), ) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="273" end="314"> async fn should_sync_manually_captured_refund() { let capture_response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), Some(types::PaymentsCaptureData { ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(None, create_customer_and_get_token().await), ) .await .expect("Capture payment response"); let refund_txn_id = utils::get_connector_transaction_id(capture_response.response.clone()).unwrap(); let refund_connector_meta = utils::get_connector_metadata(capture_response.response); let refund_response = CONNECTOR .refund_payment( refund_txn_id, Some(types::RefundsData { connector_metadata: refund_connector_meta, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(None, None), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(None, None), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="201" end="233"> async fn should_refund_manually_captured_payment() { let capture_response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), Some(types::PaymentsCaptureData { ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(None, create_customer_and_get_token().await), ) .await .expect("Capture payment response"); let refund_txn_id = utils::get_connector_transaction_id(capture_response.response.clone()).unwrap(); let refund_connector_meta = utils::get_connector_metadata(capture_response.response); let response = CONNECTOR .refund_payment( refund_txn_id, Some(types::RefundsData { connector_metadata: refund_connector_meta, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(None, None), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="183" end="197"> async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_and_void_payment( payment_method_details(), Some(types::PaymentsCancelData { connector_transaction_id: String::from(""), cancellation_reason: Some("requested_by_customer".to_string()), ..Default::default() }), get_default_payment_info(None, create_customer_and_get_token().await), ) .await .expect("Void payment response"); assert_eq!(response.status, enums::AttemptStatus::Voided); } <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="84" end="107"> async fn create_customer_and_get_token() -> Option<String> { let customer_response = CONNECTOR .create_connector_customer(customer_details(), get_default_payment_info(None, None)) .await .expect("Authorize payment response"); let connector_customer_id = match customer_response.response.unwrap() { PaymentsResponseData::ConnectorCustomerResponse { connector_customer_id, } => Some(connector_customer_id), _ => None, }; let token_response = CONNECTOR .create_connector_pm_token( token_details(), get_default_payment_info(connector_customer_id, None), ) .await .expect("Authorize payment response"); match token_response.response.unwrap() { PaymentsResponseData::TokenizationResponse { token } => Some(token), _ => None, } } <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="78" end="82"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { ..utils::PaymentAuthorizeType::default().0 }) } <file_sep path="hyperswitch/crates/router/src/connector/dummyconnector/transformers.rs" role="context" start="304" end="309"> pub enum RefundStatus { Succeeded, Failed, #[default] Processing, } <file_sep path="hyperswitch/migrations/2023-07-07-091223_create_captures_table/up.sql" role="context" start="1" end="17"> CREATE TYPE "CaptureStatus" AS ENUM ( 'started', 'charged', 'pending', 'failed' ); ALTER TYPE "IntentStatus" ADD VALUE If NOT EXISTS 'partially_captured' AFTER 'requires_capture'; CREATE TABLE captures( capture_id VARCHAR(64) NOT NULL PRIMARY KEY, payment_id VARCHAR(64) NOT NULL, merchant_id VARCHAR(64) NOT NULL, status "CaptureStatus" NOT NULL, amount BIGINT NOT NULL, currency "Currency", connector VARCHAR(255), error_message VARCHAR(255), <file_sep path="hyperswitch/crates/api_models/src/refunds.rs" role="context" start="378" end="384"> pub enum RefundStatus { Succeeded, Failed, #[default] Pending, Review, }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/utils.rs<|crate|> router anchor=collect_values_by_removing_signature kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/connector/utils.rs" role="context" start="2163" end="2190"> pub fn collect_values_by_removing_signature( value: &serde_json::Value, signature: &String, ) -> Vec<String> { match value { serde_json::Value::Null => vec!["null".to_owned()], serde_json::Value::Bool(b) => vec![b.to_string()], serde_json::Value::Number(n) => match n.as_f64() { Some(f) => vec![format!("{f:.2}")], None => vec![n.to_string()], }, serde_json::Value::String(s) => { if signature == s { vec![] } else { vec![s.clone()] } } serde_json::Value::Array(arr) => arr .iter() .flat_map(|v| collect_values_by_removing_signature(v, signature)) .collect(), serde_json::Value::Object(obj) => obj .values() .flat_map(|v| collect_values_by_removing_signature(v, signature)) .collect(), } } <file_sep path="hyperswitch/crates/router/src/connector/utils.rs" role="context" start="2202" end="2204"> pub fn get_webhook_merchant_secret_key(connector_label: &str, merchant_id: &str) -> String { format!("whsec_verification_{connector_label}_{merchant_id}") } <file_sep path="hyperswitch/crates/router/src/connector/utils.rs" role="context" start="2192" end="2199"> pub fn collect_and_sort_values_by_removing_signature( value: &serde_json::Value, signature: &String, ) -> Vec<String> { let mut values = collect_values_by_removing_signature(value, signature); values.sort(); values } <file_sep path="hyperswitch/crates/router/src/connector/utils.rs" role="context" start="2153" end="2161"> pub fn str_to_f32<S>(value: &str, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let float_value = value.parse::<f64>().map_err(|_| { serde::ser::Error::custom("Invalid string, cannot be converted to float value") })?; serializer.serialize_f64(float_value) } <file_sep path="hyperswitch/crates/router/src/connector/utils.rs" role="context" start="2144" end="2151"> pub fn to_currency_base_unit_asf64( amount: i64, currency: enums::Currency, ) -> Result<f64, error_stack::Report<errors::ConnectorError>> { currency .to_currency_base_unit_asf64(amount) .change_context(errors::ConnectorError::ParsingFailed) } <file_sep path="hyperswitch/crates/router/src/core/utils.rs" role="context" start="651" end="653"> struct Object { profile_id: Option<common_utils::id_type::ProfileId>, } <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="1670" end="1670"> type Value = PaymentMethodListRequest;
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/stax.rs<|crate|> router<|connector|> stax anchor=should_refund_succeeded_payment_multiple_times kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="398" end="429"> async fn should_refund_succeeded_payment_multiple_times() { let payment_method_token = create_customer_and_get_token().await; let response = CONNECTOR .make_payment( payment_method_details(), get_default_payment_info(None, payment_method_token.clone()), ) .await .unwrap(); //try refund for previous payment let transaction_id = utils::get_connector_transaction_id(response.response).unwrap(); for _x in 0..2 { tokio::time::sleep(Duration::from_secs(60)).await; // to avoid 404 error let refund_response = CONNECTOR .refund_payment( transaction_id.clone(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(None, payment_method_token.clone()), ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } } <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="397" end="397"> use std::{str::FromStr, time::Duration}; use router::types::{self, domain, storage::enums, PaymentsResponseData}; <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="460" end="494"> async fn should_fail_payment_for_incorrect_cvc() { let customer_response = CONNECTOR .create_connector_customer(customer_details(), get_default_payment_info(None, None)) .await .expect("Authorize payment response"); let connector_customer_id = match customer_response.response.unwrap() { PaymentsResponseData::ConnectorCustomerResponse { connector_customer_id, } => Some(connector_customer_id), _ => None, }; let token_response = CONNECTOR .create_connector_pm_token( Some(types::PaymentMethodTokenizationData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("4111111111111111").unwrap(), card_exp_month: Secret::new("11".to_string()), card_exp_year: Secret::new("2027".to_string()), card_cvc: Secret::new("123456".to_string()), ..utils::CCardType::default().0 }), browser_info: None, amount: None, currency: enums::Currency::USD, }), get_default_payment_info(connector_customer_id, None), ) .await .expect("Authorize payment response"); assert_eq!( token_response.response.unwrap_err().reason, Some(r#"{"card_cvv":["The card cvv may not be greater than 99999."]}"#.to_string()), ); } <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="433" end="455"> async fn should_sync_refund() { let refund_response = CONNECTOR .make_payment_and_refund( payment_method_details(), None, get_default_payment_info(None, create_customer_and_get_token().await), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(None, None), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="378" end="394"> async fn should_partially_refund_succeeded_payment() { let refund_response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(None, create_customer_and_get_token().await), ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="361" end="374"> async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund( payment_method_details(), None, get_default_payment_info(None, create_customer_and_get_token().await), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="78" end="82"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { ..utils::PaymentAuthorizeType::default().0 }) } <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="39" end="55"> fn get_default_payment_info( connector_customer: Option<String>, payment_method_token: Option<String>, ) -> Option<utils::PaymentInfo> { Some(utils::PaymentInfo { address: None, auth_type: None, access_token: None, connector_meta_data: None, connector_customer, payment_method_token, #[cfg(feature = "payouts")] payout_method_data: None, #[cfg(feature = "payouts")] currency: None, }) } <file_sep path="hyperswitch/crates/router/src/connector/dummyconnector/transformers.rs" role="context" start="304" end="309"> pub enum RefundStatus { Succeeded, Failed, #[default] Processing, } <file_sep path="hyperswitch/crates/api_models/src/refunds.rs" role="context" start="378" end="384"> pub enum RefundStatus { Succeeded, Failed, #[default] Pending, Review, }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/bitpay.rs<|crate|> router<|connector|> bitpay anchor=get_default_payment_info kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/bitpay.rs" role="context" start="40" end="66"> fn get_default_payment_info() -> Option<utils::PaymentInfo> { Some(utils::PaymentInfo { address: Some(PaymentAddress::new( None, Some(Address { address: Some(AddressDetails { first_name: Some(Secret::new("first".to_string())), last_name: Some(Secret::new("last".to_string())), line1: Some(Secret::new("line1".to_string())), line2: Some(Secret::new("line2".to_string())), city: Some("city".to_string()), zip: Some(Secret::new("zip".to_string())), country: Some(api_models::enums::CountryAlpha2::IN), ..Default::default() }), phone: Some(PhoneDetails { number: Some(Secret::new("9123456789".to_string())), country_code: Some("+91".to_string()), }), email: None, }), None, None, )), ..Default::default() }) } <file_sep path="hyperswitch/crates/router/tests/connectors/bitpay.rs" role="context" start="39" end="39"> use hyperswitch_domain_models::address::{Address, AddressDetails, PhoneDetails}; use masking::Secret; use router::types::{self, api, domain, storage::enums, PaymentAddress}; <file_sep path="hyperswitch/crates/router/tests/connectors/bitpay.rs" role="context" start="110" end="124"> async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); let resp = response.clone().response.ok().unwrap(); assert_eq!(response.status, enums::AttemptStatus::AuthenticationPending); let endpoint = match resp { types::PaymentsResponseData::TransactionResponse { redirection_data, .. } => Some(redirection_data), _ => None, }; assert!(endpoint.is_some()) } <file_sep path="hyperswitch/crates/router/tests/connectors/bitpay.rs" role="context" start="68" end="106"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { amount: 1, currency: enums::Currency::USD, payment_method_data: domain::PaymentMethodData::Crypto(domain::CryptoData { pay_currency: None, network: None, }), confirm: true, statement_descriptor_suffix: None, statement_descriptor: None, setup_future_usage: None, mandate_id: None, off_session: None, setup_mandate_details: None, // capture_method: Some(capture_method), browser_info: None, order_details: None, order_category: None, email: None, customer_name: None, payment_experience: None, payment_method_type: None, session_token: None, enrolled_for_3ds: false, related_transaction_id: None, router_return_url: Some(String::from("https://google.com/")), webhook_url: Some(String::from("https://google.com/")), complete_authorize_url: None, capture_method: None, customer_id: None, surcharge_details: None, request_incremental_authorization: false, metadata: None, authentication_data: None, customer_acceptance: None, ..utils::PaymentAuthorizeType::default().0 }) } <file_sep path="hyperswitch/crates/router/tests/connectors/bitpay.rs" role="context" start="33" end="35"> fn get_name(&self) -> String { "bitpay".to_string() } <file_sep path="hyperswitch/crates/router/tests/connectors/bitpay.rs" role="context" start="24" end="31"> fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .bitpay .expect("Missing connector authentication configuration") .into(), ) } <file_sep path="hyperswitch/crates/router/tests/connectors/bitpay.rs" role="context" start="128" end="143"> async fn should_sync_authorized_payment() { let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( "NPf27TDfyU5mhcTCw2oaq4".to_string(), ), ..Default::default() }), get_default_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } <file_sep path="hyperswitch/crates/router/tests/macros.rs" role="context" start="17" end="21"> struct Address { line1: String, zip: String, city: String, } <file_sep path="hyperswitch/migrations/2025-02-06-111828_drop_int_id_column_accross_database/up.sql" role="context" start="20" end="36"> ------------------------ Payment Attempt ----------------------- ALTER TABLE payment_attempt DROP COLUMN id; ------------------------ Payment Methods ----------------------- ALTER TABLE payment_methods DROP COLUMN IF EXISTS id; ------------------------ Address ----------------------- ALTER TABLE address DROP COLUMN IF EXISTS id; ------------------------ Dispute ----------------------- ALTER TABLE dispute DROP COLUMN IF EXISTS id; ------------------------ Mandate ----------------------- ALTER TABLE mandate DROP COLUMN IF EXISTS id; ------------------------ Refund -----------------------
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/cryptopay.rs<|crate|> router<|connector|> cryptopay anchor=get_default_payment_info kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/cryptopay.rs" role="context" start="40" end="66"> fn get_default_payment_info() -> Option<utils::PaymentInfo> { Some(utils::PaymentInfo { address: Some(PaymentAddress::new( None, Some(Address { address: Some(AddressDetails { first_name: Some(Secret::new("first".to_string())), last_name: Some(Secret::new("last".to_string())), line1: Some(Secret::new("line1".to_string())), line2: Some(Secret::new("line2".to_string())), city: Some("city".to_string()), zip: Some(Secret::new("zip".to_string())), country: Some(api_models::enums::CountryAlpha2::IN), ..Default::default() }), phone: Some(PhoneDetails { number: Some(Secret::new("9123456789".to_string())), country_code: Some("+91".to_string()), }), email: None, }), None, None, )), ..Default::default() }) } <file_sep path="hyperswitch/crates/router/tests/connectors/cryptopay.rs" role="context" start="39" end="39"> use hyperswitch_domain_models::address::{Address, AddressDetails, PhoneDetails}; use masking::Secret; use router::types::{self, api, domain, storage::enums, PaymentAddress}; <file_sep path="hyperswitch/crates/router/tests/connectors/cryptopay.rs" role="context" start="109" end="123"> async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::AuthenticationPending); let resp = response.response.ok().unwrap(); let endpoint = match resp { types::PaymentsResponseData::TransactionResponse { redirection_data, .. } => Some(redirection_data), _ => None, }; assert!(endpoint.is_some()) } <file_sep path="hyperswitch/crates/router/tests/connectors/cryptopay.rs" role="context" start="68" end="105"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { amount: 1, currency: enums::Currency::USD, payment_method_data: domain::PaymentMethodData::Crypto(domain::CryptoData { pay_currency: Some("XRP".to_string()), network: None, }), confirm: true, statement_descriptor_suffix: None, statement_descriptor: None, setup_future_usage: None, mandate_id: None, off_session: None, setup_mandate_details: None, browser_info: None, order_details: None, order_category: None, email: None, customer_name: None, payment_experience: None, payment_method_type: None, session_token: None, enrolled_for_3ds: false, related_transaction_id: None, router_return_url: Some(String::from("https://google.com/")), webhook_url: None, complete_authorize_url: None, capture_method: None, customer_id: None, surcharge_details: None, request_incremental_authorization: false, metadata: None, authentication_data: None, customer_acceptance: None, ..utils::PaymentAuthorizeType::default().0 }) } <file_sep path="hyperswitch/crates/router/tests/connectors/cryptopay.rs" role="context" start="33" end="35"> fn get_name(&self) -> String { "cryptopay".to_string() } <file_sep path="hyperswitch/crates/router/tests/connectors/cryptopay.rs" role="context" start="24" end="31"> fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .cryptopay .expect("Missing connector authentication configuration") .into(), ) } <file_sep path="hyperswitch/crates/router/tests/connectors/cryptopay.rs" role="context" start="146" end="161"> async fn should_sync_unresolved_payment() { let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( "7993d4c2-efbc-4360-b8ce-d1e957e6f827".to_string(), ), ..Default::default() }), get_default_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Unresolved); } <file_sep path="hyperswitch/crates/router/tests/macros.rs" role="context" start="17" end="21"> struct Address { line1: String, zip: String, city: String, } <file_sep path="hyperswitch/migrations/2025-02-06-111828_drop_int_id_column_accross_database/up.sql" role="context" start="20" end="36"> ------------------------ Payment Attempt ----------------------- ALTER TABLE payment_attempt DROP COLUMN id; ------------------------ Payment Methods ----------------------- ALTER TABLE payment_methods DROP COLUMN IF EXISTS id; ------------------------ Address ----------------------- ALTER TABLE address DROP COLUMN IF EXISTS id; ------------------------ Dispute ----------------------- ALTER TABLE dispute DROP COLUMN IF EXISTS id; ------------------------ Mandate ----------------------- ALTER TABLE mandate DROP COLUMN IF EXISTS id; ------------------------ Refund -----------------------
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/netcetera.rs<|crate|> router anchor=build_request kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/connector/netcetera.rs" role="context" start="389" end="418"> fn build_request( &self, req: &types::authentication::ConnectorAuthenticationRouterData, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { let netcetera_auth_type = netcetera::NetceteraAuthType::try_from(&req.connector_auth_type)?; Ok(Some( services::RequestBuilder::new() .method(services::Method::Post) .url( &types::authentication::ConnectorAuthenticationType::get_url( self, req, connectors, )?, ) .attach_default_headers() .headers( types::authentication::ConnectorAuthenticationType::get_headers( self, req, connectors, )?, ) .set_body( types::authentication::ConnectorAuthenticationType::get_request_body( self, req, connectors, )?, ) .add_certificate(Some(netcetera_auth_type.certificate)) .add_certificate_key(Some(netcetera_auth_type.private_key)) .build(), )) } <file_sep path="hyperswitch/crates/router/src/connector/netcetera.rs" role="context" start="388" end="388"> use hyperswitch_interfaces::authentication::ExternalAuthenticationPayload; use transformers as netcetera; use crate::{ configs::settings, core::errors::{self, CustomResult}, events::connector_api_logs::ConnectorEvent, headers, services::{self, request, ConnectorIntegration, ConnectorSpecifications, ConnectorValidation}, types::{ self, api::{self, ConnectorCommon, ConnectorCommonExt}, ErrorResponse, Response, }, utils::BytesExt, }; <file_sep path="hyperswitch/crates/router/src/connector/netcetera.rs" role="context" start="442" end="448"> fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } <file_sep path="hyperswitch/crates/router/src/connector/netcetera.rs" role="context" start="420" end="440"> fn handle_response( &self, data: &types::authentication::ConnectorAuthenticationRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult< types::authentication::ConnectorAuthenticationRouterData, errors::ConnectorError, > { let response: netcetera::NetceteraAuthenticationResponse = res .response .parse_struct("NetceteraAuthenticationResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } <file_sep path="hyperswitch/crates/router/src/connector/netcetera.rs" role="context" start="366" end="387"> fn get_request_body( &self, req: &types::authentication::ConnectorAuthenticationRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_router_data = netcetera::NetceteraRouterData::try_from(( &self.get_currency_unit(), req.request .currency .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "currency", })?, req.request .amount .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "amount", })?, req, ))?; let req_obj = netcetera::NetceteraAuthenticationRequest::try_from(&connector_router_data); Ok(RequestContent::Json(Box::new(req_obj?))) } <file_sep path="hyperswitch/crates/router/src/connector/netcetera.rs" role="context" start="357" end="364"> fn get_url( &self, req: &types::authentication::ConnectorAuthenticationRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { let base_url = build_endpoint(self.base_url(connectors), &req.connector_meta_data)?; Ok(format!("{}/3ds/authentication", base_url,)) } <file_sep path="hyperswitch/crates/router/src/core/relay.rs" role="context" start="97" end="97"> type Request = relay_api_models::RelayRefundRequestData;
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/services/authentication.rs<|crate|> router anchor=parse_jwt_payload kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="3267" end="3294"> pub async fn parse_jwt_payload<A, T>(headers: &HeaderMap, state: &A) -> RouterResult<T> where T: serde::de::DeserializeOwned, A: SessionStateInfo + Sync, { let cookie_token_result = get_cookie_from_header(headers).and_then(cookies::get_jwt_from_cookies); let auth_header_token_result = get_jwt_from_authorization_header(headers); let force_cookie = state.conf().user.force_cookies; logger::info!( user_agent = ?headers.get(headers::USER_AGENT), header_names = ?headers.keys().collect::<Vec<_>>(), is_token_equal = auth_header_token_result.as_deref().ok() == cookie_token_result.as_deref().ok(), cookie_error = ?cookie_token_result.as_ref().err(), token_error = ?auth_header_token_result.as_ref().err(), force_cookie, ); let final_token = if force_cookie { cookie_token_result? } else { auth_header_token_result?.to_owned() }; decode_jwt(&final_token, state).await } <file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="3266" end="3266"> use actix_web::http::header::HeaderMap; use router_env::logger; use serde::Serialize; use crate::{ core::{ api_keys, errors::{self, utils::StorageErrorExt, RouterResult}, }, headers, routes::app::SessionStateInfo, services::api, types::{domain, storage}, utils::OptionExt, }; pub type AuthenticationDataWithUserId = (AuthenticationData, String); <file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="3364" end="3430"> async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<(AuthenticationData, AuthenticationType)> { let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?; if payload.check_in_blacklist(state).await? { return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } authorization::check_tenant( payload.tenant_id.clone(), &state.session_state().tenant.tenant_id, )?; let profile_id = HeaderMapStruct::new(request_headers) .get_id_type_from_header::<id_type::ProfileId>(headers::X_PROFILE_ID)?; let role_info = authorization::get_role_info(state, &payload).await?; authorization::check_permission(self.permission, &role_info)?; let key_manager_state = &(&state.session_state()).into(); let key_store = state .store() .get_merchant_key_store_by_merchant_id( key_manager_state, &payload.merchant_id, &state.store().get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken) .attach_printable("Failed to fetch merchant key store for the merchant id")?; let profile = state .store() .find_business_profile_by_merchant_id_profile_id( key_manager_state, &key_store, &payload.merchant_id, &profile_id, ) .await .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; let merchant = state .store() .find_merchant_account_by_merchant_id( key_manager_state, &payload.merchant_id, &key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken) .attach_printable("Failed to fetch merchant account for the merchant id")?; let merchant_id = merchant.get_id().clone(); let auth = AuthenticationData { merchant_account: merchant, key_store, profile, platform_merchant_account: None, }; Ok(( auth, AuthenticationType::MerchantJwt { merchant_id, user_id: Some(payload.user_id), }, )) } <file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="3302" end="3355"> async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<(AuthenticationData, AuthenticationType)> { let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?; if payload.check_in_blacklist(state).await? { return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } authorization::check_tenant( payload.tenant_id.clone(), &state.session_state().tenant.tenant_id, )?; let role_info = authorization::get_role_info(state, &payload).await?; authorization::check_permission(self.permission, &role_info)?; let key_manager_state = &(&state.session_state()).into(); let key_store = state .store() .get_merchant_key_store_by_merchant_id( key_manager_state, &payload.merchant_id, &state.store().get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken) .attach_printable("Failed to fetch merchant key store for the merchant id")?; let merchant = state .store() .find_merchant_account_by_merchant_id( key_manager_state, &payload.merchant_id, &key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken) .attach_printable("Failed to fetch merchant account for the merchant id")?; let merchant_id = merchant.get_id().clone(); let auth = AuthenticationData { merchant_account: merchant, platform_merchant_account: None, key_store, profile_id: Some(payload.profile_id), }; Ok(( auth, AuthenticationType::MerchantJwt { merchant_id, user_id: Some(payload.user_id), }, )) } <file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="3202" end="3264"> async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<(AuthenticationData, AuthenticationType)> { let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?; if payload.check_in_blacklist(state).await? { return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } let profile_id = get_id_type_by_key_from_headers(headers::X_PROFILE_ID.to_string(), request_headers)? .get_required_value(headers::X_PROFILE_ID)?; let role_info = authorization::get_role_info(state, &payload).await?; authorization::check_permission(self.required_permission, &role_info)?; let key_manager_state = &(&state.session_state()).into(); let key_store = state .store() .get_merchant_key_store_by_merchant_id( key_manager_state, &payload.merchant_id, &state.store().get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken) .attach_printable("Failed to fetch merchant key store for the merchant id")?; let profile = state .store() .find_business_profile_by_merchant_id_profile_id( key_manager_state, &key_store, &payload.merchant_id, &profile_id, ) .await .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; let merchant = state .store() .find_merchant_account_by_merchant_id( key_manager_state, &payload.merchant_id, &key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken) .attach_printable("Failed to fetch merchant account for the merchant id")?; let auth = AuthenticationData { merchant_account: merchant, key_store, profile, platform_merchant_account: None, }; Ok(( auth.clone(), AuthenticationType::MerchantJwt { merchant_id: auth.merchant_account.get_id().clone(), user_id: Some(payload.user_id), }, )) } <file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="3135" end="3193"> async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<(AuthenticationData, AuthenticationType)> { let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?; if payload.check_in_blacklist(state).await? { return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } authorization::check_tenant( payload.tenant_id.clone(), &state.session_state().tenant.tenant_id, )?; let role_info = authorization::get_role_info(state, &payload).await?; authorization::check_permission(self.required_permission, &role_info)?; let key_manager_state = &(&state.session_state()).into(); let key_store = state .store() .get_merchant_key_store_by_merchant_id( key_manager_state, &payload.merchant_id, &state.store().get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken) .attach_printable("Failed to fetch merchant key store for the merchant id")?; let merchant = state .store() .find_merchant_account_by_merchant_id( key_manager_state, &payload.merchant_id, &key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken) .attach_printable("Failed to fetch merchant account for the merchant id")?; if payload.profile_id != self.profile_id { return Err(report!(errors::ApiErrorResponse::InvalidJwtToken)); } else { // if both of them are same then proceed with the profile id present in the request let auth = AuthenticationData { merchant_account: merchant, platform_merchant_account: None, key_store, profile_id: Some(self.profile_id.clone()), }; Ok(( auth.clone(), AuthenticationType::MerchantJwt { merchant_id: auth.merchant_account.get_id().clone(), user_id: Some(payload.user_id), }, )) } } <file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="3799" end="3810"> pub async fn decode_jwt<T>(token: &str, state: &impl SessionStateInfo) -> RouterResult<T> where T: serde::de::DeserializeOwned, { let conf = state.conf(); let secret = conf.secrets.get_inner().jwt_secret.peek().as_bytes(); let key = DecodingKey::from_secret(secret); decode::<T>(token, &key, &Validation::new(Algorithm::HS256)) .map(|decoded| decoded.claims) .change_context(errors::ApiErrorResponse::InvalidJwtToken) } <file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="3856" end="3864"> pub fn get_cookie_from_header(headers: &HeaderMap) -> RouterResult<&str> { let cookie = headers .get(cookies::get_cookie_header()) .ok_or(report!(errors::ApiErrorResponse::CookieNotFound))?; cookie .to_str() .change_context(errors::ApiErrorResponse::InvalidCookie) } <file_sep path="hyperswitch/crates/router/src/core/errors.rs" role="context" start="31" end="31"> pub type RouterResult<T> = CustomResult<T, ApiErrorResponse>;
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/netcetera.rs<|crate|> router anchor=build_request kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/src/connector/netcetera.rs" role="context" start="279" end="308"> fn build_request( &self, req: &types::authentication::PreAuthNRouterData, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { let netcetera_auth_type = netcetera::NetceteraAuthType::try_from(&req.connector_auth_type)?; Ok(Some( services::RequestBuilder::new() .method(services::Method::Post) .url( &types::authentication::ConnectorPreAuthenticationType::get_url( self, req, connectors, )?, ) .attach_default_headers() .headers( types::authentication::ConnectorPreAuthenticationType::get_headers( self, req, connectors, )?, ) .set_body( types::authentication::ConnectorPreAuthenticationType::get_request_body( self, req, connectors, )?, ) .add_certificate(Some(netcetera_auth_type.certificate)) .add_certificate_key(Some(netcetera_auth_type.private_key)) .build(), )) } <file_sep path="hyperswitch/crates/router/src/connector/netcetera.rs" role="context" start="278" end="278"> use hyperswitch_interfaces::authentication::ExternalAuthenticationPayload; use transformers as netcetera; use crate::{ configs::settings, core::errors::{self, CustomResult}, events::connector_api_logs::ConnectorEvent, headers, services::{self, request, ConnectorIntegration, ConnectorSpecifications, ConnectorValidation}, types::{ self, api::{self, ConnectorCommon, ConnectorCommonExt}, ErrorResponse, Response, }, utils::BytesExt, }; <file_sep path="hyperswitch/crates/router/src/connector/netcetera.rs" role="context" start="329" end="335"> fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } <file_sep path="hyperswitch/crates/router/src/connector/netcetera.rs" role="context" start="310" end="327"> fn handle_response( &self, data: &types::authentication::PreAuthNRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::authentication::PreAuthNRouterData, errors::ConnectorError> { let response: netcetera::NetceteraPreAuthenticationResponse = res .response .parse_struct("netcetera NetceteraPreAuthenticationResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } <file_sep path="hyperswitch/crates/router/src/connector/netcetera.rs" role="context" start="268" end="277"> fn get_request_body( &self, req: &types::authentication::PreAuthNRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_router_data = netcetera::NetceteraRouterData::try_from((0, req))?; let req_obj = netcetera::NetceteraPreAuthenticationRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(req_obj))) } <file_sep path="hyperswitch/crates/router/src/connector/netcetera.rs" role="context" start="259" end="266"> fn get_url( &self, req: &types::authentication::PreAuthNRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { let base_url = build_endpoint(self.base_url(connectors), &req.connector_meta_data)?; Ok(format!("{}/3ds/versioning", base_url,)) } <file_sep path="hyperswitch/crates/router/src/connector/netcetera.rs" role="context" start="366" end="387"> fn get_request_body( &self, req: &types::authentication::ConnectorAuthenticationRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_router_data = netcetera::NetceteraRouterData::try_from(( &self.get_currency_unit(), req.request .currency .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "currency", })?, req.request .amount .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "amount", })?, req, ))?; let req_obj = netcetera::NetceteraAuthenticationRequest::try_from(&connector_router_data); Ok(RequestContent::Json(Box::new(req_obj?))) } <file_sep path="hyperswitch/crates/router/src/connector/netcetera.rs" role="context" start="345" end="351"> fn get_headers( &self, req: &types::authentication::ConnectorAuthenticationRouterData, connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/services/authentication.rs<|crate|> router anchor=get_ephemeral_or_other_auth kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="3744" end="3774"> pub async fn get_ephemeral_or_other_auth<T>( headers: &HeaderMap, is_merchant_flow: bool, payload: Option<&impl ClientSecretFetch>, ) -> RouterResult<( Box<dyn AuthenticateAndFetch<AuthenticationData, T>>, api::AuthFlow, bool, )> where T: SessionStateInfo + Sync + Send, ApiKeyAuth: AuthenticateAndFetch<AuthenticationData, T>, PublishableKeyAuth: AuthenticateAndFetch<AuthenticationData, T>, EphemeralKeyAuth: AuthenticateAndFetch<AuthenticationData, T>, { let api_key = get_api_key(headers)?; if api_key.starts_with("epk") { Ok((Box::new(EphemeralKeyAuth), api::AuthFlow::Client, true)) } else if is_merchant_flow { Ok(( Box::new(HeaderAuth(ApiKeyAuth)), api::AuthFlow::Merchant, false, )) } else { let payload = payload.get_required_value("ClientSecretFetch")?; let (auth, auth_flow) = check_client_secret_and_get_auth(headers, payload)?; Ok((auth, auth_flow, false)) } } <file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="3743" end="3743"> use actix_web::http::header::HeaderMap; use crate::{ core::{ api_keys, errors::{self, utils::StorageErrorExt, RouterResult}, }, headers, routes::app::SessionStateInfo, services::api, types::{domain, storage}, utils::OptionExt, }; pub type AuthenticationDataWithUserId = (AuthenticationData, String); <file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="3789" end="3797"> pub fn is_jwt_auth(headers: &HeaderMap) -> bool { let header_map_struct = HeaderMapStruct::new(headers); match header_map_struct.get_auth_string_from_header() { Ok(auth_str) => auth_str.starts_with("Bearer"), Err(_) => get_cookie_from_header(headers) .and_then(cookies::get_jwt_from_cookies) .is_ok(), } } <file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="3777" end="3787"> pub fn is_ephemeral_auth<A: SessionStateInfo + Sync + Send>( headers: &HeaderMap, ) -> RouterResult<Box<dyn AuthenticateAndFetch<AuthenticationData, A>>> { let api_key = get_api_key(headers)?; if !api_key.starts_with("epk") { Ok(Box::new(HeaderAuth(ApiKeyAuth))) } else { Ok(Box::new(EphemeralKeyAuth)) } } <file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="3709" end="3742"> pub fn check_client_secret_and_get_auth<T>( headers: &HeaderMap, payload: &impl ClientSecretFetch, ) -> RouterResult<( Box<dyn AuthenticateAndFetch<AuthenticationData, T>>, api::AuthFlow, )> where T: SessionStateInfo + Sync + Send, ApiKeyAuth: AuthenticateAndFetch<AuthenticationData, T>, PublishableKeyAuth: AuthenticateAndFetch<AuthenticationData, T>, { let api_key = get_api_key(headers)?; if api_key.starts_with("pk_") { payload .get_client_secret() .check_value_present("client_secret") .map_err(|_| errors::ApiErrorResponse::MissingRequiredField { field_name: "client_secret", })?; return Ok(( Box::new(HeaderAuth(PublishableKeyAuth)), api::AuthFlow::Client, )); } if payload.get_client_secret().is_some() { return Err(errors::ApiErrorResponse::InvalidRequestData { message: "client_secret is not a valid parameter".to_owned(), } .into()); } Ok((Box::new(HeaderAuth(ApiKeyAuth)), api::AuthFlow::Merchant)) } <file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="3692" end="3707"> pub fn get_auth_type_and_flow<A: SessionStateInfo + Sync + Send>( headers: &HeaderMap, ) -> RouterResult<( Box<dyn AuthenticateAndFetch<AuthenticationData, A>>, api::AuthFlow, )> { let api_key = get_api_key(headers)?; if api_key.starts_with("pk_") { return Ok(( Box::new(HeaderAuth(PublishableKeyAuth)), api::AuthFlow::Client, )); } Ok((Box::new(HeaderAuth(ApiKeyAuth)), api::AuthFlow::Merchant)) } <file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="1506" end="1508"> pub fn new(headers: &'a HeaderMap) -> Self { HeaderMapStruct { headers } } <file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="3615" end="3617"> pub trait ClientSecretFetch { fn get_client_secret(&self) -> Option<&String>; } <file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="2273" end="2273"> pub struct PublishableKeyAuth; <file_sep path="hyperswitch/crates/router/src/services/api.rs" role="context" start="684" end="687"> pub enum AuthFlow { Client, Merchant, } <file_sep path="hyperswitch-card-vault/migrations/2023-10-21-104200_create-tables/up.sql" role="context" start="1" end="11"> -- Your SQL goes here CREATE TABLE merchant ( id SERIAL, tenant_id VARCHAR(255) NOT NULL, merchant_id VARCHAR(255) NOT NULL, enc_key BYTEA NOT NULL, created_at TIMESTAMP NOT NULL DEFAULT now()::TIMESTAMP, PRIMARY KEY (tenant_id, merchant_id) );
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/services/authentication.rs<|crate|> router anchor=check_client_secret_and_get_auth kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="3709" end="3742"> pub fn check_client_secret_and_get_auth<T>( headers: &HeaderMap, payload: &impl ClientSecretFetch, ) -> RouterResult<( Box<dyn AuthenticateAndFetch<AuthenticationData, T>>, api::AuthFlow, )> where T: SessionStateInfo + Sync + Send, ApiKeyAuth: AuthenticateAndFetch<AuthenticationData, T>, PublishableKeyAuth: AuthenticateAndFetch<AuthenticationData, T>, { let api_key = get_api_key(headers)?; if api_key.starts_with("pk_") { payload .get_client_secret() .check_value_present("client_secret") .map_err(|_| errors::ApiErrorResponse::MissingRequiredField { field_name: "client_secret", })?; return Ok(( Box::new(HeaderAuth(PublishableKeyAuth)), api::AuthFlow::Client, )); } if payload.get_client_secret().is_some() { return Err(errors::ApiErrorResponse::InvalidRequestData { message: "client_secret is not a valid parameter".to_owned(), } .into()); } Ok((Box::new(HeaderAuth(ApiKeyAuth)), api::AuthFlow::Merchant)) } <file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="3708" end="3708"> use actix_web::http::header::HeaderMap; use crate::core::errors::UserResult; use crate::{ core::{ api_keys, errors::{self, utils::StorageErrorExt, RouterResult}, }, headers, routes::app::SessionStateInfo, services::api, types::{domain, storage}, utils::OptionExt, }; pub type AuthenticationDataWithUserId = (AuthenticationData, String); <file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="3777" end="3787"> pub fn is_ephemeral_auth<A: SessionStateInfo + Sync + Send>( headers: &HeaderMap, ) -> RouterResult<Box<dyn AuthenticateAndFetch<AuthenticationData, A>>> { let api_key = get_api_key(headers)?; if !api_key.starts_with("epk") { Ok(Box::new(HeaderAuth(ApiKeyAuth))) } else { Ok(Box::new(EphemeralKeyAuth)) } } <file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="3744" end="3774"> pub async fn get_ephemeral_or_other_auth<T>( headers: &HeaderMap, is_merchant_flow: bool, payload: Option<&impl ClientSecretFetch>, ) -> RouterResult<( Box<dyn AuthenticateAndFetch<AuthenticationData, T>>, api::AuthFlow, bool, )> where T: SessionStateInfo + Sync + Send, ApiKeyAuth: AuthenticateAndFetch<AuthenticationData, T>, PublishableKeyAuth: AuthenticateAndFetch<AuthenticationData, T>, EphemeralKeyAuth: AuthenticateAndFetch<AuthenticationData, T>, { let api_key = get_api_key(headers)?; if api_key.starts_with("epk") { Ok((Box::new(EphemeralKeyAuth), api::AuthFlow::Client, true)) } else if is_merchant_flow { Ok(( Box::new(HeaderAuth(ApiKeyAuth)), api::AuthFlow::Merchant, false, )) } else { let payload = payload.get_required_value("ClientSecretFetch")?; let (auth, auth_flow) = check_client_secret_and_get_auth(headers, payload)?; Ok((auth, auth_flow, false)) } } <file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="3692" end="3707"> pub fn get_auth_type_and_flow<A: SessionStateInfo + Sync + Send>( headers: &HeaderMap, ) -> RouterResult<( Box<dyn AuthenticateAndFetch<AuthenticationData, A>>, api::AuthFlow, )> { let api_key = get_api_key(headers)?; if api_key.starts_with("pk_") { return Ok(( Box::new(HeaderAuth(PublishableKeyAuth)), api::AuthFlow::Client, )); } Ok((Box::new(HeaderAuth(ApiKeyAuth)), api::AuthFlow::Merchant)) } <file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="3687" end="3689"> fn get_client_secret(&self) -> Option<&String> { self.client_secret.as_ref() } <file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="1506" end="1508"> pub fn new(headers: &'a HeaderMap) -> Self { HeaderMapStruct { headers } } <file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="3812" end="3814"> pub fn get_api_key(headers: &HeaderMap) -> RouterResult<&str> { get_header_value_by_key("api-key".into(), headers)?.get_required_value("api_key") } <file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="3615" end="3617"> pub trait ClientSecretFetch { fn get_client_secret(&self) -> Option<&String>; } <file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="2273" end="2273"> pub struct PublishableKeyAuth; <file_sep path="hyperswitch/crates/router/src/services/api.rs" role="context" start="684" end="687"> pub enum AuthFlow { Client, Merchant, } <file_sep path="hyperswitch-card-vault/migrations/2023-10-21-104200_create-tables/up.sql" role="context" start="1" end="11"> -- Your SQL goes here CREATE TABLE merchant ( id SERIAL, tenant_id VARCHAR(255) NOT NULL, merchant_id VARCHAR(255) NOT NULL, enc_key BYTEA NOT NULL, created_at TIMESTAMP NOT NULL DEFAULT now()::TIMESTAMP, PRIMARY KEY (tenant_id, merchant_id) ); <file_sep path="hyperswitch/crates/api_models/src/errors/types.rs" role="context" start="86" end="100"> pub enum ApiErrorResponse { Unauthorized(ApiError), ForbiddenCommonResource(ApiError), ForbiddenPrivateResource(ApiError), Conflict(ApiError), Gone(ApiError), Unprocessable(ApiError), InternalServerError(ApiError), NotImplemented(ApiError), ConnectorError(ApiError, #[serde(skip_serializing)] StatusCode), NotFound(ApiError), MethodNotAllowed(ApiError), BadRequest(ApiError), DomainError(ApiError), }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/stax.rs<|crate|> router<|connector|> stax anchor=should_sync_manually_captured_refund kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="273" end="314"> async fn should_sync_manually_captured_refund() { let capture_response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), Some(types::PaymentsCaptureData { ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(None, create_customer_and_get_token().await), ) .await .expect("Capture payment response"); let refund_txn_id = utils::get_connector_transaction_id(capture_response.response.clone()).unwrap(); let refund_connector_meta = utils::get_connector_metadata(capture_response.response); let refund_response = CONNECTOR .refund_payment( refund_txn_id, Some(types::RefundsData { connector_metadata: refund_connector_meta, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(None, None), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(None, None), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="272" end="272"> use router::types::{self, domain, storage::enums, PaymentsResponseData}; <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="331" end="357"> async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment( payment_method_details(), get_default_payment_info(None, create_customer_and_get_token().await), ) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), get_default_payment_info(None, None), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="318" end="327"> async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment( payment_method_details(), get_default_payment_info(None, create_customer_and_get_token().await), ) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="237" end="269"> async fn should_partially_refund_manually_captured_payment() { let capture_response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), Some(types::PaymentsCaptureData { ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(None, create_customer_and_get_token().await), ) .await .expect("Capture payment response"); let refund_txn_id = utils::get_connector_transaction_id(capture_response.response.clone()).unwrap(); let refund_connector_meta = utils::get_connector_metadata(capture_response.response); let response = CONNECTOR .refund_payment( refund_txn_id, Some(types::RefundsData { refund_amount: 50, connector_metadata: refund_connector_meta, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(None, None), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="201" end="233"> async fn should_refund_manually_captured_payment() { let capture_response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), Some(types::PaymentsCaptureData { ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(None, create_customer_and_get_token().await), ) .await .expect("Capture payment response"); let refund_txn_id = utils::get_connector_transaction_id(capture_response.response.clone()).unwrap(); let refund_connector_meta = utils::get_connector_metadata(capture_response.response); let response = CONNECTOR .refund_payment( refund_txn_id, Some(types::RefundsData { connector_metadata: refund_connector_meta, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(None, None), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="84" end="107"> async fn create_customer_and_get_token() -> Option<String> { let customer_response = CONNECTOR .create_connector_customer(customer_details(), get_default_payment_info(None, None)) .await .expect("Authorize payment response"); let connector_customer_id = match customer_response.response.unwrap() { PaymentsResponseData::ConnectorCustomerResponse { connector_customer_id, } => Some(connector_customer_id), _ => None, }; let token_response = CONNECTOR .create_connector_pm_token( token_details(), get_default_payment_info(connector_customer_id, None), ) .await .expect("Authorize payment response"); match token_response.response.unwrap() { PaymentsResponseData::TokenizationResponse { token } => Some(token), _ => None, } } <file_sep path="hyperswitch/crates/router/tests/connectors/stax.rs" role="context" start="78" end="82"> fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { ..utils::PaymentAuthorizeType::default().0 }) } <file_sep path="hyperswitch/crates/router/src/connector/dummyconnector/transformers.rs" role="context" start="304" end="309"> pub enum RefundStatus { Succeeded, Failed, #[default] Processing, } <file_sep path="hyperswitch/migrations/2023-07-07-091223_create_captures_table/up.sql" role="context" start="1" end="17"> CREATE TYPE "CaptureStatus" AS ENUM ( 'started', 'charged', 'pending', 'failed' ); ALTER TYPE "IntentStatus" ADD VALUE If NOT EXISTS 'partially_captured' AFTER 'requires_capture'; CREATE TABLE captures( capture_id VARCHAR(64) NOT NULL PRIMARY KEY, payment_id VARCHAR(64) NOT NULL, merchant_id VARCHAR(64) NOT NULL, status "CaptureStatus" NOT NULL, amount BIGINT NOT NULL, currency "Currency", connector VARCHAR(255), error_message VARCHAR(255), <file_sep path="hyperswitch/crates/api_models/src/refunds.rs" role="context" start="378" end="384"> pub enum RefundStatus { Succeeded, Failed, #[default] Pending, Review, }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/tests/connectors/wise.rs<|crate|> router<|connector|> wise anchor=get_payout_info kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/tests/connectors/wise.rs" role="context" start="53" end="83"> fn get_payout_info() -> Option<PaymentInfo> { Some(PaymentInfo { currency: Some(enums::Currency::GBP), address: Some(PaymentAddress::new( None, Some(Address { address: Some(AddressDetails { country: Some(api_models::enums::CountryAlpha2::GB), city: Some("London".to_string()), zip: Some(Secret::new("10025".to_string())), line1: Some(Secret::new("50 Branson Ave".to_string())), ..Default::default() }), phone: None, email: None, }), None, None, )), payout_method_data: Some(api::PayoutMethodData::Bank(api::payouts::BankPayout::Bacs( api::BacsBankTransfer { bank_sort_code: "231470".to_string().into(), bank_account_number: "28821822".to_string().into(), bank_name: Some("Deutsche Bank".to_string()), bank_country_code: Some(enums::CountryAlpha2::NL), bank_city: Some("Amsterdam".to_string()), }, ))), ..Default::default() }) } <file_sep path="hyperswitch/crates/router/tests/connectors/wise.rs" role="context" start="52" end="52"> use hyperswitch_domain_models::address::{Address, AddressDetails}; use masking::Secret; use router::{ types, types::{api, storage::enums, PaymentAddress}, }; <file_sep path="hyperswitch/crates/router/tests/connectors/wise.rs" role="context" start="108" end="130"> async fn should_create_bacs_payout() { let payout_type = enums::PayoutType::Bank; let payout_info = WiseTest::get_payout_info(); // Create recipient let recipient_res = CONNECTOR .create_payout_recipient(payout_type.to_owned(), payout_info.to_owned()) .await .expect("Payout recipient response"); assert_eq!( recipient_res.status.unwrap(), enums::PayoutStatus::RequiresCreation ); // Create payout let create_res: types::PayoutsResponseData = CONNECTOR .create_payout(recipient_res.connector_payout_id, payout_type, payout_info) .await .expect("Payout bank creation response"); assert_eq!( create_res.status.unwrap(), enums::PayoutStatus::RequiresFulfillment ); } <file_sep path="hyperswitch/crates/router/tests/connectors/wise.rs" role="context" start="92" end="103"> async fn should_create_payout_recipient() { let payout_type = enums::PayoutType::Bank; let payment_info = WiseTest::get_payout_info(); let response = CONNECTOR .create_payout_recipient(payout_type, payment_info) .await .expect("Payout recipient creation response"); assert_eq!( response.status.unwrap(), enums::PayoutStatus::RequiresCreation ); } <file_sep path="hyperswitch/crates/router/tests/connectors/wise.rs" role="context" start="47" end="49"> fn get_name(&self) -> String { "wise".to_string() } <file_sep path="hyperswitch/crates/router/tests/connectors/wise.rs" role="context" start="38" end="45"> fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .wise .expect("Missing connector authentication configuration") .into(), ) } <file_sep path="hyperswitch/crates/router/tests/connectors/wise.rs" role="context" start="135" end="152"> async fn should_create_and_fulfill_bacs_payout() { let payout_type = enums::PayoutType::Bank; let payout_info = WiseTest::get_payout_info(); // Create recipient let recipient_res = CONNECTOR .create_payout_recipient(payout_type.to_owned(), payout_info.to_owned()) .await .expect("Payout recipient response"); assert_eq!( recipient_res.status.unwrap(), enums::PayoutStatus::RequiresCreation ); let response = CONNECTOR .create_and_fulfill_payout(recipient_res.connector_payout_id, payout_type, payout_info) .await .expect("Payout bank creation and fulfill response"); assert_eq!(response.status.unwrap(), enums::PayoutStatus::Success); } <file_sep path="hyperswitch/crates/router/tests/macros.rs" role="context" start="17" end="21"> struct Address { line1: String, zip: String, city: String, } <file_sep path="hyperswitch/migrations/2025-02-06-111828_drop_int_id_column_accross_database/up.sql" role="context" start="20" end="36"> ------------------------ Payment Attempt ----------------------- ALTER TABLE payment_attempt DROP COLUMN id; ------------------------ Payment Methods ----------------------- ALTER TABLE payment_methods DROP COLUMN IF EXISTS id; ------------------------ Address ----------------------- ALTER TABLE address DROP COLUMN IF EXISTS id; ------------------------ Dispute ----------------------- ALTER TABLE dispute DROP COLUMN IF EXISTS id; ------------------------ Mandate ----------------------- ALTER TABLE mandate DROP COLUMN IF EXISTS id; ------------------------ Refund -----------------------
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/services/authorization.rs<|crate|> router anchor=get_role_info kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/services/authorization.rs" role="context" start="21" end="58"> pub async fn get_role_info<A>(state: &A, token: &AuthToken) -> RouterResult<roles::RoleInfo> where A: SessionStateInfo + Sync, { if let Some(role_info) = roles::predefined_roles::PREDEFINED_ROLES.get(token.role_id.as_str()) { return Ok(role_info.clone()); } if let Ok(role_info) = get_role_info_from_cache(state, &token.role_id) .await .map_err(|e| logger::error!("Failed to get permissions from cache {e:?}")) { return Ok(role_info.clone()); } let role_info = get_role_info_from_db( state, &token.role_id, &token.org_id, token .tenant_id .as_ref() .unwrap_or(&state.session_state().tenant.tenant_id), ) .await?; let token_expiry = i64::try_from(token.exp).change_context(ApiErrorResponse::InternalServerError)?; let cache_ttl = token_expiry - common_utils::date_time::now_unix_timestamp(); if cache_ttl > 0 { set_role_info_in_cache(state, &token.role_id, &role_info, cache_ttl) .await .map_err(|e| logger::error!("Failed to set role info in cache {e:?}")) .ok(); } Ok(role_info) } <file_sep path="hyperswitch/crates/router/src/services/authorization.rs" role="context" start="20" end="20"> use common_utils::id_type; use router_env::logger; use super::authentication::AuthToken; use crate::{ consts, core::errors::{ApiErrorResponse, RouterResult, StorageErrorExt}, routes::app::SessionStateInfo, }; <file_sep path="hyperswitch/crates/router/src/services/authorization.rs" role="context" start="72" end="74"> pub fn get_cache_key_from_role_id(role_id: &str) -> String { format!("{}{}", consts::ROLE_INFO_CACHE_PREFIX, role_id) } <file_sep path="hyperswitch/crates/router/src/services/authorization.rs" role="context" start="60" end="70"> async fn get_role_info_from_cache<A>(state: &A, role_id: &str) -> RouterResult<roles::RoleInfo> where A: SessionStateInfo + Sync, { let redis_conn = get_redis_connection(state)?; redis_conn .get_and_deserialize_key(&get_cache_key_from_role_id(role_id).into(), "RoleInfo") .await .change_context(ApiErrorResponse::InternalServerError) } <file_sep path="hyperswitch/crates/router/src/services/authorization.rs" role="context" start="94" end="113"> pub async fn set_role_info_in_cache<A>( state: &A, role_id: &str, role_info: &roles::RoleInfo, expiry: i64, ) -> RouterResult<()> where A: SessionStateInfo + Sync, { let redis_conn = get_redis_connection(state)?; redis_conn .serialize_and_set_key_with_expiry( &get_cache_key_from_role_id(role_id).into(), role_info, expiry, ) .await .change_context(ApiErrorResponse::InternalServerError) } <file_sep path="hyperswitch/crates/router/src/services/authorization/roles.rs" role="context" start="18" end="28"> pub struct RoleInfo { role_id: String, role_name: String, groups: Vec<PermissionGroup>, scope: RoleScope, entity_type: EntityType, is_invitable: bool, is_deletable: bool, is_updatable: bool, is_internal: bool, } <file_sep path="hyperswitch/crates/api_models/src/errors/types.rs" role="context" start="86" end="100"> pub enum ApiErrorResponse { Unauthorized(ApiError), ForbiddenCommonResource(ApiError), ForbiddenPrivateResource(ApiError), Conflict(ApiError), Gone(ApiError), Unprocessable(ApiError), InternalServerError(ApiError), NotImplemented(ApiError), ConnectorError(ApiError, #[serde(skip_serializing)] StatusCode), NotFound(ApiError), MethodNotAllowed(ApiError), BadRequest(ApiError), DomainError(ApiError), }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/connector/netcetera/netcetera_types.rs<|crate|> router anchor=new kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/src/connector/netcetera/netcetera_types.rs" role="context" start="183" end="217"> pub fn new( app_ip: Option<std::net::IpAddr>, psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>, force_3ds_challenge: bool, message_version: SemanticVersion, ) -> Self { // if sca exemption is provided, we need to set the challenge indicator to NoChallengeRequestedTransactionalRiskAnalysis let three_ds_requestor_challenge_ind = if force_3ds_challenge { Some(SingleOrListElement::get_version_checked( message_version, ThreeDSRequestorChallengeIndicator::ChallengeRequestedMandate, )) } else if let Some(common_enums::ScaExemptionType::TransactionRiskAnalysis) = psd2_sca_exemption_type { Some(SingleOrListElement::get_version_checked( message_version, ThreeDSRequestorChallengeIndicator::NoChallengeRequestedTransactionalRiskAnalysis, )) } else { None }; Self { three_ds_requestor_authentication_ind: ThreeDSRequestorAuthenticationIndicator::Payment, three_ds_requestor_authentication_info: None, three_ds_requestor_challenge_ind, three_ds_requestor_prior_authentication_info: None, three_ds_requestor_dec_req_ind: None, three_ds_requestor_dec_max_time: None, app_ip, three_ds_requestor_spc_support: None, spc_incomp_ind: None, } } <file_sep path="hyperswitch/crates/router/src/connector/netcetera/netcetera_types.rs" role="context" start="182" end="182"> use std::collections::HashMap; use common_utils::{pii::Email, types::SemanticVersion}; <file_sep path="hyperswitch/crates/router/src/connector/netcetera/netcetera_types.rs" role="context" start="772" end="870"> fn try_from( (billing_address, shipping_address): ( hyperswitch_domain_models::address::Address, Option<hyperswitch_domain_models::address::Address>, ), ) -> Result<Self, Self::Error> { Ok(Self { addr_match: None, bill_addr_city: billing_address .address .as_ref() .and_then(|add| add.city.clone()), bill_addr_country: billing_address.address.as_ref().and_then(|add| { add.country.map(|country| { common_enums::Country::from_alpha2(country) .to_numeric() .to_string() }) }), bill_addr_line1: billing_address .address .as_ref() .and_then(|add| add.line1.clone()), bill_addr_line2: billing_address .address .as_ref() .and_then(|add| add.line2.clone()), bill_addr_line3: billing_address .address .as_ref() .and_then(|add| add.line3.clone()), bill_addr_post_code: billing_address .address .as_ref() .and_then(|add| add.zip.clone()), bill_addr_state: billing_address .address .as_ref() .and_then(|add| add.to_state_code_as_optional().transpose()) .transpose()?, email: billing_address.email, home_phone: billing_address .phone .clone() .map(PhoneNumber::try_from) .transpose()?, mobile_phone: billing_address .phone .clone() .map(PhoneNumber::try_from) .transpose()?, work_phone: billing_address .phone .clone() .map(PhoneNumber::try_from) .transpose()?, cardholder_name: billing_address.address.and_then(|address| { address .get_optional_full_name() .map(|name| masking::Secret::new(unidecode(&name.expose()))) }), ship_addr_city: shipping_address .as_ref() .and_then(|shipping_add| shipping_add.address.as_ref()) .and_then(|add| add.city.clone()), ship_addr_country: shipping_address .as_ref() .and_then(|shipping_add| shipping_add.address.as_ref()) .and_then(|add| { add.country.map(|country| { common_enums::Country::from_alpha2(country) .to_numeric() .to_string() }) }), ship_addr_line1: shipping_address .as_ref() .and_then(|shipping_add| shipping_add.address.as_ref()) .and_then(|add| add.line1.clone()), ship_addr_line2: shipping_address .as_ref() .and_then(|shipping_add| shipping_add.address.as_ref()) .and_then(|add| add.line2.clone()), ship_addr_line3: shipping_address .as_ref() .and_then(|shipping_add| shipping_add.address.as_ref()) .and_then(|add| add.line3.clone()), ship_addr_post_code: shipping_address .as_ref() .and_then(|shipping_add| shipping_add.address.as_ref()) .and_then(|add| add.zip.clone()), ship_addr_state: shipping_address .as_ref() .and_then(|shipping_add| shipping_add.address.as_ref()) .and_then(|add| add.to_state_code_as_optional().transpose()) .transpose()?, tax_id: None, }) } <file_sep path="hyperswitch/crates/router/src/connector/netcetera/netcetera_types.rs" role="context" start="371" end="384"> fn try_from(network: common_enums::CardNetwork) -> Result<Self, Self::Error> { match network { common_enums::CardNetwork::Visa => Ok(Self::Visa), common_enums::CardNetwork::Mastercard => Ok(Self::Mastercard), common_enums::CardNetwork::JCB => Ok(Self::Jcb), common_enums::CardNetwork::AmericanExpress => Ok(Self::AmericanExpress), common_enums::CardNetwork::DinersClub => Ok(Self::Diners), common_enums::CardNetwork::CartesBancaires => Ok(Self::CartesBancaires), common_enums::CardNetwork::UnionPay => Ok(Self::UnionPay), _ => Err(errors::ConnectorError::RequestEncodingFailedWithReason( "Invalid card network".to_string(), ))?, } } <file_sep path="hyperswitch/crates/router/src/connector/netcetera/netcetera_types.rs" role="context" start="84" end="90"> fn from(value: api_models::payments::ThreeDsCompletionIndicator) -> Self { match value { api_models::payments::ThreeDsCompletionIndicator::Success => Self::Y, api_models::payments::ThreeDsCompletionIndicator::Failure => Self::N, api_models::payments::ThreeDsCompletionIndicator::NotAvailable => Self::U, } } <file_sep path="hyperswitch/crates/router/src/connector/netcetera/netcetera_types.rs" role="context" start="66" end="71"> fn from(value: MessageCategory) -> Self { match value { MessageCategory::NonPayment => Self::NonPaymentAuthentication, MessageCategory::Payment => Self::PaymentAuthentication, } } <file_sep path="hyperswitch/crates/router/src/connector/netcetera/netcetera_types.rs" role="context" start="1473" end="1494"> fn from(value: crate::types::BrowserInformation) -> Self { Self { browser_accept_header: value.accept_header, browser_ip: value .ip_address .map(|ip| masking::Secret::new(ip.to_string())), browser_java_enabled: value.java_enabled, browser_language: value.language, browser_color_depth: value.color_depth.map(|cd| cd.to_string()), browser_screen_height: value.screen_height, browser_screen_width: value.screen_width, browser_tz: value.time_zone, browser_user_agent: value.user_agent, challenge_window_size: Some(ChallengeWindowSizeEnum::FullScreen), browser_javascript_enabled: value.java_script_enabled, // Default to ["en"] locale if accept_language is not provided accept_language: value .accept_language .map(get_list_of_accept_languages) .or(Some(vec!["en".to_string()])), } } <file_sep path="hyperswitch/crates/router/src/connector/netcetera/netcetera_types.rs" role="context" start="19" end="25"> fn get_version_checked(message_version: SemanticVersion, value: T) -> Self { if message_version.get_major() >= 2 && message_version.get_minor() >= 3 { Self::List(vec![value]) } else { Self::Single(value) } } <file_sep path="hyperswitch/crates/router/src/connector/netcetera/netcetera_types.rs" role="context" start="280" end="299"> pub enum ThreeDSRequestorChallengeIndicator { #[serde(rename = "01")] NoPreference, #[serde(rename = "02")] NoChallengeRequested, #[serde(rename = "03")] ChallengeRequested3DSRequestorPreference, #[serde(rename = "04")] ChallengeRequestedMandate, #[serde(rename = "05")] NoChallengeRequestedTransactionalRiskAnalysis, #[serde(rename = "06")] NoChallengeRequestedDataShareOnly, #[serde(rename = "07")] NoChallengeRequestedStrongConsumerAuthentication, #[serde(rename = "08")] NoChallengeRequestedWhitelistExemption, #[serde(rename = "09")] ChallengeRequestedWhitelistPrompt, } <file_sep path="hyperswitch/crates/router/src/connector/netcetera/netcetera_types.rs" role="context" start="165" end="180"> pub enum ThreeDSRequestorAuthenticationIndicator { #[serde(rename = "01")] Payment, #[serde(rename = "02")] Recurring, #[serde(rename = "03")] Installment, #[serde(rename = "04")] AddCard, #[serde(rename = "05")] MaintainCard, #[serde(rename = "06")] CardholderVerification, #[serde(rename = "07")] BillingAgreement, } <file_sep path="hyperswitch/crates/router/src/connector/netcetera/netcetera_types.rs" role="context" start="13" end="16"> pub enum SingleOrListElement<T> { Single(T), List(Vec<T>), }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/configs/settings.rs<|crate|> router anchor=deserialize_hashmap_inner kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/src/configs/settings.rs" role="context" start="1159" end="1199"> fn deserialize_hashmap_inner<K, V>( value: HashMap<String, String>, ) -> Result<HashMap<K, HashSet<V>>, String> where K: Eq + std::str::FromStr + std::hash::Hash, V: Eq + std::str::FromStr + std::hash::Hash, <K as std::str::FromStr>::Err: std::fmt::Display, <V as std::str::FromStr>::Err: std::fmt::Display, { let (values, errors) = value .into_iter() .map( |(k, v)| match (K::from_str(k.trim()), deserialize_hashset_inner(v)) { (Err(error), _) => Err(format!( "Unable to deserialize `{}` as `{}`: {error}", k, std::any::type_name::<K>() )), (_, Err(error)) => Err(error), (Ok(key), Ok(value)) => Ok((key, value)), }, ) .fold( (HashMap::new(), Vec::new()), |(mut values, mut errors), result| match result { Ok((key, value)) => { values.insert(key, value); (values, errors) } Err(error) => { errors.push(error); (values, errors) } }, ); if !errors.is_empty() { Err(format!("Some errors occurred:\n{}", errors.join("\n"))) } else { Ok(values) } } <file_sep path="hyperswitch/crates/router/src/configs/settings.rs" role="context" start="1158" end="1158"> use std::{ collections::{HashMap, HashSet}, path::PathBuf, sync::Arc, }; use crate::{ configs, core::errors::{ApplicationError, ApplicationResult}, env::{self, Env}, events::EventsConfig, routes::app, AppState, }; <file_sep path="hyperswitch/crates/router/src/configs/settings.rs" role="context" start="1214" end="1250"> fn deserialize_hashset_inner<T>(value: impl AsRef<str>) -> Result<HashSet<T>, String> where T: Eq + std::str::FromStr + std::hash::Hash, <T as std::str::FromStr>::Err: std::fmt::Display, { let (values, errors) = value .as_ref() .trim() .split(',') .map(|s| { T::from_str(s.trim()).map_err(|error| { format!( "Unable to deserialize `{}` as `{}`: {error}", s.trim(), std::any::type_name::<T>() ) }) }) .fold( (HashSet::new(), Vec::new()), |(mut values, mut errors), result| match result { Ok(t) => { values.insert(t); (values, errors) } Err(error) => { errors.push(error); (values, errors) } }, ); if !errors.is_empty() { Err(format!("Some errors occurred:\n{}", errors.join("\n"))) } else { Ok(values) } } <file_sep path="hyperswitch/crates/router/src/configs/settings.rs" role="context" start="1201" end="1212"> fn deserialize_hashmap<'a, D, K, V>(deserializer: D) -> Result<HashMap<K, HashSet<V>>, D::Error> where D: serde::Deserializer<'a>, K: Eq + std::str::FromStr + std::hash::Hash, V: Eq + std::str::FromStr + std::hash::Hash, <K as std::str::FromStr>::Err: std::fmt::Display, <V as std::str::FromStr>::Err: std::fmt::Display, { use serde::de::Error; deserialize_hashmap_inner(<HashMap<String, String>>::deserialize(deserializer)?) .map_err(D::Error::custom) } <file_sep path="hyperswitch/crates/router/src/configs/settings.rs" role="context" start="1141" end="1150"> fn default() -> Self { // We provide a static default cell id for constructing application settings. // This will only panic at application startup if we're unable to construct the default, // around the time of deserializing application settings. // And a panic at application startup is considered acceptable. #[allow(clippy::expect_used)] let cell_id = id_type::CellId::from_string("defid").expect("Failed to create a default for Cell Id"); Self { id: cell_id } } <file_sep path="hyperswitch/crates/router/src/configs/settings.rs" role="context" start="1084" end="1102"> fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { #[derive(Deserialize)] #[serde(deny_unknown_fields)] struct Inner { redis_lock_expiry_seconds: u32, delay_between_retries_in_milliseconds: u32, } let Inner { redis_lock_expiry_seconds, delay_between_retries_in_milliseconds, } = Inner::deserialize(deserializer)?; let redis_lock_expiry_milliseconds = redis_lock_expiry_seconds * 1000; Ok(Self { redis_lock_expiry_seconds, delay_between_retries_in_milliseconds, lock_retries: redis_lock_expiry_milliseconds / delay_between_retries_in_milliseconds, }) } <file_sep path="hyperswitch/crates/router/src/configs/settings.rs" role="context" start="907" end="909"> pub fn new() -> ApplicationResult<Self> { Self::with_config_path(None) }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/db/user/theme.rs<|crate|> router anchor=check_theme_with_lineage kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/db/user/theme.rs" role="context" start="96" end="150"> fn check_theme_with_lineage(theme: &storage::Theme, lineage: &ThemeLineage) -> bool { match lineage { ThemeLineage::Tenant { tenant_id } => { &theme.tenant_id == tenant_id && theme.org_id.is_none() && theme.merchant_id.is_none() && theme.profile_id.is_none() } ThemeLineage::Organization { tenant_id, org_id } => { &theme.tenant_id == tenant_id && theme .org_id .as_ref() .is_some_and(|org_id_inner| org_id_inner == org_id) && theme.merchant_id.is_none() && theme.profile_id.is_none() } ThemeLineage::Merchant { tenant_id, org_id, merchant_id, } => { &theme.tenant_id == tenant_id && theme .org_id .as_ref() .is_some_and(|org_id_inner| org_id_inner == org_id) && theme .merchant_id .as_ref() .is_some_and(|merchant_id_inner| merchant_id_inner == merchant_id) && theme.profile_id.is_none() } ThemeLineage::Profile { tenant_id, org_id, merchant_id, profile_id, } => { &theme.tenant_id == tenant_id && theme .org_id .as_ref() .is_some_and(|org_id_inner| org_id_inner == org_id) && theme .merchant_id .as_ref() .is_some_and(|merchant_id_inner| merchant_id_inner == merchant_id) && theme .profile_id .as_ref() .is_some_and(|profile_id_inner| profile_id_inner == profile_id) } } } <file_sep path="hyperswitch/crates/router/src/db/user/theme.rs" role="context" start="95" end="95"> use common_utils::types::theme::ThemeLineage; use diesel_models::user::theme as storage; <file_sep path="hyperswitch/crates/router/src/db/user/theme.rs" role="context" start="202" end="218"> async fn find_theme_by_theme_id( &self, theme_id: String, ) -> CustomResult<storage::Theme, errors::StorageError> { let themes = self.themes.lock().await; themes .iter() .find(|theme| theme.theme_id == theme_id) .cloned() .ok_or( errors::StorageError::ValueNotFound(format!( "Theme with id {} not found", theme_id )) .into(), ) } <file_sep path="hyperswitch/crates/router/src/db/user/theme.rs" role="context" start="154" end="200"> async fn insert_theme( &self, new_theme: storage::ThemeNew, ) -> CustomResult<storage::Theme, errors::StorageError> { let mut themes = self.themes.lock().await; for theme in themes.iter() { if new_theme.theme_id == theme.theme_id { return Err(errors::StorageError::DuplicateValue { entity: "theme_id", key: None, } .into()); } if new_theme.tenant_id == theme.tenant_id && new_theme.org_id == theme.org_id && new_theme.merchant_id == theme.merchant_id && new_theme.profile_id == theme.profile_id { return Err(errors::StorageError::DuplicateValue { entity: "lineage", key: None, } .into()); } } let theme = storage::Theme { theme_id: new_theme.theme_id, tenant_id: new_theme.tenant_id, org_id: new_theme.org_id, merchant_id: new_theme.merchant_id, profile_id: new_theme.profile_id, created_at: new_theme.created_at, last_modified_at: new_theme.last_modified_at, entity_type: new_theme.entity_type, theme_name: new_theme.theme_name, email_primary_color: new_theme.email_primary_color, email_foreground_color: new_theme.email_foreground_color, email_background_color: new_theme.email_background_color, email_entity_name: new_theme.email_entity_name, email_entity_logo_url: new_theme.email_entity_logo_url, }; themes.push(theme.clone()); Ok(theme) } <file_sep path="hyperswitch/crates/router/src/db/user/theme.rs" role="context" start="84" end="93"> async fn delete_theme_by_lineage_and_theme_id( &self, theme_id: String, lineage: ThemeLineage, ) -> CustomResult<storage::Theme, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::Theme::delete_by_theme_id_and_lineage(&conn, theme_id, lineage) .await .map_err(|error| report!(errors::StorageError::from(error))) } <file_sep path="hyperswitch/crates/router/src/db/user/theme.rs" role="context" start="74" end="82"> async fn find_theme_by_lineage( &self, lineage: ThemeLineage, ) -> CustomResult<storage::Theme, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Theme::find_by_lineage(&conn, lineage) .await .map_err(|error| report!(errors::StorageError::from(error))) } <file_sep path="hyperswitch/crates/router/src/db/user/theme.rs" role="context" start="259" end="278"> async fn delete_theme_by_lineage_and_theme_id( &self, theme_id: String, lineage: ThemeLineage, ) -> CustomResult<storage::Theme, errors::StorageError> { let mut themes = self.themes.lock().await; let index = themes .iter() .position(|theme| { theme.theme_id == theme_id && check_theme_with_lineage(theme, &lineage) }) .ok_or(errors::StorageError::ValueNotFound(format!( "Theme with id {} and lineage {:?} not found", theme_id, lineage )))?; let theme = themes.remove(index); Ok(theme) } <file_sep path="hyperswitch/crates/router/src/db/user/theme.rs" role="context" start="220" end="239"> async fn find_most_specific_theme_in_lineage( &self, lineage: ThemeLineage, ) -> CustomResult<storage::Theme, errors::StorageError> { let themes = self.themes.lock().await; let lineages = lineage.get_same_and_higher_lineages(); themes .iter() .filter(|theme| { lineages .iter() .any(|lineage| check_theme_with_lineage(theme, lineage)) }) .min_by_key(|theme| theme.entity_type) .ok_or( errors::StorageError::ValueNotFound("No theme found in lineage".to_string()).into(), ) .cloned() } <file_sep path="hyperswitch/migrations/2024-12-05-131123_add-email-theme-data-in-themes/up.sql" role="context" start="1" end="6"> -- Your SQL goes here ALTER TABLE themes ADD COLUMN IF NOT EXISTS email_primary_color VARCHAR(64) NOT NULL DEFAULT '#006DF9'; ALTER TABLE themes ADD COLUMN IF NOT EXISTS email_foreground_color VARCHAR(64) NOT NULL DEFAULT '#000000'; ALTER TABLE themes ADD COLUMN IF NOT EXISTS email_background_color VARCHAR(64) NOT NULL DEFAULT '#FFFFFF'; ALTER TABLE themes ADD COLUMN IF NOT EXISTS email_entity_name VARCHAR(64) NOT NULL DEFAULT 'Hyperswitch'; ALTER TABLE themes ADD COLUMN IF NOT EXISTS email_entity_logo_url TEXT NOT NULL DEFAULT 'https://app.hyperswitch.io/email-assets/HyperswitchLogo.png';
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/services/authentication.rs<|crate|> router anchor=authenticate_and_fetch kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="1662" end="1717"> async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<(AuthenticationData, AuthenticationType)> { if state.conf().platform.enabled { throw_error_if_platform_merchant_authentication_required(request_headers)?; } V2AdminApiAuth .authenticate_and_fetch(request_headers, state) .await?; let merchant_id = HeaderMapStruct::new(request_headers) .get_id_type_from_header::<id_type::MerchantId>(headers::X_MERCHANT_ID)?; let profile_id = get_id_type_by_key_from_headers(headers::X_PROFILE_ID.to_string(), request_headers)? .get_required_value(headers::X_PROFILE_ID)?; let key_manager_state = &(&state.session_state()).into(); let key_store = state .store() .get_merchant_key_store_by_merchant_id( key_manager_state, &merchant_id, &state.store().get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let profile = state .store() .find_business_profile_by_merchant_id_profile_id( key_manager_state, &key_store, &merchant_id, &profile_id, ) .await .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; let merchant = state .store() .find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; let auth = AuthenticationData { merchant_account: merchant, key_store, profile, platform_merchant_account: None, }; Ok(( auth, AuthenticationType::AdminApiAuthWithMerchantId { merchant_id }, )) } <file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="1661" end="1661"> use actix_web::http::header::HeaderMap; use common_utils::{date_time, fp_utils, id_type}; use self::blacklist::BlackList; use self::detached::ExtractedPayload; use self::detached::GetAuthType; use super::authorization::{self, permissions::Permission}; use crate::core::errors::UserResult; use crate::{ core::{ api_keys, errors::{self, utils::StorageErrorExt, RouterResult}, }, headers, routes::app::SessionStateInfo, services::api, types::{domain, storage}, utils::OptionExt, }; pub type AuthenticationDataWithUserId = (AuthenticationData, String); <file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="1780" end="1796"> async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<(AuthenticationData, AuthenticationType)> { let api_key = get_api_key(request_headers).change_context(errors::ApiErrorResponse::Unauthorized)?; let ephemeral_key = state .store() .get_ephemeral_key(api_key) .await .change_context(errors::ApiErrorResponse::Unauthorized)?; MerchantIdAuth(ephemeral_key.merchant_id) .authenticate_and_fetch(request_headers, state) .await } <file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="1727" end="1768"> async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<(AuthenticationDataWithoutProfile, AuthenticationType)> { if state.conf().platform.enabled { throw_error_if_platform_merchant_authentication_required(request_headers)?; } V2AdminApiAuth .authenticate_and_fetch(request_headers, state) .await?; let merchant_id = HeaderMapStruct::new(request_headers) .get_id_type_from_header::<id_type::MerchantId>(headers::X_MERCHANT_ID)?; let key_manager_state = &(&state.session_state()).into(); let key_store = state .store() .get_merchant_key_store_by_merchant_id( key_manager_state, &merchant_id, &state.store().get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let merchant = state .store() .find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; let auth = AuthenticationDataWithoutProfile { merchant_account: merchant, key_store, }; Ok(( auth, AuthenticationType::AdminApiAuthWithMerchantId { merchant_id }, )) } <file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="1614" end="1653"> async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<(AuthenticationData, AuthenticationType)> { AdminApiAuth .authenticate_and_fetch(request_headers, state) .await?; let merchant_id = HeaderMapStruct::new(request_headers) .get_id_type_from_header::<id_type::MerchantId>(headers::X_MERCHANT_ID)?; let key_manager_state = &(&state.session_state()).into(); let key_store = state .store() .get_merchant_key_store_by_merchant_id( key_manager_state, &merchant_id, &state.store().get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let merchant = state .store() .find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; let auth = AuthenticationData { merchant_account: merchant, platform_merchant_account: None, key_store, profile_id: None, }; Ok(( auth, AuthenticationType::AdminApiAuthWithMerchantId { merchant_id }, )) } <file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="1575" end="1601"> pub fn get_id_type_from_header_if_present<T>(&self, key: &str) -> RouterResult<Option<T>> where T: TryFrom< std::borrow::Cow<'static, str>, Error = error_stack::Report<errors::ValidationError>, >, { self.headers .get(key) .map(|value| value.to_str()) .transpose() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "`{key}` in headers", }) .attach_printable(format!( "Failed to convert header value to string for header key: {}", key ))? .map(|value| { T::try_from(std::borrow::Cow::Owned(value.to_owned())).change_context( errors::ApiErrorResponse::InvalidRequestData { message: format!("`{}` header is invalid", key), }, ) }) .transpose() } <file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="1506" end="1508"> pub fn new(headers: &'a HeaderMap) -> Self { HeaderMapStruct { headers } } <file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="3830" end="3843"> pub fn get_id_type_by_key_from_headers<T: FromStr>( key: String, headers: &HeaderMap, ) -> RouterResult<Option<T>> { get_header_value_by_key(key.clone(), headers)? .map(|str_value| T::from_str(str_value)) .transpose() .map_err(|_err| { error_stack::report!(errors::ApiErrorResponse::InvalidDataFormat { field_name: key, expected_format: "Valid Id String".to_string(), }) }) } <file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="1501" end="1503"> pub(crate) struct HeaderMapStruct<'a> { headers: &'a HeaderMap, } <file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="1106" end="1106"> pub struct V2AdminApiAuth; <file_sep path="hyperswitch/crates/router/tests/utils.rs" role="context" start="389" end="391"> pub struct MerchantId { merchant_id: common_utils::id_type::MerchantId, } <file_sep path="hyperswitch/crates/api_models/src/errors/types.rs" role="context" start="86" end="100"> pub enum ApiErrorResponse { Unauthorized(ApiError), ForbiddenCommonResource(ApiError), ForbiddenPrivateResource(ApiError), Conflict(ApiError), Gone(ApiError), Unprocessable(ApiError), InternalServerError(ApiError), NotImplemented(ApiError), ConnectorError(ApiError, #[serde(skip_serializing)] StatusCode), NotFound(ApiError), MethodNotAllowed(ApiError), BadRequest(ApiError), DomainError(ApiError), }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/core/routing/helpers.rs<|crate|> router anchor=get_default_config_key kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/core/routing/helpers.rs" role="context" start="506" end="515"> pub fn get_default_config_key( merchant_id: &str, transaction_type: &storage::enums::TransactionType, ) -> String { match transaction_type { storage::enums::TransactionType::Payment => format!("routing_default_{merchant_id}"), #[cfg(feature = "payouts")] storage::enums::TransactionType::Payout => format!("routing_default_po_{merchant_id}"), } } <file_sep path="hyperswitch/crates/router/src/core/routing/helpers.rs" role="context" start="505" end="505"> use std::str::FromStr; use crate::{ core::errors::{self, RouterResult}, db::StorageInterface, routes::SessionState, types::{domain, storage}, utils::StringExt, }; <file_sep path="hyperswitch/crates/router/src/core/routing/helpers.rs" role="context" start="551" end="570"> async fn refresh_dynamic_routing_cache<T, F, Fut>( state: &SessionState, key: &str, func: F, ) -> RouterResult<T> where F: FnOnce() -> Fut + Send, T: Cacheable + serde::Serialize + serde::de::DeserializeOwned + Debug + Clone, Fut: futures::Future<Output = errors::CustomResult<T, errors::StorageError>> + Send, { cache::get_or_populate_in_memory( state.store.get_cache_store().as_ref(), key, func, &cache::SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("unable to populate SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE") } <file_sep path="hyperswitch/crates/router/src/core/routing/helpers.rs" role="context" start="539" end="549"> async fn get_cached_dynamic_routing_config_for_profile( state: &SessionState, key: &str, ) -> Option<Arc<Self>> { cache::SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE .get_val::<Arc<Self>>(cache::CacheKey { key: key.to_string(), prefix: state.tenant.redis_key_prefix.clone(), }) .await } <file_sep path="hyperswitch/crates/router/src/core/routing/helpers.rs" role="context" start="500" end="502"> pub fn get_routing_dictionary_key(merchant_id: &str) -> String { format!("routing_dict_{merchant_id}") } <file_sep path="hyperswitch/crates/router/src/core/routing/helpers.rs" role="context" start="392" end="496"> pub async fn validate_connectors_in_routing_config( state: &SessionState, key_store: &domain::MerchantKeyStore, merchant_id: &id_type::MerchantId, profile_id: &id_type::ProfileId, routing_algorithm: &routing_types::RoutingAlgorithm, ) -> RouterResult<()> { let all_mcas = state .store .find_merchant_connector_account_by_merchant_id_and_disabled_list( &state.into(), merchant_id, true, key_store, ) .await .change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: merchant_id.get_string_repr().to_owned(), })?; let name_mca_id_set = all_mcas .iter() .filter(|mca| mca.profile_id == *profile_id) .map(|mca| (&mca.connector_name, mca.get_id())) .collect::<FxHashSet<_>>(); let name_set = all_mcas .iter() .filter(|mca| mca.profile_id == *profile_id) .map(|mca| &mca.connector_name) .collect::<FxHashSet<_>>(); let connector_choice = |choice: &routing_types::RoutableConnectorChoice| { if let Some(ref mca_id) = choice.merchant_connector_id { error_stack::ensure!( name_mca_id_set.contains(&(&choice.connector.to_string(), mca_id.clone())), errors::ApiErrorResponse::InvalidRequestData { message: format!( "connector with name '{}' and merchant connector account id '{:?}' not found for the given profile", choice.connector, mca_id, ) } ); } else { error_stack::ensure!( name_set.contains(&choice.connector.to_string()), errors::ApiErrorResponse::InvalidRequestData { message: format!( "connector with name '{}' not found for the given profile", choice.connector, ) } ); } Ok(()) }; match routing_algorithm { routing_types::RoutingAlgorithm::Single(choice) => { connector_choice(choice)?; } routing_types::RoutingAlgorithm::Priority(list) => { for choice in list { connector_choice(choice)?; } } routing_types::RoutingAlgorithm::VolumeSplit(splits) => { for split in splits { connector_choice(&split.connector)?; } } routing_types::RoutingAlgorithm::Advanced(program) => { let check_connector_selection = |selection: &routing_types::ConnectorSelection| -> RouterResult<()> { match selection { routing_types::ConnectorSelection::VolumeSplit(splits) => { for split in splits { connector_choice(&split.connector)?; } } routing_types::ConnectorSelection::Priority(list) => { for choice in list { connector_choice(choice)?; } } } Ok(()) }; check_connector_selection(&program.default_selection)?; for rule in &program.rules { check_connector_selection(&rule.connector_selection)?; } } } Ok(()) } <file_sep path="hyperswitch/crates/router/src/core/routing/helpers.rs" role="context" start="59" end="101"> pub async fn get_merchant_default_config( db: &dyn StorageInterface, // Cannot make this as merchant id domain type because, we are passing profile id also here merchant_id: &str, transaction_type: &storage::enums::TransactionType, ) -> RouterResult<Vec<routing_types::RoutableConnectorChoice>> { let key = get_default_config_key(merchant_id, transaction_type); let maybe_config = db.find_config_by_key(&key).await; match maybe_config { Ok(config) => config .config .parse_struct("Vec<RoutableConnectors>") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Merchant default config has invalid structure"), Err(e) if e.current_context().is_db_not_found() => { let new_config_conns = Vec::<routing_types::RoutableConnectorChoice>::new(); let serialized = new_config_conns .encode_to_string_of_json() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Error while creating and serializing new merchant default config", )?; let new_config = configs::ConfigNew { key, config: serialized, }; db.insert_config(new_config) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error inserting new default routing config into DB")?; Ok(new_config_conns) } Err(e) => Err(e) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error fetching default config for merchant"), } } <file_sep path="hyperswitch/crates/router/src/core/routing/helpers.rs" role="context" start="105" end="127"> pub async fn update_merchant_default_config( db: &dyn StorageInterface, merchant_id: &str, connectors: Vec<routing_types::RoutableConnectorChoice>, transaction_type: &storage::enums::TransactionType, ) -> RouterResult<()> { let key = get_default_config_key(merchant_id, transaction_type); let config_str = connectors .encode_to_string_of_json() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to serialize merchant default routing config during update")?; let config_update = configs::ConfigUpdate::Update { config: Some(config_str), }; db.update_config_by_key(&key, config_update) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error updating the default routing config in DB")?; Ok(()) } <file_sep path="hyperswitch/crates/router/src/connector/nmi/transformers.rs" role="context" start="23" end="30"> pub enum TransactionType { Auth, Capture, Refund, Sale, Validate, Void, } <file_sep path="hyperswitch/migrations/2024-07-31-063531_alter_customer_id_in_payouts/up.sql" role="context" start="1" end="9"> ALTER TABLE payouts ALTER COLUMN customer_id DROP NOT NULL, ALTER COLUMN address_id DROP NOT NULL; ALTER TABLE payout_attempt ALTER COLUMN customer_id DROP NOT NULL,
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/services/authentication.rs<|crate|> router anchor=authenticate_and_fetch kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="528" end="633"> async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<(AuthenticationData, AuthenticationType)> { let api_key = get_api_key(request_headers) .change_context(errors::ApiErrorResponse::Unauthorized)? .trim(); if api_key.is_empty() { return Err(errors::ApiErrorResponse::Unauthorized) .attach_printable("API key is empty"); } let api_key = api_keys::PlaintextApiKey::from(api_key); let hash_key = { let config = state.conf(); config.api_keys.get_inner().get_hash_key()? }; let hashed_api_key = api_key.keyed_hash(hash_key.peek()); let stored_api_key = state .store() .find_api_key_by_hash_optional(hashed_api_key.into()) .await .change_context(errors::ApiErrorResponse::InternalServerError) // If retrieve failed .attach_printable("Failed to retrieve API key")? .ok_or(report!(errors::ApiErrorResponse::Unauthorized)) // If retrieve returned `None` .attach_printable("Merchant not authenticated")?; if stored_api_key .expires_at .map(|expires_at| expires_at < date_time::now()) .unwrap_or(false) { return Err(report!(errors::ApiErrorResponse::Unauthorized)) .attach_printable("API key has expired"); } let key_manager_state = &(&state.session_state()).into(); let key_store = state .store() .get_merchant_key_store_by_merchant_id( key_manager_state, &stored_api_key.merchant_id, &state.store().get_master_key().to_vec().into(), ) .await .change_context(errors::ApiErrorResponse::Unauthorized) .attach_printable("Failed to fetch merchant key store for the merchant id")?; let profile_id = get_header_value_by_key(headers::X_PROFILE_ID.to_string(), request_headers)? .map(id_type::ProfileId::from_str) .transpose() .change_context(errors::ValidationError::IncorrectValueProvided { field_name: "X-Profile-Id", }) .change_context(errors::ApiErrorResponse::Unauthorized)?; let merchant = state .store() .find_merchant_account_by_merchant_id( key_manager_state, &stored_api_key.merchant_id, &key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; // Get connected merchant account if API call is done by Platform merchant account on behalf of connected merchant account let (merchant, platform_merchant_account) = if state.conf().platform.enabled { get_platform_merchant_account(state, request_headers, merchant).await? } else { (merchant, None) }; let key_store = if platform_merchant_account.is_some() { state .store() .get_merchant_key_store_by_merchant_id( key_manager_state, merchant.get_id(), &state.store().get_master_key().to_vec().into(), ) .await .change_context(errors::ApiErrorResponse::Unauthorized) .attach_printable("Failed to fetch merchant key store for the merchant id")? } else { key_store }; let auth = AuthenticationData { merchant_account: merchant, platform_merchant_account, key_store, profile_id, }; Ok(( auth.clone(), AuthenticationType::ApiKey { merchant_id: auth.merchant_account.get_id().clone(), key_id: stored_api_key.key_id, }, )) } <file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="527" end="527"> use actix_web::http::header::HeaderMap; use common_utils::{date_time, fp_utils, id_type}; use error_stack::{report, ResultExt}; use self::blacklist::BlackList; use self::detached::ExtractedPayload; use self::detached::GetAuthType; use super::authorization::{self, permissions::Permission}; use crate::core::errors::UserResult; use crate::{ core::{ api_keys, errors::{self, utils::StorageErrorExt, RouterResult}, }, headers, routes::app::SessionStateInfo, services::api, types::{domain, storage}, utils::OptionExt, }; pub type AuthenticationDataWithUserId = (AuthenticationData, String); <file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="652" end="671"> async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<(AuthenticationData, AuthenticationType)> { let (auth_data, auth_type) = ApiKeyAuth .authenticate_and_fetch(request_headers, state) .await?; let merchant_id_from_route = self.0.clone(); let merchant_id_from_api_key = auth_data.merchant_account.get_id(); if merchant_id_from_route != *merchant_id_from_api_key { return Err(report!(errors::ApiErrorResponse::Unauthorized)).attach_printable( "Merchant ID from route and Merchant ID from api-key in header do not match", ); } Ok((auth_data, auth_type)) } <file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="641" end="643"> fn get_auth_type(&self) -> detached::PayloadType { detached::PayloadType::ApiKey } <file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="414" end="519"> async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<(AuthenticationData, AuthenticationType)> { let api_key = get_api_key(request_headers) .change_context(errors::ApiErrorResponse::Unauthorized)? .trim(); if api_key.is_empty() { return Err(errors::ApiErrorResponse::Unauthorized) .attach_printable("API key is empty"); } let profile_id = HeaderMapStruct::new(request_headers) .get_id_type_from_header::<id_type::ProfileId>(headers::X_PROFILE_ID)?; let api_key = api_keys::PlaintextApiKey::from(api_key); let hash_key = { let config = state.conf(); config.api_keys.get_inner().get_hash_key()? }; let hashed_api_key = api_key.keyed_hash(hash_key.peek()); let stored_api_key = state .store() .find_api_key_by_hash_optional(hashed_api_key.into()) .await .change_context(errors::ApiErrorResponse::InternalServerError) // If retrieve failed .attach_printable("Failed to retrieve API key")? .ok_or(report!(errors::ApiErrorResponse::Unauthorized)) // If retrieve returned `None` .attach_printable("Merchant not authenticated")?; if stored_api_key .expires_at .map(|expires_at| expires_at < date_time::now()) .unwrap_or(false) { return Err(report!(errors::ApiErrorResponse::Unauthorized)) .attach_printable("API key has expired"); } let key_manager_state = &(&state.session_state()).into(); let key_store = state .store() .get_merchant_key_store_by_merchant_id( key_manager_state, &stored_api_key.merchant_id, &state.store().get_master_key().to_vec().into(), ) .await .change_context(errors::ApiErrorResponse::Unauthorized) .attach_printable("Failed to fetch merchant key store for the merchant id")?; let merchant = state .store() .find_merchant_account_by_merchant_id( key_manager_state, &stored_api_key.merchant_id, &key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; // Get connected merchant account if API call is done by Platform merchant account on behalf of connected merchant account let (merchant, platform_merchant_account) = if state.conf().platform.enabled { get_platform_merchant_account(state, request_headers, merchant).await? } else { (merchant, None) }; let key_store = if platform_merchant_account.is_some() { state .store() .get_merchant_key_store_by_merchant_id( key_manager_state, merchant.get_id(), &state.store().get_master_key().to_vec().into(), ) .await .change_context(errors::ApiErrorResponse::Unauthorized) .attach_printable("Failed to fetch merchant key store for the merchant id")? } else { key_store }; let profile = state .store() .find_business_profile_by_profile_id(key_manager_state, &key_store, &profile_id) .await .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; let auth = AuthenticationData { merchant_account: merchant, platform_merchant_account, key_store, profile, }; Ok(( auth.clone(), AuthenticationType::ApiKey { merchant_id: auth.merchant_account.get_id().clone(), key_id: stored_api_key.key_id, }, )) } <file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="399" end="405"> async fn authenticate_and_fetch( &self, _request_headers: &HeaderMap, _state: &A, ) -> RouterResult<(Option<T>, AuthenticationType)> { Ok((None, AuthenticationType::NoAuth)) } <file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="3991" end="4014"> async fn get_platform_merchant_account<A>( state: &A, request_headers: &HeaderMap, merchant_account: domain::MerchantAccount, ) -> RouterResult<(domain::MerchantAccount, Option<domain::MerchantAccount>)> where A: SessionStateInfo + Sync, { let connected_merchant_id = get_and_validate_connected_merchant_id(request_headers, &merchant_account)?; match connected_merchant_id { Some(merchant_id) => { let connected_merchant_account = get_connected_merchant_account( state, merchant_id, merchant_account.organization_id.clone(), ) .await?; Ok((connected_merchant_account, Some(merchant_account))) } None => Ok((merchant_account, None)), } } <file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="3812" end="3814"> pub fn get_api_key(headers: &HeaderMap) -> RouterResult<&str> { get_header_value_by_key("api-key".into(), headers)?.get_required_value("api_key") } <file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="113" end="157"> pub enum AuthenticationType { ApiKey { merchant_id: id_type::MerchantId, key_id: id_type::ApiKeyId, }, AdminApiKey, AdminApiAuthWithMerchantId { merchant_id: id_type::MerchantId, }, OrganizationJwt { org_id: id_type::OrganizationId, user_id: String, }, MerchantJwt { merchant_id: id_type::MerchantId, user_id: Option<String>, }, MerchantJwtWithProfileId { merchant_id: id_type::MerchantId, profile_id: Option<id_type::ProfileId>, user_id: String, }, UserJwt { user_id: String, }, SinglePurposeJwt { user_id: String, purpose: TokenPurpose, }, SinglePurposeOrLoginJwt { user_id: String, purpose: Option<TokenPurpose>, role_id: Option<String>, }, MerchantId { merchant_id: id_type::MerchantId, }, PublishableKey { merchant_id: id_type::MerchantId, }, WebhookAuth { merchant_id: id_type::MerchantId, }, NoAuth, } <file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="64" end="69"> pub struct AuthenticationData { pub merchant_account: domain::MerchantAccount, pub platform_merchant_account: Option<domain::MerchantAccount>, pub key_store: domain::MerchantKeyStore, pub profile_id: Option<id_type::ProfileId>, } <file_sep path="hyperswitch/crates/router/tests/utils.rs" role="context" start="394" end="396"> pub struct ApiKey { api_key: String, } <file_sep path="hyperswitch-encryption-service/migrations/2024-05-28-075150_create_dek_table/up.sql" role="context" start="1" end="9"> CREATE TABLE IF NOT EXISTS data_key_store ( id SERIAL PRIMARY KEY, key_identifier VARCHAR(255) NOT NULL, data_identifier VARCHAR(20) NOT NULL, encryption_key bytea NOT NULL, version VARCHAR(30) NOT NULL, created_at TIMESTAMP NOT NULL ); <file_sep path="hyperswitch/crates/api_models/src/errors/types.rs" role="context" start="86" end="100"> pub enum ApiErrorResponse { Unauthorized(ApiError), ForbiddenCommonResource(ApiError), ForbiddenPrivateResource(ApiError), Conflict(ApiError), Gone(ApiError), Unprocessable(ApiError), InternalServerError(ApiError), NotImplemented(ApiError), ConnectorError(ApiError, #[serde(skip_serializing)] StatusCode), NotFound(ApiError), MethodNotAllowed(ApiError), BadRequest(ApiError), DomainError(ApiError), }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/services/authentication.rs<|crate|> router anchor=authenticate_and_fetch kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="414" end="519"> async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<(AuthenticationData, AuthenticationType)> { let api_key = get_api_key(request_headers) .change_context(errors::ApiErrorResponse::Unauthorized)? .trim(); if api_key.is_empty() { return Err(errors::ApiErrorResponse::Unauthorized) .attach_printable("API key is empty"); } let profile_id = HeaderMapStruct::new(request_headers) .get_id_type_from_header::<id_type::ProfileId>(headers::X_PROFILE_ID)?; let api_key = api_keys::PlaintextApiKey::from(api_key); let hash_key = { let config = state.conf(); config.api_keys.get_inner().get_hash_key()? }; let hashed_api_key = api_key.keyed_hash(hash_key.peek()); let stored_api_key = state .store() .find_api_key_by_hash_optional(hashed_api_key.into()) .await .change_context(errors::ApiErrorResponse::InternalServerError) // If retrieve failed .attach_printable("Failed to retrieve API key")? .ok_or(report!(errors::ApiErrorResponse::Unauthorized)) // If retrieve returned `None` .attach_printable("Merchant not authenticated")?; if stored_api_key .expires_at .map(|expires_at| expires_at < date_time::now()) .unwrap_or(false) { return Err(report!(errors::ApiErrorResponse::Unauthorized)) .attach_printable("API key has expired"); } let key_manager_state = &(&state.session_state()).into(); let key_store = state .store() .get_merchant_key_store_by_merchant_id( key_manager_state, &stored_api_key.merchant_id, &state.store().get_master_key().to_vec().into(), ) .await .change_context(errors::ApiErrorResponse::Unauthorized) .attach_printable("Failed to fetch merchant key store for the merchant id")?; let merchant = state .store() .find_merchant_account_by_merchant_id( key_manager_state, &stored_api_key.merchant_id, &key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; // Get connected merchant account if API call is done by Platform merchant account on behalf of connected merchant account let (merchant, platform_merchant_account) = if state.conf().platform.enabled { get_platform_merchant_account(state, request_headers, merchant).await? } else { (merchant, None) }; let key_store = if platform_merchant_account.is_some() { state .store() .get_merchant_key_store_by_merchant_id( key_manager_state, merchant.get_id(), &state.store().get_master_key().to_vec().into(), ) .await .change_context(errors::ApiErrorResponse::Unauthorized) .attach_printable("Failed to fetch merchant key store for the merchant id")? } else { key_store }; let profile = state .store() .find_business_profile_by_profile_id(key_manager_state, &key_store, &profile_id) .await .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; let auth = AuthenticationData { merchant_account: merchant, platform_merchant_account, key_store, profile, }; Ok(( auth.clone(), AuthenticationType::ApiKey { merchant_id: auth.merchant_account.get_id().clone(), key_id: stored_api_key.key_id, }, )) } <file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="413" end="413"> use actix_web::http::header::HeaderMap; use common_utils::{date_time, fp_utils, id_type}; use error_stack::{report, ResultExt}; use self::blacklist::BlackList; use self::detached::ExtractedPayload; use self::detached::GetAuthType; use super::authorization::{self, permissions::Permission}; use crate::core::errors::UserResult; use crate::{ core::{ api_keys, errors::{self, utils::StorageErrorExt, RouterResult}, }, headers, routes::app::SessionStateInfo, services::api, types::{domain, storage}, utils::OptionExt, }; pub type AuthenticationDataWithUserId = (AuthenticationData, String); <file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="641" end="643"> fn get_auth_type(&self) -> detached::PayloadType { detached::PayloadType::ApiKey } <file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="528" end="633"> async fn authenticate_and_fetch( &self, request_headers: &HeaderMap, state: &A, ) -> RouterResult<(AuthenticationData, AuthenticationType)> { let api_key = get_api_key(request_headers) .change_context(errors::ApiErrorResponse::Unauthorized)? .trim(); if api_key.is_empty() { return Err(errors::ApiErrorResponse::Unauthorized) .attach_printable("API key is empty"); } let api_key = api_keys::PlaintextApiKey::from(api_key); let hash_key = { let config = state.conf(); config.api_keys.get_inner().get_hash_key()? }; let hashed_api_key = api_key.keyed_hash(hash_key.peek()); let stored_api_key = state .store() .find_api_key_by_hash_optional(hashed_api_key.into()) .await .change_context(errors::ApiErrorResponse::InternalServerError) // If retrieve failed .attach_printable("Failed to retrieve API key")? .ok_or(report!(errors::ApiErrorResponse::Unauthorized)) // If retrieve returned `None` .attach_printable("Merchant not authenticated")?; if stored_api_key .expires_at .map(|expires_at| expires_at < date_time::now()) .unwrap_or(false) { return Err(report!(errors::ApiErrorResponse::Unauthorized)) .attach_printable("API key has expired"); } let key_manager_state = &(&state.session_state()).into(); let key_store = state .store() .get_merchant_key_store_by_merchant_id( key_manager_state, &stored_api_key.merchant_id, &state.store().get_master_key().to_vec().into(), ) .await .change_context(errors::ApiErrorResponse::Unauthorized) .attach_printable("Failed to fetch merchant key store for the merchant id")?; let profile_id = get_header_value_by_key(headers::X_PROFILE_ID.to_string(), request_headers)? .map(id_type::ProfileId::from_str) .transpose() .change_context(errors::ValidationError::IncorrectValueProvided { field_name: "X-Profile-Id", }) .change_context(errors::ApiErrorResponse::Unauthorized)?; let merchant = state .store() .find_merchant_account_by_merchant_id( key_manager_state, &stored_api_key.merchant_id, &key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; // Get connected merchant account if API call is done by Platform merchant account on behalf of connected merchant account let (merchant, platform_merchant_account) = if state.conf().platform.enabled { get_platform_merchant_account(state, request_headers, merchant).await? } else { (merchant, None) }; let key_store = if platform_merchant_account.is_some() { state .store() .get_merchant_key_store_by_merchant_id( key_manager_state, merchant.get_id(), &state.store().get_master_key().to_vec().into(), ) .await .change_context(errors::ApiErrorResponse::Unauthorized) .attach_printable("Failed to fetch merchant key store for the merchant id")? } else { key_store }; let auth = AuthenticationData { merchant_account: merchant, platform_merchant_account, key_store, profile_id, }; Ok(( auth.clone(), AuthenticationType::ApiKey { merchant_id: auth.merchant_account.get_id().clone(), key_id: stored_api_key.key_id, }, )) } <file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="399" end="405"> async fn authenticate_and_fetch( &self, _request_headers: &HeaderMap, _state: &A, ) -> RouterResult<(Option<T>, AuthenticationType)> { Ok((None, AuthenticationType::NoAuth)) } <file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="385" end="391"> async fn authenticate_and_fetch( &self, _request_headers: &HeaderMap, _state: &A, ) -> RouterResult<((), AuthenticationType)> { Ok(((), AuthenticationType::NoAuth)) } <file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="3991" end="4014"> async fn get_platform_merchant_account<A>( state: &A, request_headers: &HeaderMap, merchant_account: domain::MerchantAccount, ) -> RouterResult<(domain::MerchantAccount, Option<domain::MerchantAccount>)> where A: SessionStateInfo + Sync, { let connected_merchant_id = get_and_validate_connected_merchant_id(request_headers, &merchant_account)?; match connected_merchant_id { Some(merchant_id) => { let connected_merchant_account = get_connected_merchant_account( state, merchant_id, merchant_account.organization_id.clone(), ) .await?; Ok((connected_merchant_account, Some(merchant_account))) } None => Ok((merchant_account, None)), } } <file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="1506" end="1508"> pub fn new(headers: &'a HeaderMap) -> Self { HeaderMapStruct { headers } } <file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="1501" end="1503"> pub(crate) struct HeaderMapStruct<'a> { headers: &'a HeaderMap, } <file_sep path="hyperswitch/crates/router/src/services/authentication.rs" role="context" start="113" end="157"> pub enum AuthenticationType { ApiKey { merchant_id: id_type::MerchantId, key_id: id_type::ApiKeyId, }, AdminApiKey, AdminApiAuthWithMerchantId { merchant_id: id_type::MerchantId, }, OrganizationJwt { org_id: id_type::OrganizationId, user_id: String, }, MerchantJwt { merchant_id: id_type::MerchantId, user_id: Option<String>, }, MerchantJwtWithProfileId { merchant_id: id_type::MerchantId, profile_id: Option<id_type::ProfileId>, user_id: String, }, UserJwt { user_id: String, }, SinglePurposeJwt { user_id: String, purpose: TokenPurpose, }, SinglePurposeOrLoginJwt { user_id: String, purpose: Option<TokenPurpose>, role_id: Option<String>, }, MerchantId { merchant_id: id_type::MerchantId, }, PublishableKey { merchant_id: id_type::MerchantId, }, WebhookAuth { merchant_id: id_type::MerchantId, }, NoAuth, } <file_sep path="hyperswitch/crates/router/tests/utils.rs" role="context" start="394" end="396"> pub struct ApiKey { api_key: String, } <file_sep path="hyperswitch-encryption-service/migrations/2024-05-28-075150_create_dek_table/up.sql" role="context" start="1" end="9"> CREATE TABLE IF NOT EXISTS data_key_store ( id SERIAL PRIMARY KEY, key_identifier VARCHAR(255) NOT NULL, data_identifier VARCHAR(20) NOT NULL, encryption_key bytea NOT NULL, version VARCHAR(30) NOT NULL, created_at TIMESTAMP NOT NULL ); <file_sep path="hyperswitch/crates/api_models/src/errors/types.rs" role="context" start="86" end="100"> pub enum ApiErrorResponse { Unauthorized(ApiError), ForbiddenCommonResource(ApiError), ForbiddenPrivateResource(ApiError), Conflict(ApiError), Gone(ApiError), Unprocessable(ApiError), InternalServerError(ApiError), NotImplemented(ApiError), ConnectorError(ApiError, #[serde(skip_serializing)] StatusCode), NotFound(ApiError), MethodNotAllowed(ApiError), BadRequest(ApiError), DomainError(ApiError), }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payment_methods/transformers.rs<|crate|> router anchor=get_dotted_jws kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/src/core/payment_methods/transformers.rs" role="context" start="204" end="209"> pub fn get_dotted_jws(jws: encryption::JwsBody) -> String { let header = jws.header; let payload = jws.payload; let signature = jws.signature; format!("{header}.{payload}.{signature}") } <file_sep path="hyperswitch/crates/router/src/core/payment_methods/transformers.rs" role="context" start="203" end="203"> use crate::{ configs::settings, core::errors::{self, CustomResult}, headers, pii::{prelude::*, Secret}, services::{api as services, encryption, EncryptionAlgorithm}, types::{api, domain}, utils::OptionExt, }; <file_sep path="hyperswitch/crates/router/src/core/payment_methods/transformers.rs" role="context" start="253" end="286"> pub async fn get_decrypted_vault_response_payload( jwekey: &settings::Jwekey, jwe_body: encryption::JweBody, decryption_scheme: settings::DecryptionScheme, ) -> CustomResult<String, errors::VaultError> { let public_key = jwekey.vault_encryption_key.peek().as_bytes(); let private_key = jwekey.vault_private_key.peek().as_bytes(); let jwt = get_dotted_jwe(jwe_body); let alg = match decryption_scheme { settings::DecryptionScheme::RsaOaep => jwe::RSA_OAEP, settings::DecryptionScheme::RsaOaep256 => jwe::RSA_OAEP_256, }; let jwe_decrypted = encryption::decrypt_jwe( &jwt, encryption::KeyIdCheck::SkipKeyIdCheck, private_key, alg, ) .await .change_context(errors::VaultError::SaveCardFailed) .attach_printable("Jwe Decryption failed for JweBody for vault")?; let jws = jwe_decrypted .parse_struct("JwsBody") .change_context(errors::VaultError::ResponseDeserializationFailed)?; let jws_body = get_dotted_jws(jws); encryption::verify_sign(jws_body, public_key) .change_context(errors::VaultError::SaveCardFailed) .attach_printable("Jws Decryption failed for JwsBody for vault") } <file_sep path="hyperswitch/crates/router/src/core/payment_methods/transformers.rs" role="context" start="211" end="251"> pub async fn get_decrypted_response_payload( jwekey: &settings::Jwekey, jwe_body: encryption::JweBody, locker_choice: Option<api_enums::LockerChoice>, decryption_scheme: settings::DecryptionScheme, ) -> CustomResult<String, errors::VaultError> { let target_locker = locker_choice.unwrap_or(api_enums::LockerChoice::HyperswitchCardVault); let public_key = match target_locker { api_enums::LockerChoice::HyperswitchCardVault => { jwekey.vault_encryption_key.peek().as_bytes() } }; let private_key = jwekey.vault_private_key.peek().as_bytes(); let jwt = get_dotted_jwe(jwe_body); let alg = match decryption_scheme { settings::DecryptionScheme::RsaOaep => jwe::RSA_OAEP, settings::DecryptionScheme::RsaOaep256 => jwe::RSA_OAEP_256, }; let jwe_decrypted = encryption::decrypt_jwe( &jwt, encryption::KeyIdCheck::SkipKeyIdCheck, private_key, alg, ) .await .change_context(errors::VaultError::SaveCardFailed) .attach_printable("Jwe Decryption failed for JweBody for vault")?; let jws = jwe_decrypted .parse_struct("JwsBody") .change_context(errors::VaultError::ResponseDeserializationFailed)?; let jws_body = get_dotted_jws(jws); encryption::verify_sign(jws_body, public_key) .change_context(errors::VaultError::SaveCardFailed) .attach_printable("Jws Decryption failed for JwsBody for vault") } <file_sep path="hyperswitch/crates/router/src/core/payment_methods/transformers.rs" role="context" start="195" end="202"> pub fn get_dotted_jwe(jwe: encryption::JweBody) -> String { let header = jwe.header; let encryption_key = jwe.encrypted_key; let iv = jwe.iv; let encryption_payload = jwe.encrypted_payload; let tag = jwe.tag; format!("{header}.{encryption_key}.{iv}.{encryption_payload}.{tag}") } <file_sep path="hyperswitch/crates/router/src/core/payment_methods/transformers.rs" role="context" start="35" end="40"> pub fn update_requestor_card_reference(&mut self, card_reference: Option<String>) { match self { Self::LockerCard(c) => c.requestor_card_reference = card_reference, Self::LockerGeneric(_) => (), } }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payments/transformers.rs<|crate|> router anchor=paypal_sdk_next_steps_check kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/core/payments/transformers.rs" role="context" start="2678" end="2692"> pub fn paypal_sdk_next_steps_check( payment_attempt: storage::PaymentAttempt, ) -> RouterResult<Option<api_models::payments::SdkNextActionData>> { let paypal_connector_metadata: Option<Result<api_models::payments::SdkNextActionData, _>> = payment_attempt.connector_metadata.map(|metadata| { metadata.parse_value("SdkNextActionData").map_err(|_| { crate::logger::warn!( "SdkNextActionData parsing failed for paypal_connector_metadata" ) }) }); let paypal_next_steps = paypal_connector_metadata.transpose().ok().flatten(); Ok(paypal_next_steps) } <file_sep path="hyperswitch/crates/router/src/core/payments/transformers.rs" role="context" start="2677" end="2677"> use api_models::payments::{ Address, ConnectorMandateReferenceId, CustomerDetails, CustomerDetailsResponse, FrmMessage, RequestSurchargeDetails, }; use diesel_models::{ ephemeral_key, payment_attempt::ConnectorMandateReferenceId as DieselConnectorMandateReferenceId, }; use hyperswitch_domain_models::{payments::payment_intent::CustomerData, router_request_types}; use crate::{ configs::settings::ConnectorRequestReferenceIdConfig, core::{ errors::{self, RouterResponse, RouterResult}, payments::{self, helpers}, utils as core_utils, }, headers::X_PAYMENT_CONFIRM_SOURCE, routes::{metrics, SessionState}, services::{self, RedirectForm}, types::{ self, api::{self, ConnectorTransactionId}, domain, storage::{self, enums}, transformers::{ForeignFrom, ForeignInto, ForeignTryFrom}, MultipleCaptureRequestData, }, utils::{OptionExt, ValueExt}, }; <file_sep path="hyperswitch/crates/router/src/core/payments/transformers.rs" role="context" start="2706" end="2718"> pub fn wait_screen_next_steps_check( payment_attempt: storage::PaymentAttempt, ) -> RouterResult<Option<api_models::payments::WaitScreenInstructions>> { let display_info_with_timer_steps: Option< Result<api_models::payments::WaitScreenInstructions, _>, > = payment_attempt .connector_metadata .map(|metadata| metadata.parse_value("WaitScreenInstructions")); let display_info_with_timer_instructions = display_info_with_timer_steps.transpose().ok().flatten(); Ok(display_info_with_timer_instructions) } <file_sep path="hyperswitch/crates/router/src/core/payments/transformers.rs" role="context" start="2694" end="2704"> pub fn fetch_qr_code_url_next_steps_check( payment_attempt: storage::PaymentAttempt, ) -> RouterResult<Option<api_models::payments::FetchQrCodeInformation>> { let qr_code_steps: Option<Result<api_models::payments::FetchQrCodeInformation, _>> = payment_attempt .connector_metadata .map(|metadata| metadata.parse_value("FetchQrCodeInformation")); let qr_code_fetch_url = qr_code_steps.transpose().ok().flatten(); Ok(qr_code_fetch_url) } <file_sep path="hyperswitch/crates/router/src/core/payments/transformers.rs" role="context" start="2668" end="2677"> pub fn qr_code_next_steps_check( payment_attempt: storage::PaymentAttempt, ) -> RouterResult<Option<api_models::payments::QrCodeInformation>> { let qr_code_steps: Option<Result<api_models::payments::QrCodeInformation, _>> = payment_attempt .connector_metadata .map(|metadata| metadata.parse_value("QrCodeInformation")); let qr_code_instructions = qr_code_steps.transpose().ok().flatten(); Ok(qr_code_instructions) } <file_sep path="hyperswitch/crates/router/src/core/payments/transformers.rs" role="context" start="2609" end="2666"> pub fn third_party_sdk_session_next_action<Op>( payment_attempt: &storage::PaymentAttempt, operation: &Op, ) -> bool where Op: Debug, { // If the operation is confirm, we will send session token response in next action if format!("{operation:?}").eq("PaymentConfirm") { let condition1 = payment_attempt .connector .as_ref() .map(|connector| { matches!(connector.as_str(), "trustpay") || matches!(connector.as_str(), "payme") }) .and_then(|is_connector_supports_third_party_sdk| { if is_connector_supports_third_party_sdk { payment_attempt .payment_method .map(|pm| matches!(pm, diesel_models::enums::PaymentMethod::Wallet)) } else { Some(false) } }) .unwrap_or(false); // This condition to be triggered for open banking connectors, third party SDK session token will be provided let condition2 = payment_attempt .connector .as_ref() .map(|connector| matches!(connector.as_str(), "plaid")) .and_then(|is_connector_supports_third_party_sdk| { if is_connector_supports_third_party_sdk { payment_attempt .payment_method .map(|pm| matches!(pm, diesel_models::enums::PaymentMethod::OpenBanking)) .and_then(|first_match| { payment_attempt .payment_method_type .map(|pmt| { matches!( pmt, diesel_models::enums::PaymentMethodType::OpenBankingPIS ) }) .map(|second_match| first_match && second_match) }) } else { Some(false) } }) .unwrap_or(false); condition1 || condition2 } else { false } } <file_sep path="hyperswitch/crates/router/src/core/payments/transformers.rs" role="context" start="1835" end="1861"> fn generate_response( payment_data: D, _customer: Option<domain::Customer>, _auth_flow: services::AuthFlow, _base_url: &str, _operation: Op, _connector_request_reference_id_config: &ConnectorRequestReferenceIdConfig, _connector_http_status_code: Option<u16>, _external_latency: Option<u128>, _is_latency_header_enabled: Option<bool>, ) -> RouterResponse<Self> { let papal_sdk_next_action = paypal_sdk_next_steps_check(payment_data.get_payment_attempt().clone())?; let next_action = papal_sdk_next_action.map(|paypal_next_action_data| { api_models::payments::NextActionData::InvokeSdkClient { next_action_data: paypal_next_action_data, } }); Ok(services::ApplicationResponse::JsonWithHeaders(( Self { payment_id: payment_data.get_payment_intent().payment_id.clone(), next_action, status: payment_data.get_payment_intent().status, }, vec![], ))) } <file_sep path="hyperswitch/crates/router/src/core/payments/transformers.rs" role="context" start="2025" end="2606"> pub fn payments_to_payments_response<Op, F: Clone, D>( payment_data: D, captures: Option<Vec<storage::Capture>>, customer: Option<domain::Customer>, _auth_flow: services::AuthFlow, base_url: &str, operation: &Op, connector_request_reference_id_config: &ConnectorRequestReferenceIdConfig, connector_http_status_code: Option<u16>, external_latency: Option<u128>, _is_latency_header_enabled: Option<bool>, ) -> RouterResponse<api::PaymentsResponse> where Op: Debug, D: OperationSessionGetters<F>, { use std::ops::Not; let payment_attempt = payment_data.get_payment_attempt().clone(); let payment_intent = payment_data.get_payment_intent().clone(); let payment_link_data = payment_data.get_payment_link_data(); let currency = payment_attempt .currency .as_ref() .get_required_value("currency")?; let amount = currency .to_currency_base_unit( payment_attempt .net_amount .get_total_amount() .get_amount_as_i64(), ) .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "amount", })?; let mandate_id = payment_attempt.mandate_id.clone(); let refunds_response = payment_data.get_refunds().is_empty().not().then(|| { payment_data .get_refunds() .into_iter() .map(ForeignInto::foreign_into) .collect() }); let disputes_response = payment_data.get_disputes().is_empty().not().then(|| { payment_data .get_disputes() .into_iter() .map(ForeignInto::foreign_into) .collect() }); let incremental_authorizations_response = payment_data.get_authorizations().is_empty().not().then(|| { payment_data .get_authorizations() .into_iter() .map(ForeignInto::foreign_into) .collect() }); let external_authentication_details = payment_data .get_authentication() .map(ForeignInto::foreign_into); let attempts_response = payment_data.get_attempts().map(|attempts| { attempts .into_iter() .map(ForeignInto::foreign_into) .collect() }); let captures_response = captures.map(|captures| { captures .into_iter() .map(ForeignInto::foreign_into) .collect() }); let merchant_id = payment_attempt.merchant_id.to_owned(); let payment_method_type = payment_attempt .payment_method_type .as_ref() .map(ToString::to_string) .unwrap_or("".to_owned()); let payment_method = payment_attempt .payment_method .as_ref() .map(ToString::to_string) .unwrap_or("".to_owned()); let additional_payment_method_data: Option<api_models::payments::AdditionalPaymentData> = payment_attempt .payment_method_data .clone() .and_then(|data| match data { serde_json::Value::Null => None, // This is to handle the case when the payment_method_data is null _ => Some(data.parse_value("AdditionalPaymentData")), }) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse the AdditionalPaymentData from payment_attempt.payment_method_data")?; let surcharge_details = payment_attempt .net_amount .get_surcharge_amount() .map(|surcharge_amount| RequestSurchargeDetails { surcharge_amount, tax_amount: payment_attempt.net_amount.get_tax_on_surcharge(), }); let merchant_decision = payment_intent.merchant_decision.to_owned(); let frm_message = payment_data.get_frm_message().map(FrmMessage::foreign_from); let payment_method_data = additional_payment_method_data.map(api::PaymentMethodDataResponse::from); let payment_method_data_response = (payment_method_data.is_some() || payment_data .get_address() .get_request_payment_method_billing() .is_some()) .then_some(api_models::payments::PaymentMethodDataResponseWithBilling { payment_method_data, billing: payment_data .get_address() .get_request_payment_method_billing() .cloned() .map(From::from), }); let mut headers = connector_http_status_code .map(|status_code| { vec![( "connector_http_status_code".to_string(), Maskable::new_normal(status_code.to_string()), )] }) .unwrap_or_default(); if let Some(payment_confirm_source) = payment_intent.payment_confirm_source { headers.push(( X_PAYMENT_CONFIRM_SOURCE.to_string(), Maskable::new_normal(payment_confirm_source.to_string()), )) } // For the case when we don't have Customer data directly stored in Payment intent let customer_table_response: Option<CustomerDetailsResponse> = customer.as_ref().map(ForeignInto::foreign_into); // If we have customer data in Payment Intent and if the customer is not deleted, We are populating the Retrieve response from the // same. If the customer is deleted then we use the customer table to populate customer details let customer_details_response = if let Some(customer_details_raw) = payment_intent.customer_details.clone() { let customer_details_encrypted = serde_json::from_value::<CustomerData>(customer_details_raw.into_inner().expose()); if let Ok(customer_details_encrypted_data) = customer_details_encrypted { Some(CustomerDetailsResponse { id: customer_table_response .as_ref() .and_then(|customer_data| customer_data.id.clone()), name: customer_table_response .as_ref() .and_then(|customer_data| customer_data.name.clone()) .or(customer_details_encrypted_data .name .or(customer.as_ref().and_then(|customer| { customer.name.as_ref().map(|name| name.clone().into_inner()) }))), email: customer_table_response .as_ref() .and_then(|customer_data| customer_data.email.clone()) .or(customer_details_encrypted_data.email.or(customer .as_ref() .and_then(|customer| customer.email.clone().map(pii::Email::from)))), phone: customer_table_response .as_ref() .and_then(|customer_data| customer_data.phone.clone()) .or(customer_details_encrypted_data .phone .or(customer.as_ref().and_then(|customer| { customer .phone .as_ref() .map(|phone| phone.clone().into_inner()) }))), phone_country_code: customer_table_response .as_ref() .and_then(|customer_data| customer_data.phone_country_code.clone()) .or(customer_details_encrypted_data .phone_country_code .or(customer .as_ref() .and_then(|customer| customer.phone_country_code.clone()))), }) } else { customer_table_response } } else { customer_table_response }; headers.extend( external_latency .map(|latency| { vec![( X_HS_LATENCY.to_string(), Maskable::new_normal(latency.to_string()), )] }) .unwrap_or_default(), ); let output = if payments::is_start_pay(&operation) && payment_attempt.authentication_data.is_some() { let redirection_data = payment_attempt .authentication_data .clone() .get_required_value("redirection_data")?; let form: RedirectForm = serde_json::from_value(redirection_data) .map_err(|_| errors::ApiErrorResponse::InternalServerError)?; services::ApplicationResponse::Form(Box::new(services::RedirectionFormData { redirect_form: form, payment_method_data: payment_data.get_payment_method_data().cloned(), amount, currency: currency.to_string(), })) } else { let mut next_action_response = None; let bank_transfer_next_steps = bank_transfer_next_steps_check(payment_attempt.clone())?; let next_action_voucher = voucher_next_steps_check(payment_attempt.clone())?; let next_action_mobile_payment = mobile_payment_next_steps_check(&payment_attempt)?; let next_action_containing_qr_code_url = qr_code_next_steps_check(payment_attempt.clone())?; let papal_sdk_next_action = paypal_sdk_next_steps_check(payment_attempt.clone())?; let next_action_containing_fetch_qr_code_url = fetch_qr_code_url_next_steps_check(payment_attempt.clone())?; let next_action_containing_wait_screen = wait_screen_next_steps_check(payment_attempt.clone())?; let next_action_invoke_hidden_frame = next_action_invoke_hidden_frame(&payment_attempt)?; if payment_intent.status == enums::IntentStatus::RequiresCustomerAction || bank_transfer_next_steps.is_some() || next_action_voucher.is_some() || next_action_containing_qr_code_url.is_some() || next_action_containing_wait_screen.is_some() || papal_sdk_next_action.is_some() || next_action_containing_fetch_qr_code_url.is_some() || payment_data.get_authentication().is_some() { next_action_response = bank_transfer_next_steps .map(|bank_transfer| { api_models::payments::NextActionData::DisplayBankTransferInformation { bank_transfer_steps_and_charges_details: bank_transfer, } }) .or(next_action_voucher.map(|voucher_data| { api_models::payments::NextActionData::DisplayVoucherInformation { voucher_details: voucher_data, } })) .or(next_action_mobile_payment.map(|mobile_payment_data| { api_models::payments::NextActionData::CollectOtp { consent_data_required: mobile_payment_data.consent_data_required, } })) .or(next_action_containing_qr_code_url.map(|qr_code_data| { api_models::payments::NextActionData::foreign_from(qr_code_data) })) .or(next_action_containing_fetch_qr_code_url.map(|fetch_qr_code_data| { api_models::payments::NextActionData::FetchQrCodeInformation { qr_code_fetch_url: fetch_qr_code_data.qr_code_fetch_url } })) .or(papal_sdk_next_action.map(|paypal_next_action_data| { api_models::payments::NextActionData::InvokeSdkClient{ next_action_data: paypal_next_action_data } })) .or(next_action_containing_wait_screen.map(|wait_screen_data| { api_models::payments::NextActionData::WaitScreenInformation { display_from_timestamp: wait_screen_data.display_from_timestamp, display_to_timestamp: wait_screen_data.display_to_timestamp, } })) .or(payment_attempt.authentication_data.as_ref().map(|_| { api_models::payments::NextActionData::RedirectToUrl { redirect_to_url: helpers::create_startpay_url( base_url, &payment_attempt, &payment_intent, ), } })) .or(match payment_data.get_authentication().as_ref(){ Some(authentication) => { if payment_intent.status == common_enums::IntentStatus::RequiresCustomerAction && authentication.cavv.is_none() && authentication.is_separate_authn_required(){ // if preAuthn and separate authentication needed. let poll_config = payment_data.get_poll_config().unwrap_or_default(); let request_poll_id = core_utils::get_external_authentication_request_poll_id(&payment_intent.payment_id); let payment_connector_name = payment_attempt.connector .as_ref() .get_required_value("connector")?; Some(api_models::payments::NextActionData::ThreeDsInvoke { three_ds_data: api_models::payments::ThreeDsData { three_ds_authentication_url: helpers::create_authentication_url(base_url, &payment_attempt), three_ds_authorize_url: helpers::create_authorize_url( base_url, &payment_attempt, payment_connector_name, ), three_ds_method_details: authentication.three_ds_method_url.as_ref().zip(authentication.three_ds_method_data.as_ref()).map(|(three_ds_method_url,three_ds_method_data )|{ api_models::payments::ThreeDsMethodData::AcsThreeDsMethodData { three_ds_method_data_submission: true, three_ds_method_data: Some(three_ds_method_data.clone()), three_ds_method_url: Some(three_ds_method_url.to_owned()), } }).unwrap_or(api_models::payments::ThreeDsMethodData::AcsThreeDsMethodData { three_ds_method_data_submission: false, three_ds_method_data: None, three_ds_method_url: None, }), poll_config: api_models::payments::PollConfigResponse {poll_id: request_poll_id, delay_in_secs: poll_config.delay_in_secs, frequency: poll_config.frequency}, message_version: authentication.message_version.as_ref() .map(|version| version.to_string()), directory_server_id: authentication.directory_server_id.clone(), }, }) }else{ None } }, None => None }) .or(match next_action_invoke_hidden_frame{ Some(threeds_invoke_data) => Some(construct_connector_invoke_hidden_frame( threeds_invoke_data, )?), None => None }); }; // next action check for third party sdk session (for ex: Apple pay through trustpay has third party sdk session response) if third_party_sdk_session_next_action(&payment_attempt, operation) { next_action_response = Some( api_models::payments::NextActionData::ThirdPartySdkSessionToken { session_token: payment_data.get_sessions_token().first().cloned(), }, ) } let routed_through = payment_attempt.connector.clone(); let connector_label = routed_through.as_ref().and_then(|connector_name| { core_utils::get_connector_label( payment_intent.business_country, payment_intent.business_label.as_ref(), payment_attempt.business_sub_label.as_ref(), connector_name, ) }); let mandate_data = payment_data.get_setup_mandate().map(|d| api::MandateData { customer_acceptance: d .customer_acceptance .clone() .map(|d| api::CustomerAcceptance { acceptance_type: match d.acceptance_type { hyperswitch_domain_models::mandates::AcceptanceType::Online => { api::AcceptanceType::Online } hyperswitch_domain_models::mandates::AcceptanceType::Offline => { api::AcceptanceType::Offline } }, accepted_at: d.accepted_at, online: d.online.map(|d| api::OnlineMandate { ip_address: d.ip_address, user_agent: d.user_agent, }), }), mandate_type: d.mandate_type.clone().map(|d| match d { hyperswitch_domain_models::mandates::MandateDataType::MultiUse(Some(i)) => { api::MandateType::MultiUse(Some(api::MandateAmountData { amount: i.amount, currency: i.currency, start_date: i.start_date, end_date: i.end_date, metadata: i.metadata, })) } hyperswitch_domain_models::mandates::MandateDataType::SingleUse(i) => { api::MandateType::SingleUse(api::payments::MandateAmountData { amount: i.amount, currency: i.currency, start_date: i.start_date, end_date: i.end_date, metadata: i.metadata, }) } hyperswitch_domain_models::mandates::MandateDataType::MultiUse(None) => { api::MandateType::MultiUse(None) } }), update_mandate_id: d.update_mandate_id.clone(), }); let order_tax_amount = payment_data .get_payment_attempt() .net_amount .get_order_tax_amount() .or_else(|| { payment_data .get_payment_intent() .tax_details .clone() .and_then(|tax| { tax.payment_method_type .map(|a| a.order_tax_amount) .or_else(|| tax.default.map(|a| a.order_tax_amount)) }) }); let connector_mandate_id = payment_data.get_mandate_id().and_then(|mandate| { mandate .mandate_reference_id .as_ref() .and_then(|mandate_ref| match mandate_ref { api_models::payments::MandateReferenceId::ConnectorMandateId( connector_mandate_reference_id, ) => connector_mandate_reference_id.get_connector_mandate_id(), _ => None, }) }); let connector_transaction_id = payment_attempt .get_connector_payment_id() .map(ToString::to_string); let payments_response = api::PaymentsResponse { payment_id: payment_intent.payment_id, merchant_id: payment_intent.merchant_id, status: payment_intent.status, amount: payment_attempt.net_amount.get_order_amount(), net_amount: payment_attempt.get_total_amount(), amount_capturable: payment_attempt.amount_capturable, amount_received: payment_intent.amount_captured, connector: routed_through, client_secret: payment_intent.client_secret.map(Secret::new), created: Some(payment_intent.created_at), currency: currency.to_string(), customer_id: customer.as_ref().map(|cus| cus.clone().customer_id), customer: customer_details_response, description: payment_intent.description, refunds: refunds_response, disputes: disputes_response, attempts: attempts_response, captures: captures_response, mandate_id, mandate_data, setup_future_usage: payment_intent.setup_future_usage, off_session: payment_intent.off_session, capture_on: None, capture_method: payment_attempt.capture_method, payment_method: payment_attempt.payment_method, payment_method_data: payment_method_data_response, payment_token: payment_attempt.payment_token, shipping: payment_data .get_address() .get_shipping() .cloned() .map(From::from), billing: payment_data .get_address() .get_payment_billing() .cloned() .map(From::from), order_details: payment_intent.order_details, email: customer .as_ref() .and_then(|cus| cus.email.as_ref().map(|s| s.to_owned())), name: customer .as_ref() .and_then(|cus| cus.name.as_ref().map(|s| s.to_owned())), phone: customer .as_ref() .and_then(|cus| cus.phone.as_ref().map(|s| s.to_owned())), return_url: payment_intent.return_url, authentication_type: payment_attempt.authentication_type, statement_descriptor_name: payment_intent.statement_descriptor_name, statement_descriptor_suffix: payment_intent.statement_descriptor_suffix, next_action: next_action_response, cancellation_reason: payment_attempt.cancellation_reason, error_code: payment_attempt.error_code, error_message: payment_attempt .error_reason .or(payment_attempt.error_message), unified_code: payment_attempt.unified_code, unified_message: payment_attempt.unified_message, payment_experience: payment_attempt.payment_experience, payment_method_type: payment_attempt.payment_method_type, connector_label, business_country: payment_intent.business_country, business_label: payment_intent.business_label, business_sub_label: payment_attempt.business_sub_label, allowed_payment_method_types: payment_intent.allowed_payment_method_types, ephemeral_key: payment_data .get_ephemeral_key() .map(ForeignFrom::foreign_from), manual_retry_allowed: helpers::is_manual_retry_allowed( &payment_intent.status, &payment_attempt.status, connector_request_reference_id_config, &merchant_id, ), connector_transaction_id, frm_message, metadata: payment_intent.metadata, connector_metadata: payment_intent.connector_metadata, feature_metadata: payment_intent.feature_metadata, reference_id: payment_attempt.connector_response_reference_id, payment_link: payment_link_data, profile_id: payment_intent.profile_id, surcharge_details, attempt_count: payment_intent.attempt_count, merchant_decision, merchant_connector_id: payment_attempt.merchant_connector_id, incremental_authorization_allowed: payment_intent.incremental_authorization_allowed, authorization_count: payment_intent.authorization_count, incremental_authorizations: incremental_authorizations_response, external_authentication_details, external_3ds_authentication_attempted: payment_attempt .external_three_ds_authentication_attempted, expires_on: payment_intent.session_expiry, fingerprint: payment_intent.fingerprint_id, browser_info: payment_attempt.browser_info, payment_method_id: payment_attempt.payment_method_id, payment_method_status: payment_data .get_payment_method_info() .map(|info| info.status), updated: Some(payment_intent.modified_at), split_payments: payment_attempt.charges, frm_metadata: payment_intent.frm_metadata, merchant_order_reference_id: payment_intent.merchant_order_reference_id, order_tax_amount, connector_mandate_id, shipping_cost: payment_intent.shipping_cost, capture_before: payment_attempt.capture_before, extended_authorization_applied: payment_attempt.extended_authorization_applied, card_discovery: payment_attempt.card_discovery, force_3ds_challenge: payment_intent.force_3ds_challenge, force_3ds_challenge_trigger: payment_intent.force_3ds_challenge_trigger, issuer_error_code: payment_attempt.issuer_error_code, issuer_error_message: payment_attempt.issuer_error_message, }; services::ApplicationResponse::JsonWithHeaders((payments_response, headers)) }; metrics::PAYMENT_OPS_COUNT.add( 1, router_env::metric_attributes!( ("operation", format!("{:?}", operation)), ("merchant", merchant_id.clone()), ("payment_method_type", payment_method_type), ("payment_method", payment_method), ), ); Ok(output) } <file_sep path="hyperswitch/crates/router/src/core/errors.rs" role="context" start="31" end="31"> pub type RouterResult<T> = CustomResult<T, ApiErrorResponse>; <file_sep path="hyperswitch/v2_compatible_migrations/2024-08-28-081721_add_v2_columns/up.sql" role="context" start="37" end="53"> ADD COLUMN frm_merchant_decision VARCHAR(64), ADD COLUMN statement_descriptor VARCHAR(255), ADD COLUMN enable_payment_link BOOLEAN, ADD COLUMN apply_mit_exemption BOOLEAN, ADD COLUMN customer_present BOOLEAN, ADD COLUMN routing_algorithm_id VARCHAR(64), ADD COLUMN payment_link_config JSONB; ALTER TABLE payment_attempt ADD COLUMN payment_method_type_v2 VARCHAR, ADD COLUMN connector_payment_id VARCHAR(128), ADD COLUMN payment_method_subtype VARCHAR(64), ADD COLUMN routing_result JSONB, ADD COLUMN authentication_applied "AuthenticationType", ADD COLUMN external_reference_id VARCHAR(128), ADD COLUMN tax_on_surcharge BIGINT, ADD COLUMN payment_method_billing_address BYTEA, <file_sep path="hyperswitch/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/event.test.js" role="context" start="61" end="78"> "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.", ); } // Response body should have value "succeeded" for "status" if (jsonData?.status) { pm.test( "[POST]::/payments - Content check if value for 'status' matches 'succeeded'", function () { pm.expect(jsonData.status).to.eql("succeeded"); }, ); }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/core/webhooks/incoming_v2.rs<|crate|> router anchor=fetch_mca_and_connector kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/core/webhooks/incoming_v2.rs" role="context" start="773" end="795"> async fn fetch_mca_and_connector( state: &SessionState, connector_id: &common_utils::id_type::MerchantConnectorAccountId, key_store: &domain::MerchantKeyStore, ) -> CustomResult<(domain::MerchantConnectorAccount, ConnectorEnum, String), errors::ApiErrorResponse> { let db = &state.store; let mca = db .find_merchant_connector_account_by_id(&state.into(), connector_id, key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: connector_id.get_string_repr().to_owned(), }) .attach_printable("error while fetching merchant_connector_account from connector_id")?; let (connector, connector_name) = get_connector_by_connector_name( state, &mca.connector_name.to_string(), Some(mca.get_id()), )?; Ok((mca, connector, connector_name)) } <file_sep path="hyperswitch/crates/router/src/core/webhooks/incoming_v2.rs" role="context" start="772" end="772"> use common_utils::{ errors::ReportSwitchExt, events::ApiEventsType, types::keymanager::KeyManagerState, }; use crate::{ core::{ api_locking, errors::{self, ConnectorErrorExt, CustomResult, RouterResponse, StorageErrorExt}, metrics, payments::{ self, transformers::{GenerateResponse, ToResponse}, }, 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, ConnectorData, GetToken, IncomingWebhook}, domain, storage::enums, transformers::ForeignInto, }, }; <file_sep path="hyperswitch/crates/router/src/core/webhooks/incoming_v2.rs" role="context" start="726" end="770"> fn get_connector_by_connector_name( state: &SessionState, connector_name: &str, merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, ) -> CustomResult<(ConnectorEnum, String), errors::ApiErrorResponse> { let authentication_connector = api_models::enums::convert_authentication_connector(connector_name); #[cfg(feature = "frm")] { let frm_connector = api_models::enums::convert_frm_connector(connector_name); if frm_connector.is_some() { let frm_connector_data = api::FraudCheckConnectorData::get_connector_by_name(connector_name)?; return Ok(( frm_connector_data.connector, frm_connector_data.connector_name.to_string(), )); } } let (connector, connector_name) = if authentication_connector.is_some() { let authentication_connector_data = api::AuthenticationConnectorData::get_connector_by_name(connector_name)?; ( authentication_connector_data.connector, authentication_connector_data.connector_name.to_string(), ) } else { let connector_data = ConnectorData::get_connector_by_name( &state.conf.connectors, connector_name, GetToken::Connector, merchant_connector_id, ) .change_context(errors::ApiErrorResponse::InvalidRequestData { message: "invalid connector name received".to_string(), }) .attach_printable("Failed construction of ConnectorData")?; ( connector_data.connector, connector_data.connector_name.to_string(), ) }; Ok((connector, connector_name)) } <file_sep path="hyperswitch/crates/router/src/core/webhooks/incoming_v2.rs" role="context" start="666" end="724"> async fn verify_webhook_source_verification_call( connector: ConnectorEnum, state: &SessionState, merchant_account: &domain::MerchantAccount, merchant_connector_account: domain::MerchantConnectorAccount, connector_name: &str, request_details: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<bool, errors::ConnectorError> { let connector_data = ConnectorData::get_connector_by_name( &state.conf.connectors, connector_name, GetToken::Connector, None, ) .change_context(errors::ConnectorError::WebhookSourceVerificationFailed) .attach_printable("invalid connector name received in payment attempt")?; let connector_integration: services::BoxedWebhookSourceVerificationConnectorIntegrationInterface< hyperswitch_domain_models::router_flow_types::VerifyWebhookSource, VerifyWebhookSourceRequestData, VerifyWebhookSourceResponseData, > = connector_data.connector.get_connector_integration(); let connector_webhook_secrets = connector .get_webhook_source_verification_merchant_secret( merchant_account.get_id(), connector_name, merchant_connector_account.connector_webhook_details.clone(), ) .await .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; let router_data = construct_webhook_router_data( state, connector_name, merchant_connector_account, merchant_account, &connector_webhook_secrets, request_details, ) .await .change_context(errors::ConnectorError::WebhookSourceVerificationFailed) .attach_printable("Failed while constructing webhook router data")?; let response = services::execute_connector_processing_step( state, connector_integration, &router_data, payments::CallConnectorAction::Trigger, None, ) .await?; let verification_result = response .response .map(|response| response.verify_webhook_status); match verification_result { Ok(VerifyWebhookStatus::SourceVerified) => Ok(true), _ => Ok(false), } } <file_sep path="hyperswitch/crates/router/src/core/webhooks/incoming_v2.rs" role="context" start="122" end="396"> async fn incoming_webhooks_core<W: types::OutgoingWebhookType>( state: SessionState, req_state: ReqState, req: &actix_web::HttpRequest, merchant_account: domain::MerchantAccount, profile: domain::Profile, key_store: domain::MerchantKeyStore, connector_id: &common_utils::id_type::MerchantConnectorAccountId, body: actix_web::web::Bytes, _is_relay_webhook: bool, ) -> errors::RouterResult<( services::ApplicationResponse<serde_json::Value>, WebhookResponseTracker, serde_json::Value, )> { metrics::WEBHOOK_INCOMING_COUNT.add( 1, router_env::metric_attributes!((MERCHANT_ID, merchant_account.get_id().clone())), ); let mut request_details = IncomingWebhookRequestDetails { method: req.method().clone(), uri: req.uri().clone(), headers: req.headers(), query_params: req.query_string().to_string(), body: &body, }; // Fetch the merchant connector account to get the webhooks source secret // `webhooks source secret` is a secret shared between the merchant and connector // This is used for source verification and webhooks integrity let (merchant_connector_account, connector, connector_name) = fetch_mca_and_connector(&state, connector_id, &key_store).await?; let decoded_body = connector .decode_webhook_body( &request_details, merchant_account.get_id(), merchant_connector_account.connector_webhook_details.clone(), connector_name.as_str(), ) .await .switch() .attach_printable("There was an error in incoming webhook body decoding")?; request_details.body = &decoded_body; let event_type = match connector .get_webhook_event_type(&request_details) .allow_webhook_event_type_not_found( state .clone() .conf .webhooks .ignore_error .event_type .unwrap_or(true), ) .switch() .attach_printable("Could not find event type in incoming webhook body")? { Some(event_type) => event_type, // Early return allows us to acknowledge the webhooks that we do not support None => { logger::error!( webhook_payload =? request_details.body, "Failed while identifying the event type", ); metrics::WEBHOOK_EVENT_TYPE_IDENTIFICATION_FAILURE_COUNT.add( 1, router_env::metric_attributes!( (MERCHANT_ID, merchant_account.get_id().clone()), ("connector", connector_name) ), ); let response = connector .get_webhook_api_response(&request_details, None) .switch() .attach_printable("Failed while early return in case of event type parsing")?; return Ok(( response, WebhookResponseTracker::NoEffect, serde_json::Value::Null, )); } }; logger::info!(event_type=?event_type); let is_webhook_event_supported = !matches!( event_type, webhooks::IncomingWebhookEvent::EventNotSupported ); let is_webhook_event_enabled = !utils::is_webhook_event_disabled( &*state.clone().store, connector_name.as_str(), merchant_account.get_id(), &event_type, ) .await; //process webhook further only if webhook event is enabled and is not event_not_supported let process_webhook_further = is_webhook_event_enabled && is_webhook_event_supported; logger::info!(process_webhook=?process_webhook_further); let flow_type: api::WebhookFlow = event_type.into(); let mut event_object: Box<dyn masking::ErasedMaskSerialize> = Box::new(serde_json::Value::Null); let webhook_effect = if process_webhook_further && !matches!(flow_type, api::WebhookFlow::ReturnResponse) { let object_ref_id = connector .get_webhook_object_reference_id(&request_details) .switch() .attach_printable("Could not find object reference id in incoming webhook body")?; let connector_enum = api_models::enums::Connector::from_str(&connector_name) .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "connector", }) .attach_printable_lazy(|| { format!("unable to parse connector name {connector_name:?}") })?; let connectors_with_source_verification_call = &state.conf.webhook_source_verification_call; let source_verified = if connectors_with_source_verification_call .connectors_with_webhook_source_verification_call .contains(&connector_enum) { verify_webhook_source_verification_call( connector.clone(), &state, &merchant_account, merchant_connector_account.clone(), &connector_name, &request_details, ) .await .or_else(|error| match error.current_context() { errors::ConnectorError::WebhookSourceVerificationFailed => { logger::error!(?error, "Source Verification Failed"); Ok(false) } _ => Err(error), }) .switch() .attach_printable("There was an issue in incoming webhook source verification")? } else { connector .clone() .verify_webhook_source( &request_details, merchant_account.get_id(), merchant_connector_account.connector_webhook_details.clone(), merchant_connector_account.connector_account_details.clone(), connector_name.as_str(), ) .await .or_else(|error| match error.current_context() { errors::ConnectorError::WebhookSourceVerificationFailed => { logger::error!(?error, "Source Verification Failed"); Ok(false) } _ => Err(error), }) .switch() .attach_printable("There was an issue in incoming webhook source verification")? }; logger::info!(source_verified=?source_verified); if source_verified { metrics::WEBHOOK_SOURCE_VERIFIED_COUNT.add( 1, router_env::metric_attributes!((MERCHANT_ID, merchant_account.get_id().clone())), ); } // If source verification is mandatory and source is not verified, fail with webhook authentication error // else continue the flow match ( connector.is_webhook_source_verification_mandatory(), source_verified, ) { (true, false) => Err(errors::ApiErrorResponse::WebhookAuthenticationFailed)?, _ => { event_object = connector .get_webhook_resource_object(&request_details) .switch() .attach_printable("Could not find resource object in incoming webhook body")?; let webhook_details = api::IncomingWebhookDetails { object_reference_id: object_ref_id.clone(), resource_object: serde_json::to_vec(&event_object) .change_context(errors::ParsingError::EncodeError("byte-vec")) .attach_printable("Unable to convert webhook payload to a value") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "There was an issue when encoding the incoming webhook body to bytes", )?, }; match flow_type { api::WebhookFlow::Payment => Box::pin(payments_incoming_webhook_flow( state.clone(), req_state, merchant_account, profile, key_store, webhook_details, source_verified, )) .await .attach_printable("Incoming webhook flow for payments failed")?, api::WebhookFlow::Refund => todo!(), api::WebhookFlow::Dispute => todo!(), api::WebhookFlow::BankTransfer => todo!(), api::WebhookFlow::ReturnResponse => WebhookResponseTracker::NoEffect, api::WebhookFlow::Mandate => todo!(), api::WebhookFlow::ExternalAuthentication => todo!(), api::WebhookFlow::FraudCheck => todo!(), #[cfg(feature = "payouts")] api::WebhookFlow::Payout => todo!(), api::WebhookFlow::Subscription => todo!(), #[cfg(all(feature = "revenue_recovery", feature = "v2"))] api::WebhookFlow::Recovery => { Box::pin(recovery_incoming::recovery_incoming_webhook_flow( state.clone(), merchant_account, profile, key_store, webhook_details, source_verified, &connector, merchant_connector_account, &connector_name, &request_details, event_type, req_state, &object_ref_id, )) .await .change_context(errors::ApiErrorResponse::WebhookProcessingFailure) .attach_printable("Failed to process recovery incoming webhook")? } } } } } else { metrics::WEBHOOK_INCOMING_FILTERED_COUNT.add( 1, router_env::metric_attributes!((MERCHANT_ID, merchant_account.get_id().clone())), ); WebhookResponseTracker::NoEffect }; let response = connector .get_webhook_api_response(&request_details, None) .switch() .attach_printable("Could not get incoming webhook api response from connector")?; let serialized_request = event_object .masked_serialize() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Could not convert webhook effect to string")?; Ok((response, webhook_effect, serialized_request)) } <file_sep path="hyperswitch/crates/router/src/routes/app.rs" role="context" start="104" end="125"> pub struct SessionState { pub store: Box<dyn StorageInterface>, /// Global store is used for global schema operations in tables like Users and Tenants pub global_store: Box<dyn GlobalStorageInterface>, pub accounts_store: Box<dyn AccountsStorageInterface>, pub conf: Arc<settings::Settings<RawSecret>>, pub api_client: Box<dyn crate::services::ApiClient>, pub event_handler: EventsHandler, #[cfg(feature = "email")] pub email_client: Arc<Box<dyn EmailService>>, #[cfg(feature = "olap")] pub pool: AnalyticsProvider, pub file_storage_client: Arc<dyn FileStorageInterface>, pub request_id: Option<RequestId>, pub base_url: String, pub tenant: Tenant, #[cfg(feature = "olap")] pub opensearch_client: Option<Arc<OpenSearchClient>>, pub grpc_client: Arc<GrpcClients>, pub theme_storage_client: Arc<dyn FileStorageInterface>, pub locale: String, } <file_sep path="hyperswitch/migrations/2023-04-06-092008_create_merchant_ek/up.sql" role="context" start="1" end="6"> CREATE TABLE merchant_key_store( merchant_id VARCHAR(255) NOT NULL PRIMARY KEY, key bytea NOT NULL, created_at TIMESTAMP NOT NULL ); <file_sep path="hyperswitch/crates/api_models/src/errors/types.rs" role="context" start="86" end="100"> pub enum ApiErrorResponse { Unauthorized(ApiError), ForbiddenCommonResource(ApiError), ForbiddenPrivateResource(ApiError), Conflict(ApiError), Gone(ApiError), Unprocessable(ApiError), InternalServerError(ApiError), NotImplemented(ApiError), ConnectorError(ApiError, #[serde(skip_serializing)] StatusCode), NotFound(ApiError), MethodNotAllowed(ApiError), BadRequest(ApiError), DomainError(ApiError), }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payment_methods/surcharge_decision_configs.rs<|crate|> router anchor=generate_surcharge_details_and_populate_surcharge_metadata kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/core/payment_methods/surcharge_decision_configs.rs" role="context" start="70" end="101"> pub fn generate_surcharge_details_and_populate_surcharge_metadata( &self, backend_input: &backend::BackendInput, payment_attempt: &storage::PaymentAttempt, surcharge_metadata_and_key: (&mut types::SurchargeMetadata, types::SurchargeKey), ) -> ConditionalConfigResult<Option<types::SurchargeDetails>> { match self { Self::Generate(interpreter) => { let surcharge_output = execute_dsl_and_get_conditional_config( backend_input.clone(), &interpreter.cached_algorithm, )?; Ok(surcharge_output .surcharge_details .map(|surcharge_details| { get_surcharge_details_from_surcharge_output( surcharge_details, payment_attempt, ) }) .transpose()? .inspect(|surcharge_details| { let (surcharge_metadata, surcharge_key) = surcharge_metadata_and_key; surcharge_metadata .insert_surcharge_details(surcharge_key, surcharge_details.clone()); })) } Self::Predetermined(request_surcharge_details) => Ok(Some( types::SurchargeDetails::from((request_surcharge_details, payment_attempt)), )), } } <file_sep path="hyperswitch/crates/router/src/core/payment_methods/surcharge_decision_configs.rs" role="context" start="69" end="69"> use api_models::{ payment_methods::SurchargeDetailsResponse, payments, routing, surcharge_decision_configs::{self, SurchargeDecisionConfigs, SurchargeDecisionManagerRecord}, }; use common_utils::{ext_traits::StringExt, types as common_utils_types}; use common_utils::{ ext_traits::{OptionExt, StringExt}, types as common_utils_types, }; use error_stack::{self, ResultExt}; use euclid::{ backend, backend::{inputs as dsl_inputs, EuclidBackend}, }; use storage_impl::redis::cache::{self, SURCHARGE_CACHE}; use crate::{ core::{ errors::{self, ConditionalConfigError as ConfigError}, payments::{ conditional_configs::ConditionalConfigResult, routing::make_dsl_input_for_surcharge, types, }, }, db::StorageInterface, types::{ storage::{self, payment_attempt::PaymentAttemptExt}, transformers::ForeignTryFrom, }, SessionState, }; <file_sep path="hyperswitch/crates/router/src/core/payment_methods/surcharge_decision_configs.rs" role="context" start="120" end="237"> pub async fn perform_surcharge_decision_management_for_payment_method_list( state: &SessionState, algorithm_ref: routing::RoutingAlgorithmRef, payment_attempt: &storage::PaymentAttempt, payment_intent: &storage::PaymentIntent, billing_address: Option<hyperswitch_domain_models::address::Address>, response_payment_method_types: &mut [api_models::payment_methods::ResponsePaymentMethodsEnabled], ) -> ConditionalConfigResult<( types::SurchargeMetadata, surcharge_decision_configs::MerchantSurchargeConfigs, )> { let mut surcharge_metadata = types::SurchargeMetadata::new(payment_attempt.attempt_id.clone()); let (surcharge_source, merchant_surcharge_configs) = match ( payment_attempt.get_surcharge_details(), algorithm_ref.surcharge_config_algo_id, ) { (Some(request_surcharge_details), _) => ( SurchargeSource::Predetermined(request_surcharge_details), surcharge_decision_configs::MerchantSurchargeConfigs::default(), ), (None, Some(algorithm_id)) => { let cached_algo = ensure_algorithm_cached( &*state.store, &payment_attempt.merchant_id, algorithm_id.as_str(), ) .await?; let merchant_surcharge_config = cached_algo.merchant_surcharge_configs.clone(); ( SurchargeSource::Generate(cached_algo), merchant_surcharge_config, ) } (None, None) => { return Ok(( surcharge_metadata, surcharge_decision_configs::MerchantSurchargeConfigs::default(), )) } }; let surcharge_source_log_message = match &surcharge_source { SurchargeSource::Generate(_) => "Surcharge was calculated through surcharge rules", SurchargeSource::Predetermined(_) => "Surcharge was sent in payment create request", }; logger::debug!(payment_method_list_surcharge_source = surcharge_source_log_message); let mut backend_input = make_dsl_input_for_surcharge(payment_attempt, payment_intent, billing_address) .change_context(ConfigError::InputConstructionError)?; for payment_methods_enabled in response_payment_method_types.iter_mut() { for payment_method_type_response in &mut payment_methods_enabled.payment_method_types.iter_mut() { let payment_method_type = payment_method_type_response.payment_method_type; backend_input.payment_method.payment_method_type = Some(payment_method_type); backend_input.payment_method.payment_method = Some(payment_methods_enabled.payment_method); if let Some(card_network_list) = &mut payment_method_type_response.card_networks { for card_network_type in card_network_list.iter_mut() { backend_input.payment_method.card_network = Some(card_network_type.card_network.clone()); let surcharge_details = surcharge_source .generate_surcharge_details_and_populate_surcharge_metadata( &backend_input, payment_attempt, ( &mut surcharge_metadata, types::SurchargeKey::PaymentMethodData( payment_methods_enabled.payment_method, payment_method_type_response.payment_method_type, Some(card_network_type.card_network.clone()), ), ), )?; card_network_type.surcharge_details = surcharge_details .map(|surcharge_details| { SurchargeDetailsResponse::foreign_try_from(( &surcharge_details, payment_attempt, )) .change_context(ConfigError::DslExecutionError) .attach_printable("Error while constructing Surcharge response type") }) .transpose()?; } } else { let surcharge_details = surcharge_source .generate_surcharge_details_and_populate_surcharge_metadata( &backend_input, payment_attempt, ( &mut surcharge_metadata, types::SurchargeKey::PaymentMethodData( payment_methods_enabled.payment_method, payment_method_type_response.payment_method_type, None, ), ), )?; payment_method_type_response.surcharge_details = surcharge_details .map(|surcharge_details| { SurchargeDetailsResponse::foreign_try_from(( &surcharge_details, payment_attempt, )) .change_context(ConfigError::DslExecutionError) .attach_printable("Error while constructing Surcharge response type") }) .transpose()?; } } } Ok((surcharge_metadata, merchant_surcharge_configs)) } <file_sep path="hyperswitch/crates/router/src/core/payment_methods/surcharge_decision_configs.rs" role="context" start="105" end="117"> pub async fn perform_surcharge_decision_management_for_payment_method_list( _state: &SessionState, _algorithm_ref: routing::RoutingAlgorithmRef, _payment_attempt: &storage::PaymentAttempt, _payment_intent: &storage::PaymentIntent, _billing_address: Option<payments::Address>, _response_payment_method_types: &mut [api_models::payment_methods::ResponsePaymentMethodsEnabled], ) -> ConditionalConfigResult<( types::SurchargeMetadata, surcharge_decision_configs::MerchantSurchargeConfigs, )> { todo!() } <file_sep path="hyperswitch/crates/router/src/core/payment_methods/surcharge_decision_configs.rs" role="context" start="50" end="59"> fn try_from(value: SurchargeDecisionManagerRecord) -> Result<Self, Self::Error> { let cached_algorithm = backend::VirInterpreterBackend::with_program(value.algorithm) .change_context(ConfigError::DslBackendInitError) .attach_printable("Error initializing DSL interpreter backend")?; let merchant_surcharge_configs = value.merchant_surcharge_configs; Ok(Self { cached_algorithm, merchant_surcharge_configs, }) } <file_sep path="hyperswitch/crates/router/src/core/payment_methods/surcharge_decision_configs.rs" role="context" start="457" end="493"> fn get_surcharge_details_from_surcharge_output( surcharge_details: surcharge_decision_configs::SurchargeDetailsOutput, payment_attempt: &storage::PaymentAttempt, ) -> ConditionalConfigResult<types::SurchargeDetails> { let surcharge_amount = match surcharge_details.surcharge.clone() { surcharge_decision_configs::SurchargeOutput::Fixed { amount } => amount, surcharge_decision_configs::SurchargeOutput::Rate(percentage) => percentage .apply_and_ceil_result(payment_attempt.net_amount.get_total_amount()) .change_context(ConfigError::DslExecutionError) .attach_printable("Failed to Calculate surcharge amount by applying percentage")?, }; let tax_on_surcharge_amount = surcharge_details .tax_on_surcharge .clone() .map(|tax_on_surcharge| { tax_on_surcharge .apply_and_ceil_result(surcharge_amount) .change_context(ConfigError::DslExecutionError) .attach_printable("Failed to Calculate tax amount") }) .transpose()? .unwrap_or_default(); Ok(types::SurchargeDetails { original_amount: payment_attempt.net_amount.get_order_amount(), surcharge: match surcharge_details.surcharge { surcharge_decision_configs::SurchargeOutput::Fixed { amount } => { common_utils_types::Surcharge::Fixed(amount) } surcharge_decision_configs::SurchargeOutput::Rate(percentage) => { common_utils_types::Surcharge::Rate(percentage) } }, tax_on_surcharge: surcharge_details.tax_on_surcharge, surcharge_amount, tax_on_surcharge_amount, }) } <file_sep path="hyperswitch/crates/router/src/core/payment_methods/surcharge_decision_configs.rs" role="context" start="526" end="535"> pub fn execute_dsl_and_get_conditional_config( backend_input: dsl_inputs::BackendInput, interpreter: &backend::VirInterpreterBackend<SurchargeDecisionConfigs>, ) -> ConditionalConfigResult<SurchargeDecisionConfigs> { let routing_output = interpreter .execute(backend_input) .map(|out| out.connector_selection) .change_context(ConfigError::DslExecutionError)?; Ok(routing_output) } <file_sep path="hyperswitch/crates/router/src/core/payments/types.rs" role="context" start="232" end="239"> pub enum SurchargeKey { Token(String), PaymentMethodData( common_enums::PaymentMethod, common_enums::PaymentMethodType, Option<common_enums::CardNetwork>, ), } <file_sep path="hyperswitch/v2_compatible_migrations/2024-08-28-081721_add_v2_columns/up.sql" role="context" start="37" end="53"> ADD COLUMN frm_merchant_decision VARCHAR(64), ADD COLUMN statement_descriptor VARCHAR(255), ADD COLUMN enable_payment_link BOOLEAN, ADD COLUMN apply_mit_exemption BOOLEAN, ADD COLUMN customer_present BOOLEAN, ADD COLUMN routing_algorithm_id VARCHAR(64), ADD COLUMN payment_link_config JSONB; ALTER TABLE payment_attempt ADD COLUMN payment_method_type_v2 VARCHAR, ADD COLUMN connector_payment_id VARCHAR(128), ADD COLUMN payment_method_subtype VARCHAR(64), ADD COLUMN routing_result JSONB, ADD COLUMN authentication_applied "AuthenticationType", ADD COLUMN external_reference_id VARCHAR(128), ADD COLUMN tax_on_surcharge BIGINT, ADD COLUMN payment_method_billing_address BYTEA,
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/core/admin.rs<|crate|> router anchor=create_profiles_for_each_business_details kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/core/admin.rs" role="context" start="566" end="601"> async fn create_profiles_for_each_business_details( state: &SessionState, merchant_account: domain::MerchantAccount, primary_business_details: &Vec<admin_types::PrimaryBusinessDetails>, key_store: &domain::MerchantKeyStore, ) -> RouterResult<Vec<domain::Profile>> { let mut business_profiles_vector = Vec::with_capacity(primary_business_details.len()); // This must ideally be run in a transaction, // if there is an error in inserting some profile, because of unique constraints // the whole query must be rolled back for business_profile in primary_business_details { let profile_name = format!("{}_{}", business_profile.country, business_profile.business); let profile_create_request = api_models::admin::ProfileCreate { profile_name: Some(profile_name), ..Default::default() }; create_and_insert_business_profile( state, profile_create_request, merchant_account.clone(), key_store, ) .await .map_err(|profile_insert_error| { crate::logger::warn!("Profile already exists {profile_insert_error:?}"); }) .map(|business_profile| business_profiles_vector.push(business_profile)) .ok(); } Ok(business_profiles_vector) } <file_sep path="hyperswitch/crates/router/src/core/admin.rs" role="context" start="565" end="565"> use api_models::{ admin::{self as admin_types}, enums as api_enums, routing as routing_types, }; use diesel_models::{business_profile::CardTestingGuardConfig, organization::OrganizationBridge}; use crate::types::transformers::ForeignFrom; use crate::{ consts, core::{ encryption::transfer_encryption_key, errors::{self, RouterResponse, RouterResult, StorageErrorExt}, payment_methods::{cards, transformers}, payments::helpers, pm_auth::helpers::PaymentAuthConnectorDataExt, routing, utils as core_utils, }, db::{AccountsStorageInterface, StorageInterface}, routes::{metrics, SessionState}, services::{ self, api::{self as service_api, client}, authentication, pm_auth as payment_initiation_service, }, types::{ self, api::{self, admin}, domain::{ self, types::{self as domain_types, AsyncLift}, }, storage::{self, enums::MerchantStorageScheme}, transformers::{ForeignInto, ForeignTryFrom, ForeignTryInto}, }, utils, }; <file_sep path="hyperswitch/crates/router/src/core/admin.rs" role="context" start="688" end="713"> pub async fn list_merchant_account( state: SessionState, organization_id: api_models::organization::OrganizationId, ) -> RouterResponse<Vec<api::MerchantAccountResponse>> { let merchant_accounts = state .store .list_merchant_accounts_by_organization_id( &(&state).into(), &organization_id.organization_id, ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let merchant_accounts = merchant_accounts .into_iter() .map(|merchant_account| { api::MerchantAccountResponse::foreign_try_from(merchant_account).change_context( errors::ApiErrorResponse::InvalidDataValue { field_name: "merchant_account", }, ) }) .collect::<Result<Vec<_>, _>>()?; Ok(services::ApplicationResponse::Json(merchant_accounts)) } <file_sep path="hyperswitch/crates/router/src/core/admin.rs" role="context" start="607" end="684"> async fn create_domain_model_from_request( self, state: &SessionState, key_store: domain::MerchantKeyStore, identifier: &id_type::MerchantId, ) -> RouterResult<domain::MerchantAccount> { let publishable_key = create_merchant_publishable_key(); let db = &*state.accounts_store; let metadata = self.get_metadata_as_secret().change_context( errors::ApiErrorResponse::InvalidDataValue { field_name: "metadata", }, )?; let merchant_details = self.get_merchant_details_as_secret().change_context( errors::ApiErrorResponse::InvalidDataValue { field_name: "merchant_details", }, )?; let organization = CreateOrValidateOrganization::new(self.organization_id.clone()) .create_or_validate(db) .await?; let key = key_store.key.into_inner(); let id = identifier.to_owned(); let key_manager_state = state.into(); let identifier = km_types::Identifier::Merchant(id.clone()); async { Ok::<_, error_stack::Report<common_utils::errors::CryptoError>>( domain::MerchantAccount::from(domain::MerchantAccountSetter { id, merchant_name: Some( domain_types::crypto_operation( &key_manager_state, type_name!(domain::MerchantAccount), domain_types::CryptoOperation::Encrypt( self.merchant_name .map(|merchant_name| merchant_name.into_inner()), ), identifier.clone(), key.peek(), ) .await .and_then(|val| val.try_into_operation())?, ), merchant_details: merchant_details .async_lift(|inner| async { domain_types::crypto_operation( &key_manager_state, type_name!(domain::MerchantAccount), domain_types::CryptoOperation::EncryptOptional(inner), identifier.clone(), key.peek(), ) .await .and_then(|val| val.try_into_optionaloperation()) }) .await?, publishable_key, metadata, storage_scheme: MerchantStorageScheme::PostgresOnly, created_at: date_time::now(), modified_at: date_time::now(), organization_id: organization.get_organization_id(), recon_status: diesel_models::enums::ReconStatus::NotRequested, is_platform_account: false, version: common_types::consts::API_VERSION, product_type: self.product_type, }), ) } .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed to encrypt merchant details") } <file_sep path="hyperswitch/crates/router/src/core/admin.rs" role="context" start="546" end="561"> async fn create_default_business_profile( &self, state: &SessionState, merchant_account: domain::MerchantAccount, key_store: &domain::MerchantKeyStore, ) -> RouterResult<domain::Profile> { let business_profile = create_and_insert_business_profile( state, api_models::admin::ProfileCreate::default(), merchant_account.clone(), key_store, ) .await?; Ok(business_profile) } <file_sep path="hyperswitch/crates/router/src/core/admin.rs" role="context" start="508" end="543"> async fn create_profiles( &self, state: &SessionState, merchant_account: &mut domain::MerchantAccount, key_store: &domain::MerchantKeyStore, ) -> RouterResult<()> { match self { Self::CreateFromPrimaryBusinessDetails { primary_business_details, } => { let business_profiles = Self::create_profiles_for_each_business_details( state, merchant_account.clone(), primary_business_details, key_store, ) .await?; // Update the default business profile in merchant account if business_profiles.len() == 1 { merchant_account.default_profile = business_profiles .first() .map(|business_profile| business_profile.get_id().to_owned()) } } Self::CreateDefaultProfile => { let business_profile = self .create_default_business_profile(state, merchant_account.clone(), key_store) .await?; merchant_account.default_profile = Some(business_profile.get_id().to_owned()); } } Ok(()) } <file_sep path="hyperswitch/crates/router/src/core/admin.rs" role="context" start="3587" end="3609"> pub async fn create_and_insert_business_profile( state: &SessionState, request: api::ProfileCreate, merchant_account: domain::MerchantAccount, key_store: &domain::MerchantKeyStore, ) -> RouterResult<domain::Profile> { let business_profile_new = admin::create_profile_from_merchant_account(state, merchant_account, request, key_store) .await?; let profile_name = business_profile_new.profile_name.clone(); state .store .insert_business_profile(&state.into(), key_store, business_profile_new) .await .to_duplicate_response(errors::ApiErrorResponse::GenericDuplicateError { message: format!( "Business Profile with the profile_name {profile_name} already exists" ), }) .attach_printable("Failed to insert Business profile because of duplication error") } <file_sep path="hyperswitch/crates/router/src/routes/app.rs" role="context" start="1906" end="1906"> pub struct Profile; <file_sep path="hyperswitch/v2_compatible_migrations/2024-08-28-081757_drop_not_null_constraints_on_v1_columns/up.sql" role="context" start="5" end="21"> ALTER COLUMN org_id DROP NOT NULL; -- Create index on org_id in organization table -- This is done to mullify the effects of droping primary key for v1 CREATE INDEX idx_organization_org_id ON organization (org_id); ------------------------ Merchant Account ------------------- -- Drop not null in merchant_account table for v1 columns that are dropped in v2 ALTER TABLE merchant_account DROP CONSTRAINT merchant_account_pkey, ALTER COLUMN merchant_id DROP NOT NULL, ALTER COLUMN primary_business_details DROP NOT NULL, ALTER COLUMN is_recon_enabled DROP NOT NULL; -- This is done to mullify the effects of droping primary key for v1 CREATE INDEX idx_merchant_account_merchant_id ON merchant_account (merchant_id); <file_sep path="hyperswitch/crates/api_models/src/admin.rs" role="context" start="1853" end="1996"> pub struct ProfileCreate { /// The name of profile #[schema(max_length = 64)] pub profile_name: Option<String>, /// The URL to redirect after the completion of the operation #[schema(value_type = Option<String>, max_length = 255, example = "https://www.example.com/success")] pub return_url: Option<url::Url>, /// A boolean value to indicate if payment response hash needs to be enabled #[schema(default = true, example = true)] pub enable_payment_response_hash: Option<bool>, /// Refers to the hash key used for calculating the signature for webhooks and redirect response. If the value is not provided, a value is automatically generated. pub payment_response_hash_key: Option<String>, /// A boolean value to indicate if redirect to merchant with http post needs to be enabled #[schema(default = false, example = true)] pub redirect_to_merchant_with_http_post: Option<bool>, /// Webhook related details pub webhook_details: Option<WebhookDetails>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// The routing algorithm to be used for routing payments to desired connectors #[schema(value_type = Option<Object>,example = json!({"type": "single", "data": "stripe"}))] pub routing_algorithm: Option<serde_json::Value>, /// Will be used to determine the time till which your payment will be active once the payment session starts #[schema(example = 900)] pub intent_fulfillment_time: Option<u32>, /// The frm routing algorithm to be used for routing payments to desired FRM's #[schema(value_type = Option<Object>,example = json!({"type": "single", "data": "signifyd"}))] pub frm_routing_algorithm: Option<serde_json::Value>, /// The routing algorithm to be used to process the incoming request from merchant to outgoing payment processor or payment method. The default is 'Custom' #[cfg(feature = "payouts")] #[schema(value_type = Option<RoutingAlgorithm>,example = json!({"type": "single", "data": "wise"}))] pub payout_routing_algorithm: Option<serde_json::Value>, /// Verified Apple Pay domains for a particular profile pub applepay_verified_domains: Option<Vec<String>>, /// Client Secret Default expiry for all payments created under this profile #[schema(example = 900)] pub session_expiry: Option<u32>, /// Default Payment Link config for all payment links created under this profile pub payment_link_config: Option<BusinessPaymentLinkConfig>, /// External 3DS authentication details pub authentication_connector_details: Option<AuthenticationConnectorDetails>, /// Whether to use the billing details passed when creating the intent as payment method billing pub use_billing_as_payment_method_billing: Option<bool>, /// A boolean value to indicate if customer shipping details needs to be collected from wallet /// connector only if it is required field for connector (Eg. Apple Pay, Google Pay etc) #[schema(default = false, example = false)] pub collect_shipping_details_from_wallet_connector: Option<bool>, /// A boolean value to indicate if customer billing details needs to be collected from wallet /// connector only if it is required field for connector (Eg. Apple Pay, Google Pay etc) #[schema(default = false, example = false)] pub collect_billing_details_from_wallet_connector: Option<bool>, /// A boolean value to indicate if customer shipping details needs to be collected from wallet /// connector irrespective of connector required fields (Eg. Apple pay, Google pay etc) #[schema(default = false, example = false)] pub always_collect_shipping_details_from_wallet_connector: Option<bool>, /// A boolean value to indicate if customer billing details needs to be collected from wallet /// connector irrespective of connector required fields (Eg. Apple pay, Google pay etc) #[schema(default = false, example = false)] pub always_collect_billing_details_from_wallet_connector: Option<bool>, /// Indicates if the MIT (merchant initiated transaction) payments can be made connector /// agnostic, i.e., MITs may be processed through different connector than CIT (customer /// initiated transaction) based on the routing rules. /// If set to `false`, MIT will go through the same connector as the CIT. pub is_connector_agnostic_mit_enabled: Option<bool>, /// Default payout link config #[schema(value_type = Option<BusinessPayoutLinkConfig>)] pub payout_link_config: Option<BusinessPayoutLinkConfig>, /// These key-value pairs are sent as additional custom headers in the outgoing webhook request. It is recommended not to use more than four key-value pairs. #[schema(value_type = Option<Object>, example = r#"{ "key1": "value-1", "key2": "value-2" }"#)] pub outgoing_webhook_custom_http_headers: Option<HashMap<String, String>>, /// Merchant Connector id to be stored for tax_calculator connector #[schema(value_type = Option<String>)] pub tax_connector_id: Option<id_type::MerchantConnectorAccountId>, /// Indicates if tax_calculator connector is enabled or not. /// If set to `true` tax_connector_id will be checked. #[serde(default)] pub is_tax_connector_enabled: bool, /// Indicates if network tokenization is enabled or not. #[serde(default)] pub is_network_tokenization_enabled: bool, /// Indicates if is_auto_retries_enabled is enabled or not. pub is_auto_retries_enabled: Option<bool>, /// Maximum number of auto retries allowed for a payment pub max_auto_retries_enabled: Option<u8>, /// Bool indicating if extended authentication must be requested for all payments #[schema(value_type = Option<bool>)] pub always_request_extended_authorization: Option<primitive_wrappers::AlwaysRequestExtendedAuthorization>, /// Indicates if click to pay is enabled or not. #[serde(default)] pub is_click_to_pay_enabled: bool, /// Product authentication ids #[schema(value_type = Option<Object>, example = r#"{ "click_to_pay": "mca_ushduqwhdohwd", "netcetera": "mca_kwqhudqwd" }"#)] pub authentication_product_ids: Option<common_types::payments::AuthenticationConnectorAccountMap>, /// Card Testing Guard Configs pub card_testing_guard_config: Option<CardTestingGuardConfig>, ///Indicates if clear pan retries is enabled or not. pub is_clear_pan_retries_enabled: Option<bool>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, /// Indicates if debit routing is enabled or not #[schema(value_type = Option<bool>)] pub is_debit_routing_enabled: Option<bool>, //Merchant country for the profile #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub merchant_business_country: Option<api_enums::CountryAlpha2>, }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/core/blocklist/transformers.rs<|crate|> router anchor=generate_fingerprint_request kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/core/blocklist/transformers.rs" role="context" start="35" end="60"> async fn generate_fingerprint_request( jwekey: &settings::Jwekey, locker: &settings::Locker, payload: &blocklist::GenerateFingerprintRequest, locker_choice: api_enums::LockerChoice, ) -> CustomResult<services::Request, errors::VaultError> { let payload = payload .encode_to_vec() .change_context(errors::VaultError::RequestEncodingFailed)?; let private_key = jwekey.vault_private_key.peek().as_bytes(); let jws = encryption::jws_sign_payload(&payload, &locker.locker_signing_key_id, private_key) .await .change_context(errors::VaultError::RequestEncodingFailed)?; let jwe_payload = generate_jwe_payload_for_request(jwekey, &jws, locker_choice).await?; let mut url = match locker_choice { api_enums::LockerChoice::HyperswitchCardVault => locker.host.to_owned(), }; url.push_str(LOCKER_FINGERPRINT_PATH); let mut request = services::Request::new(services::Method::Post, &url); request.add_header(headers::CONTENT_TYPE, "application/json".into()); request.set_body(RequestContent::Json(Box::new(jwe_payload))); Ok(request) } <file_sep path="hyperswitch/crates/router/src/core/blocklist/transformers.rs" role="context" start="34" end="34"> use api_models::{blocklist, enums as api_enums}; use common_utils::{ ext_traits::{Encode, StringExt}, request::RequestContent, }; use crate::{ configs::settings, core::{ errors::{self, CustomResult}, payment_methods::transformers as payment_methods, }, headers, routes, services::{api as services, encryption, EncryptionAlgorithm}, types::{storage, transformers::ForeignFrom}, utils::ConnectorResponseExt, }; <file_sep path="hyperswitch/crates/router/src/core/blocklist/transformers.rs" role="context" start="114" end="129"> pub async fn generate_fingerprint( state: &routes::SessionState, card_number: StrongSecret<String>, hash_key: StrongSecret<String>, locker_choice: api_enums::LockerChoice, ) -> CustomResult<blocklist::GenerateFingerprintResponsePayload, errors::VaultError> { let payload = blocklist::GenerateFingerprintRequest { card: blocklist::Card { card_number }, hash_key, }; let generate_fingerprint_resp = call_to_locker_for_fingerprint(state, &payload, locker_choice).await?; Ok(generate_fingerprint_resp) } <file_sep path="hyperswitch/crates/router/src/core/blocklist/transformers.rs" role="context" start="62" end="111"> async fn generate_jwe_payload_for_request( jwekey: &settings::Jwekey, jws: &str, locker_choice: api_enums::LockerChoice, ) -> CustomResult<encryption::JweBody, errors::VaultError> { let jws_payload: Vec<&str> = jws.split('.').collect(); let generate_jws_body = |payload: Vec<&str>| -> Option<encryption::JwsBody> { Some(encryption::JwsBody { header: payload.first()?.to_string(), payload: payload.get(1)?.to_string(), signature: payload.get(2)?.to_string(), }) }; let jws_body = generate_jws_body(jws_payload).ok_or(errors::VaultError::GenerateFingerprintFailed)?; let payload = jws_body .encode_to_vec() .change_context(errors::VaultError::GenerateFingerprintFailed)?; let public_key = match locker_choice { api_enums::LockerChoice::HyperswitchCardVault => { jwekey.vault_encryption_key.peek().as_bytes() } }; let jwe_encrypted = encryption::encrypt_jwe(&payload, public_key, EncryptionAlgorithm::A256GCM, None) .await .change_context(errors::VaultError::SaveCardFailed) .attach_printable("Error on jwe encrypt")?; let jwe_payload: Vec<&str> = jwe_encrypted.split('.').collect(); let generate_jwe_body = |payload: Vec<&str>| -> Option<encryption::JweBody> { Some(encryption::JweBody { header: payload.first()?.to_string(), iv: payload.get(2)?.to_string(), encrypted_payload: payload.get(3)?.to_string(), tag: payload.get(4)?.to_string(), encrypted_key: payload.get(1)?.to_string(), }) }; let jwe_body = generate_jwe_body(jwe_payload).ok_or(errors::VaultError::GenerateFingerprintFailed)?; Ok(jwe_body) } <file_sep path="hyperswitch/crates/router/src/core/blocklist/transformers.rs" role="context" start="26" end="32"> fn foreign_from(from: storage::Blocklist) -> Self { Self { fingerprint_id: from.fingerprint_id, data_kind: from.data_kind, created_at: from.created_at, } } <file_sep path="hyperswitch/crates/router/src/core/blocklist/transformers.rs" role="context" start="132" end="163"> async fn call_to_locker_for_fingerprint( state: &routes::SessionState, payload: &blocklist::GenerateFingerprintRequest, locker_choice: api_enums::LockerChoice, ) -> CustomResult<blocklist::GenerateFingerprintResponsePayload, errors::VaultError> { let locker = &state.conf.locker; let jwekey = state.conf.jwekey.get_inner(); let request = generate_fingerprint_request(jwekey, locker, payload, locker_choice).await?; let response = services::call_connector_api(state, request, "call_locker_to_get_fingerprint") .await .change_context(errors::VaultError::GenerateFingerprintFailed); let jwe_body: encryption::JweBody = response .get_response_inner("JweBody") .change_context(errors::VaultError::GenerateFingerprintFailed)?; let decrypted_payload = decrypt_generate_fingerprint_response_payload( jwekey, jwe_body, Some(locker_choice), locker.decryption_scheme.clone(), ) .await .change_context(errors::VaultError::GenerateFingerprintFailed) .attach_printable("Error getting decrypted fingerprint response payload")?; let generate_fingerprint_response: blocklist::GenerateFingerprintResponsePayload = decrypted_payload .parse_struct("GenerateFingerprintResponse") .change_context(errors::VaultError::ResponseDeserializationFailed)?; Ok(generate_fingerprint_response) } <file_sep path="hyperswitch-card-vault/migrations/2023-10-21-104200_create-tables/up.sql" role="context" start="5" end="21"> tenant_id VARCHAR(255) NOT NULL, merchant_id VARCHAR(255) NOT NULL, enc_key BYTEA NOT NULL, created_at TIMESTAMP NOT NULL DEFAULT now()::TIMESTAMP, PRIMARY KEY (tenant_id, merchant_id) ); CREATE TABLE locker ( id SERIAL, locker_id VARCHAR(255) NOT NULL, tenant_id VARCHAR(255) NOT NULL, merchant_id VARCHAR(255) NOT NULL, customer_id VARCHAR(255) NOT NULL, enc_data BYTEA NOT NULL, created_at TIMESTAMP NOT NULL DEFAULT now()::TIMESTAMP, <file_sep path="hyperswitch/crates/api_models/src/enums.rs" role="context" start="393" end="395"> pub enum LockerChoice { HyperswitchCardVault, }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payments/helpers.rs<|crate|> router anchor=verify_payment_intent_time_and_client_secret kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="3684" end="3729"> pub async fn verify_payment_intent_time_and_client_secret( state: &SessionState, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, client_secret: Option<String>, ) -> error_stack::Result<Option<PaymentIntent>, errors::ApiErrorResponse> { let db = &*state.store; client_secret .async_map(|cs| async move { let payment_id = get_payment_id_from_client_secret(&cs)?; let payment_id = id_type::PaymentId::wrap(payment_id).change_context( errors::ApiErrorResponse::InvalidDataValue { field_name: "payment_id", }, )?; #[cfg(feature = "v1")] let payment_intent = db .find_payment_intent_by_payment_id_merchant_id( &state.into(), &payment_id, merchant_account.get_id(), key_store, merchant_account.storage_scheme, ) .await .change_context(errors::ApiErrorResponse::PaymentNotFound)?; #[cfg(feature = "v2")] let payment_intent = db .find_payment_intent_by_id( &state.into(), &payment_id, key_store, merchant_account.storage_scheme, ) .await .change_context(errors::ApiErrorResponse::PaymentNotFound)?; authenticate_client_secret(Some(&cs), &payment_intent)?; Ok(payment_intent) }) .await .transpose() } <file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="3683" end="3683"> // A function to perform database lookup and then verify the client secret pub async fn verify_payment_intent_time_and_client_secret( state: &SessionState, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, client_secret: Option<String>, ) -> error_stack::Result<Option<PaymentIntent>, errors::ApiErrorResponse> { todo!() } #[cfg(feature = "v1")] // A function to perform database lookup and then verify the client secret pub async fn verify_payment_intent_time_and_client_secret( state: &SessionState, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, client_secret: Option<String>, ) -> error_stack::Result<Option<PaymentIntent>, errors::ApiErrorResponse> { let db = &*state.store; client_secret .async_map(|cs| async move { let payment_id = get_payment_id_from_client_secret(&cs)?; let payment_id = id_type::PaymentId::wrap(payment_id).change_context( errors::ApiErrorResponse::InvalidDataValue { <file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="3765" end="3770"> pub(crate) fn get_payment_id_from_client_secret(cs: &str) -> RouterResult<String> { let (payment_id, _) = cs .rsplit_once("_secret_") .ok_or(errors::ApiErrorResponse::ClientSecretInvalid)?; Ok(payment_id.to_string()) } <file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="3733" end="3762"> pub fn validate_business_details( business_country: Option<api_enums::CountryAlpha2>, business_label: Option<&String>, merchant_account: &domain::MerchantAccount, ) -> RouterResult<()> { let primary_business_details = merchant_account .primary_business_details .clone() .parse_value::<Vec<api_models::admin::PrimaryBusinessDetails>>("PrimaryBusinessDetails") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed to parse primary business details")?; business_country .zip(business_label) .map(|(business_country, business_label)| { primary_business_details .iter() .find(|business_details| { &business_details.business == business_label && business_details.country == business_country }) .ok_or(errors::ApiErrorResponse::PreconditionFailed { message: "business_details are not configured in the merchant account" .to_string(), }) }) .transpose()?; Ok(()) } <file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="3673" end="3680"> pub async fn verify_payment_intent_time_and_client_secret( state: &SessionState, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, client_secret: Option<String>, ) -> error_stack::Result<Option<PaymentIntent>, errors::ApiErrorResponse> { todo!() } <file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="3643" end="3669"> pub(crate) fn validate_pm_or_token_given( payment_method: &Option<api_enums::PaymentMethod>, payment_method_data: &Option<api::PaymentMethodData>, payment_method_type: &Option<api_enums::PaymentMethodType>, mandate_type: &Option<api::MandateTransactionType>, token: &Option<String>, ctp_service_details: &Option<api_models::payments::CtpServiceDetails>, ) -> Result<(), errors::ApiErrorResponse> { utils::when( !matches!( payment_method_type, Some(api_enums::PaymentMethodType::Paypal) ) && !matches!( mandate_type, Some(api::MandateTransactionType::RecurringMandateTransaction) ) && token.is_none() && (payment_method_data.is_none() || payment_method.is_none()) && ctp_service_details.is_none(), || { Err(errors::ApiErrorResponse::InvalidRequestData { message: "A payment token or payment method data or ctp service details is required" .to_string(), }) }, ) } <file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="3592" end="3612"> pub fn authenticate_client_secret( request_client_secret: Option<&common_utils::types::ClientSecret>, payment_intent: &PaymentIntent, ) -> Result<(), errors::ApiErrorResponse> { match (request_client_secret, &payment_intent.client_secret) { (Some(req_cs), pi_cs) => { if req_cs != pi_cs { Err(errors::ApiErrorResponse::ClientSecretInvalid) } else { let current_timestamp = common_utils::date_time::now(); let session_expiry = payment_intent.session_expiry; fp_utils::when(current_timestamp > session_expiry, || { Err(errors::ApiErrorResponse::ClientSecretExpired) }) } } _ => Ok(()), } } <file_sep path="hyperswitch/crates/router/tests/utils.rs" role="context" start="409" end="411"> pub struct PaymentId { payment_id: common_utils::id_type::PaymentId, } <file_sep path="hyperswitch/v2_compatible_migrations/2024-08-28-081721_add_v2_columns/up.sql" role="context" start="19" end="35"> -- Intentionally not adding a default value here since we would have to -- check if any merchants have enabled this from configs table, -- before filling data for this column. -- If no merchants have enabled this, then we can use `false` as the default value -- when adding the column, later we can drop the default added for the column -- so that we ensure new records inserted always have a value for the column. ADD COLUMN should_collect_cvv_during_payment BOOLEAN; ALTER TABLE payment_intent ADD COLUMN merchant_reference_id VARCHAR(64), ADD COLUMN billing_address BYTEA DEFAULT NULL, ADD COLUMN shipping_address BYTEA DEFAULT NULL, ADD COLUMN capture_method "CaptureMethod", ADD COLUMN authentication_type "AuthenticationType", ADD COLUMN amount_to_capture bigint, ADD COLUMN prerouting_algorithm JSONB, ADD COLUMN surcharge_amount bigint, <file_sep path="hyperswitch/crates/api_models/src/errors/types.rs" role="context" start="86" end="100"> pub enum ApiErrorResponse { Unauthorized(ApiError), ForbiddenCommonResource(ApiError), ForbiddenPrivateResource(ApiError), Conflict(ApiError), Gone(ApiError), Unprocessable(ApiError), InternalServerError(ApiError), NotImplemented(ApiError), ConnectorError(ApiError, #[serde(skip_serializing)] StatusCode), NotFound(ApiError), MethodNotAllowed(ApiError), BadRequest(ApiError), DomainError(ApiError), } <file_sep path="hyperswitch/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/event.test.js" role="context" start="61" end="78"> "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.", ); } // Response body should have value "succeeded" for "status" if (jsonData?.status) { pm.test( "[POST]::/payments - Content check if value for 'status' matches 'succeeded'", function () { pm.expect(jsonData.status).to.eql("succeeded"); }, ); }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payment_methods/transformers.rs<|crate|> router anchor=get_decrypted_vault_response_payload kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/src/core/payment_methods/transformers.rs" role="context" start="253" end="286"> pub async fn get_decrypted_vault_response_payload( jwekey: &settings::Jwekey, jwe_body: encryption::JweBody, decryption_scheme: settings::DecryptionScheme, ) -> CustomResult<String, errors::VaultError> { let public_key = jwekey.vault_encryption_key.peek().as_bytes(); let private_key = jwekey.vault_private_key.peek().as_bytes(); let jwt = get_dotted_jwe(jwe_body); let alg = match decryption_scheme { settings::DecryptionScheme::RsaOaep => jwe::RSA_OAEP, settings::DecryptionScheme::RsaOaep256 => jwe::RSA_OAEP_256, }; let jwe_decrypted = encryption::decrypt_jwe( &jwt, encryption::KeyIdCheck::SkipKeyIdCheck, private_key, alg, ) .await .change_context(errors::VaultError::SaveCardFailed) .attach_printable("Jwe Decryption failed for JweBody for vault")?; let jws = jwe_decrypted .parse_struct("JwsBody") .change_context(errors::VaultError::ResponseDeserializationFailed)?; let jws_body = get_dotted_jws(jws); encryption::verify_sign(jws_body, public_key) .change_context(errors::VaultError::SaveCardFailed) .attach_printable("Jws Decryption failed for JwsBody for vault") } <file_sep path="hyperswitch/crates/router/src/core/payment_methods/transformers.rs" role="context" start="252" end="252"> use josekit::jwe; use crate::{ configs::settings, core::errors::{self, CustomResult}, headers, pii::{prelude::*, Secret}, services::{api as services, encryption, EncryptionAlgorithm}, types::{api, domain}, utils::OptionExt, }; <file_sep path="hyperswitch/crates/router/src/core/payment_methods/transformers.rs" role="context" start="335" end="382"> pub async fn mk_basilisk_req( jwekey: &settings::Jwekey, jws: &str, locker_choice: api_enums::LockerChoice, ) -> CustomResult<encryption::JweBody, errors::VaultError> { let jws_payload: Vec<&str> = jws.split('.').collect(); let generate_jws_body = |payload: Vec<&str>| -> Option<encryption::JwsBody> { Some(encryption::JwsBody { header: payload.first()?.to_string(), payload: payload.get(1)?.to_string(), signature: payload.get(2)?.to_string(), }) }; let jws_body = generate_jws_body(jws_payload).ok_or(errors::VaultError::SaveCardFailed)?; let payload = jws_body .encode_to_vec() .change_context(errors::VaultError::SaveCardFailed)?; let public_key = match locker_choice { api_enums::LockerChoice::HyperswitchCardVault => { jwekey.vault_encryption_key.peek().as_bytes() } }; let jwe_encrypted = encryption::encrypt_jwe(&payload, public_key, EncryptionAlgorithm::A256GCM, None) .await .change_context(errors::VaultError::SaveCardFailed) .attach_printable("Error on jwe encrypt")?; let jwe_payload: Vec<&str> = jwe_encrypted.split('.').collect(); let generate_jwe_body = |payload: Vec<&str>| -> Option<encryption::JweBody> { Some(encryption::JweBody { header: payload.first()?.to_string(), iv: payload.get(2)?.to_string(), encrypted_payload: payload.get(3)?.to_string(), tag: payload.get(4)?.to_string(), encrypted_key: payload.get(1)?.to_string(), }) }; let jwe_body = generate_jwe_body(jwe_payload).ok_or(errors::VaultError::SaveCardFailed)?; Ok(jwe_body) } <file_sep path="hyperswitch/crates/router/src/core/payment_methods/transformers.rs" role="context" start="289" end="333"> pub async fn create_jwe_body_for_vault( jwekey: &settings::Jwekey, jws: &str, ) -> CustomResult<encryption::JweBody, errors::VaultError> { let jws_payload: Vec<&str> = jws.split('.').collect(); let generate_jws_body = |payload: Vec<&str>| -> Option<encryption::JwsBody> { Some(encryption::JwsBody { header: payload.first()?.to_string(), payload: payload.get(1)?.to_string(), signature: payload.get(2)?.to_string(), }) }; let jws_body = generate_jws_body(jws_payload).ok_or(errors::VaultError::RequestEncryptionFailed)?; let payload = jws_body .encode_to_vec() .change_context(errors::VaultError::RequestEncodingFailed)?; let public_key = jwekey.vault_encryption_key.peek().as_bytes(); let jwe_encrypted = encryption::encrypt_jwe(&payload, public_key, EncryptionAlgorithm::A256GCM, None) .await .change_context(errors::VaultError::SaveCardFailed) .attach_printable("Error on jwe encrypt")?; let jwe_payload: Vec<&str> = jwe_encrypted.split('.').collect(); let generate_jwe_body = |payload: Vec<&str>| -> Option<encryption::JweBody> { Some(encryption::JweBody { header: payload.first()?.to_string(), iv: payload.get(2)?.to_string(), encrypted_payload: payload.get(3)?.to_string(), tag: payload.get(4)?.to_string(), encrypted_key: payload.get(1)?.to_string(), }) }; let jwe_body = generate_jwe_body(jwe_payload).ok_or(errors::VaultError::RequestEncodingFailed)?; Ok(jwe_body) } <file_sep path="hyperswitch/crates/router/src/core/payment_methods/transformers.rs" role="context" start="211" end="251"> pub async fn get_decrypted_response_payload( jwekey: &settings::Jwekey, jwe_body: encryption::JweBody, locker_choice: Option<api_enums::LockerChoice>, decryption_scheme: settings::DecryptionScheme, ) -> CustomResult<String, errors::VaultError> { let target_locker = locker_choice.unwrap_or(api_enums::LockerChoice::HyperswitchCardVault); let public_key = match target_locker { api_enums::LockerChoice::HyperswitchCardVault => { jwekey.vault_encryption_key.peek().as_bytes() } }; let private_key = jwekey.vault_private_key.peek().as_bytes(); let jwt = get_dotted_jwe(jwe_body); let alg = match decryption_scheme { settings::DecryptionScheme::RsaOaep => jwe::RSA_OAEP, settings::DecryptionScheme::RsaOaep256 => jwe::RSA_OAEP_256, }; let jwe_decrypted = encryption::decrypt_jwe( &jwt, encryption::KeyIdCheck::SkipKeyIdCheck, private_key, alg, ) .await .change_context(errors::VaultError::SaveCardFailed) .attach_printable("Jwe Decryption failed for JweBody for vault")?; let jws = jwe_decrypted .parse_struct("JwsBody") .change_context(errors::VaultError::ResponseDeserializationFailed)?; let jws_body = get_dotted_jws(jws); encryption::verify_sign(jws_body, public_key) .change_context(errors::VaultError::SaveCardFailed) .attach_printable("Jws Decryption failed for JwsBody for vault") } <file_sep path="hyperswitch/crates/router/src/core/payment_methods/transformers.rs" role="context" start="204" end="209"> pub fn get_dotted_jws(jws: encryption::JwsBody) -> String { let header = jws.header; let payload = jws.payload; let signature = jws.signature; format!("{header}.{payload}.{signature}") } <file_sep path="hyperswitch/crates/router/src/core/payment_methods/transformers.rs" role="context" start="195" end="202"> pub fn get_dotted_jwe(jwe: encryption::JweBody) -> String { let header = jwe.header; let encryption_key = jwe.encrypted_key; let iv = jwe.iv; let encryption_payload = jwe.encrypted_payload; let tag = jwe.tag; format!("{header}.{encryption_key}.{iv}.{encryption_payload}.{tag}") }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/core/routing/helpers.rs<|crate|> router anchor=get_merchant_default_config kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/core/routing/helpers.rs" role="context" start="59" end="101"> pub async fn get_merchant_default_config( db: &dyn StorageInterface, // Cannot make this as merchant id domain type because, we are passing profile id also here merchant_id: &str, transaction_type: &storage::enums::TransactionType, ) -> RouterResult<Vec<routing_types::RoutableConnectorChoice>> { let key = get_default_config_key(merchant_id, transaction_type); let maybe_config = db.find_config_by_key(&key).await; match maybe_config { Ok(config) => config .config .parse_struct("Vec<RoutableConnectors>") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Merchant default config has invalid structure"), Err(e) if e.current_context().is_db_not_found() => { let new_config_conns = Vec::<routing_types::RoutableConnectorChoice>::new(); let serialized = new_config_conns .encode_to_string_of_json() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Error while creating and serializing new merchant default config", )?; let new_config = configs::ConfigNew { key, config: serialized, }; db.insert_config(new_config) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error inserting new default routing config into DB")?; Ok(new_config_conns) } Err(e) => Err(e) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error fetching default config for merchant"), } } <file_sep path="hyperswitch/crates/router/src/core/routing/helpers.rs" role="context" start="58" end="58"> use std::str::FromStr; use api_models::routing as routing_types; use diesel_models::configs; use crate::db::errors::StorageErrorExt; use crate::types::domain::MerchantConnectorAccount; use crate::{ core::errors::{self, RouterResult}, db::StorageInterface, routes::SessionState, types::{domain, storage}, utils::StringExt, }; use crate::{core::metrics as core_metrics, types::transformers::ForeignInto}; <file_sep path="hyperswitch/crates/router/src/core/routing/helpers.rs" role="context" start="129" end="150"> pub async fn update_merchant_routing_dictionary( db: &dyn StorageInterface, merchant_id: &str, dictionary: routing_types::RoutingDictionary, ) -> RouterResult<()> { let key = get_routing_dictionary_key(merchant_id); let dictionary_str = dictionary .encode_to_string_of_json() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to serialize routing dictionary during update")?; let config_update = configs::ConfigUpdate::Update { config: Some(dictionary_str), }; db.update_config_by_key(&key, config_update) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error saving routing dictionary to DB")?; Ok(()) } <file_sep path="hyperswitch/crates/router/src/core/routing/helpers.rs" role="context" start="105" end="127"> pub async fn update_merchant_default_config( db: &dyn StorageInterface, merchant_id: &str, connectors: Vec<routing_types::RoutableConnectorChoice>, transaction_type: &storage::enums::TransactionType, ) -> RouterResult<()> { let key = get_default_config_key(merchant_id, transaction_type); let config_str = connectors .encode_to_string_of_json() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to serialize merchant default routing config during update")?; let config_update = configs::ConfigUpdate::Update { config: Some(config_str), }; db.update_config_by_key(&key, config_update) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error updating the default routing config in DB")?; Ok(()) } <file_sep path="hyperswitch/crates/router/src/core/routing/helpers.rs" role="context" start="506" end="515"> pub fn get_default_config_key( merchant_id: &str, transaction_type: &storage::enums::TransactionType, ) -> String { match transaction_type { storage::enums::TransactionType::Payment => format!("routing_default_{merchant_id}"), #[cfg(feature = "payouts")] storage::enums::TransactionType::Payout => format!("routing_default_po_{merchant_id}"), } } <file_sep path="hyperswitch/crates/router/src/core/routing/helpers.rs" role="context" start="1616" end="1634"> pub fn new( payment_method: Option<common_enums::PaymentMethod>, payment_method_type: Option<common_enums::PaymentMethodType>, authentication_type: Option<common_enums::AuthenticationType>, currency: Option<common_enums::Currency>, country: Option<common_enums::CountryAlpha2>, card_network: Option<String>, card_bin: Option<String>, ) -> Self { Self { payment_method, payment_method_type, authentication_type, currency, country, card_network, card_bin, } } <file_sep path="hyperswitch/crates/router/tests/utils.rs" role="context" start="399" end="401"> pub struct Error { pub message: Message, } <file_sep path="hyperswitch-card-vault/migrations/2023-10-21-104200_create-tables/up.sql" role="context" start="1" end="11"> -- Your SQL goes here CREATE TABLE merchant ( id SERIAL, tenant_id VARCHAR(255) NOT NULL, merchant_id VARCHAR(255) NOT NULL, enc_key BYTEA NOT NULL, created_at TIMESTAMP NOT NULL DEFAULT now()::TIMESTAMP, PRIMARY KEY (tenant_id, merchant_id) ); <file_sep path="hyperswitch/crates/api_models/src/errors/types.rs" role="context" start="86" end="100"> pub enum ApiErrorResponse { Unauthorized(ApiError), ForbiddenCommonResource(ApiError), ForbiddenPrivateResource(ApiError), Conflict(ApiError), Gone(ApiError), Unprocessable(ApiError), InternalServerError(ApiError), NotImplemented(ApiError), ConnectorError(ApiError, #[serde(skip_serializing)] StatusCode), NotFound(ApiError), MethodNotAllowed(ApiError), BadRequest(ApiError), DomainError(ApiError), }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/core/routing.rs<|crate|> router anchor=unlink_routing_config_under_profile kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/core/routing.rs" role="context" start="673" end="724"> pub async fn unlink_routing_config_under_profile( state: SessionState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, profile_id: common_utils::id_type::ProfileId, transaction_type: &enums::TransactionType, ) -> RouterResponse<routing_types::RoutingDictionaryRecord> { metrics::ROUTING_UNLINK_CONFIG.add(1, &[]); let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let business_profile = core_utils::validate_and_get_business_profile( db, key_manager_state, &key_store, Some(&profile_id), merchant_account.get_id(), ) .await? .get_required_value("Profile")?; let routing_algo_id = match transaction_type { enums::TransactionType::Payment => business_profile.routing_algorithm_id.clone(), #[cfg(feature = "payouts")] enums::TransactionType::Payout => business_profile.payout_routing_algorithm_id.clone(), }; if let Some(algorithm_id) = routing_algo_id { let record = RoutingAlgorithmUpdate::fetch_routing_algo( merchant_account.get_id(), &algorithm_id, db, ) .await?; let response = record.0.foreign_into(); admin::ProfileWrapper::new(business_profile) .update_profile_and_invalidate_routing_config_for_active_algorithm_id_update( db, key_manager_state, &key_store, algorithm_id, transaction_type, ) .await?; metrics::ROUTING_UNLINK_CONFIG_SUCCESS_RESPONSE.add(1, &[]); Ok(service_api::ApplicationResponse::Json(response)) } else { Err(errors::ApiErrorResponse::PreconditionFailed { message: "Algorithm is already inactive".to_string(), })? } } <file_sep path="hyperswitch/crates/router/src/core/routing.rs" role="context" start="672" end="672"> use api_models::{ enums, mandates as mandates_api, routing, routing::{self as routing_types, RoutingRetrieveQuery}, }; use common_utils::ext_traits::AsyncExt; use super::payouts; use super::{ errors::RouterResult, payments::{ routing::{self as payments_routing}, OperationSessionGetters, }, }; use crate::{core::admin, utils::ValueExt}; use crate::{ core::{ errors::{self, CustomResult, RouterResponse, StorageErrorExt}, metrics, utils as core_utils, }, db::StorageInterface, routes::SessionState, services::api as service_api, types::{ api, domain, storage::{self, enums as storage_enums}, transformers::{ForeignInto, ForeignTryFrom}, }, utils::{self, OptionExt}, }; <file_sep path="hyperswitch/crates/router/src/core/routing.rs" role="context" start="820" end="893"> pub async fn update_default_fallback_routing( state: SessionState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, profile_id: common_utils::id_type::ProfileId, updated_list_of_connectors: Vec<routing_types::RoutableConnectorChoice>, ) -> RouterResponse<Vec<routing_types::RoutableConnectorChoice>> { metrics::ROUTING_UPDATE_CONFIG.add(1, &[]); let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let profile = core_utils::validate_and_get_business_profile( db, key_manager_state, &key_store, Some(&profile_id), merchant_account.get_id(), ) .await? .get_required_value("Profile")?; let profile_wrapper = admin::ProfileWrapper::new(profile); let default_list_of_connectors = profile_wrapper.get_default_fallback_list_of_connector_under_profile()?; utils::when( default_list_of_connectors.len() != updated_list_of_connectors.len(), || { Err(errors::ApiErrorResponse::PreconditionFailed { message: "current config and updated config have different lengths".to_string(), }) }, )?; let existing_set_of_default_connectors: FxHashSet<String> = FxHashSet::from_iter( default_list_of_connectors .iter() .map(|conn_choice| conn_choice.to_string()), ); let updated_set_of_default_connectors: FxHashSet<String> = FxHashSet::from_iter( updated_list_of_connectors .iter() .map(|conn_choice| conn_choice.to_string()), ); let symmetric_diff_between_existing_and_updated_connectors: Vec<String> = existing_set_of_default_connectors .symmetric_difference(&updated_set_of_default_connectors) .cloned() .collect(); utils::when( !symmetric_diff_between_existing_and_updated_connectors.is_empty(), || { Err(errors::ApiErrorResponse::InvalidRequestData { message: format!( "connector mismatch between old and new configs ({})", symmetric_diff_between_existing_and_updated_connectors.join(", ") ), }) }, )?; profile_wrapper .update_default_fallback_routing_of_connectors_under_profile( db, &updated_list_of_connectors, key_manager_state, &key_store, ) .await?; metrics::ROUTING_UPDATE_CONFIG_SUCCESS_RESPONSE.add(1, &[]); Ok(service_api::ApplicationResponse::Json( updated_list_of_connectors, )) } <file_sep path="hyperswitch/crates/router/src/core/routing.rs" role="context" start="727" end="817"> pub async fn unlink_routing_config( state: SessionState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, request: routing_types::RoutingConfigRequest, authentication_profile_id: Option<common_utils::id_type::ProfileId>, transaction_type: &enums::TransactionType, ) -> RouterResponse<routing_types::RoutingDictionaryRecord> { metrics::ROUTING_UNLINK_CONFIG.add(1, &[]); let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let profile_id = request .profile_id .get_required_value("profile_id") .change_context(errors::ApiErrorResponse::MissingRequiredField { field_name: "profile_id", }) .attach_printable("Profile_id not provided")?; let business_profile = core_utils::validate_and_get_business_profile( db, key_manager_state, &key_store, Some(&profile_id), merchant_account.get_id(), ) .await?; match business_profile { Some(business_profile) => { core_utils::validate_profile_id_from_auth_layer( authentication_profile_id, &business_profile, )?; let routing_algo_ref: routing_types::RoutingAlgorithmRef = match transaction_type { enums::TransactionType::Payment => business_profile.routing_algorithm.clone(), #[cfg(feature = "payouts")] enums::TransactionType::Payout => business_profile.payout_routing_algorithm.clone(), } .map(|val| val.parse_value("RoutingAlgorithmRef")) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("unable to deserialize routing algorithm ref from merchant account")? .unwrap_or_default(); let timestamp = common_utils::date_time::now_unix_timestamp(); match routing_algo_ref.algorithm_id { Some(algorithm_id) => { let routing_algorithm: routing_types::RoutingAlgorithmRef = routing_types::RoutingAlgorithmRef { algorithm_id: None, timestamp, config_algo_id: routing_algo_ref.config_algo_id.clone(), surcharge_config_algo_id: routing_algo_ref.surcharge_config_algo_id, }; let record = db .find_routing_algorithm_by_profile_id_algorithm_id( &profile_id, &algorithm_id, ) .await .to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?; let response = record.foreign_into(); helpers::update_profile_active_algorithm_ref( db, key_manager_state, &key_store, business_profile, routing_algorithm, transaction_type, ) .await?; metrics::ROUTING_UNLINK_CONFIG_SUCCESS_RESPONSE.add(1, &[]); Ok(service_api::ApplicationResponse::Json(response)) } None => Err(errors::ApiErrorResponse::PreconditionFailed { message: "Algorithm is already inactive".to_string(), })?, } } None => Err(errors::ApiErrorResponse::InvalidRequestData { message: "The business_profile is not present".to_string(), } .into()), } } <file_sep path="hyperswitch/crates/router/src/core/routing.rs" role="context" start="632" end="670"> pub async fn retrieve_routing_algorithm_from_algorithm_id( state: SessionState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, authentication_profile_id: Option<common_utils::id_type::ProfileId>, algorithm_id: common_utils::id_type::RoutingId, ) -> RouterResponse<routing_types::MerchantRoutingAlgorithm> { metrics::ROUTING_RETRIEVE_CONFIG.add(1, &[]); let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let routing_algorithm = db .find_routing_algorithm_by_algorithm_id_merchant_id( &algorithm_id, merchant_account.get_id(), ) .await .to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?; let business_profile = core_utils::validate_and_get_business_profile( db, key_manager_state, &key_store, Some(&routing_algorithm.profile_id), merchant_account.get_id(), ) .await? .get_required_value("Profile") .change_context(errors::ApiErrorResponse::ResourceIdNotFound)?; core_utils::validate_profile_id_from_auth_layer(authentication_profile_id, &business_profile)?; let response = routing_types::MerchantRoutingAlgorithm::foreign_try_from(routing_algorithm) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("unable to parse routing algorithm")?; metrics::ROUTING_RETRIEVE_CONFIG_SUCCESS_RESPONSE.add(1, &[]); Ok(service_api::ApplicationResponse::Json(response)) } <file_sep path="hyperswitch/crates/router/src/core/routing.rs" role="context" start="596" end="629"> pub async fn retrieve_routing_algorithm_from_algorithm_id( state: SessionState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, authentication_profile_id: Option<common_utils::id_type::ProfileId>, algorithm_id: common_utils::id_type::RoutingId, ) -> RouterResponse<routing_types::MerchantRoutingAlgorithm> { metrics::ROUTING_RETRIEVE_CONFIG.add(1, &[]); let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let routing_algorithm = RoutingAlgorithmUpdate::fetch_routing_algo(merchant_account.get_id(), &algorithm_id, db) .await?; let business_profile = core_utils::validate_and_get_business_profile( db, key_manager_state, &key_store, Some(&routing_algorithm.0.profile_id), merchant_account.get_id(), ) .await? .get_required_value("Profile") .change_context(errors::ApiErrorResponse::ResourceIdNotFound)?; core_utils::validate_profile_id_from_auth_layer(authentication_profile_id, &business_profile)?; let response = routing_types::MerchantRoutingAlgorithm::foreign_try_from(routing_algorithm.0) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("unable to parse routing algorithm")?; metrics::ROUTING_RETRIEVE_CONFIG_SUCCESS_RESPONSE.add(1, &[]); Ok(service_api::ApplicationResponse::Json(response)) } <file_sep path="hyperswitch/crates/router/src/core/routing.rs" role="context" start="123" end="133"> pub async fn fetch_routing_algo( merchant_id: &common_utils::id_type::MerchantId, algorithm_id: &common_utils::id_type::RoutingId, db: &dyn StorageInterface, ) -> RouterResult<Self> { let routing_algo = db .find_routing_algorithm_by_algorithm_id_merchant_id(algorithm_id, merchant_id) .await .change_context(errors::ApiErrorResponse::ResourceIdNotFound)?; Ok(Self(routing_algo)) } <file_sep path="hyperswitch/crates/router/src/core/routing.rs" role="context" start="75" end="93"> pub fn new( setup_mandate: Option<&'a mandates::MandateData>, payment_attempt: &'a storage::PaymentAttempt, payment_intent: &'a storage::PaymentIntent, payment_method_data: Option<&'a domain::PaymentMethodData>, address: &'a payment_address::PaymentAddress, recurring_details: Option<&'a mandates_api::RecurringDetails>, currency: storage_enums::Currency, ) -> Self { Self { setup_mandate, payment_attempt, payment_intent, payment_method_data, address, recurring_details, currency, } } <file_sep path="hyperswitch/crates/router/src/core/routing.rs" role="context" start="97" end="97"> struct RoutingAlgorithmUpdate(RoutingAlgorithm); <file_sep path="hyperswitch/crates/router/src/routes/app.rs" role="context" start="1906" end="1906"> pub struct Profile; <file_sep path="hyperswitch/migrations/2024-07-31-063531_alter_customer_id_in_payouts/up.sql" role="context" start="1" end="9"> ALTER TABLE payouts ALTER COLUMN customer_id DROP NOT NULL, ALTER COLUMN address_id DROP NOT NULL; ALTER TABLE payout_attempt ALTER COLUMN customer_id DROP NOT NULL,
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payments/payment_methods.rs<|crate|> router anchor=list_payment_methods kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/core/payments/payment_methods.rs" role="context" start="15" end="70"> pub async fn list_payment_methods( state: routes::SessionState, merchant_account: domain::MerchantAccount, profile: domain::Profile, key_store: domain::MerchantKeyStore, payment_id: id_type::GlobalPaymentId, _req: api_models::payments::PaymentMethodsListRequest, header_payload: &hyperswitch_domain_models::payments::HeaderPayload, ) -> errors::RouterResponse<api_models::payments::PaymentMethodListResponseForPayments> { let db = &*state.store; let key_manager_state = &(&state).into(); let payment_intent = db .find_payment_intent_by_id( key_manager_state, &payment_id, &key_store, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; validate_payment_status_for_payment_method_list(payment_intent.status)?; let client_secret = header_payload .client_secret .as_ref() .get_required_value("client_secret header") .change_context(errors::ApiErrorResponse::MissingRequiredField { field_name: "client_secret header", })?; payment_intent.validate_client_secret(client_secret)?; let payment_connector_accounts = db .list_enabled_connector_accounts_by_profile_id( key_manager_state, profile.get_id(), &key_store, common_enums::ConnectorType::PaymentProcessor, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("error when fetching merchant connector accounts")?; let response = hyperswitch_domain_models::merchant_connector_account::FlattenedPaymentMethodsEnabled::from_payment_connectors_list(payment_connector_accounts) .perform_filtering() .get_required_fields(RequiredFieldsInput::new()) .perform_surcharge_calculation() .generate_response(); Ok(hyperswitch_domain_models::api::ApplicationResponse::Json( response, )) } <file_sep path="hyperswitch/crates/router/src/core/payments/payment_methods.rs" role="context" start="14" end="14"> use common_utils::{ext_traits::OptionExt, id_type}; use super::errors; use crate::{db::errors::StorageErrorExt, routes, types::domain}; <file_sep path="hyperswitch/crates/router/src/core/payments/payment_methods.rs" role="context" start="87" end="106"> fn get_required_fields( self, _input: RequiredFieldsInput, ) -> RequiredFieldsForEnabledPaymentMethodTypes { let required_fields_info = self .0 .into_iter() .map( |payment_methods_enabled| RequiredFieldsForEnabledPaymentMethod { required_field: None, payment_method_type: payment_methods_enabled.payment_method, payment_method_subtype: payment_methods_enabled .payment_methods_enabled .payment_method_subtype, }, ) .collect(); RequiredFieldsForEnabledPaymentMethodTypes(required_fields_info) } <file_sep path="hyperswitch/crates/router/src/core/payments/payment_methods.rs" role="context" start="76" end="78"> fn new() -> Self { Self {} } <file_sep path="hyperswitch/crates/router/src/core/payments/payment_methods.rs" role="context" start="189" end="212"> fn validate_payment_status_for_payment_method_list( intent_status: common_enums::IntentStatus, ) -> Result<(), errors::ApiErrorResponse> { match intent_status { common_enums::IntentStatus::RequiresPaymentMethod => Ok(()), common_enums::IntentStatus::Succeeded | common_enums::IntentStatus::Failed | common_enums::IntentStatus::Cancelled | common_enums::IntentStatus::Processing | common_enums::IntentStatus::RequiresCustomerAction | common_enums::IntentStatus::RequiresMerchantAction | common_enums::IntentStatus::RequiresCapture | common_enums::IntentStatus::PartiallyCaptured | common_enums::IntentStatus::RequiresConfirmation | common_enums::IntentStatus::PartiallyCapturedAndCapturable => { Err(errors::ApiErrorResponse::PaymentUnexpectedState { current_flow: "list_payment_methods".to_string(), field_name: "status".to_string(), current_value: intent_status.to_string(), states: ["requires_payment_method".to_string()].join(", "), }) } } } <file_sep path="hyperswitch/crates/router/src/core/payments/payment_methods.rs" role="context" start="73" end="73"> struct RequiredFieldsInput {} <file_sep path="hyperswitch/crates/router/src/routes/app.rs" role="context" start="1906" end="1906"> pub struct Profile; <file_sep path="hyperswitch/v2_compatible_migrations/2024-08-28-081757_drop_not_null_constraints_on_v1_columns/up.sql" role="context" start="5" end="21"> ALTER COLUMN org_id DROP NOT NULL; -- Create index on org_id in organization table -- This is done to mullify the effects of droping primary key for v1 CREATE INDEX idx_organization_org_id ON organization (org_id); ------------------------ Merchant Account ------------------- -- Drop not null in merchant_account table for v1 columns that are dropped in v2 ALTER TABLE merchant_account DROP CONSTRAINT merchant_account_pkey, ALTER COLUMN merchant_id DROP NOT NULL, ALTER COLUMN primary_business_details DROP NOT NULL, ALTER COLUMN is_recon_enabled DROP NOT NULL; -- This is done to mullify the effects of droping primary key for v1 CREATE INDEX idx_merchant_account_merchant_id ON merchant_account (merchant_id); <file_sep path="hyperswitch/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/event.test.js" role="context" start="61" end="78"> "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.", ); } // Response body should have value "succeeded" for "status" if (jsonData?.status) { pm.test( "[POST]::/payments - Content check if value for 'status' matches 'succeeded'", function () { pm.expect(jsonData.status).to.eql("succeeded"); }, ); }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/core/admin.rs<|crate|> router anchor=create_profile_from_business_labels kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/core/admin.rs" role="context" start="771" end="834"> pub async fn create_profile_from_business_labels( state: &SessionState, db: &dyn StorageInterface, key_store: &domain::MerchantKeyStore, merchant_id: &id_type::MerchantId, new_business_details: Vec<admin_types::PrimaryBusinessDetails>, ) -> RouterResult<()> { let key_manager_state = &state.into(); let merchant_account = db .find_merchant_account_by_merchant_id(key_manager_state, merchant_id, key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let old_business_details = merchant_account .primary_business_details .clone() .parse_value::<Vec<admin_types::PrimaryBusinessDetails>>("PrimaryBusinessDetails") .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "routing_algorithm", }) .attach_printable("Invalid routing algorithm given")?; // find the diff between two vectors let business_profiles_to_create = new_business_details .into_iter() .filter(|business_details| !old_business_details.contains(business_details)) .collect::<Vec<_>>(); for business_profile in business_profiles_to_create { let profile_name = format!("{}_{}", business_profile.country, business_profile.business); let profile_create_request = admin_types::ProfileCreate { profile_name: Some(profile_name), ..Default::default() }; let profile_create_result = create_and_insert_business_profile( state, profile_create_request, merchant_account.clone(), key_store, ) .await .map_err(|profile_insert_error| { // If there is any duplicate error, we need not take any action crate::logger::warn!("Profile already exists {profile_insert_error:?}"); }); // If a profile is created, then unset the default profile if profile_create_result.is_ok() && merchant_account.default_profile.is_some() { let unset_default_profile = domain::MerchantAccountUpdate::UnsetDefaultProfile; db.update_merchant( key_manager_state, merchant_account.clone(), unset_default_profile, key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; } } Ok(()) } <file_sep path="hyperswitch/crates/router/src/core/admin.rs" role="context" start="770" end="770"> .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; Ok(service_api::ApplicationResponse::Json( api::MerchantAccountResponse::foreign_try_from(merchant_account) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to construct response")?, )) } #[cfg(feature = "v1")] /// For backwards compatibility, whenever new business labels are passed in /// primary_business_details, create a profile pub async fn create_profile_from_business_labels( state: &SessionState, db: &dyn StorageInterface, key_store: &domain::MerchantKeyStore, merchant_id: &id_type::MerchantId, new_business_details: Vec<admin_types::PrimaryBusinessDetails>, ) -> RouterResult<()> { let key_manager_state = &state.into(); let merchant_account = db .find_merchant_account_by_merchant_id(key_manager_state, merchant_id, key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; <file_sep path="hyperswitch/crates/router/src/core/admin.rs" role="context" start="990" end="1048"> async fn get_update_merchant_object( self, state: &SessionState, _merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, ) -> RouterResult<storage::MerchantAccountUpdate> { let key_manager_state = &state.into(); let key = key_store.key.get_inner().peek(); let merchant_details = self.get_merchant_details_as_secret().change_context( errors::ApiErrorResponse::InvalidDataValue { field_name: "merchant_details", }, )?; let metadata = self.get_metadata_as_secret().change_context( errors::ApiErrorResponse::InvalidDataValue { field_name: "metadata", }, )?; let identifier = km_types::Identifier::Merchant(key_store.merchant_id.clone()); Ok(storage::MerchantAccountUpdate::Update { merchant_name: self .merchant_name .map(Secret::new) .async_lift(|inner| async { domain_types::crypto_operation( key_manager_state, type_name!(storage::MerchantAccount), domain_types::CryptoOperation::EncryptOptional(inner), identifier.clone(), key, ) .await .and_then(|val| val.try_into_optionaloperation()) }) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt merchant name")?, merchant_details: merchant_details .async_lift(|inner| async { domain_types::crypto_operation( key_manager_state, type_name!(storage::MerchantAccount), domain_types::CryptoOperation::EncryptOptional(inner), identifier.clone(), key, ) .await .and_then(|val| val.try_into_optionaloperation()) }) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt merchant details")?, metadata: metadata.map(Box::new), publishable_key: None, }) } <file_sep path="hyperswitch/crates/router/src/core/admin.rs" role="context" start="850" end="984"> async fn get_update_merchant_object( self, state: &SessionState, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, ) -> RouterResult<storage::MerchantAccountUpdate> { let key_manager_state = &state.into(); let key = key_store.key.get_inner().peek(); let db = state.store.as_ref(); let primary_business_details = self.get_primary_details_as_value().change_context( errors::ApiErrorResponse::InvalidDataValue { field_name: "primary_business_details", }, )?; let pm_collect_link_config = self.get_pm_link_config_as_value().change_context( errors::ApiErrorResponse::InvalidDataValue { field_name: "pm_collect_link_config", }, )?; let merchant_details = self.get_merchant_details_as_secret().change_context( errors::ApiErrorResponse::InvalidDataValue { field_name: "merchant_details", }, )?; self.parse_routing_algorithm().change_context( errors::ApiErrorResponse::InvalidDataValue { field_name: "routing_algorithm", }, )?; let webhook_details = self.webhook_details.map(ForeignInto::foreign_into); let parent_merchant_id = get_parent_merchant( state, self.sub_merchants_enabled, self.parent_merchant_id.as_ref(), key_store, ) .await?; // This supports changing the business profile by passing in the profile_id let business_profile_id_update = if let Some(ref profile_id) = self.default_profile { // Validate whether profile_id passed in request is valid and is linked to the merchant core_utils::validate_and_get_business_profile( state.store.as_ref(), key_manager_state, key_store, Some(profile_id), merchant_id, ) .await? .map(|business_profile| Some(business_profile.get_id().to_owned())) } else { None }; #[cfg(any(feature = "v1", feature = "v2"))] // In order to support backwards compatibility, if a business_labels are passed in the update // call, then create new profiles with the profile_name as business_label self.primary_business_details .clone() .async_map(|primary_business_details| async { let _ = create_profile_from_business_labels( state, db, key_store, merchant_id, primary_business_details, ) .await; }) .await; let identifier = km_types::Identifier::Merchant(key_store.merchant_id.clone()); Ok(storage::MerchantAccountUpdate::Update { merchant_name: self .merchant_name .map(Secret::new) .async_lift(|inner| async { domain_types::crypto_operation( key_manager_state, type_name!(storage::MerchantAccount), domain_types::CryptoOperation::EncryptOptional(inner), identifier.clone(), key, ) .await .and_then(|val| val.try_into_optionaloperation()) }) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt merchant name")?, merchant_details: merchant_details .async_lift(|inner| async { domain_types::crypto_operation( key_manager_state, type_name!(storage::MerchantAccount), domain_types::CryptoOperation::EncryptOptional(inner), identifier.clone(), key, ) .await .and_then(|val| val.try_into_optionaloperation()) }) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt merchant details")?, return_url: self.return_url.map(|a| a.to_string()), webhook_details, sub_merchants_enabled: self.sub_merchants_enabled, parent_merchant_id, enable_payment_response_hash: self.enable_payment_response_hash, payment_response_hash_key: self.payment_response_hash_key, redirect_to_merchant_with_http_post: self.redirect_to_merchant_with_http_post, locker_id: self.locker_id, metadata: self.metadata, publishable_key: None, primary_business_details, frm_routing_algorithm: self.frm_routing_algorithm, intent_fulfillment_time: None, #[cfg(feature = "payouts")] payout_routing_algorithm: self.payout_routing_algorithm, #[cfg(not(feature = "payouts"))] payout_routing_algorithm: None, default_profile: business_profile_id_update, payment_link_config: None, pm_collect_link_config, routing_algorithm: self.routing_algorithm, }) } <file_sep path="hyperswitch/crates/router/src/core/admin.rs" role="context" start="740" end="766"> pub async fn get_merchant_account( state: SessionState, req: api::MerchantId, _profile_id: Option<id_type::ProfileId>, ) -> RouterResponse<api::MerchantAccountResponse> { let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let key_store = db .get_merchant_key_store_by_merchant_id( key_manager_state, &req.merchant_id, &db.get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let merchant_account = db .find_merchant_account_by_merchant_id(key_manager_state, &req.merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; Ok(service_api::ApplicationResponse::Json( api::MerchantAccountResponse::foreign_try_from(merchant_account) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to construct response")?, )) } <file_sep path="hyperswitch/crates/router/src/core/admin.rs" role="context" start="716" end="738"> pub async fn list_merchant_account( state: SessionState, req: api_models::admin::MerchantAccountListRequest, ) -> RouterResponse<Vec<api::MerchantAccountResponse>> { let merchant_accounts = state .store .list_merchant_accounts_by_organization_id(&(&state).into(), &req.organization_id) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let merchant_accounts = merchant_accounts .into_iter() .map(|merchant_account| { api::MerchantAccountResponse::foreign_try_from(merchant_account).change_context( errors::ApiErrorResponse::InvalidDataValue { field_name: "merchant_account", }, ) }) .collect::<Result<Vec<_>, _>>()?; Ok(services::ApplicationResponse::Json(merchant_accounts)) } <file_sep path="hyperswitch/crates/router/src/core/admin.rs" role="context" start="3587" end="3609"> pub async fn create_and_insert_business_profile( state: &SessionState, request: api::ProfileCreate, merchant_account: domain::MerchantAccount, key_store: &domain::MerchantKeyStore, ) -> RouterResult<domain::Profile> { let business_profile_new = admin::create_profile_from_merchant_account(state, merchant_account, request, key_store) .await?; let profile_name = business_profile_new.profile_name.clone(); state .store .insert_business_profile(&state.into(), key_store, business_profile_new) .await .to_duplicate_response(errors::ApiErrorResponse::GenericDuplicateError { message: format!( "Business Profile with the profile_name {profile_name} already exists" ), }) .attach_printable("Failed to insert Business profile because of duplication error") } <file_sep path="hyperswitch/crates/router/src/routes/app.rs" role="context" start="1906" end="1906"> pub struct Profile; <file_sep path="hyperswitch-encryption-service/migrations/2024-05-28-075150_create_dek_table/up.sql" role="context" start="1" end="9"> CREATE TABLE IF NOT EXISTS data_key_store ( id SERIAL PRIMARY KEY, key_identifier VARCHAR(255) NOT NULL, data_identifier VARCHAR(20) NOT NULL, encryption_key bytea NOT NULL, version VARCHAR(30) NOT NULL, created_at TIMESTAMP NOT NULL ); <file_sep path="hyperswitch/crates/api_models/src/errors/types.rs" role="context" start="86" end="100"> pub enum ApiErrorResponse { Unauthorized(ApiError), ForbiddenCommonResource(ApiError), ForbiddenPrivateResource(ApiError), Conflict(ApiError), Gone(ApiError), Unprocessable(ApiError), InternalServerError(ApiError), NotImplemented(ApiError), ConnectorError(ApiError, #[serde(skip_serializing)] StatusCode), NotFound(ApiError), MethodNotAllowed(ApiError), BadRequest(ApiError), DomainError(ApiError), }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payments/helpers.rs<|crate|> router anchor=modify_payment_intent_and_payment_attempt kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="4546" end="4625"> pub async fn modify_payment_intent_and_payment_attempt( &self, request: &api_models::payments::PaymentsRequest, fetched_payment_intent: PaymentIntent, fetched_payment_attempt: PaymentAttempt, state: &SessionState, key_store: &domain::MerchantKeyStore, storage_scheme: storage::enums::MerchantStorageScheme, ) -> RouterResult<(PaymentIntent, PaymentAttempt)> { match self { Self::SameOld => Ok((fetched_payment_intent, fetched_payment_attempt)), Self::New => { let db = &*state.store; let key_manager_state = &state.into(); let new_attempt_count = fetched_payment_intent.attempt_count + 1; let new_payment_attempt_to_insert = Self::make_new_payment_attempt( request .payment_method_data .as_ref() .and_then(|request_payment_method_data| { request_payment_method_data.payment_method_data.as_ref() }), fetched_payment_attempt, new_attempt_count, storage_scheme, ); #[cfg(feature = "v1")] let new_payment_attempt = db .insert_payment_attempt(new_payment_attempt_to_insert, storage_scheme) .await .to_duplicate_response(errors::ApiErrorResponse::DuplicatePayment { payment_id: fetched_payment_intent.get_id().to_owned(), })?; #[cfg(feature = "v2")] let new_payment_attempt = db .insert_payment_attempt( key_manager_state, key_store, new_payment_attempt_to_insert, storage_scheme, ) .await .to_duplicate_response(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to insert payment attempt")?; let updated_payment_intent = db .update_payment_intent( key_manager_state, fetched_payment_intent, storage::PaymentIntentUpdate::StatusAndAttemptUpdate { status: payment_intent_status_fsm( request.payment_method_data.as_ref().and_then( |request_payment_method_data| { request_payment_method_data.payment_method_data.as_ref() }, ), Some(true), ), active_attempt_id: new_payment_attempt.get_id().to_owned(), attempt_count: new_attempt_count, updated_by: storage_scheme.to_string(), }, key_store, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; logger::info!( "manual_retry payment for {:?} with attempt_id {:?}", updated_payment_intent.get_id(), new_payment_attempt.get_id() ); Ok((updated_payment_intent, new_payment_attempt)) } } } <file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="4545" end="4545"> // #[inline(always)] // fn make_new_payment_attempt( // _payment_method_data: Option<&api_models::payments::PaymentMethodData>, // _old_payment_attempt: PaymentAttempt, // _new_attempt_count: i16, // _storage_scheme: enums::MerchantStorageScheme, // ) -> PaymentAttempt { // todo!() // } #[cfg(feature = "v1")] #[instrument(skip_all)] pub async fn modify_payment_intent_and_payment_attempt( &self, request: &api_models::payments::PaymentsRequest, fetched_payment_intent: PaymentIntent, fetched_payment_attempt: PaymentAttempt, state: &SessionState, key_store: &domain::MerchantKeyStore, storage_scheme: storage::enums::MerchantStorageScheme, ) -> RouterResult<(PaymentIntent, PaymentAttempt)> { match self { Self::SameOld => Ok((fetched_payment_intent, fetched_payment_attempt)), Self::New => { let db = &*state.store; <file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="4690" end="4708"> fn test_client_secret_parse() { let client_secret1 = "pay_3TgelAms4RQec8xSStjF_secret_fc34taHLw1ekPgNh92qr"; let client_secret2 = "pay_3Tgel__Ams4RQ_secret_ec8xSStjF_secret_fc34taHLw1ekPgNh92qr"; let client_secret3 = "pay_3Tgel__Ams4RQ_secret_ec8xSStjF_secret__secret_fc34taHLw1ekPgNh92qr"; assert_eq!( "pay_3TgelAms4RQec8xSStjF", super::get_payment_id_from_client_secret(client_secret1).unwrap() ); assert_eq!( "pay_3Tgel__Ams4RQ_secret_ec8xSStjF", super::get_payment_id_from_client_secret(client_secret2).unwrap() ); assert_eq!( "pay_3Tgel__Ams4RQ_secret_ec8xSStjF_secret_", super::get_payment_id_from_client_secret(client_secret3).unwrap() ); } <file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="4629" end="4684"> pub fn is_manual_retry_allowed( intent_status: &storage_enums::IntentStatus, attempt_status: &storage_enums::AttemptStatus, connector_request_reference_id_config: &ConnectorRequestReferenceIdConfig, merchant_id: &id_type::MerchantId, ) -> Option<bool> { let is_payment_status_eligible_for_retry = match intent_status { enums::IntentStatus::Failed => match attempt_status { enums::AttemptStatus::Started | enums::AttemptStatus::AuthenticationPending | enums::AttemptStatus::AuthenticationSuccessful | enums::AttemptStatus::Authorized | enums::AttemptStatus::Charged | enums::AttemptStatus::Authorizing | enums::AttemptStatus::CodInitiated | enums::AttemptStatus::VoidInitiated | enums::AttemptStatus::CaptureInitiated | enums::AttemptStatus::Unresolved | enums::AttemptStatus::Pending | enums::AttemptStatus::ConfirmationAwaited | enums::AttemptStatus::PartialCharged | enums::AttemptStatus::PartialChargedAndChargeable | enums::AttemptStatus::Voided | enums::AttemptStatus::AutoRefunded | enums::AttemptStatus::PaymentMethodAwaited | enums::AttemptStatus::DeviceDataCollectionPending => { logger::error!("Payment Attempt should not be in this state because Attempt to Intent status mapping doesn't allow it"); None } storage_enums::AttemptStatus::VoidFailed | storage_enums::AttemptStatus::RouterDeclined | storage_enums::AttemptStatus::CaptureFailed => Some(false), storage_enums::AttemptStatus::AuthenticationFailed | storage_enums::AttemptStatus::AuthorizationFailed | storage_enums::AttemptStatus::Failure => Some(true), }, enums::IntentStatus::Cancelled | enums::IntentStatus::RequiresCapture | enums::IntentStatus::PartiallyCaptured | enums::IntentStatus::PartiallyCapturedAndCapturable | enums::IntentStatus::Processing | enums::IntentStatus::Succeeded => Some(false), enums::IntentStatus::RequiresCustomerAction | enums::IntentStatus::RequiresMerchantAction | enums::IntentStatus::RequiresPaymentMethod | enums::IntentStatus::RequiresConfirmation => None, }; let is_merchant_id_enabled_for_retries = !connector_request_reference_id_config .merchant_ids_send_payment_id_as_connector_request_id .contains(merchant_id); is_payment_status_eligible_for_retry .map(|payment_status_check| payment_status_check && is_merchant_id_enabled_for_retries) } <file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="4441" end="4528"> fn make_new_payment_attempt( payment_method_data: Option<&api_models::payments::PaymentMethodData>, old_payment_attempt: PaymentAttempt, new_attempt_count: i16, storage_scheme: enums::MerchantStorageScheme, ) -> storage::PaymentAttemptNew { let created_at @ modified_at @ last_synced = Some(common_utils::date_time::now()); storage::PaymentAttemptNew { attempt_id: old_payment_attempt .payment_id .get_attempt_id(new_attempt_count), payment_id: old_payment_attempt.payment_id, merchant_id: old_payment_attempt.merchant_id, // A new payment attempt is getting created so, used the same function which is used to populate status in PaymentCreate Flow. status: payment_attempt_status_fsm(payment_method_data, Some(true)), currency: old_payment_attempt.currency, save_to_locker: old_payment_attempt.save_to_locker, connector: None, error_message: None, offer_amount: old_payment_attempt.offer_amount, payment_method_id: None, payment_method: None, capture_method: old_payment_attempt.capture_method, capture_on: old_payment_attempt.capture_on, confirm: old_payment_attempt.confirm, authentication_type: old_payment_attempt.authentication_type, created_at, modified_at, last_synced, cancellation_reason: None, amount_to_capture: old_payment_attempt.amount_to_capture, // Once the payment_attempt is authorised then mandate_id is created. If this payment attempt is authorised then mandate_id will be overridden. // Since mandate_id is a contract between merchant and customer to debit customers amount adding it to newly created attempt mandate_id: old_payment_attempt.mandate_id, // The payment could be done from a different browser or same browser, it would probably be overridden by request data. browser_info: None, error_code: None, payment_token: None, connector_metadata: None, payment_experience: None, payment_method_type: None, payment_method_data: None, // In case it is passed in create and not in confirm, business_sub_label: old_payment_attempt.business_sub_label, // If the algorithm is entered in Create call from server side, it needs to be populated here, however it could be overridden from the request. straight_through_algorithm: old_payment_attempt.straight_through_algorithm, mandate_details: old_payment_attempt.mandate_details, preprocessing_step_id: None, error_reason: None, multiple_capture_count: None, connector_response_reference_id: None, amount_capturable: old_payment_attempt.net_amount.get_total_amount(), updated_by: storage_scheme.to_string(), authentication_data: None, encoded_data: None, merchant_connector_id: None, unified_code: None, unified_message: None, net_amount: old_payment_attempt.net_amount, external_three_ds_authentication_attempted: old_payment_attempt .external_three_ds_authentication_attempted, authentication_connector: None, authentication_id: None, mandate_data: old_payment_attempt.mandate_data, // New payment method billing address can be passed for a retry payment_method_billing_address_id: None, fingerprint_id: None, client_source: old_payment_attempt.client_source, client_version: old_payment_attempt.client_version, customer_acceptance: old_payment_attempt.customer_acceptance, organization_id: old_payment_attempt.organization_id, profile_id: old_payment_attempt.profile_id, connector_mandate_detail: None, request_extended_authorization: None, extended_authorization_applied: None, capture_before: None, card_discovery: None, } } <file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="4321" end="4427"> pub fn get_attempt_type( payment_intent: &PaymentIntent, payment_attempt: &PaymentAttempt, request: &api_models::payments::PaymentsRequest, action: &str, ) -> RouterResult<AttemptType> { match payment_intent.status { enums::IntentStatus::Failed => { if matches!( request.retry_action, Some(api_models::enums::RetryAction::ManualRetry) ) { metrics::MANUAL_RETRY_REQUEST_COUNT.add( 1, router_env::metric_attributes!(( "merchant_id", payment_attempt.merchant_id.clone(), )), ); match payment_attempt.status { enums::AttemptStatus::Started | enums::AttemptStatus::AuthenticationPending | enums::AttemptStatus::AuthenticationSuccessful | enums::AttemptStatus::Authorized | enums::AttemptStatus::Charged | enums::AttemptStatus::Authorizing | enums::AttemptStatus::CodInitiated | enums::AttemptStatus::VoidInitiated | enums::AttemptStatus::CaptureInitiated | enums::AttemptStatus::Unresolved | enums::AttemptStatus::Pending | enums::AttemptStatus::ConfirmationAwaited | enums::AttemptStatus::PartialCharged | enums::AttemptStatus::PartialChargedAndChargeable | enums::AttemptStatus::Voided | enums::AttemptStatus::AutoRefunded | enums::AttemptStatus::PaymentMethodAwaited | enums::AttemptStatus::DeviceDataCollectionPending => { metrics::MANUAL_RETRY_VALIDATION_FAILED.add( 1, router_env::metric_attributes!(( "merchant_id", payment_attempt.merchant_id.clone(), )), ); Err(errors::ApiErrorResponse::InternalServerError) .attach_printable("Payment Attempt unexpected state") } storage_enums::AttemptStatus::VoidFailed | storage_enums::AttemptStatus::RouterDeclined | storage_enums::AttemptStatus::CaptureFailed => { metrics::MANUAL_RETRY_VALIDATION_FAILED.add( 1, router_env::metric_attributes!(( "merchant_id", payment_attempt.merchant_id.clone(), )), ); Err(report!(errors::ApiErrorResponse::PreconditionFailed { message: format!("You cannot {action} this payment because it has status {}, and the previous attempt has the status {}", payment_intent.status, payment_attempt.status) } )) } storage_enums::AttemptStatus::AuthenticationFailed | storage_enums::AttemptStatus::AuthorizationFailed | storage_enums::AttemptStatus::Failure => { metrics::MANUAL_RETRY_COUNT.add( 1, router_env::metric_attributes!(( "merchant_id", payment_attempt.merchant_id.clone(), )), ); Ok(AttemptType::New) } } } else { Err(report!(errors::ApiErrorResponse::PreconditionFailed { message: format!("You cannot {action} this payment because it has status {}, you can pass `retry_action` as `manual_retry` in request to try this payment again", payment_intent.status) } )) } } enums::IntentStatus::Cancelled | enums::IntentStatus::RequiresCapture | enums::IntentStatus::PartiallyCaptured | enums::IntentStatus::PartiallyCapturedAndCapturable | enums::IntentStatus::Processing | enums::IntentStatus::Succeeded => { Err(report!(errors::ApiErrorResponse::PreconditionFailed { message: format!( "You cannot {action} this payment because it has status {}", payment_intent.status, ), })) } enums::IntentStatus::RequiresCustomerAction | enums::IntentStatus::RequiresMerchantAction | enums::IntentStatus::RequiresPaymentMethod | enums::IntentStatus::RequiresConfirmation => Ok(AttemptType::SameOld), } } <file_sep path="hyperswitch/crates/router/src/core/payments/helpers.rs" role="context" start="1375" end="1386"> pub fn payment_intent_status_fsm( payment_method_data: Option<&api::PaymentMethodData>, confirm: Option<bool>, ) -> storage_enums::IntentStatus { match payment_method_data { Some(_) => match confirm { Some(true) => storage_enums::IntentStatus::RequiresPaymentMethod, _ => storage_enums::IntentStatus::RequiresConfirmation, }, None => storage_enums::IntentStatus::RequiresPaymentMethod, } } <file_sep path="hyperswitch/crates/router/src/core/errors.rs" role="context" start="31" end="31"> pub type RouterResult<T> = CustomResult<T, ApiErrorResponse>; <file_sep path="hyperswitch/v2_compatible_migrations/2024-08-28-081721_add_v2_columns/up.sql" role="context" start="19" end="35"> -- Intentionally not adding a default value here since we would have to -- check if any merchants have enabled this from configs table, -- before filling data for this column. -- If no merchants have enabled this, then we can use `false` as the default value -- when adding the column, later we can drop the default added for the column -- so that we ensure new records inserted always have a value for the column. ADD COLUMN should_collect_cvv_during_payment BOOLEAN; ALTER TABLE payment_intent ADD COLUMN merchant_reference_id VARCHAR(64), ADD COLUMN billing_address BYTEA DEFAULT NULL, ADD COLUMN shipping_address BYTEA DEFAULT NULL, ADD COLUMN capture_method "CaptureMethod", ADD COLUMN authentication_type "AuthenticationType", ADD COLUMN amount_to_capture bigint, ADD COLUMN prerouting_algorithm JSONB, ADD COLUMN surcharge_amount bigint, <file_sep path="hyperswitch/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/event.test.js" role="context" start="61" end="78"> "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.", ); } // Response body should have value "succeeded" for "status" if (jsonData?.status) { pm.test( "[POST]::/payments - Content check if value for 'status' matches 'succeeded'", function () { pm.expect(jsonData.status).to.eql("succeeded"); }, ); }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/core/admin.rs<|crate|> router anchor=create_merchant_account kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/core/admin.rs" role="context" start="185" end="265"> pub async fn create_merchant_account( state: SessionState, req: api::MerchantAccountCreate, ) -> RouterResponse<api::MerchantAccountResponse> { #[cfg(feature = "keymanager_create")] use common_utils::{keymanager, types::keymanager::EncryptionTransferRequest}; let db = state.store.as_ref(); let key = services::generate_aes256_key() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to generate aes 256 key")?; let master_key = db.get_master_key(); let key_manager_state: &KeyManagerState = &(&state).into(); let merchant_id = req.get_merchant_reference_id(); let identifier = km_types::Identifier::Merchant(merchant_id.clone()); #[cfg(feature = "keymanager_create")] { use base64::Engine; use crate::consts::BASE64_ENGINE; if key_manager_state.enabled { keymanager::transfer_key_to_key_manager( key_manager_state, EncryptionTransferRequest { identifier: identifier.clone(), key: BASE64_ENGINE.encode(key), }, ) .await .change_context(errors::ApiErrorResponse::DuplicateMerchantAccount) .attach_printable("Failed to insert key to KeyManager")?; } } let key_store = domain::MerchantKeyStore { merchant_id: merchant_id.clone(), key: domain_types::crypto_operation( key_manager_state, type_name!(domain::MerchantKeyStore), domain_types::CryptoOperation::Encrypt(key.to_vec().into()), identifier.clone(), master_key, ) .await .and_then(|val| val.try_into_operation()) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to decrypt data from key store")?, created_at: date_time::now(), }; let domain_merchant_account = req .create_domain_model_from_request(&state, key_store.clone(), &merchant_id) .await?; let key_manager_state = &(&state).into(); db.insert_merchant_key_store( key_manager_state, key_store.clone(), &master_key.to_vec().into(), ) .await .to_duplicate_response(errors::ApiErrorResponse::DuplicateMerchantAccount)?; let merchant_account = db .insert_merchant(key_manager_state, domain_merchant_account, &key_store) .await .to_duplicate_response(errors::ApiErrorResponse::DuplicateMerchantAccount)?; add_publishable_key_to_decision_service(&state, &merchant_account); insert_merchant_configs(db, &merchant_id).await?; Ok(service_api::ApplicationResponse::Json( api::MerchantAccountResponse::foreign_try_from(merchant_account) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while generating response")?, )) } <file_sep path="hyperswitch/crates/router/src/core/admin.rs" role="context" start="184" end="184"> } #[cfg(all(feature = "v2", feature = "olap"))] { CreateOrValidateOrganization::new(org_id.organization_id) .create_or_validate(state.accounts_store.as_ref()) .await .map(ForeignFrom::foreign_from) .map(service_api::ApplicationResponse::Json) } } #[cfg(feature = "olap")] pub async fn create_merchant_account( state: SessionState, req: api::MerchantAccountCreate, ) -> RouterResponse<api::MerchantAccountResponse> { #[cfg(feature = "keymanager_create")] use common_utils::{keymanager, types::keymanager::EncryptionTransferRequest}; let db = state.store.as_ref(); let key = services::generate_aes256_key() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to generate aes 256 key")?; <file_sep path="hyperswitch/crates/router/src/core/admin.rs" role="context" start="441" end="447"> fn new(organization_id: Option<id_type::OrganizationId>) -> Self { if let Some(organization_id) = organization_id { Self::Validate { organization_id } } else { Self::Create } } <file_sep path="hyperswitch/crates/router/src/core/admin.rs" role="context" start="281" end="421"> async fn create_domain_model_from_request( self, state: &SessionState, key_store: domain::MerchantKeyStore, identifier: &id_type::MerchantId, ) -> RouterResult<domain::MerchantAccount> { let db = &*state.accounts_store; let publishable_key = create_merchant_publishable_key(); let primary_business_details = self.get_primary_details_as_value().change_context( errors::ApiErrorResponse::InvalidDataValue { field_name: "primary_business_details", }, )?; let webhook_details = self.webhook_details.clone().map(ForeignInto::foreign_into); let pm_collect_link_config = self.get_pm_link_config_as_value().change_context( errors::ApiErrorResponse::InvalidDataValue { field_name: "pm_collect_link_config", }, )?; let merchant_details = self.get_merchant_details_as_secret().change_context( errors::ApiErrorResponse::InvalidDataValue { field_name: "merchant_details", }, )?; self.parse_routing_algorithm() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "routing_algorithm", }) .attach_printable("Invalid routing algorithm given")?; let metadata = self.get_metadata_as_secret().change_context( errors::ApiErrorResponse::InvalidDataValue { field_name: "metadata", }, )?; // Get the enable payment response hash as a boolean, where the default value is true let enable_payment_response_hash = self.get_enable_payment_response_hash(); let payment_response_hash_key = self.get_payment_response_hash_key(); let parent_merchant_id = get_parent_merchant( state, self.sub_merchants_enabled, self.parent_merchant_id.as_ref(), &key_store, ) .await?; let organization = CreateOrValidateOrganization::new(self.organization_id) .create_or_validate(db) .await?; let key = key_store.key.clone().into_inner(); let key_manager_state = state.into(); let merchant_account = async { Ok::<_, error_stack::Report<common_utils::errors::CryptoError>>( domain::MerchantAccountSetter { merchant_id: identifier.clone(), merchant_name: self .merchant_name .async_lift(|inner| async { domain_types::crypto_operation( &key_manager_state, type_name!(domain::MerchantAccount), domain_types::CryptoOperation::EncryptOptional(inner), km_types::Identifier::Merchant(key_store.merchant_id.clone()), key.peek(), ) .await .and_then(|val| val.try_into_optionaloperation()) }) .await?, merchant_details: merchant_details .async_lift(|inner| async { domain_types::crypto_operation( &key_manager_state, type_name!(domain::MerchantAccount), domain_types::CryptoOperation::EncryptOptional(inner), km_types::Identifier::Merchant(key_store.merchant_id.clone()), key.peek(), ) .await .and_then(|val| val.try_into_optionaloperation()) }) .await?, return_url: self.return_url.map(|a| a.to_string()), webhook_details, routing_algorithm: Some(serde_json::json!({ "algorithm_id": null, "timestamp": 0 })), sub_merchants_enabled: self.sub_merchants_enabled, parent_merchant_id, enable_payment_response_hash, payment_response_hash_key, redirect_to_merchant_with_http_post: self .redirect_to_merchant_with_http_post .unwrap_or_default(), publishable_key, locker_id: self.locker_id, metadata, storage_scheme: MerchantStorageScheme::PostgresOnly, primary_business_details, created_at: date_time::now(), modified_at: date_time::now(), intent_fulfillment_time: None, frm_routing_algorithm: self.frm_routing_algorithm, #[cfg(feature = "payouts")] payout_routing_algorithm: self.payout_routing_algorithm, #[cfg(not(feature = "payouts"))] payout_routing_algorithm: None, organization_id: organization.get_organization_id(), is_recon_enabled: false, default_profile: None, recon_status: diesel_models::enums::ReconStatus::NotRequested, payment_link_config: None, pm_collect_link_config, version: common_types::consts::API_VERSION, is_platform_account: false, product_type: self.product_type, }, ) } .await .change_context(errors::ApiErrorResponse::InternalServerError)?; let mut domain_merchant_account = domain::MerchantAccount::from(merchant_account); CreateProfile::new(self.primary_business_details.clone()) .create_profiles(state, &mut domain_merchant_account, &key_store) .await?; Ok(domain_merchant_account) } <file_sep path="hyperswitch/crates/router/src/core/admin.rs" role="context" start="162" end="182"> pub async fn get_organization( state: SessionState, org_id: api::OrganizationId, ) -> RouterResponse<api::OrganizationResponse> { #[cfg(all(feature = "v1", feature = "olap"))] { CreateOrValidateOrganization::new(Some(org_id.organization_id)) .create_or_validate(state.accounts_store.as_ref()) .await .map(ForeignFrom::foreign_from) .map(service_api::ApplicationResponse::Json) } #[cfg(all(feature = "v2", feature = "olap"))] { CreateOrValidateOrganization::new(org_id.organization_id) .create_or_validate(state.accounts_store.as_ref()) .await .map(ForeignFrom::foreign_from) .map(service_api::ApplicationResponse::Json) } } <file_sep path="hyperswitch/crates/router/src/core/admin.rs" role="context" start="136" end="159"> pub async fn update_organization( state: SessionState, org_id: api::OrganizationId, req: api::OrganizationUpdateRequest, ) -> RouterResponse<api::OrganizationResponse> { let organization_update = diesel_models::organization::OrganizationUpdate::Update { organization_name: req.organization_name, organization_details: req.organization_details, metadata: req.metadata, }; state .accounts_store .update_organization_by_org_id(&org_id.organization_id, organization_update) .await .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError { message: "organization with the given id does not exist".to_string(), }) .attach_printable(format!( "Failed to update organization with organization_id: {:?}", org_id.organization_id )) .map(ForeignFrom::foreign_from) .map(service_api::ApplicationResponse::Json) } <file_sep path="hyperswitch/crates/router/src/core/admin.rs" role="context" start="95" end="115"> fn add_publishable_key_to_decision_service( state: &SessionState, merchant_account: &domain::MerchantAccount, ) { let state = state.clone(); let publishable_key = merchant_account.publishable_key.clone(); let merchant_id = merchant_account.get_id().clone(); authentication::decision::spawn_tracked_job( async move { authentication::decision::add_publishable_key( &state, publishable_key.into(), merchant_id, None, ) .await }, authentication::decision::ADD, ); } <file_sep path="hyperswitch/crates/router/src/core/admin.rs" role="context" start="71" end="92"> pub async fn insert_merchant_configs( db: &dyn StorageInterface, merchant_id: &id_type::MerchantId, ) -> RouterResult<()> { db.insert_config(configs::ConfigNew { key: merchant_id.get_requires_cvv_key(), config: "true".to_string(), }) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error while setting requires_cvv config")?; db.insert_config(configs::ConfigNew { key: merchant_id.get_merchant_fingerprint_secret_key(), config: utils::generate_id(consts::FINGERPRINT_SECRET_LENGTH, "fs"), }) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error while inserting merchant fingerprint secret")?; Ok(()) } <file_sep path="hyperswitch/crates/router/src/routes/app.rs" role="context" start="104" end="125"> pub struct SessionState { pub store: Box<dyn StorageInterface>, /// Global store is used for global schema operations in tables like Users and Tenants pub global_store: Box<dyn GlobalStorageInterface>, pub accounts_store: Box<dyn AccountsStorageInterface>, pub conf: Arc<settings::Settings<RawSecret>>, pub api_client: Box<dyn crate::services::ApiClient>, pub event_handler: EventsHandler, #[cfg(feature = "email")] pub email_client: Arc<Box<dyn EmailService>>, #[cfg(feature = "olap")] pub pool: AnalyticsProvider, pub file_storage_client: Arc<dyn FileStorageInterface>, pub request_id: Option<RequestId>, pub base_url: String, pub tenant: Tenant, #[cfg(feature = "olap")] pub opensearch_client: Option<Arc<OpenSearchClient>>, pub grpc_client: Arc<GrpcClients>, pub theme_storage_client: Arc<dyn FileStorageInterface>, pub locale: String, } <file_sep path="hyperswitch-card-vault/migrations/2023-10-21-104200_create-tables/up.sql" role="context" start="1" end="11"> -- Your SQL goes here CREATE TABLE merchant ( id SERIAL, tenant_id VARCHAR(255) NOT NULL, merchant_id VARCHAR(255) NOT NULL, enc_key BYTEA NOT NULL, created_at TIMESTAMP NOT NULL DEFAULT now()::TIMESTAMP, PRIMARY KEY (tenant_id, merchant_id) );
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/core/relay.rs<|crate|> router anchor=relay_retrieve kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/core/relay.rs" role="context" start="297" end="392"> pub async fn relay_retrieve( state: SessionState, merchant_account: domain::MerchantAccount, profile_id_optional: Option<id_type::ProfileId>, key_store: domain::MerchantKeyStore, req: relay_api_models::RelayRetrieveRequest, ) -> RouterResponse<relay_api_models::RelayResponse> { let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let merchant_id = merchant_account.get_id(); let relay_id = &req.id; let profile_id_from_auth_layer = profile_id_optional.get_required_value("ProfileId")?; db.find_business_profile_by_merchant_id_profile_id( key_manager_state, &key_store, merchant_id, &profile_id_from_auth_layer, ) .await .change_context(errors::ApiErrorResponse::ProfileNotFound { id: profile_id_from_auth_layer.get_string_repr().to_owned(), })?; let relay_record_result = db .find_relay_by_id(key_manager_state, &key_store, relay_id) .await; let relay_record = match relay_record_result { Err(error) => { if error.current_context().is_db_not_found() { Err(error).change_context(errors::ApiErrorResponse::GenericNotFoundError { message: "relay not found".to_string(), })? } else { Err(error) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("error while fetch relay record")? } } Ok(relay) => relay, }; #[cfg(feature = "v1")] let connector_account = db .find_by_merchant_connector_account_merchant_id_merchant_connector_id( key_manager_state, merchant_id, &relay_record.connector_id, &key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: relay_record.connector_id.get_string_repr().to_string(), })?; #[cfg(feature = "v2")] let connector_account = db .find_merchant_connector_account_by_id( key_manager_state, &relay_record.connector_id, &key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: relay_record.connector_id.get_string_repr().to_string(), })?; let relay_response = match relay_record.relay_type { common_enums::RelayType::Refund => { if should_call_connector_for_relay_refund_status(&relay_record, req.force_sync) { let relay_response = sync_relay_refund_with_gateway( &state, &merchant_account, &relay_record, connector_account, ) .await?; db.update_relay(key_manager_state, &key_store, relay_record, relay_response) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update the relay record")? } else { relay_record } } }; let response = relay_api_models::RelayResponse::from(relay_response); Ok(hyperswitch_domain_models::api::ApplicationResponse::Json( response, )) } <file_sep path="hyperswitch/crates/router/src/core/relay.rs" role="context" start="296" end="296"> use api_models::relay as relay_api_models; use common_enums::RelayStatus; use common_utils::{ self, fp_utils, id_type::{self, GenerateId}, }; use hyperswitch_domain_models::relay; use super::errors::{self, ConnectorErrorExt, RouterResponse, RouterResult, StorageErrorExt}; use crate::{ core::payments, routes::SessionState, services, types::{ api::{self}, domain, }, utils::OptionExt, }; <file_sep path="hyperswitch/crates/router/src/core/relay.rs" role="context" start="400" end="451"> pub async fn sync_relay_refund_with_gateway( state: &SessionState, merchant_account: &domain::MerchantAccount, relay_record: &relay::Relay, connector_account: domain::MerchantConnectorAccount, ) -> RouterResult<relay::RelayUpdate> { let connector_id = &relay_record.connector_id; let merchant_id = merchant_account.get_id(); #[cfg(feature = "v1")] let connector_name = &connector_account.connector_name; #[cfg(feature = "v2")] let connector_name = &connector_account.connector_name.to_string(); let connector_data: api::ConnectorData = api::ConnectorData::get_connector_by_name( &state.conf.connectors, connector_name, api::GetToken::Connector, Some(connector_id.clone()), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get the connector")?; let router_data = utils::construct_relay_refund_router_data( state, merchant_id, &connector_account, relay_record, ) .await?; let connector_integration: services::BoxedRefundConnectorIntegrationInterface< api::RSync, hyperswitch_domain_models::router_request_types::RefundsData, hyperswitch_domain_models::router_response_types::RefundsResponseData, > = connector_data.connector.get_connector_integration(); let router_data_res = services::execute_connector_processing_step( state, connector_integration, &router_data, payments::CallConnectorAction::Trigger, None, ) .await .to_refund_failed_response()?; let relay_response = relay::RelayUpdate::from(router_data_res.response); Ok(relay_response) } <file_sep path="hyperswitch/crates/router/src/core/relay.rs" role="context" start="394" end="398"> fn should_call_connector_for_relay_refund_status(relay: &relay::Relay, force_sync: bool) -> bool { // This allows refund sync at connector level if force_sync is enabled, or // check if the refund is in terminal state !matches!(relay.status, RelayStatus::Failure | RelayStatus::Success) && force_sync } <file_sep path="hyperswitch/crates/router/src/core/relay.rs" role="context" start="222" end="295"> pub async fn relay<T: RelayInterface>( state: SessionState, merchant_account: domain::MerchantAccount, profile_id_optional: Option<id_type::ProfileId>, key_store: domain::MerchantKeyStore, req: RelayRequestInner<T>, ) -> RouterResponse<relay_api_models::RelayResponse> { let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let merchant_id = merchant_account.get_id(); let connector_id = &req.connector_id; let profile_id_from_auth_layer = profile_id_optional.get_required_value("ProfileId")?; let profile = db .find_business_profile_by_merchant_id_profile_id( key_manager_state, &key_store, merchant_id, &profile_id_from_auth_layer, ) .await .change_context(errors::ApiErrorResponse::ProfileNotFound { id: profile_id_from_auth_layer.get_string_repr().to_owned(), })?; #[cfg(feature = "v1")] let connector_account = db .find_by_merchant_connector_account_merchant_id_merchant_connector_id( key_manager_state, merchant_id, connector_id, &key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: connector_id.get_string_repr().to_string(), })?; #[cfg(feature = "v2")] let connector_account = db .find_merchant_connector_account_by_id(key_manager_state, connector_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: connector_id.get_string_repr().to_string(), })?; T::validate_relay_request(&req.data)?; let relay_domain = T::get_domain_models(req, merchant_id, profile.get_id()); let relay_record = db .insert_relay(key_manager_state, &key_store, relay_domain) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to insert a relay record in db")?; let relay_response = T::process_relay(&state, merchant_account, connector_account, &relay_record) .await .attach_printable("Failed to process relay")?; let relay_update_record = db .update_relay(key_manager_state, &key_store, relay_record, relay_response) .await .change_context(errors::ApiErrorResponse::InternalServerError)?; let response = T::generate_response(relay_update_record) .attach_printable("Failed to generate relay response")?; Ok(hyperswitch_domain_models::api::ApplicationResponse::Json( response, )) } <file_sep path="hyperswitch/crates/router/src/core/relay.rs" role="context" start="200" end="220"> pub async fn relay_flow_decider( state: SessionState, merchant_account: domain::MerchantAccount, profile_id_optional: Option<id_type::ProfileId>, key_store: domain::MerchantKeyStore, request: relay_api_models::RelayRequest, ) -> RouterResponse<relay_api_models::RelayResponse> { let relay_flow_request = match request.relay_type { common_enums::RelayType::Refund => { RelayRequestInner::<RelayRefund>::from_relay_request(request)? } }; relay( state, merchant_account, profile_id_optional, key_store, relay_flow_request, ) .await } <file_sep path="hyperswitch/v2_compatible_migrations/2024-08-28-081721_add_v2_columns/up.sql" role="context" start="59" end="70"> ALTER TABLE merchant_connector_account ADD COLUMN IF NOT EXISTS feature_metadata JSONB; ALTER TABLE payment_methods ADD COLUMN IF NOT EXISTS locker_fingerprint_id VARCHAR(64), ADD COLUMN IF NOT EXISTS payment_method_type_v2 VARCHAR(64), ADD COLUMN IF NOT EXISTS payment_method_subtype VARCHAR(64); ALTER TABLE refund ADD COLUMN IF NOT EXISTS id VARCHAR(64), ADD COLUMN IF NOT EXISTS merchant_reference_id VARCHAR(64), ADD COLUMN IF NOT EXISTS connector_id VARCHAR(64);
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payments/types.rs<|crate|> router anchor=get_surcharge_metadata_redis_key kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/core/payments/types.rs" role="context" start="271" end="273"> pub fn get_surcharge_metadata_redis_key(payment_attempt_id: &str) -> String { format!("surcharge_metadata_{}", payment_attempt_id) } <file_sep path="hyperswitch/crates/router/src/core/payments/types.rs" role="context" start="270" end="270"> pub use hyperswitch_domain_models::router_request_types::{ AuthenticationData, SplitRefundsRequest, StripeSplitRefund, SurchargeDetails, }; <file_sep path="hyperswitch/crates/router/src/core/payments/types.rs" role="context" start="283" end="299"> pub fn get_surcharge_details_redis_hashset_key(surcharge_key: &SurchargeKey) -> String { match surcharge_key { SurchargeKey::Token(token) => { format!("token_{}", token) } SurchargeKey::PaymentMethodData(payment_method, payment_method_type, card_network) => { if let Some(card_network) = card_network { format!( "{}_{}_{}", payment_method, payment_method_type, card_network ) } else { format!("{}_{}", payment_method, payment_method_type) } } } } <file_sep path="hyperswitch/crates/router/src/core/payments/types.rs" role="context" start="274" end="282"> pub fn get_individual_surcharge_key_value_pairs(&self) -> Vec<(String, SurchargeDetails)> { self.surcharge_results .iter() .map(|(surcharge_key, surcharge_details)| { let key = Self::get_surcharge_details_redis_hashset_key(surcharge_key); (key, surcharge_details.to_owned()) }) .collect() } <file_sep path="hyperswitch/crates/router/src/core/payments/types.rs" role="context" start="268" end="270"> pub fn get_surcharge_details(&self, surcharge_key: SurchargeKey) -> Option<&SurchargeDetails> { self.surcharge_results.get(&surcharge_key) } <file_sep path="hyperswitch/crates/router/src/core/payments/types.rs" role="context" start="260" end="267"> pub fn insert_surcharge_details( &mut self, surcharge_key: SurchargeKey, surcharge_details: SurchargeDetails, ) { self.surcharge_results .insert(surcharge_key, surcharge_details); } <file_sep path="hyperswitch/crates/router/src/core/payments/types.rs" role="context" start="301" end="339"> pub async fn persist_individual_surcharge_details_in_redis( &self, state: &SessionState, business_profile: &Profile, ) -> RouterResult<()> { if !self.is_empty_result() { let redis_conn = state .store .get_redis_conn() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get redis connection")?; let redis_key = Self::get_surcharge_metadata_redis_key(&self.payment_attempt_id); let mut value_list = Vec::with_capacity(self.get_surcharge_results_size()); for (key, value) in self.get_individual_surcharge_key_value_pairs().into_iter() { value_list.push(( key, value .encode_to_string_of_json() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to encode to string of json")?, )); } let intent_fulfillment_time = business_profile .get_order_fulfillment_time() .unwrap_or(router_consts::DEFAULT_FULFILLMENT_TIME); redis_conn .set_hash_fields( &redis_key.as_str().into(), value_list, Some(intent_fulfillment_time), ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to write to redis")?; logger::debug!("Surcharge results stored in redis with key = {}", redis_key); } Ok(()) } <file_sep path="hyperswitch/crates/router/src/core/payments/types.rs" role="context" start="342" end="366"> pub async fn get_individual_surcharge_detail_from_redis( state: &SessionState, surcharge_key: SurchargeKey, payment_attempt_id: &str, ) -> CustomResult<SurchargeDetails, RedisError> { let redis_conn = state .store .get_redis_conn() .attach_printable("Failed to get redis connection")?; let redis_key = Self::get_surcharge_metadata_redis_key(payment_attempt_id); let value_key = Self::get_surcharge_details_redis_hashset_key(&surcharge_key); let result = redis_conn .get_hash_field_and_deserialize( &redis_key.as_str().into(), &value_key, "SurchargeDetails", ) .await; logger::debug!( "Surcharge result fetched from redis with key = {} and {}", redis_key, value_key ); result } <file_sep path="hyperswitch/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/event.test.js" role="context" start="61" end="78"> "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.", ); } // Response body should have value "succeeded" for "status" if (jsonData?.status) { pm.test( "[POST]::/payments - Content check if value for 'status' matches 'succeeded'", function () { pm.expect(jsonData.status).to.eql("succeeded"); }, ); }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/core/admin.rs<|crate|> router anchor=create_merchant_publishable_key kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/src/core/admin.rs" role="context" start="63" end="69"> pub fn create_merchant_publishable_key() -> String { format!( "pk_{}_{}", router_env::env::prefix_for_env(), Uuid::new_v4().simple() ) } <file_sep path="hyperswitch/crates/router/src/core/admin.rs" role="context" start="62" end="62"> use uuid::Uuid; <file_sep path="hyperswitch/crates/router/src/core/admin.rs" role="context" start="95" end="115"> fn add_publishable_key_to_decision_service( state: &SessionState, merchant_account: &domain::MerchantAccount, ) { let state = state.clone(); let publishable_key = merchant_account.publishable_key.clone(); let merchant_id = merchant_account.get_id().clone(); authentication::decision::spawn_tracked_job( async move { authentication::decision::add_publishable_key( &state, publishable_key.into(), merchant_id, None, ) .await }, authentication::decision::ADD, ); } <file_sep path="hyperswitch/crates/router/src/core/admin.rs" role="context" start="71" end="92"> pub async fn insert_merchant_configs( db: &dyn StorageInterface, merchant_id: &id_type::MerchantId, ) -> RouterResult<()> { db.insert_config(configs::ConfigNew { key: merchant_id.get_requires_cvv_key(), config: "true".to_string(), }) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error while setting requires_cvv config")?; db.insert_config(configs::ConfigNew { key: merchant_id.get_merchant_fingerprint_secret_key(), config: utils::generate_id(consts::FINGERPRINT_SECRET_LENGTH, "fs"), }) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error while inserting merchant fingerprint secret")?; Ok(()) } <file_sep path="hyperswitch/crates/router/src/core/admin.rs" role="context" start="607" end="684"> async fn create_domain_model_from_request( self, state: &SessionState, key_store: domain::MerchantKeyStore, identifier: &id_type::MerchantId, ) -> RouterResult<domain::MerchantAccount> { let publishable_key = create_merchant_publishable_key(); let db = &*state.accounts_store; let metadata = self.get_metadata_as_secret().change_context( errors::ApiErrorResponse::InvalidDataValue { field_name: "metadata", }, )?; let merchant_details = self.get_merchant_details_as_secret().change_context( errors::ApiErrorResponse::InvalidDataValue { field_name: "merchant_details", }, )?; let organization = CreateOrValidateOrganization::new(self.organization_id.clone()) .create_or_validate(db) .await?; let key = key_store.key.into_inner(); let id = identifier.to_owned(); let key_manager_state = state.into(); let identifier = km_types::Identifier::Merchant(id.clone()); async { Ok::<_, error_stack::Report<common_utils::errors::CryptoError>>( domain::MerchantAccount::from(domain::MerchantAccountSetter { id, merchant_name: Some( domain_types::crypto_operation( &key_manager_state, type_name!(domain::MerchantAccount), domain_types::CryptoOperation::Encrypt( self.merchant_name .map(|merchant_name| merchant_name.into_inner()), ), identifier.clone(), key.peek(), ) .await .and_then(|val| val.try_into_operation())?, ), merchant_details: merchant_details .async_lift(|inner| async { domain_types::crypto_operation( &key_manager_state, type_name!(domain::MerchantAccount), domain_types::CryptoOperation::EncryptOptional(inner), identifier.clone(), key.peek(), ) .await .and_then(|val| val.try_into_optionaloperation()) }) .await?, publishable_key, metadata, storage_scheme: MerchantStorageScheme::PostgresOnly, created_at: date_time::now(), modified_at: date_time::now(), organization_id: organization.get_organization_id(), recon_status: diesel_models::enums::ReconStatus::NotRequested, is_platform_account: false, version: common_types::consts::API_VERSION, product_type: self.product_type, }), ) } .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed to encrypt merchant details") } <file_sep path="hyperswitch/crates/router/src/core/admin.rs" role="context" start="281" end="421"> async fn create_domain_model_from_request( self, state: &SessionState, key_store: domain::MerchantKeyStore, identifier: &id_type::MerchantId, ) -> RouterResult<domain::MerchantAccount> { let db = &*state.accounts_store; let publishable_key = create_merchant_publishable_key(); let primary_business_details = self.get_primary_details_as_value().change_context( errors::ApiErrorResponse::InvalidDataValue { field_name: "primary_business_details", }, )?; let webhook_details = self.webhook_details.clone().map(ForeignInto::foreign_into); let pm_collect_link_config = self.get_pm_link_config_as_value().change_context( errors::ApiErrorResponse::InvalidDataValue { field_name: "pm_collect_link_config", }, )?; let merchant_details = self.get_merchant_details_as_secret().change_context( errors::ApiErrorResponse::InvalidDataValue { field_name: "merchant_details", }, )?; self.parse_routing_algorithm() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "routing_algorithm", }) .attach_printable("Invalid routing algorithm given")?; let metadata = self.get_metadata_as_secret().change_context( errors::ApiErrorResponse::InvalidDataValue { field_name: "metadata", }, )?; // Get the enable payment response hash as a boolean, where the default value is true let enable_payment_response_hash = self.get_enable_payment_response_hash(); let payment_response_hash_key = self.get_payment_response_hash_key(); let parent_merchant_id = get_parent_merchant( state, self.sub_merchants_enabled, self.parent_merchant_id.as_ref(), &key_store, ) .await?; let organization = CreateOrValidateOrganization::new(self.organization_id) .create_or_validate(db) .await?; let key = key_store.key.clone().into_inner(); let key_manager_state = state.into(); let merchant_account = async { Ok::<_, error_stack::Report<common_utils::errors::CryptoError>>( domain::MerchantAccountSetter { merchant_id: identifier.clone(), merchant_name: self .merchant_name .async_lift(|inner| async { domain_types::crypto_operation( &key_manager_state, type_name!(domain::MerchantAccount), domain_types::CryptoOperation::EncryptOptional(inner), km_types::Identifier::Merchant(key_store.merchant_id.clone()), key.peek(), ) .await .and_then(|val| val.try_into_optionaloperation()) }) .await?, merchant_details: merchant_details .async_lift(|inner| async { domain_types::crypto_operation( &key_manager_state, type_name!(domain::MerchantAccount), domain_types::CryptoOperation::EncryptOptional(inner), km_types::Identifier::Merchant(key_store.merchant_id.clone()), key.peek(), ) .await .and_then(|val| val.try_into_optionaloperation()) }) .await?, return_url: self.return_url.map(|a| a.to_string()), webhook_details, routing_algorithm: Some(serde_json::json!({ "algorithm_id": null, "timestamp": 0 })), sub_merchants_enabled: self.sub_merchants_enabled, parent_merchant_id, enable_payment_response_hash, payment_response_hash_key, redirect_to_merchant_with_http_post: self .redirect_to_merchant_with_http_post .unwrap_or_default(), publishable_key, locker_id: self.locker_id, metadata, storage_scheme: MerchantStorageScheme::PostgresOnly, primary_business_details, created_at: date_time::now(), modified_at: date_time::now(), intent_fulfillment_time: None, frm_routing_algorithm: self.frm_routing_algorithm, #[cfg(feature = "payouts")] payout_routing_algorithm: self.payout_routing_algorithm, #[cfg(not(feature = "payouts"))] payout_routing_algorithm: None, organization_id: organization.get_organization_id(), is_recon_enabled: false, default_profile: None, recon_status: diesel_models::enums::ReconStatus::NotRequested, payment_link_config: None, pm_collect_link_config, version: common_types::consts::API_VERSION, is_platform_account: false, product_type: self.product_type, }, ) } .await .change_context(errors::ApiErrorResponse::InternalServerError)?; let mut domain_merchant_account = domain::MerchantAccount::from(merchant_account); CreateProfile::new(self.primary_business_details.clone()) .create_profiles(state, &mut domain_merchant_account, &key_store) .await?; Ok(domain_merchant_account) }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/core/webhooks/outgoing.rs<|crate|> router anchor=increment_webhook_outgoing_received_count kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/core/webhooks/outgoing.rs" role="context" start="895" end="900"> fn increment_webhook_outgoing_received_count(merchant_id: &common_utils::id_type::MerchantId) { metrics::WEBHOOK_OUTGOING_RECEIVED_COUNT.add( 1, router_env::metric_attributes!((MERCHANT_ID, merchant_id.clone())), ) } <file_sep path="hyperswitch/crates/router/src/core/webhooks/outgoing.rs" role="context" start="894" end="894"> use common_utils::{ ext_traits::{Encode, StringExt}, request::RequestContent, type_name, types::keymanager::{Identifier, KeyManagerState}, }; use router_env::{ instrument, tracing::{self, Instrument}, }; use super::{types, utils, MERCHANT_ID}; use crate::{ core::{ errors::{self, CustomResult}, metrics, }, db::StorageInterface, events::outgoing_webhook_logs::{ OutgoingWebhookEvent, OutgoingWebhookEventContent, OutgoingWebhookEventMetric, }, logger, routes::{app::SessionStateInfo, SessionState}, services, types::{ api, domain::{self}, storage::{self, enums}, transformers::ForeignFrom, }, utils::{OptionExt, ValueExt}, workflows::outgoing_webhook_retry, }; <file_sep path="hyperswitch/crates/router/src/core/webhooks/outgoing.rs" role="context" start="923" end="951"> async fn error_response_handler( state: SessionState, merchant_id: &common_utils::id_type::MerchantId, delivery_attempt: enums::WebhookDeliveryAttempt, status_code: u16, log_message: &'static str, schedule_webhook_retry: ScheduleWebhookRetry, ) -> CustomResult<(), errors::WebhooksFlowError> { metrics::WEBHOOK_OUTGOING_NOT_RECEIVED_COUNT.add( 1, router_env::metric_attributes!((MERCHANT_ID, merchant_id.clone())), ); let error = report!(errors::WebhooksFlowError::NotReceivedByMerchant); logger::warn!(?error, ?delivery_attempt, status_code, %log_message); if let ScheduleWebhookRetry::WithProcessTracker(process_tracker) = schedule_webhook_retry { // Schedule a retry attempt for webhook delivery outgoing_webhook_retry::retry_webhook_delivery_task( &*state.store, merchant_id, *process_tracker, ) .await .change_context(errors::WebhooksFlowError::OutgoingWebhookRetrySchedulingFailed)?; } Err(error) } <file_sep path="hyperswitch/crates/router/src/core/webhooks/outgoing.rs" role="context" start="902" end="921"> async fn success_response_handler( state: SessionState, merchant_id: &common_utils::id_type::MerchantId, process_tracker: Option<storage::ProcessTracker>, business_status: &'static str, ) -> CustomResult<(), errors::WebhooksFlowError> { increment_webhook_outgoing_received_count(merchant_id); match process_tracker { Some(process_tracker) => state .store .as_scheduler() .finish_process_with_business_status(process_tracker, business_status) .await .change_context( errors::WebhooksFlowError::OutgoingWebhookProcessTrackerTaskUpdateFailed, ), None => Ok(()), } } <file_sep path="hyperswitch/crates/router/src/core/webhooks/outgoing.rs" role="context" start="857" end="893"> async fn update_overall_delivery_status_in_storage( state: SessionState, merchant_key_store: domain::MerchantKeyStore, merchant_id: &common_utils::id_type::MerchantId, updated_event: domain::Event, ) -> CustomResult<(), errors::WebhooksFlowError> { let key_manager_state = &(&state).into(); let update_overall_delivery_status = domain::EventUpdate::OverallDeliveryStatusUpdate { is_overall_delivery_successful: true, }; let initial_attempt_id = updated_event.initial_attempt_id.as_ref(); let delivery_attempt = updated_event.delivery_attempt; if let Some(( initial_attempt_id, enums::WebhookDeliveryAttempt::InitialAttempt | enums::WebhookDeliveryAttempt::AutomaticRetry, )) = initial_attempt_id.zip(delivery_attempt) { state .store .update_event_by_merchant_id_event_id( key_manager_state, merchant_id, initial_attempt_id.as_str(), update_overall_delivery_status, &merchant_key_store, ) .await .change_context(errors::WebhooksFlowError::WebhookEventUpdationFailed) .attach_printable("Failed to update initial delivery attempt")?; } Ok(()) } <file_sep path="hyperswitch/crates/router/src/core/webhooks/outgoing.rs" role="context" start="777" end="855"> async fn update_event_in_storage( state: SessionState, merchant_key_store: domain::MerchantKeyStore, merchant_id: &common_utils::id_type::MerchantId, event_id: &str, response: reqwest::Response, ) -> CustomResult<domain::Event, errors::WebhooksFlowError> { let status_code = response.status(); let is_webhook_notified = status_code.is_success(); let key_manager_state = &(&state).into(); let response_headers = response .headers() .iter() .map(|(name, value)| { ( name.as_str().to_owned(), value .to_str() .map(|s| Secret::from(String::from(s))) .unwrap_or_else(|error| { logger::warn!( "Response header {} contains non-UTF-8 characters: {error:?}", name.as_str() ); Secret::from(String::from("Non-UTF-8 header value")) }), ) }) .collect::<Vec<_>>(); let response_body = response .text() .await .map(Secret::from) .unwrap_or_else(|error| { logger::warn!("Response contains non-UTF-8 characters: {error:?}"); Secret::from(String::from("Non-UTF-8 response body")) }); let response_to_store = OutgoingWebhookResponseContent { body: Some(response_body), headers: Some(response_headers), status_code: Some(status_code.as_u16()), error_message: None, }; let event_update = domain::EventUpdate::UpdateResponse { is_webhook_notified, response: Some( crypto_operation( key_manager_state, type_name!(domain::Event), CryptoOperation::Encrypt( response_to_store .encode_to_string_of_json() .change_context( errors::WebhooksFlowError::OutgoingWebhookResponseEncodingFailed, ) .map(Secret::new)?, ), Identifier::Merchant(merchant_key_store.merchant_id.clone()), merchant_key_store.key.get_inner().peek(), ) .await .and_then(|val| val.try_into_operation()) .change_context(errors::WebhooksFlowError::WebhookEventUpdationFailed) .attach_printable("Failed to encrypt outgoing webhook response content")?, ), }; state .store .update_event_by_merchant_id_event_id( key_manager_state, merchant_id, event_id, event_update, &merchant_key_store, ) .await .change_context(errors::WebhooksFlowError::WebhookEventUpdationFailed) } <file_sep path="hyperswitch/crates/router/src/core/webhooks/outgoing.rs" role="context" start="238" end="455"> async fn trigger_webhook_to_merchant( state: SessionState, business_profile: domain::Profile, merchant_key_store: &domain::MerchantKeyStore, event: domain::Event, request_content: OutgoingWebhookRequestContent, delivery_attempt: enums::WebhookDeliveryAttempt, process_tracker: Option<storage::ProcessTracker>, ) -> CustomResult<(), errors::WebhooksFlowError> { let webhook_url = match ( get_webhook_url_from_business_profile(&business_profile), process_tracker.clone(), ) { (Ok(webhook_url), _) => Ok(webhook_url), (Err(error), Some(process_tracker)) => { if !error .current_context() .is_webhook_delivery_retryable_error() { logger::debug!("Failed to obtain merchant webhook URL, aborting retries"); state .store .as_scheduler() .finish_process_with_business_status(process_tracker, business_status::FAILURE) .await .change_context( errors::WebhooksFlowError::OutgoingWebhookProcessTrackerTaskUpdateFailed, )?; } Err(error) } (Err(error), None) => Err(error), }?; let event_id = event.event_id; let headers = request_content .headers .into_iter() .map(|(name, value)| (name, value.into_masked())) .collect(); let request = services::RequestBuilder::new() .method(services::Method::Post) .url(&webhook_url) .attach_default_headers() .headers(headers) .set_body(RequestContent::RawBytes( request_content.body.expose().into_bytes(), )) .build(); let response = state .api_client .send_request(&state, request, Some(OUTGOING_WEBHOOK_TIMEOUT_SECS), false) .await; metrics::WEBHOOK_OUTGOING_COUNT.add( 1, router_env::metric_attributes!((MERCHANT_ID, business_profile.merchant_id.clone())), ); logger::debug!(outgoing_webhook_response=?response); match delivery_attempt { enums::WebhookDeliveryAttempt::InitialAttempt => match response { Err(client_error) => { api_client_error_handler( state.clone(), merchant_key_store.clone(), &business_profile.merchant_id, &event_id, client_error, delivery_attempt, ScheduleWebhookRetry::NoSchedule, ) .await? } Ok(response) => { let status_code = response.status(); let updated_event = update_event_in_storage( state.clone(), merchant_key_store.clone(), &business_profile.merchant_id, &event_id, response, ) .await?; if status_code.is_success() { update_overall_delivery_status_in_storage( state.clone(), merchant_key_store.clone(), &business_profile.merchant_id, updated_event, ) .await?; success_response_handler( state.clone(), &business_profile.merchant_id, process_tracker, business_status::INITIAL_DELIVERY_ATTEMPT_SUCCESSFUL, ) .await?; } else { error_response_handler( state.clone(), &business_profile.merchant_id, delivery_attempt, status_code.as_u16(), "Ignoring error when sending webhook to merchant", ScheduleWebhookRetry::NoSchedule, ) .await?; } } }, enums::WebhookDeliveryAttempt::AutomaticRetry => { let process_tracker = process_tracker .get_required_value("process_tracker") .change_context(errors::WebhooksFlowError::OutgoingWebhookRetrySchedulingFailed) .attach_printable("`process_tracker` is unavailable in automatic retry flow")?; match response { Err(client_error) => { api_client_error_handler( state.clone(), merchant_key_store.clone(), &business_profile.merchant_id, &event_id, client_error, delivery_attempt, ScheduleWebhookRetry::WithProcessTracker(Box::new(process_tracker)), ) .await?; } Ok(response) => { let status_code = response.status(); let updated_event = update_event_in_storage( state.clone(), merchant_key_store.clone(), &business_profile.merchant_id, &event_id, response, ) .await?; if status_code.is_success() { update_overall_delivery_status_in_storage( state.clone(), merchant_key_store.clone(), &business_profile.merchant_id, updated_event, ) .await?; success_response_handler( state.clone(), &business_profile.merchant_id, Some(process_tracker), "COMPLETED_BY_PT", ) .await?; } else { error_response_handler( state.clone(), &business_profile.merchant_id, delivery_attempt, status_code.as_u16(), "An error occurred when sending webhook to merchant", ScheduleWebhookRetry::WithProcessTracker(Box::new(process_tracker)), ) .await?; } } } } enums::WebhookDeliveryAttempt::ManualRetry => match response { Err(client_error) => { api_client_error_handler( state.clone(), merchant_key_store.clone(), &business_profile.merchant_id, &event_id, client_error, delivery_attempt, ScheduleWebhookRetry::NoSchedule, ) .await? } Ok(response) => { let status_code = response.status(); let _updated_event = update_event_in_storage( state.clone(), merchant_key_store.clone(), &business_profile.merchant_id, &event_id, response, ) .await?; if status_code.is_success() { increment_webhook_outgoing_received_count(&business_profile.merchant_id); } else { error_response_handler( state, &business_profile.merchant_id, delivery_attempt, status_code.as_u16(), "Ignoring error when sending webhook to merchant", ScheduleWebhookRetry::NoSchedule, ) .await?; } } }, } Ok(()) } <file_sep path="hyperswitch/crates/router/tests/utils.rs" role="context" start="389" end="391"> pub struct MerchantId { merchant_id: common_utils::id_type::MerchantId, } <file_sep path="hyperswitch/crates/api_models/src/admin.rs" role="context" start="698" end="700"> pub struct MerchantId { pub merchant_id: id_type::MerchantId, }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/core/utils.rs<|crate|> router anchor=invalid_id_format_error kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/core/utils.rs" role="context" start="461" end="469"> fn invalid_id_format_error(key: &str) -> errors::ApiErrorResponse { errors::ApiErrorResponse::InvalidDataFormat { field_name: key.to_string(), expected_format: format!( "length should be less than {} characters", consts::MAX_ID_LENGTH ), } } <file_sep path="hyperswitch/crates/router/src/core/utils.rs" role="context" start="460" end="460"> use std::{collections::HashSet, marker::PhantomData, str::FromStr}; use common_utils::{ errors::CustomResult, ext_traits::AsyncExt, types::{keymanager::KeyManagerState, ConnectorTransactionIdTrait, MinorUnit}, }; use crate::{ configs::Settings, consts, core::{ errors::{self, RouterResult, StorageErrorExt}, payments::PaymentData, }, db::StorageInterface, routes::SessionState, types::{ self, api, domain, storage::{self, enums}, PollConfig, }, utils::{generate_id, generate_uuid, OptionExt, ValueExt}, }; <file_sep path="hyperswitch/crates/router/src/core/utils.rs" role="context" start="479" end="484"> pub fn validate_uuid(uuid: String, key: &str) -> Result<String, errors::ApiErrorResponse> { match (Uuid::parse_str(&uuid), uuid.len() > consts::MAX_ID_LENGTH) { (Ok(_), false) => Ok(uuid), (_, _) => Err(invalid_id_format_error(key)), } } <file_sep path="hyperswitch/crates/router/src/core/utils.rs" role="context" start="471" end="477"> pub fn validate_id(id: String, key: &str) -> Result<String, errors::ApiErrorResponse> { if id.len() > consts::MAX_ID_LENGTH { Err(invalid_id_format_error(key)) } else { Ok(id) } } <file_sep path="hyperswitch/crates/router/src/core/utils.rs" role="context" start="451" end="459"> pub fn get_or_generate_uuid( key: &str, provided_id: Option<&String>, ) -> Result<String, errors::ApiErrorResponse> { let validate_id = |id: String| validate_uuid(id, key); provided_id .cloned() .map_or(Ok(generate_uuid()), validate_id) } <file_sep path="hyperswitch/crates/router/src/core/utils.rs" role="context" start="440" end="449"> pub fn get_or_generate_id( key: &str, provided_id: &Option<String>, prefix: &str, ) -> Result<String, errors::ApiErrorResponse> { let validate_id = |id| validate_id(id, key); provided_id .clone() .map_or(Ok(generate_id(consts::ID_LENGTH, prefix)), validate_id) } <file_sep path="hyperswitch/crates/api_models/src/errors/types.rs" role="context" start="86" end="100"> pub enum ApiErrorResponse { Unauthorized(ApiError), ForbiddenCommonResource(ApiError), ForbiddenPrivateResource(ApiError), Conflict(ApiError), Gone(ApiError), Unprocessable(ApiError), InternalServerError(ApiError), NotImplemented(ApiError), ConnectorError(ApiError, #[serde(skip_serializing)] StatusCode), NotFound(ApiError), MethodNotAllowed(ApiError), BadRequest(ApiError), DomainError(ApiError), }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/core/utils.rs<|crate|> router anchor=invalid_id_format_error kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/src/core/utils.rs" role="context" start="461" end="469"> fn invalid_id_format_error(key: &str) -> errors::ApiErrorResponse { errors::ApiErrorResponse::InvalidDataFormat { field_name: key.to_string(), expected_format: format!( "length should be less than {} characters", consts::MAX_ID_LENGTH ), } } <file_sep path="hyperswitch/crates/router/src/core/utils.rs" role="context" start="460" end="460"> use std::{collections::HashSet, marker::PhantomData, str::FromStr}; use common_utils::{ errors::CustomResult, ext_traits::AsyncExt, types::{keymanager::KeyManagerState, ConnectorTransactionIdTrait, MinorUnit}, }; use crate::{ configs::Settings, consts, core::{ errors::{self, RouterResult, StorageErrorExt}, payments::PaymentData, }, db::StorageInterface, routes::SessionState, types::{ self, api, domain, storage::{self, enums}, PollConfig, }, utils::{generate_id, generate_uuid, OptionExt, ValueExt}, }; <file_sep path="hyperswitch/crates/router/src/core/utils.rs" role="context" start="479" end="484"> pub fn validate_uuid(uuid: String, key: &str) -> Result<String, errors::ApiErrorResponse> { match (Uuid::parse_str(&uuid), uuid.len() > consts::MAX_ID_LENGTH) { (Ok(_), false) => Ok(uuid), (_, _) => Err(invalid_id_format_error(key)), } } <file_sep path="hyperswitch/crates/router/src/core/utils.rs" role="context" start="471" end="477"> pub fn validate_id(id: String, key: &str) -> Result<String, errors::ApiErrorResponse> { if id.len() > consts::MAX_ID_LENGTH { Err(invalid_id_format_error(key)) } else { Ok(id) } } <file_sep path="hyperswitch/crates/router/src/core/utils.rs" role="context" start="451" end="459"> pub fn get_or_generate_uuid( key: &str, provided_id: Option<&String>, ) -> Result<String, errors::ApiErrorResponse> { let validate_id = |id: String| validate_uuid(id, key); provided_id .cloned() .map_or(Ok(generate_uuid()), validate_id) } <file_sep path="hyperswitch/crates/router/src/core/utils.rs" role="context" start="440" end="449"> pub fn get_or_generate_id( key: &str, provided_id: &Option<String>, prefix: &str, ) -> Result<String, errors::ApiErrorResponse> { let validate_id = |id| validate_id(id, key); provided_id .clone() .map_or(Ok(generate_id(consts::ID_LENGTH, prefix)), validate_id) }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payment_methods/cards.rs<|crate|> router anchor=store_default_payment_method kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="269" end="278"> 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>, ) { todo!() } <file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="268" end="268"> created: Some(common_utils::date_time::now()), recurring_enabled: false, //[#219] installment_payment_enabled: false, //[#219] payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), last_used_at: Some(common_utils::date_time::now()), client_secret: None, }; (payment_method_response, None) } #[cfg(all(feature = "v2", 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>, ) { todo!() } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") <file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="366" end="375"> 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> { todo!() } <file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="284" end="362"> 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 = { let existing_pm_by_pmid = db .find_payment_method( key_manager_state, key_store, &payment_method_id, merchant_account.storage_scheme, ) .await; if let Err(err) = existing_pm_by_pmid { if err.current_context().is_db_not_found() { locker_id = Some(payment_method_id.clone()); let existing_pm_by_locker_id = db .find_payment_method_by_locker_id( key_manager_state, key_store, &payment_method_id, merchant_account.storage_scheme, ) .await; match &existing_pm_by_locker_id { Ok(pm) => payment_method_id.clone_from(pm.get_id()), Err(_) => payment_method_id = generate_id(consts::ID_LENGTH, "pm"), }; existing_pm_by_locker_id } else { Err(err) } } else { existing_pm_by_pmid } }; payment_method_id.clone_into(&mut resp.payment_method_id); match payment_method { Ok(pm) => Ok(pm), Err(err) => { if err.current_context().is_db_not_found() { insert_payment_method( state, resp, &req, key_store, merchant_account.get_id(), customer_id, resp.metadata.clone().map(|val| val.expose()), None, locker_id, None, req.network_transaction_id.clone(), merchant_account.storage_scheme, None, None, None, None, ) .await } else { Err(err) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error while finding payment method") } } } } <file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="238" end="266"> 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, payment_method: req.payment_method, payment_method_type: req.payment_method_type, #[cfg(feature = "payouts")] bank_transfer: None, card: None, metadata: req.metadata.clone(), created: Some(common_utils::date_time::now()), recurring_enabled: false, //[#219] installment_payment_enabled: false, //[#219] payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), last_used_at: Some(common_utils::date_time::now()), client_secret: None, }; (payment_method_response, None) } <file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="133" end="232"> pub async fn create_payment_method( state: &routes::SessionState, req: &api::PaymentMethodCreate, customer_id: &id_type::CustomerId, payment_method_id: &str, locker_id: Option<String>, merchant_id: &id_type::MerchantId, pm_metadata: Option<serde_json::Value>, customer_acceptance: Option<serde_json::Value>, payment_method_data: crypto::OptionalEncryptableValue, key_store: &domain::MerchantKeyStore, connector_mandate_details: Option<serde_json::Value>, status: Option<enums::PaymentMethodStatus>, network_transaction_id: Option<String>, storage_scheme: MerchantStorageScheme, payment_method_billing_address: crypto::OptionalEncryptableValue, card_scheme: Option<String>, network_token_requestor_reference_id: Option<String>, network_token_locker_id: Option<String>, network_token_payment_method_data: crypto::OptionalEncryptableValue, ) -> errors::CustomResult<domain::PaymentMethod, errors::ApiErrorResponse> { let db = &*state.store; let customer = db .find_customer_by_customer_id_merchant_id( &state.into(), customer_id, merchant_id, key_store, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?; let client_secret = generate_id( consts::ID_LENGTH, format!("{payment_method_id}_secret").as_str(), ); let current_time = common_utils::date_time::now(); let response = db .insert_payment_method( &state.into(), key_store, domain::PaymentMethod { customer_id: customer_id.to_owned(), merchant_id: merchant_id.to_owned(), payment_method_id: payment_method_id.to_string(), locker_id, payment_method: req.payment_method, payment_method_type: req.payment_method_type, payment_method_issuer: req.payment_method_issuer.clone(), scheme: req.card_network.clone().or(card_scheme), metadata: pm_metadata.map(Secret::new), payment_method_data, connector_mandate_details, customer_acceptance: customer_acceptance.map(Secret::new), client_secret: Some(client_secret), status: status.unwrap_or(enums::PaymentMethodStatus::Active), network_transaction_id: network_transaction_id.to_owned(), payment_method_issuer_code: None, accepted_currency: None, token: None, cardholder_name: None, issuer_name: None, issuer_country: None, payer_country: None, is_stored: None, swift_code: None, direct_debit_token: None, created_at: current_time, last_modified: current_time, last_used_at: current_time, payment_method_billing_address, updated_by: None, version: common_types::consts::API_VERSION, network_token_requestor_reference_id, network_token_locker_id, network_token_payment_method_data, }, storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to add payment method in db")?; if customer.default_payment_method_id.is_none() && req.payment_method.is_some() { let _ = set_default_payment_method( state, merchant_id, key_store.clone(), customer_id, payment_method_id.to_owned(), storage_scheme, ) .await .map_err(|error| logger::error!(?error, "Failed to set the payment method as default")); } Ok(response) } <file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="1712" end="1981"> pub async fn save_migration_payment_method( state: &routes::SessionState, req: api::PaymentMethodCreate, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, migration_status: &mut migration::RecordMigrationStatusBuilder, ) -> errors::RouterResponse<api::PaymentMethodResponse> { req.validate()?; let db = &*state.store; let merchant_id = merchant_account.get_id(); let customer_id = req.customer_id.clone().get_required_value("customer_id")?; let payment_method = req.payment_method.get_required_value("payment_method")?; let key_manager_state = state.into(); let payment_method_billing_address: Option<Encryptable<Secret<serde_json::Value>>> = req .billing .clone() .async_map(|billing| create_encrypted_data(&key_manager_state, key_store, billing)) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt Payment method billing address")?; let connector_mandate_details = req .connector_mandate_details .clone() .map(serde_json::to_value) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError)?; let network_transaction_id = req.network_transaction_id.clone(); let response = match payment_method { #[cfg(feature = "payouts")] api_enums::PaymentMethod::BankTransfer => match req.bank_transfer.clone() { Some(bank) => add_bank_to_locker( state, req.clone(), merchant_account, key_store, &bank, &customer_id, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Add PaymentMethod Failed"), _ => Ok(store_default_payment_method( &req, &customer_id, merchant_id, )), }, api_enums::PaymentMethod::Card => match req.card.clone() { Some(card) => { let mut card_details = card; card_details = helpers::populate_bin_details_for_payment_method_create( card_details.clone(), db, ) .await; migration::validate_card_expiry( &card_details.card_exp_month, &card_details.card_exp_year, )?; Box::pin(add_card_to_locker( state, req.clone(), &card_details, &customer_id, merchant_account, None, )) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Add Card Failed") } _ => Ok(store_default_payment_method( &req, &customer_id, merchant_id, )), }, _ => Ok(store_default_payment_method( &req, &customer_id, merchant_id, )), }; let (mut resp, duplication_check) = response?; migration_status.card_migrated(true); match duplication_check { Some(duplication_check) => match duplication_check { payment_methods::DataDuplicationCheck::Duplicated => { let existing_pm = get_or_insert_payment_method( state, req.clone(), &mut resp, merchant_account, &customer_id, key_store, ) .await?; resp.client_secret = existing_pm.client_secret; } payment_methods::DataDuplicationCheck::MetaDataChanged => { if let Some(card) = req.card.clone() { let existing_pm = get_or_insert_payment_method( state, req.clone(), &mut resp, merchant_account, &customer_id, key_store, ) .await?; let client_secret = existing_pm.client_secret.clone(); delete_card_from_locker( state, &customer_id, merchant_id, existing_pm .locker_id .as_ref() .unwrap_or(&existing_pm.payment_method_id), ) .await?; let add_card_resp = add_card_hs( state, req.clone(), &card, &customer_id, merchant_account, api::enums::LockerChoice::HyperswitchCardVault, Some( existing_pm .locker_id .as_ref() .unwrap_or(&existing_pm.payment_method_id), ), ) .await; if let Err(err) = add_card_resp { logger::error!(vault_err=?err); db.delete_payment_method_by_merchant_id_payment_method_id( &(state.into()), key_store, merchant_id, &resp.payment_method_id, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?; Err(report!(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while updating card metadata changes"))? }; let existing_pm_data = get_card_details_without_locker_fallback(&existing_pm, state).await?; let updated_card = Some(api::CardDetailFromLocker { scheme: existing_pm.scheme.clone(), last4_digits: Some(card.card_number.get_last4()), issuer_country: card .card_issuing_country .or(existing_pm_data.issuer_country), card_isin: Some(card.card_number.get_card_isin()), card_number: Some(card.card_number), expiry_month: Some(card.card_exp_month), expiry_year: Some(card.card_exp_year), card_token: None, card_fingerprint: None, card_holder_name: card .card_holder_name .or(existing_pm_data.card_holder_name), nick_name: card.nick_name.or(existing_pm_data.nick_name), card_network: card.card_network.or(existing_pm_data.card_network), card_issuer: card.card_issuer.or(existing_pm_data.card_issuer), card_type: card.card_type.or(existing_pm_data.card_type), saved_to_locker: true, }); let updated_pmd = updated_card.as_ref().map(|card| { PaymentMethodsData::Card(CardDetailsPaymentMethod::from(card.clone())) }); let pm_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>> = updated_pmd .async_map(|updated_pmd| { create_encrypted_data(&key_manager_state, key_store, updated_pmd) }) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt payment method data")?; let pm_update = storage::PaymentMethodUpdate::PaymentMethodDataUpdate { payment_method_data: pm_data_encrypted.map(Into::into), }; db.update_payment_method( &(state.into()), key_store, existing_pm, pm_update, merchant_account.storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to add payment method in db")?; resp.client_secret = client_secret; } } }, None => { let pm_metadata = resp.metadata.as_ref().map(|data| data.peek()); let locker_id = if resp.payment_method == Some(api_enums::PaymentMethod::Card) || resp.payment_method == Some(api_enums::PaymentMethod::BankTransfer) { Some(resp.payment_method_id) } else { None }; resp.payment_method_id = generate_id(consts::ID_LENGTH, "pm"); let pm = insert_payment_method( state, &resp, &req, key_store, merchant_id, &customer_id, pm_metadata.cloned(), None, locker_id, connector_mandate_details.clone(), network_transaction_id.clone(), merchant_account.storage_scheme, payment_method_billing_address, None, None, None, ) .await?; resp.client_secret = pm.client_secret; } } migration_status.card_migrated(true); migration_status.network_transaction_id_migrated( network_transaction_id.and_then(|val| (!val.is_empty_after_trim()).then_some(true)), ); migration_status.connector_mandate_details_migrated( connector_mandate_details .and_then(|val| if val == json!({}) { None } else { Some(true) }) .or_else(|| { req.connector_mandate_details .and_then(|val| (!val.0.is_empty()).then_some(false)) }), ); Ok(services::ApplicationResponse::Json(resp)) } <file_sep path="hyperswitch/crates/router/src/core/payment_methods/cards.rs" role="context" start="1454" end="1705"> pub async fn add_payment_method( state: &routes::SessionState, req: api::PaymentMethodCreate, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, ) -> errors::RouterResponse<api::PaymentMethodResponse> { req.validate()?; let db = &*state.store; let merchant_id = merchant_account.get_id(); let customer_id = req.customer_id.clone().get_required_value("customer_id")?; let payment_method = req.payment_method.get_required_value("payment_method")?; let key_manager_state = state.into(); let payment_method_billing_address: Option<Encryptable<Secret<serde_json::Value>>> = req .billing .clone() .async_map(|billing| create_encrypted_data(&key_manager_state, key_store, billing)) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt Payment method billing address")?; let connector_mandate_details = req .connector_mandate_details .clone() .map(serde_json::to_value) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError)?; let response = match payment_method { #[cfg(feature = "payouts")] api_enums::PaymentMethod::BankTransfer => match req.bank_transfer.clone() { Some(bank) => add_bank_to_locker( state, req.clone(), merchant_account, key_store, &bank, &customer_id, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Add PaymentMethod Failed"), _ => Ok(store_default_payment_method( &req, &customer_id, merchant_id, )), }, api_enums::PaymentMethod::Card => match req.card.clone() { Some(card) => { let mut card_details = card; card_details = helpers::populate_bin_details_for_payment_method_create( card_details.clone(), db, ) .await; helpers::validate_card_expiry( &card_details.card_exp_month, &card_details.card_exp_year, )?; Box::pin(add_card_to_locker( state, req.clone(), &card_details, &customer_id, merchant_account, None, )) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Add Card Failed") } _ => Ok(store_default_payment_method( &req, &customer_id, merchant_id, )), }, _ => Ok(store_default_payment_method( &req, &customer_id, merchant_id, )), }; let (mut resp, duplication_check) = response?; match duplication_check { Some(duplication_check) => match duplication_check { payment_methods::DataDuplicationCheck::Duplicated => { let existing_pm = get_or_insert_payment_method( state, req.clone(), &mut resp, merchant_account, &customer_id, key_store, ) .await?; resp.client_secret = existing_pm.client_secret; } payment_methods::DataDuplicationCheck::MetaDataChanged => { if let Some(card) = req.card.clone() { let existing_pm = get_or_insert_payment_method( state, req.clone(), &mut resp, merchant_account, &customer_id, key_store, ) .await?; let client_secret = existing_pm.client_secret.clone(); delete_card_from_locker( state, &customer_id, merchant_id, existing_pm .locker_id .as_ref() .unwrap_or(&existing_pm.payment_method_id), ) .await?; let add_card_resp = add_card_hs( state, req.clone(), &card, &customer_id, merchant_account, api::enums::LockerChoice::HyperswitchCardVault, Some( existing_pm .locker_id .as_ref() .unwrap_or(&existing_pm.payment_method_id), ), ) .await; if let Err(err) = add_card_resp { logger::error!(vault_err=?err); db.delete_payment_method_by_merchant_id_payment_method_id( &(state.into()), key_store, merchant_id, &resp.payment_method_id, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?; Err(report!(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while updating card metadata changes"))? }; let existing_pm_data = get_card_details_without_locker_fallback(&existing_pm, state).await?; let updated_card = Some(api::CardDetailFromLocker { scheme: existing_pm.scheme.clone(), last4_digits: Some(card.card_number.get_last4()), issuer_country: card .card_issuing_country .or(existing_pm_data.issuer_country), card_isin: Some(card.card_number.get_card_isin()), card_number: Some(card.card_number), expiry_month: Some(card.card_exp_month), expiry_year: Some(card.card_exp_year), card_token: None, card_fingerprint: None, card_holder_name: card .card_holder_name .or(existing_pm_data.card_holder_name), nick_name: card.nick_name.or(existing_pm_data.nick_name), card_network: card.card_network.or(existing_pm_data.card_network), card_issuer: card.card_issuer.or(existing_pm_data.card_issuer), card_type: card.card_type.or(existing_pm_data.card_type), saved_to_locker: true, }); let updated_pmd = updated_card.as_ref().map(|card| { PaymentMethodsData::Card(CardDetailsPaymentMethod::from(card.clone())) }); let pm_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>> = updated_pmd .async_map(|updated_pmd| { create_encrypted_data(&key_manager_state, key_store, updated_pmd) }) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt payment method data")?; let pm_update = storage::PaymentMethodUpdate::PaymentMethodDataUpdate { payment_method_data: pm_data_encrypted.map(Into::into), }; db.update_payment_method( &(state.into()), key_store, existing_pm, pm_update, merchant_account.storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to add payment method in db")?; resp.client_secret = client_secret; } } }, None => { let pm_metadata = resp.metadata.as_ref().map(|data| data.peek()); let locker_id = if resp.payment_method == Some(api_enums::PaymentMethod::Card) || resp.payment_method == Some(api_enums::PaymentMethod::BankTransfer) { Some(resp.payment_method_id) } else { None }; resp.payment_method_id = generate_id(consts::ID_LENGTH, "pm"); let pm = insert_payment_method( state, &resp, &req, key_store, merchant_id, &customer_id, pm_metadata.cloned(), None, locker_id, connector_mandate_details, req.network_transaction_id.clone(), merchant_account.storage_scheme, payment_method_billing_address, None, None, None, ) .await?; resp.client_secret = pm.client_secret; } } Ok(services::ApplicationResponse::Json(resp)) } <file_sep path="hyperswitch/crates/router/tests/utils.rs" role="context" start="389" end="391"> pub struct MerchantId { merchant_id: common_utils::id_type::MerchantId, } <file_sep path="hyperswitch/crates/api_models/src/admin.rs" role="context" start="698" end="700"> pub struct MerchantId { pub merchant_id: id_type::MerchantId, }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payments/flows/session_flow.rs<|crate|> router anchor=is_session_response_delayed kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/core/payments/flows/session_flow.rs" role="context" start="1183" end="1193"> fn is_session_response_delayed( state: &routes::SessionState, connector: &api::ConnectorData, ) -> bool { let connectors_with_delayed_response = &state .conf .delayed_session_response .connectors_with_delayed_session_response; connectors_with_delayed_response.contains(&connector.connector_name) } <file_sep path="hyperswitch/crates/router/src/core/payments/flows/session_flow.rs" role="context" start="1182" end="1182"> use crate::{ consts::PROTOCOL, core::{ errors::{self, ConnectorErrorExt, RouterResult}, payments::{self, access_token, helpers, transformers, PaymentData}, }, headers, logger, routes::{self, app::settings, metrics}, services, types::{ self, api::{self, enums}, domain, }, utils::OptionExt, }; <file_sep path="hyperswitch/crates/router/src/core/payments/flows/session_flow.rs" role="context" start="1223" end="1257"> fn create_paypal_sdk_session_token( _state: &routes::SessionState, router_data: &types::PaymentsSessionRouterData, connector: &api::ConnectorData, _business_profile: &domain::Profile, ) -> RouterResult<types::PaymentsSessionRouterData> { let connector_metadata = router_data.connector_meta_data.clone(); let paypal_sdk_data = connector_metadata .clone() .parse_value::<payment_types::PaypalSdkSessionTokenData>("PaypalSdkSessionTokenData") .change_context(errors::ConnectorError::NoConnectorMetaData) .attach_printable(format!( "cannot parse paypal_sdk metadata from the given value {connector_metadata:?}" )) .change_context(errors::ApiErrorResponse::InvalidDataFormat { field_name: "connector_metadata".to_string(), expected_format: "paypal_sdk_metadata_format".to_string(), })?; Ok(types::PaymentsSessionRouterData { response: Ok(types::PaymentsResponseData::SessionResponse { session_token: payment_types::SessionToken::Paypal(Box::new( payment_types::PaypalSessionTokenResponse { connector: connector.connector_name.to_string(), session_token: paypal_sdk_data.data.client_id, sdk_next_action: payment_types::SdkNextAction { next_action: payment_types::NextActionCall::PostSessionTokens, }, }, )), }), ..router_data.clone() }) } <file_sep path="hyperswitch/crates/router/src/core/payments/flows/session_flow.rs" role="context" start="1195" end="1205"> fn log_session_response_if_error( response: &Result<Result<types::Response, types::Response>, Report<errors::ApiClientError>>, ) { if let Err(error) = response.as_ref() { logger::error!(?error); }; response .as_ref() .ok() .map(|res| res.as_ref().map_err(|error| logger::error!(?error))); } <file_sep path="hyperswitch/crates/router/src/core/payments/flows/session_flow.rs" role="context" start="1133" end="1181"> fn get_allowed_payment_methods_from_cards( gpay_info: payment_types::GooglePayWalletDetails, gpay_token_specific_data: &payment_types::GooglePayTokenizationSpecification, is_billing_details_required: bool, ) -> RouterResult<payment_types::GpayAllowedPaymentMethods> { let billing_address_parameters = is_billing_details_required.then_some(payment_types::GpayBillingAddressParameters { phone_number_required: is_billing_details_required, format: payment_types::GpayBillingAddressFormat::FULL, }); let protocol_version: Option<String> = gpay_token_specific_data .parameters .public_key .as_ref() .map(|_| PROTOCOL.to_string()); Ok(payment_types::GpayAllowedPaymentMethods { parameters: payment_types::GpayAllowedMethodsParameters { billing_address_required: Some(is_billing_details_required), billing_address_parameters: billing_address_parameters.clone(), ..gpay_info.google_pay.cards }, payment_method_type: CARD.to_string(), tokenization_specification: payment_types::GpayTokenizationSpecification { token_specification_type: gpay_token_specific_data.tokenization_type.to_string(), parameters: payment_types::GpayTokenParameters { protocol_version, public_key: gpay_token_specific_data.parameters.public_key.clone(), gateway: gpay_token_specific_data.parameters.gateway.clone(), gateway_merchant_id: gpay_token_specific_data .parameters .gateway_merchant_id .clone() .expose_option(), stripe_publishable_key: gpay_token_specific_data .parameters .stripe_publishable_key .clone() .expose_option(), stripe_version: gpay_token_specific_data .parameters .stripe_version .clone() .expose_option(), }, }, }) } <file_sep path="hyperswitch/crates/router/src/core/payments/flows/session_flow.rs" role="context" start="925" end="1128"> fn create_gpay_session_token( state: &routes::SessionState, router_data: &types::PaymentsSessionRouterData, connector: &api::ConnectorData, business_profile: &domain::Profile, ) -> RouterResult<types::PaymentsSessionRouterData> { // connector_wallet_details is being parse into admin types to check specifically if google_pay field is present // this is being done because apple_pay details from metadata is also being filled into connector_wallets_details let google_pay_wallets_details = router_data .connector_wallets_details .clone() .parse_value::<admin_types::ConnectorWalletDetails>("ConnectorWalletDetails") .change_context(errors::ConnectorError::NoConnectorWalletDetails) .attach_printable(format!( "cannot parse connector_wallets_details from the given value {:?}", router_data.connector_wallets_details )) .map_err(|err| { logger::debug!( "Failed to parse connector_wallets_details for google_pay flow: {:?}", err ); }) .ok() .and_then(|connector_wallets_details| connector_wallets_details.google_pay); let connector_metadata = router_data.connector_meta_data.clone(); let delayed_response = is_session_response_delayed(state, connector); if delayed_response { Ok(types::PaymentsSessionRouterData { response: Ok(types::PaymentsResponseData::SessionResponse { session_token: payment_types::SessionToken::GooglePay(Box::new( payment_types::GpaySessionTokenResponse::ThirdPartyResponse( payment_types::GooglePayThirdPartySdk { delayed_session_token: true, connector: connector.connector_name.to_string(), sdk_next_action: payment_types::SdkNextAction { next_action: payment_types::NextActionCall::Confirm, }, }, ), )), }), ..router_data.clone() }) } else { let is_billing_details_required = is_billing_address_required_to_be_collected_from_wallet( state, connector, business_profile, enums::PaymentMethodType::GooglePay, ); let required_amount_type = StringMajorUnitForConnector; let google_pay_amount = required_amount_type .convert( router_data.request.minor_amount, router_data.request.currency, ) .change_context(errors::ApiErrorResponse::PreconditionFailed { message: "Failed to convert amount to string major unit for googlePay".to_string(), })?; let session_data = router_data.request.clone(); let transaction_info = payment_types::GpayTransactionInfo { country_code: session_data.country.unwrap_or_default(), currency_code: router_data.request.currency, total_price_status: "Final".to_string(), total_price: google_pay_amount, }; let required_shipping_contact_fields = is_shipping_address_required_to_be_collected_form_wallet( state, connector, business_profile, enums::PaymentMethodType::GooglePay, ); if google_pay_wallets_details.is_some() { let gpay_data = router_data .connector_wallets_details .clone() .parse_value::<payment_types::GooglePayWalletDetails>("GooglePayWalletDetails") .change_context(errors::ConnectorError::NoConnectorWalletDetails) .attach_printable(format!( "cannot parse gpay connector_wallets_details from the given value {:?}", router_data.connector_wallets_details )) .change_context(errors::ApiErrorResponse::InvalidDataFormat { field_name: "connector_wallets_details".to_string(), expected_format: "gpay_connector_wallets_details_format".to_string(), })?; let payment_types::GooglePayProviderDetails::GooglePayMerchantDetails(gpay_info) = gpay_data.google_pay.provider_details.clone(); let gpay_allowed_payment_methods = get_allowed_payment_methods_from_cards( gpay_data, &gpay_info.merchant_info.tokenization_specification, is_billing_details_required, )?; Ok(types::PaymentsSessionRouterData { response: Ok(types::PaymentsResponseData::SessionResponse { session_token: payment_types::SessionToken::GooglePay(Box::new( payment_types::GpaySessionTokenResponse::GooglePaySession( payment_types::GooglePaySessionResponse { merchant_info: payment_types::GpayMerchantInfo { merchant_name: gpay_info.merchant_info.merchant_name, merchant_id: gpay_info.merchant_info.merchant_id, }, allowed_payment_methods: vec![gpay_allowed_payment_methods], transaction_info, connector: connector.connector_name.to_string(), sdk_next_action: payment_types::SdkNextAction { next_action: payment_types::NextActionCall::Confirm, }, delayed_session_token: false, secrets: None, shipping_address_required: required_shipping_contact_fields, // We pass Email as a required field irrespective of // collect_billing_details_from_wallet_connector or // collect_shipping_details_from_wallet_connector as it is common to both. email_required: required_shipping_contact_fields || is_billing_details_required, shipping_address_parameters: api_models::payments::GpayShippingAddressParameters { phone_number_required: required_shipping_contact_fields, }, }, ), )), }), ..router_data.clone() }) } else { let billing_address_parameters = is_billing_details_required.then_some( payment_types::GpayBillingAddressParameters { phone_number_required: is_billing_details_required, format: payment_types::GpayBillingAddressFormat::FULL, }, ); let gpay_data = connector_metadata .clone() .parse_value::<payment_types::GpaySessionTokenData>("GpaySessionTokenData") .change_context(errors::ConnectorError::NoConnectorMetaData) .attach_printable(format!( "cannot parse gpay metadata from the given value {connector_metadata:?}" )) .change_context(errors::ApiErrorResponse::InvalidDataFormat { field_name: "connector_metadata".to_string(), expected_format: "gpay_metadata_format".to_string(), })?; let gpay_allowed_payment_methods = gpay_data .data .allowed_payment_methods .into_iter() .map( |allowed_payment_methods| payment_types::GpayAllowedPaymentMethods { parameters: payment_types::GpayAllowedMethodsParameters { billing_address_required: Some(is_billing_details_required), billing_address_parameters: billing_address_parameters.clone(), ..allowed_payment_methods.parameters }, ..allowed_payment_methods }, ) .collect(); Ok(types::PaymentsSessionRouterData { response: Ok(types::PaymentsResponseData::SessionResponse { session_token: payment_types::SessionToken::GooglePay(Box::new( payment_types::GpaySessionTokenResponse::GooglePaySession( payment_types::GooglePaySessionResponse { merchant_info: gpay_data.data.merchant_info, allowed_payment_methods: gpay_allowed_payment_methods, transaction_info, connector: connector.connector_name.to_string(), sdk_next_action: payment_types::SdkNextAction { next_action: payment_types::NextActionCall::Confirm, }, delayed_session_token: false, secrets: None, shipping_address_required: required_shipping_contact_fields, // We pass Email as a required field irrespective of // collect_billing_details_from_wallet_connector or // collect_shipping_details_from_wallet_connector as it is common to both. email_required: required_shipping_contact_fields || is_billing_details_required, shipping_address_parameters: api_models::payments::GpayShippingAddressParameters { phone_number_required: required_shipping_contact_fields, }, }, ), )), }), ..router_data.clone() }) } } } <file_sep path="hyperswitch/crates/router/src/core/payments/flows/session_flow.rs" role="context" start="253" end="573"> async fn create_applepay_session_token( state: &routes::SessionState, router_data: &types::PaymentsSessionRouterData, connector: &api::ConnectorData, business_profile: &domain::Profile, header_payload: hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<types::PaymentsSessionRouterData> { let delayed_response = is_session_response_delayed(state, connector); if delayed_response { let delayed_response_apple_pay_session = Some(payment_types::ApplePaySessionResponse::NoSessionResponse); create_apple_pay_session_response( router_data, delayed_response_apple_pay_session, None, // Apple pay payment request will be none for delayed session response connector.connector_name.to_string(), delayed_response, payment_types::NextActionCall::Confirm, header_payload, ) } else { // Get the apple pay metadata let apple_pay_metadata = helpers::get_applepay_metadata(router_data.connector_meta_data.clone()) .attach_printable( "Failed to to fetch apple pay certificates during session call", )?; // Get payment request data , apple pay session request and merchant keys let ( payment_request_data, apple_pay_session_request_optional, apple_pay_merchant_cert, apple_pay_merchant_cert_key, apple_pay_merchant_identifier, merchant_business_country, merchant_configured_domain_optional, ) = match apple_pay_metadata { payment_types::ApplepaySessionTokenMetadata::ApplePayCombined( apple_pay_combined_metadata, ) => match apple_pay_combined_metadata { payment_types::ApplePayCombinedMetadata::Simplified { payment_request_data, session_token_data, } => { logger::info!("Apple pay simplified flow"); let merchant_identifier = state .conf .applepay_merchant_configs .get_inner() .common_merchant_identifier .clone() .expose(); let merchant_business_country = session_token_data.merchant_business_country; let apple_pay_session_request = get_session_request_for_simplified_apple_pay( merchant_identifier.clone(), session_token_data.clone(), ); let apple_pay_merchant_cert = state .conf .applepay_decrypt_keys .get_inner() .apple_pay_merchant_cert .clone(); let apple_pay_merchant_cert_key = state .conf .applepay_decrypt_keys .get_inner() .apple_pay_merchant_cert_key .clone(); ( payment_request_data, Ok(apple_pay_session_request), apple_pay_merchant_cert, apple_pay_merchant_cert_key, merchant_identifier, merchant_business_country, Some(session_token_data.initiative_context), ) } payment_types::ApplePayCombinedMetadata::Manual { payment_request_data, session_token_data, } => { logger::info!("Apple pay manual flow"); let apple_pay_session_request = get_session_request_for_manual_apple_pay( session_token_data.clone(), header_payload.x_merchant_domain.clone(), ); let merchant_business_country = session_token_data.merchant_business_country; ( payment_request_data, apple_pay_session_request, session_token_data.certificate.clone(), session_token_data.certificate_keys, session_token_data.merchant_identifier, merchant_business_country, session_token_data.initiative_context, ) } }, payment_types::ApplepaySessionTokenMetadata::ApplePay(apple_pay_metadata) => { logger::info!("Apple pay manual flow"); let apple_pay_session_request = get_session_request_for_manual_apple_pay( apple_pay_metadata.session_token_data.clone(), header_payload.x_merchant_domain.clone(), ); let merchant_business_country = apple_pay_metadata .session_token_data .merchant_business_country; ( apple_pay_metadata.payment_request_data, apple_pay_session_request, apple_pay_metadata.session_token_data.certificate.clone(), apple_pay_metadata .session_token_data .certificate_keys .clone(), apple_pay_metadata.session_token_data.merchant_identifier, merchant_business_country, apple_pay_metadata.session_token_data.initiative_context, ) } }; // Get amount info for apple pay let amount_info = get_apple_pay_amount_info( payment_request_data.label.as_str(), router_data.request.to_owned(), )?; let required_billing_contact_fields = if business_profile .always_collect_billing_details_from_wallet_connector .unwrap_or(false) { Some(payment_types::ApplePayBillingContactFields(vec![ payment_types::ApplePayAddressParameters::PostalAddress, ])) } else if business_profile .collect_billing_details_from_wallet_connector .unwrap_or(false) { let billing_variants = enums::FieldType::get_billing_variants(); is_dynamic_fields_required( &state.conf.required_fields, enums::PaymentMethod::Wallet, enums::PaymentMethodType::ApplePay, connector.connector_name, billing_variants, ) .then_some(payment_types::ApplePayBillingContactFields(vec![ payment_types::ApplePayAddressParameters::PostalAddress, ])) } else { None }; let required_shipping_contact_fields = if business_profile .always_collect_shipping_details_from_wallet_connector .unwrap_or(false) { Some(payment_types::ApplePayShippingContactFields(vec![ payment_types::ApplePayAddressParameters::PostalAddress, payment_types::ApplePayAddressParameters::Phone, payment_types::ApplePayAddressParameters::Email, ])) } else if business_profile .collect_shipping_details_from_wallet_connector .unwrap_or(false) { let shipping_variants = enums::FieldType::get_shipping_variants(); is_dynamic_fields_required( &state.conf.required_fields, enums::PaymentMethod::Wallet, enums::PaymentMethodType::ApplePay, connector.connector_name, shipping_variants, ) .then_some(payment_types::ApplePayShippingContactFields(vec![ payment_types::ApplePayAddressParameters::PostalAddress, payment_types::ApplePayAddressParameters::Phone, payment_types::ApplePayAddressParameters::Email, ])) } else { None }; // If collect_shipping_details_from_wallet_connector is false, we check if // collect_billing_details_from_wallet_connector is true. If it is, then we pass the Email and Phone in // ApplePayShippingContactFields as it is a required parameter and ApplePayBillingContactFields // does not contain Email and Phone. let required_shipping_contact_fields_updated = if required_billing_contact_fields.is_some() && required_shipping_contact_fields.is_none() { Some(payment_types::ApplePayShippingContactFields(vec![ payment_types::ApplePayAddressParameters::Phone, payment_types::ApplePayAddressParameters::Email, ])) } else { required_shipping_contact_fields }; // Get apple pay payment request let applepay_payment_request = get_apple_pay_payment_request( amount_info, payment_request_data, router_data.request.to_owned(), apple_pay_merchant_identifier.as_str(), merchant_business_country, required_billing_contact_fields, required_shipping_contact_fields_updated, )?; let apple_pay_session_response = match ( header_payload.browser_name.clone(), header_payload.x_client_platform.clone(), ) { (Some(common_enums::BrowserName::Safari), Some(common_enums::ClientPlatform::Web)) | (None, None) => { let apple_pay_session_request = apple_pay_session_request_optional .attach_printable("Failed to obtain apple pay session request")?; let applepay_session_request = build_apple_pay_session_request( state, apple_pay_session_request.clone(), apple_pay_merchant_cert.clone(), apple_pay_merchant_cert_key.clone(), )?; let response = services::call_connector_api( state, applepay_session_request, "create_apple_pay_session_token", ) .await; let updated_response = match ( response.as_ref().ok(), header_payload.x_merchant_domain.clone(), ) { (Some(Err(error)), Some(_)) => { logger::error!( "Retry apple pay session call with the merchant configured domain {error:?}" ); let merchant_configured_domain = merchant_configured_domain_optional .get_required_value("apple pay domain") .attach_printable("Failed to get domain for apple pay session call")?; let apple_pay_retry_session_request = payment_types::ApplepaySessionRequest { initiative_context: merchant_configured_domain, ..apple_pay_session_request }; let applepay_retry_session_request = build_apple_pay_session_request( state, apple_pay_retry_session_request, apple_pay_merchant_cert, apple_pay_merchant_cert_key, )?; services::call_connector_api( state, applepay_retry_session_request, "create_apple_pay_session_token", ) .await } _ => response, }; // logging the error if present in session call response log_session_response_if_error(&updated_response); updated_response .ok() .and_then(|apple_pay_res| { apple_pay_res .map(|res| { let response: Result< payment_types::NoThirdPartySdkSessionResponse, Report<common_utils::errors::ParsingError>, > = res.response.parse_struct("NoThirdPartySdkSessionResponse"); // logging the parsing failed error if let Err(error) = response.as_ref() { logger::error!(?error); }; response.ok() }) .ok() }) .flatten() } _ => { logger::debug!("Skipping apple pay session call based on the browser name"); None } }; let session_response = apple_pay_session_response.map(payment_types::ApplePaySessionResponse::NoThirdPartySdk); create_apple_pay_session_response( router_data, session_response, Some(applepay_payment_request), connector.connector_name.to_string(), delayed_response, payment_types::NextActionCall::Confirm, header_payload, ) } } <file_sep path="hyperswitch/crates/router/src/routes/app.rs" role="context" start="104" end="125"> pub struct SessionState { pub store: Box<dyn StorageInterface>, /// Global store is used for global schema operations in tables like Users and Tenants pub global_store: Box<dyn GlobalStorageInterface>, pub accounts_store: Box<dyn AccountsStorageInterface>, pub conf: Arc<settings::Settings<RawSecret>>, pub api_client: Box<dyn crate::services::ApiClient>, pub event_handler: EventsHandler, #[cfg(feature = "email")] pub email_client: Arc<Box<dyn EmailService>>, #[cfg(feature = "olap")] pub pool: AnalyticsProvider, pub file_storage_client: Arc<dyn FileStorageInterface>, pub request_id: Option<RequestId>, pub base_url: String, pub tenant: Tenant, #[cfg(feature = "olap")] pub opensearch_client: Option<Arc<OpenSearchClient>>, pub grpc_client: Arc<GrpcClients>, pub theme_storage_client: Arc<dyn FileStorageInterface>, pub locale: String, } <file_sep path="hyperswitch/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/event.test.js" role="context" start="61" end="78"> "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.", ); } // Response body should have value "succeeded" for "status" if (jsonData?.status) { pm.test( "[POST]::/payments - Content check if value for 'status' matches 'succeeded'", function () { pm.expect(jsonData.status).to.eql("succeeded"); }, ); }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payments/flows/authorize_flow.rs<|crate|> router anchor=create_connector_customer kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/core/payments/flows/authorize_flow.rs" role="context" start="316" end="328"> async fn create_connector_customer<'a>( &self, state: &SessionState, connector: &api::ConnectorData, ) -> RouterResult<Option<String>> { customers::create_connector_customer( state, connector, self, types::ConnectorCustomerData::try_from(self)?, ) .await } <file_sep path="hyperswitch/crates/router/src/core/payments/flows/authorize_flow.rs" role="context" start="315" end="315"> use crate::{ core::{ errors::{ConnectorErrorExt, RouterResult}, mandate, payments::{ self, access_token, customers, helpers, tokenization, transformers, PaymentData, }, }, logger, routes::{metrics, SessionState}, services::{self, api::ConnectorValidation}, types::{ self, api, domain, transformers::{ForeignFrom, ForeignTryFrom}, }, utils::OptionExt, }; <file_sep path="hyperswitch/crates/router/src/core/payments/flows/authorize_flow.rs" role="context" start="402" end="422"> fn decide_authentication_type(&mut self) { if let hyperswitch_domain_models::payment_method_data::PaymentMethodData::Wallet( hyperswitch_domain_models::payment_method_data::WalletData::GooglePay(google_pay_data), ) = &self.request.payment_method_data { if let Some(assurance_details) = google_pay_data.info.assurance_details.as_ref() { // Step up the transaction to 3DS when either assurance_details.card_holder_authenticated or assurance_details.account_verified is false if !assurance_details.card_holder_authenticated || !assurance_details.account_verified { logger::info!("Googlepay transaction stepped up to 3DS"); self.auth_type = diesel_models::enums::AuthenticationType::ThreeDs; } } } if self.auth_type == diesel_models::enums::AuthenticationType::ThreeDs && !self.request.enrolled_for_3ds { self.auth_type = diesel_models::enums::AuthenticationType::NoThreeDs } } <file_sep path="hyperswitch/crates/router/src/core/payments/flows/authorize_flow.rs" role="context" start="330" end="391"> async fn build_flow_specific_connector_request( &mut self, state: &SessionState, connector: &api::ConnectorData, call_connector_action: payments::CallConnectorAction, ) -> RouterResult<(Option<services::Request>, bool)> { match call_connector_action { payments::CallConnectorAction::Trigger => { connector .connector .validate_connector_against_payment_request( self.request.capture_method, self.payment_method, self.request.payment_method_type, ) .to_payment_failed_response()?; if crate::connector::utils::PaymentsAuthorizeRequestData::is_customer_initiated_mandate_payment( &self.request, ) { connector .connector .validate_mandate_payment( self.request.payment_method_type, self.request.payment_method_data.clone(), ) .to_payment_failed_response()?; } let connector_integration: services::BoxedPaymentConnectorIntegrationInterface< api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData, > = connector.connector.get_connector_integration(); metrics::EXECUTE_PRETASK_COUNT.add( 1, router_env::metric_attributes!( ("connector", connector.connector_name.to_string()), ("flow", format!("{:?}", api::Authorize)), ), ); logger::debug!(completed_pre_tasks=?true); if self.should_proceed_with_authorize() { self.decide_authentication_type(); logger::debug!(auth_type=?self.auth_type); Ok(( connector_integration .build_request(self, &state.conf.connectors) .to_payment_failed_response()?, true, )) } else { Ok((None, false)) } } _ => Ok((None, true)), } } <file_sep path="hyperswitch/crates/router/src/core/payments/flows/authorize_flow.rs" role="context" start="308" end="314"> async fn postprocessing_steps<'a>( self, state: &SessionState, connector: &api::ConnectorData, ) -> RouterResult<Self> { authorize_postprocessing_steps(state, &self, true, connector).await } <file_sep path="hyperswitch/crates/router/src/core/payments/flows/authorize_flow.rs" role="context" start="300" end="306"> async fn preprocessing_steps<'a>( self, state: &SessionState, connector: &api::ConnectorData, ) -> RouterResult<Self> { authorize_preprocessing_steps(state, &self, true, connector).await } <file_sep path="hyperswitch/crates/router/src/core/errors.rs" role="context" start="31" end="31"> pub type RouterResult<T> = CustomResult<T, ApiErrorResponse>; <file_sep path="hyperswitch/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/event.test.js" role="context" start="61" end="78"> "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.", ); } // Response body should have value "succeeded" for "status" if (jsonData?.status) { pm.test( "[POST]::/payments - Content check if value for 'status' matches 'succeeded'", function () { pm.expect(jsonData.status).to.eql("succeeded"); }, ); }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payment_link.rs<|crate|> router anchor=extract_payment_link_config kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/core/payment_link.rs" role="context" start="593" end="601"> pub fn extract_payment_link_config( pl_config: serde_json::Value, ) -> Result<PaymentLinkConfig, error_stack::Report<errors::ApiErrorResponse>> { serde_json::from_value::<PaymentLinkConfig>(pl_config).change_context( errors::ApiErrorResponse::InvalidDataValue { field_name: "payment_link_config", }, ) } <file_sep path="hyperswitch/crates/router/src/core/payment_link.rs" role="context" start="592" end="592"> use api_models::{ admin::PaymentLinkConfig, payments::{PaymentLinkData, PaymentLinkStatusWrap}, }; use error_stack::{report, ResultExt}; use super::{ errors::{self, RouterResult, StorageErrorExt}, payments::helpers, }; use crate::{ consts::{ self, DEFAULT_ALLOWED_DOMAINS, DEFAULT_BACKGROUND_COLOR, DEFAULT_DISPLAY_SDK_ONLY, DEFAULT_ENABLE_BUTTON_ONLY_ON_FORM_READY, DEFAULT_ENABLE_SAVED_PAYMENT_METHOD, DEFAULT_HIDE_CARD_NICKNAME_FIELD, DEFAULT_MERCHANT_LOGO, DEFAULT_PRODUCT_IMG, DEFAULT_SDK_LAYOUT, DEFAULT_SHOW_CARD_FORM, }, errors::RouterResponse, get_payment_link_config_value, get_payment_link_config_value_based_on_priority, routes::SessionState, services, types::{ api::payment_link::PaymentLinkResponseExt, domain, storage::{enums as storage_enums, payment_link::PaymentLink}, transformers::{ForeignFrom, ForeignInto}, }, }; <file_sep path="hyperswitch/crates/router/src/core/payment_link.rs" role="context" start="724" end="735"> fn capitalize_first_char(s: &str) -> String { if let Some(first_char) = s.chars().next() { let capitalized = first_char.to_uppercase(); let mut result = capitalized.to_string(); if let Some(remaining) = s.get(1..) { result.push_str(remaining); } result } else { s.to_owned() } } <file_sep path="hyperswitch/crates/router/src/core/payment_link.rs" role="context" start="603" end="722"> pub fn get_payment_link_config_based_on_priority( payment_create_link_config: Option<api_models::payments::PaymentCreatePaymentLinkConfig>, business_link_config: Option<diesel_models::business_profile::BusinessPaymentLinkConfig>, merchant_name: String, default_domain_name: String, payment_link_config_id: Option<String>, ) -> Result<(PaymentLinkConfig, String), error_stack::Report<errors::ApiErrorResponse>> { let (domain_name, business_theme_configs, allowed_domains, branding_visibility) = if let Some(business_config) = business_link_config { ( business_config .domain_name .clone() .map(|d_name| { logger::info!("domain name set to custom domain https://{:?}", d_name); format!("https://{}", d_name) }) .unwrap_or_else(|| default_domain_name.clone()), payment_link_config_id .and_then(|id| { business_config .business_specific_configs .as_ref() .and_then(|specific_configs| specific_configs.get(&id).cloned()) }) .or(business_config.default_config), business_config.allowed_domains, business_config.branding_visibility, ) } else { (default_domain_name, None, None, None) }; let ( theme, logo, seller_name, sdk_layout, display_sdk_only, enabled_saved_payment_method, hide_card_nickname_field, show_card_form_by_default, enable_button_only_on_form_ready, ) = get_payment_link_config_value!( payment_create_link_config, business_theme_configs, (theme, DEFAULT_BACKGROUND_COLOR.to_string()), (logo, DEFAULT_MERCHANT_LOGO.to_string()), (seller_name, merchant_name.clone()), (sdk_layout, DEFAULT_SDK_LAYOUT.to_owned()), (display_sdk_only, DEFAULT_DISPLAY_SDK_ONLY), ( enabled_saved_payment_method, DEFAULT_ENABLE_SAVED_PAYMENT_METHOD ), (hide_card_nickname_field, DEFAULT_HIDE_CARD_NICKNAME_FIELD), (show_card_form_by_default, DEFAULT_SHOW_CARD_FORM), ( enable_button_only_on_form_ready, DEFAULT_ENABLE_BUTTON_ONLY_ON_FORM_READY ) ); let ( details_layout, background_image, payment_button_text, custom_message_for_card_terms, payment_button_colour, skip_status_screen, background_colour, payment_button_text_colour, sdk_ui_rules, payment_link_ui_rules, ) = get_payment_link_config_value!( payment_create_link_config, business_theme_configs, (details_layout), (background_image, |background_image| background_image .foreign_into()), (payment_button_text), (custom_message_for_card_terms), (payment_button_colour), (skip_status_screen), (background_colour), (payment_button_text_colour), (sdk_ui_rules), (payment_link_ui_rules), ); let payment_link_config = PaymentLinkConfig { theme, logo, seller_name, sdk_layout, display_sdk_only, enabled_saved_payment_method, hide_card_nickname_field, show_card_form_by_default, allowed_domains, branding_visibility, skip_status_screen, transaction_details: payment_create_link_config.as_ref().and_then( |payment_link_config| payment_link_config.theme_config.transaction_details.clone(), ), details_layout, background_image, payment_button_text, custom_message_for_card_terms, payment_button_colour, background_colour, payment_button_text_colour, sdk_ui_rules, payment_link_ui_rules, enable_button_only_on_form_ready, }; Ok((payment_link_config, domain_name)) } <file_sep path="hyperswitch/crates/router/src/core/payment_link.rs" role="context" start="537" end="591"> fn validate_order_details( order_details: Option<Vec<Secret<serde_json::Value>>>, currency: api_models::enums::Currency, ) -> Result< Option<Vec<api_models::payments::OrderDetailsWithStringAmount>>, error_stack::Report<errors::ApiErrorResponse>, > { let required_conversion_type = StringMajorUnitForCore; let order_details = order_details .map(|order_details| { order_details .iter() .map(|data| { data.to_owned() .parse_value("OrderDetailsWithAmount") .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "OrderDetailsWithAmount", }) .attach_printable("Unable to parse OrderDetailsWithAmount") }) .collect::<Result<Vec<api_models::payments::OrderDetailsWithAmount>, _>>() }) .transpose()?; let updated_order_details = match order_details { Some(mut order_details) => { let mut order_details_amount_string_array: Vec< api_models::payments::OrderDetailsWithStringAmount, > = Vec::new(); for order in order_details.iter_mut() { let mut order_details_amount_string : api_models::payments::OrderDetailsWithStringAmount = Default::default(); if order.product_img_link.is_none() { order_details_amount_string.product_img_link = Some(DEFAULT_PRODUCT_IMG.to_string()) } else { order_details_amount_string .product_img_link .clone_from(&order.product_img_link) }; order_details_amount_string.amount = required_conversion_type .convert(order.amount, currency) .change_context(errors::ApiErrorResponse::AmountConversionFailed { amount_type: "StringMajorUnit", })?; order_details_amount_string.product_name = capitalize_first_char(&order.product_name.clone()); order_details_amount_string.quantity = order.quantity; order_details_amount_string_array.push(order_details_amount_string) } Some(order_details_amount_string_array) } None => None, }; Ok(updated_order_details) } <file_sep path="hyperswitch/crates/router/src/core/payment_link.rs" role="context" start="525" end="535"> pub fn check_payment_link_status( payment_link_expiry: PrimitiveDateTime, ) -> api_models::payments::PaymentLinkStatus { let curr_time = common_utils::date_time::now(); if curr_time > payment_link_expiry { api_models::payments::PaymentLinkStatus::Expired } else { api_models::payments::PaymentLinkStatus::Active } } <file_sep path="hyperswitch/crates/router/src/core/payment_link.rs" role="context" start="756" end="923"> pub async fn get_payment_link_status( state: SessionState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, merchant_id: common_utils::id_type::MerchantId, payment_id: common_utils::id_type::PaymentId, ) -> RouterResponse<services::PaymentLinkFormData> { let db = &*state.store; let key_manager_state = &(&state).into(); let payment_intent = db .find_payment_intent_by_payment_id_merchant_id( key_manager_state, &payment_id, &merchant_id, &key_store, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let attempt_id = payment_intent.active_attempt.get_id().clone(); let payment_attempt = db .find_payment_attempt_by_payment_id_merchant_id_attempt_id( &payment_intent.payment_id, &merchant_id, &attempt_id.clone(), merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let payment_link_id = payment_intent .payment_link_id .get_required_value("payment_link_id") .change_context(errors::ApiErrorResponse::PaymentLinkNotFound)?; let merchant_name_from_merchant_account = merchant_account .merchant_name .clone() .map(|merchant_name| merchant_name.into_inner().peek().to_owned()) .unwrap_or_default(); let payment_link = db .find_payment_link_by_payment_link_id(&payment_link_id) .await .to_not_found_response(errors::ApiErrorResponse::PaymentLinkNotFound)?; let payment_link_config = if let Some(pl_config_value) = payment_link.payment_link_config { extract_payment_link_config(pl_config_value)? } else { PaymentLinkConfig { theme: DEFAULT_BACKGROUND_COLOR.to_string(), logo: DEFAULT_MERCHANT_LOGO.to_string(), seller_name: merchant_name_from_merchant_account, sdk_layout: DEFAULT_SDK_LAYOUT.to_owned(), display_sdk_only: DEFAULT_DISPLAY_SDK_ONLY, enabled_saved_payment_method: DEFAULT_ENABLE_SAVED_PAYMENT_METHOD, hide_card_nickname_field: DEFAULT_HIDE_CARD_NICKNAME_FIELD, show_card_form_by_default: DEFAULT_SHOW_CARD_FORM, allowed_domains: DEFAULT_ALLOWED_DOMAINS, transaction_details: None, background_image: None, details_layout: None, branding_visibility: None, payment_button_text: None, custom_message_for_card_terms: None, payment_button_colour: None, skip_status_screen: None, background_colour: None, payment_button_text_colour: None, sdk_ui_rules: None, payment_link_ui_rules: None, enable_button_only_on_form_ready: DEFAULT_ENABLE_BUTTON_ONLY_ON_FORM_READY, } }; let currency = payment_intent .currency .ok_or(errors::ApiErrorResponse::MissingRequiredField { field_name: "currency", })?; let required_conversion_type = StringMajorUnitForCore; let amount = required_conversion_type .convert(payment_attempt.get_total_amount(), currency) .change_context(errors::ApiErrorResponse::AmountConversionFailed { amount_type: "StringMajorUnit", })?; // converting first letter of merchant name to upperCase let merchant_name = capitalize_first_char(&payment_link_config.seller_name); let css_script = get_color_scheme_css(&payment_link_config); let profile_id = payment_link .profile_id .or(payment_intent.profile_id) .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("Profile id missing in payment link and payment intent")?; let business_profile = db .find_business_profile_by_profile_id(key_manager_state, &key_store, &profile_id) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; let return_url = if let Some(payment_create_return_url) = payment_intent.return_url.clone() { payment_create_return_url } else { business_profile .return_url .ok_or(errors::ApiErrorResponse::MissingRequiredField { field_name: "return_url", })? }; let (unified_code, unified_message) = if let Some((code, message)) = payment_attempt .unified_code .as_ref() .zip(payment_attempt.unified_message.as_ref()) { (code.to_owned(), message.to_owned()) } else { ( consts::DEFAULT_UNIFIED_ERROR_CODE.to_owned(), consts::DEFAULT_UNIFIED_ERROR_MESSAGE.to_owned(), ) }; let unified_translated_message = helpers::get_unified_translation( &state, unified_code.to_owned(), unified_message.to_owned(), state.locale.clone(), ) .await .or(Some(unified_message)); let payment_details = api_models::payments::PaymentLinkStatusDetails { amount, currency, payment_id: payment_intent.payment_id, merchant_name, merchant_logo: payment_link_config.logo.clone(), created: payment_link.created_at, status: PaymentLinkStatusWrap::IntentStatus(payment_intent.status), error_code: payment_attempt.error_code, error_message: payment_attempt.error_message, redirect: true, theme: payment_link_config.theme.clone(), return_url, locale: Some(state.locale.clone()), transaction_details: payment_link_config.transaction_details, unified_code: Some(unified_code), unified_message: unified_translated_message, }; let js_script = get_js_script(&PaymentLinkData::PaymentLinkStatusDetails(Box::new( payment_details, )))?; let payment_link_status_data = services::PaymentLinkStatusData { js_script, css_script, }; Ok(services::ApplicationResponse::PaymentLinkForm(Box::new( services::api::PaymentLinkAction::PaymentLinkStatus(payment_link_status_data), ))) } <file_sep path="hyperswitch/crates/router/src/core/payment_link.rs" role="context" start="78" end="306"> pub async fn form_payment_link_data( state: &SessionState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, merchant_id: common_utils::id_type::MerchantId, payment_id: common_utils::id_type::PaymentId, ) -> RouterResult<(PaymentLink, PaymentLinkData, PaymentLinkConfig)> { let db = &*state.store; let key_manager_state = &state.into(); let payment_intent = db .find_payment_intent_by_payment_id_merchant_id( &(state).into(), &payment_id, &merchant_id, &key_store, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let payment_link_id = payment_intent .payment_link_id .get_required_value("payment_link_id") .change_context(errors::ApiErrorResponse::PaymentLinkNotFound)?; let merchant_name_from_merchant_account = merchant_account .merchant_name .clone() .map(|merchant_name| merchant_name.into_inner().peek().to_owned()) .unwrap_or_default(); let payment_link = db .find_payment_link_by_payment_link_id(&payment_link_id) .await .to_not_found_response(errors::ApiErrorResponse::PaymentLinkNotFound)?; let payment_link_config = if let Some(pl_config_value) = payment_link.payment_link_config.clone() { extract_payment_link_config(pl_config_value)? } else { PaymentLinkConfig { theme: DEFAULT_BACKGROUND_COLOR.to_string(), logo: DEFAULT_MERCHANT_LOGO.to_string(), seller_name: merchant_name_from_merchant_account, sdk_layout: DEFAULT_SDK_LAYOUT.to_owned(), display_sdk_only: DEFAULT_DISPLAY_SDK_ONLY, enabled_saved_payment_method: DEFAULT_ENABLE_SAVED_PAYMENT_METHOD, hide_card_nickname_field: DEFAULT_HIDE_CARD_NICKNAME_FIELD, show_card_form_by_default: DEFAULT_SHOW_CARD_FORM, allowed_domains: DEFAULT_ALLOWED_DOMAINS, transaction_details: None, background_image: None, details_layout: None, branding_visibility: None, payment_button_text: None, custom_message_for_card_terms: None, payment_button_colour: None, skip_status_screen: None, background_colour: None, payment_button_text_colour: None, sdk_ui_rules: None, payment_link_ui_rules: None, enable_button_only_on_form_ready: DEFAULT_ENABLE_BUTTON_ONLY_ON_FORM_READY, } }; let profile_id = payment_link .profile_id .clone() .or(payment_intent.profile_id) .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("Profile id missing in payment link and payment intent")?; let business_profile = db .find_business_profile_by_profile_id(key_manager_state, &key_store, &profile_id) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; let return_url = if let Some(payment_create_return_url) = payment_intent.return_url.clone() { payment_create_return_url } else { business_profile .return_url .ok_or(errors::ApiErrorResponse::MissingRequiredField { field_name: "return_url", })? }; let (currency, client_secret) = validate_sdk_requirements( payment_intent.currency, payment_intent.client_secret.clone(), )?; let required_conversion_type = StringMajorUnitForCore; let amount = required_conversion_type .convert(payment_intent.amount, currency) .change_context(errors::ApiErrorResponse::AmountConversionFailed { amount_type: "StringMajorUnit", })?; let order_details = validate_order_details(payment_intent.order_details.clone(), currency)?; let session_expiry = payment_link.fulfilment_time.unwrap_or_else(|| { payment_intent .created_at .saturating_add(time::Duration::seconds(DEFAULT_SESSION_EXPIRY)) }); // converting first letter of merchant name to upperCase let merchant_name = capitalize_first_char(&payment_link_config.seller_name); let payment_link_status = check_payment_link_status(session_expiry); let is_payment_link_terminal_state = check_payment_link_invalid_conditions( payment_intent.status, &[ storage_enums::IntentStatus::Cancelled, storage_enums::IntentStatus::Failed, storage_enums::IntentStatus::Processing, storage_enums::IntentStatus::RequiresCapture, storage_enums::IntentStatus::RequiresMerchantAction, storage_enums::IntentStatus::Succeeded, storage_enums::IntentStatus::PartiallyCaptured, storage_enums::IntentStatus::RequiresCustomerAction, ], ); if is_payment_link_terminal_state || payment_link_status == api_models::payments::PaymentLinkStatus::Expired { let status = match payment_link_status { api_models::payments::PaymentLinkStatus::Active => { logger::info!("displaying status page as the requested payment link has reached terminal state with payment status as {:?}", payment_intent.status); PaymentLinkStatusWrap::IntentStatus(payment_intent.status) } api_models::payments::PaymentLinkStatus::Expired => { if is_payment_link_terminal_state { logger::info!("displaying status page as the requested payment link has reached terminal state with payment status as {:?}", payment_intent.status); PaymentLinkStatusWrap::IntentStatus(payment_intent.status) } else { logger::info!( "displaying status page as the requested payment link has expired" ); PaymentLinkStatusWrap::PaymentLinkStatus( api_models::payments::PaymentLinkStatus::Expired, ) } } }; let attempt_id = payment_intent.active_attempt.get_id().clone(); let payment_attempt = db .find_payment_attempt_by_payment_id_merchant_id_attempt_id( &payment_intent.payment_id, &merchant_id, &attempt_id.clone(), merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let payment_details = api_models::payments::PaymentLinkStatusDetails { amount, currency, payment_id: payment_intent.payment_id, merchant_name, merchant_logo: payment_link_config.logo.clone(), created: payment_link.created_at, status, error_code: payment_attempt.error_code, error_message: payment_attempt.error_message, redirect: false, theme: payment_link_config.theme.clone(), return_url: return_url.clone(), locale: Some(state.clone().locale), transaction_details: payment_link_config.transaction_details.clone(), unified_code: payment_attempt.unified_code, unified_message: payment_attempt.unified_message, }; return Ok(( payment_link, PaymentLinkData::PaymentLinkStatusDetails(Box::new(payment_details)), payment_link_config, )); }; let payment_link_details = api_models::payments::PaymentLinkDetails { amount, currency, payment_id: payment_intent.payment_id, merchant_name, order_details, return_url, session_expiry, pub_key: merchant_account.publishable_key, client_secret, merchant_logo: payment_link_config.logo.clone(), max_items_visible_after_collapse: 3, theme: payment_link_config.theme.clone(), merchant_description: payment_intent.description, sdk_layout: payment_link_config.sdk_layout.clone(), display_sdk_only: payment_link_config.display_sdk_only, hide_card_nickname_field: payment_link_config.hide_card_nickname_field, show_card_form_by_default: payment_link_config.show_card_form_by_default, locale: Some(state.clone().locale), transaction_details: payment_link_config.transaction_details.clone(), background_image: payment_link_config.background_image.clone(), details_layout: payment_link_config.details_layout, branding_visibility: payment_link_config.branding_visibility, payment_button_text: payment_link_config.payment_button_text.clone(), custom_message_for_card_terms: payment_link_config.custom_message_for_card_terms.clone(), payment_button_colour: payment_link_config.payment_button_colour.clone(), skip_status_screen: payment_link_config.skip_status_screen, background_colour: payment_link_config.background_colour.clone(), payment_button_text_colour: payment_link_config.payment_button_text_colour.clone(), sdk_ui_rules: payment_link_config.sdk_ui_rules.clone(), payment_link_ui_rules: payment_link_config.payment_link_ui_rules.clone(), status: payment_intent.status, enable_button_only_on_form_ready: payment_link_config.enable_button_only_on_form_ready, }; Ok(( payment_link, PaymentLinkData::PaymentLinkDetails(Box::new(payment_link_details)), payment_link_config, )) } <file_sep path="hyperswitch/crates/api_models/src/errors/types.rs" role="context" start="86" end="100"> pub enum ApiErrorResponse { Unauthorized(ApiError), ForbiddenCommonResource(ApiError), ForbiddenPrivateResource(ApiError), Conflict(ApiError), Gone(ApiError), Unprocessable(ApiError), InternalServerError(ApiError), NotImplemented(ApiError), ConnectorError(ApiError, #[serde(skip_serializing)] StatusCode), NotFound(ApiError), MethodNotAllowed(ApiError), BadRequest(ApiError), DomainError(ApiError), }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payments/tokenization.rs<|crate|> router anchor=from kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/core/payments/tokenization.rs" role="context" start="57" end="65"> fn from(router_data: &types::RouterData<F, Req, types::PaymentsResponseData>) -> Self { Self { request: router_data.request.clone(), response: router_data.response.clone(), payment_method_token: router_data.payment_method_token.clone(), payment_method: router_data.payment_method, attempt_status: router_data.status, } } <file_sep path="hyperswitch/crates/router/src/core/payments/tokenization.rs" role="context" start="56" end="56"> use crate::{ consts, core::{ errors::{self, ConnectorErrorExt, RouterResult, StorageErrorExt}, mandate, payment_methods::{self, cards::create_encrypted_data, network_tokenization}, payments, }, logger, routes::{metrics, SessionState}, services, types::{ self, api::{self, CardDetailFromLocker, CardDetailsPaymentMethod, PaymentMethodCreateExt}, domain, storage::enums as storage_enums, }, utils::{generate_id, OptionExt}, }; <file_sep path="hyperswitch/crates/router/src/core/payments/tokenization.rs" role="context" start="800" end="817"> pub async fn save_payment_method<FData>( _state: &SessionState, _connector_name: String, _save_payment_method_data: SavePaymentMethodData<FData>, _customer_id: Option<id_type::CustomerId>, _merchant_account: &domain::MerchantAccount, _payment_method_type: Option<storage_enums::PaymentMethodType>, _key_store: &domain::MerchantKeyStore, _billing_name: Option<Secret<String>>, _payment_method_billing_address: Option<&api::Address>, _business_profile: &domain::Profile, _connector_mandate_request_reference_id: Option<String>, ) -> RouterResult<SavePaymentMethodDataResponse> where FData: mandate::MandateBehaviour + Clone, { todo!() } <file_sep path="hyperswitch/crates/router/src/core/payments/tokenization.rs" role="context" start="78" end="794"> pub async fn save_payment_method<FData>( state: &SessionState, connector_name: String, save_payment_method_data: SavePaymentMethodData<FData>, customer_id: Option<id_type::CustomerId>, merchant_account: &domain::MerchantAccount, payment_method_type: Option<storage_enums::PaymentMethodType>, key_store: &domain::MerchantKeyStore, billing_name: Option<Secret<String>>, payment_method_billing_address: Option<&hyperswitch_domain_models::address::Address>, business_profile: &domain::Profile, mut original_connector_mandate_reference_id: Option<ConnectorMandateReferenceId>, merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, ) -> RouterResult<SavePaymentMethodDataResponse> where FData: mandate::MandateBehaviour + Clone, { let mut pm_status = None; match save_payment_method_data.response { Ok(responses) => { let db = &*state.store; let token_store = state .conf .tokenization .0 .get(&connector_name.to_string()) .map(|token_filter| token_filter.long_lived_token) .unwrap_or(false); let network_transaction_id = match &responses { types::PaymentsResponseData::TransactionResponse { network_txn_id, .. } => { network_txn_id.clone() } _ => None, }; let network_transaction_id = if save_payment_method_data.request.get_setup_future_usage() == Some(storage_enums::FutureUsage::OffSession) { if network_transaction_id.is_some() { network_transaction_id } else { logger::info!("Skip storing network transaction id"); None } } else { None }; let connector_token = if token_store { let tokens = save_payment_method_data .payment_method_token .to_owned() .get_required_value("payment_token")?; let token = match tokens { types::PaymentMethodToken::Token(connector_token) => connector_token.expose(), types::PaymentMethodToken::ApplePayDecrypt(_) => { Err(errors::ApiErrorResponse::NotSupported { message: "Apple Pay Decrypt token is not supported".to_string(), })? } types::PaymentMethodToken::PazeDecrypt(_) => { Err(errors::ApiErrorResponse::NotSupported { message: "Paze Decrypt token is not supported".to_string(), })? } types::PaymentMethodToken::GooglePayDecrypt(_) => { Err(errors::ApiErrorResponse::NotSupported { message: "Google Pay Decrypt token is not supported".to_string(), })? } }; Some((connector_name, token)) } else { None }; let mandate_data_customer_acceptance = save_payment_method_data .request .get_setup_mandate_details() .and_then(|mandate_data| mandate_data.customer_acceptance.clone()); let customer_acceptance = save_payment_method_data .request .get_customer_acceptance() .or(mandate_data_customer_acceptance.clone().map(From::from)) .map(|ca| ca.encode_to_value()) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to serialize customer acceptance to value")?; let (connector_mandate_id, mandate_metadata, connector_mandate_request_reference_id) = match responses { types::PaymentsResponseData::TransactionResponse { mandate_reference, .. } => { if let Some(ref mandate_ref) = *mandate_reference { ( mandate_ref.connector_mandate_id.clone(), mandate_ref.mandate_metadata.clone(), mandate_ref.connector_mandate_request_reference_id.clone(), ) } else { (None, None, None) } } _ => (None, None, None), }; let pm_id = if customer_acceptance.is_some() { let payment_method_create_request = payment_methods::get_payment_method_create_request( Some(&save_payment_method_data.request.get_payment_method_data()), Some(save_payment_method_data.payment_method), payment_method_type, &customer_id.clone(), billing_name, payment_method_billing_address, ) .await?; let customer_id = customer_id.to_owned().get_required_value("customer_id")?; let merchant_id = merchant_account.get_id(); let is_network_tokenization_enabled = business_profile.is_network_tokenization_enabled; let ( (mut resp, duplication_check, network_token_requestor_ref_id), network_token_resp, ) = if !state.conf.locker.locker_enabled { let (res, dc) = skip_saving_card_in_locker( merchant_account, payment_method_create_request.to_owned(), ) .await?; ((res, dc, None), None) } else { pm_status = Some(common_enums::PaymentMethodStatus::from( save_payment_method_data.attempt_status, )); let (res, dc) = Box::pin(save_in_locker( state, merchant_account, payment_method_create_request.to_owned(), )) .await?; if is_network_tokenization_enabled { let pm_data = &save_payment_method_data.request.get_payment_method_data(); match pm_data { domain::PaymentMethodData::Card(card) => { let ( network_token_resp, _network_token_duplication_check, //the duplication check is discarded, since each card has only one token, handling card duplication check will be suffice network_token_requestor_ref_id, ) = Box::pin(save_network_token_in_locker( state, merchant_account, card, payment_method_create_request.clone(), )) .await?; ( (res, dc, network_token_requestor_ref_id), network_token_resp, ) } _ => ((res, dc, None), None), //network_token_resp is None in case of other payment methods } } else { ((res, dc, None), None) } }; let network_token_locker_id = match network_token_resp { Some(ref token_resp) => { if network_token_requestor_ref_id.is_some() { Some(token_resp.payment_method_id.clone()) } else { None } } None => None, }; let optional_pm_details = match ( resp.card.as_ref(), save_payment_method_data.request.get_payment_method_data(), ) { (Some(card), _) => Some(PaymentMethodsData::Card( CardDetailsPaymentMethod::from(card.clone()), )), ( _, domain::PaymentMethodData::Wallet(domain::WalletData::GooglePay(googlepay)), ) => Some(PaymentMethodsData::WalletDetails( PaymentMethodDataWalletInfo::from(googlepay), )), _ => None, }; let key_manager_state = state.into(); let pm_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>> = optional_pm_details .async_map(|pm| create_encrypted_data(&key_manager_state, key_store, pm)) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt payment method data")?; let pm_network_token_data_encrypted: Option< Encryptable<Secret<serde_json::Value>>, > = match network_token_resp { Some(token_resp) => { let pm_token_details = token_resp.card.as_ref().map(|card| { PaymentMethodsData::Card(CardDetailsPaymentMethod::from(card.clone())) }); pm_token_details .async_map(|pm_card| { create_encrypted_data(&key_manager_state, key_store, pm_card) }) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt payment method data")? } None => None, }; let encrypted_payment_method_billing_address: Option< Encryptable<Secret<serde_json::Value>>, > = payment_method_billing_address .async_map(|address| { create_encrypted_data(&key_manager_state, key_store, address.clone()) }) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt payment method billing address")?; let mut payment_method_id = resp.payment_method_id.clone(); let mut locker_id = None; match duplication_check { Some(duplication_check) => match duplication_check { payment_methods::transformers::DataDuplicationCheck::Duplicated => { let payment_method = { let existing_pm_by_pmid = db .find_payment_method( &(state.into()), key_store, &payment_method_id, merchant_account.storage_scheme, ) .await; if let Err(err) = existing_pm_by_pmid { if err.current_context().is_db_not_found() { locker_id = Some(payment_method_id.clone()); let existing_pm_by_locker_id = db .find_payment_method_by_locker_id( &(state.into()), key_store, &payment_method_id, merchant_account.storage_scheme, ) .await; match &existing_pm_by_locker_id { Ok(pm) => { payment_method_id.clone_from(&pm.payment_method_id); } Err(_) => { payment_method_id = generate_id(consts::ID_LENGTH, "pm") } }; existing_pm_by_locker_id } else { Err(err) } } else { existing_pm_by_pmid } }; resp.payment_method_id = payment_method_id; match payment_method { Ok(pm) => { let pm_metadata = create_payment_method_metadata( pm.metadata.as_ref(), connector_token, )?; payment_methods::cards::update_payment_method_metadata_and_last_used( state, key_store, db, pm.clone(), pm_metadata, merchant_account.storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to add payment method in db")?; } Err(err) => { if err.current_context().is_db_not_found() { let pm_metadata = create_payment_method_metadata(None, connector_token)?; payment_methods::cards::create_payment_method( state, &payment_method_create_request, &customer_id, &resp.payment_method_id, locker_id, merchant_id, pm_metadata, customer_acceptance, pm_data_encrypted, key_store, None, pm_status, network_transaction_id, merchant_account.storage_scheme, encrypted_payment_method_billing_address, resp.card.and_then(|card| { card.card_network .map(|card_network| card_network.to_string()) }), network_token_requestor_ref_id, network_token_locker_id, pm_network_token_data_encrypted, ) .await } else { Err(err) .change_context( errors::ApiErrorResponse::InternalServerError, ) .attach_printable("Error while finding payment method") }?; } }; } payment_methods::transformers::DataDuplicationCheck::MetaDataChanged => { if let Some(card) = payment_method_create_request.card.clone() { let payment_method = { let existing_pm_by_pmid = db .find_payment_method( &(state.into()), key_store, &payment_method_id, merchant_account.storage_scheme, ) .await; if let Err(err) = existing_pm_by_pmid { if err.current_context().is_db_not_found() { locker_id = Some(payment_method_id.clone()); let existing_pm_by_locker_id = db .find_payment_method_by_locker_id( &(state.into()), key_store, &payment_method_id, merchant_account.storage_scheme, ) .await; match &existing_pm_by_locker_id { Ok(pm) => { payment_method_id .clone_from(&pm.payment_method_id); } Err(_) => { payment_method_id = generate_id(consts::ID_LENGTH, "pm") } }; existing_pm_by_locker_id } else { Err(err) } } else { existing_pm_by_pmid } }; resp.payment_method_id = payment_method_id; let existing_pm = match payment_method { Ok(pm) => { let mandate_details = pm .connector_mandate_details .clone() .map(|val| { val.parse_value::<PaymentsMandateReference>( "PaymentsMandateReference", ) }) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to deserialize to Payment Mandate Reference ")?; if let Some((mandate_details, merchant_connector_id)) = mandate_details.zip(merchant_connector_id) { let connector_mandate_details = update_connector_mandate_details_status( merchant_connector_id, mandate_details, ConnectorMandateStatus::Inactive, )?; payment_methods::cards::update_payment_method_connector_mandate_details( state, key_store, db, pm.clone(), connector_mandate_details, merchant_account.storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to add payment method in db")?; } Ok(pm) } Err(err) => { if err.current_context().is_db_not_found() { payment_methods::cards::create_payment_method( state, &payment_method_create_request, &customer_id, &resp.payment_method_id, locker_id, merchant_id, resp.metadata.clone().map(|val| val.expose()), customer_acceptance, pm_data_encrypted, key_store, None, pm_status, network_transaction_id, merchant_account.storage_scheme, encrypted_payment_method_billing_address, resp.card.and_then(|card| { card.card_network.map(|card_network| { card_network.to_string() }) }), network_token_requestor_ref_id, network_token_locker_id, pm_network_token_data_encrypted, ) .await } else { Err(err) .change_context( errors::ApiErrorResponse::InternalServerError, ) .attach_printable( "Error while finding payment method", ) } } }?; payment_methods::cards::delete_card_from_locker( state, &customer_id, merchant_id, existing_pm .locker_id .as_ref() .unwrap_or(&existing_pm.payment_method_id), ) .await?; let add_card_resp = payment_methods::cards::add_card_hs( state, payment_method_create_request, &card, &customer_id, merchant_account, api::enums::LockerChoice::HyperswitchCardVault, Some( existing_pm .locker_id .as_ref() .unwrap_or(&existing_pm.payment_method_id), ), ) .await; if let Err(err) = add_card_resp { logger::error!(vault_err=?err); db.delete_payment_method_by_merchant_id_payment_method_id( &(state.into()), key_store, merchant_id, &resp.payment_method_id, ) .await .to_not_found_response( errors::ApiErrorResponse::PaymentMethodNotFound, )?; Err(report!(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Failed while updating card metadata changes", ))? }; let existing_pm_data = payment_methods::cards::get_card_details_without_locker_fallback(&existing_pm,state) .await?; // scheme should be updated in case of co-badged cards let card_scheme = card .card_network .clone() .map(|card_network| card_network.to_string()) .or(existing_pm_data.scheme.clone()); let updated_card = Some(CardDetailFromLocker { scheme: card_scheme.clone(), last4_digits: Some(card.card_number.get_last4()), issuer_country: card .card_issuing_country .or(existing_pm_data.issuer_country), card_isin: Some(card.card_number.get_card_isin()), card_number: Some(card.card_number), expiry_month: Some(card.card_exp_month), expiry_year: Some(card.card_exp_year), card_token: None, card_fingerprint: None, card_holder_name: card .card_holder_name .or(existing_pm_data.card_holder_name), nick_name: card.nick_name.or(existing_pm_data.nick_name), card_network: card .card_network .or(existing_pm_data.card_network), card_issuer: card.card_issuer.or(existing_pm_data.card_issuer), card_type: card.card_type.or(existing_pm_data.card_type), saved_to_locker: true, }); let updated_pmd = updated_card.as_ref().map(|card| { PaymentMethodsData::Card(CardDetailsPaymentMethod::from( card.clone(), )) }); let pm_data_encrypted: Option< Encryptable<Secret<serde_json::Value>>, > = updated_pmd .async_map(|pmd| { create_encrypted_data(&key_manager_state, key_store, pmd) }) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt payment method data")?; payment_methods::cards::update_payment_method_and_last_used( state, key_store, db, existing_pm, pm_data_encrypted.map(Into::into), merchant_account.storage_scheme, card_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to add payment method in db")?; } } }, None => { let customer_saved_pm_option = if payment_method_type .map(|payment_method_type_value| { payment_method_type_value .should_check_for_customer_saved_payment_method_type() }) .unwrap_or(false) { match state .store .find_payment_method_by_customer_id_merchant_id_list( &(state.into()), key_store, &customer_id, merchant_id, None, ) .await { Ok(customer_payment_methods) => Ok(customer_payment_methods .iter() .find(|payment_method| { payment_method.get_payment_method_subtype() == payment_method_type }) .cloned()), Err(error) => { if error.current_context().is_db_not_found() { Ok(None) } else { Err(error) .change_context( errors::ApiErrorResponse::InternalServerError, ) .attach_printable( "failed to find payment methods for a customer", ) } } } } else { Ok(None) }?; if let Some(customer_saved_pm) = customer_saved_pm_option { payment_methods::cards::update_last_used_at( &customer_saved_pm, state, merchant_account.storage_scheme, key_store, ) .await .map_err(|e| { logger::error!("Failed to update last used at: {:?}", e); }) .ok(); resp.payment_method_id = customer_saved_pm.payment_method_id; } else { let pm_metadata = create_payment_method_metadata(None, connector_token)?; locker_id = resp.payment_method.and_then(|pm| { if pm == PaymentMethod::Card { Some(resp.payment_method_id) } else { None } }); resp.payment_method_id = generate_id(consts::ID_LENGTH, "pm"); payment_methods::cards::create_payment_method( state, &payment_method_create_request, &customer_id, &resp.payment_method_id, locker_id, merchant_id, pm_metadata, customer_acceptance, pm_data_encrypted, key_store, None, pm_status, network_transaction_id, merchant_account.storage_scheme, encrypted_payment_method_billing_address, resp.card.and_then(|card| { card.card_network .map(|card_network| card_network.to_string()) }), network_token_requestor_ref_id, network_token_locker_id, pm_network_token_data_encrypted, ) .await?; }; } } Some(resp.payment_method_id) } else { None }; // check if there needs to be a config if yes then remove it to a different place let connector_mandate_reference_id = if connector_mandate_id.is_some() { if let Some(ref mut record) = original_connector_mandate_reference_id { record.update( connector_mandate_id, None, None, mandate_metadata, connector_mandate_request_reference_id, ); Some(record.clone()) } else { Some(ConnectorMandateReferenceId::new( connector_mandate_id, None, None, mandate_metadata, connector_mandate_request_reference_id, )) } } else { None }; Ok(SavePaymentMethodDataResponse { payment_method_id: pm_id, payment_method_status: pm_status, connector_mandate_reference_id, }) } Err(_) => Ok(SavePaymentMethodDataResponse { payment_method_id: None, payment_method_status: None, connector_mandate_reference_id: None, }), } } <file_sep path="hyperswitch/crates/router/src/core/payments/tokenization.rs" role="context" start="1006" end="1076"> pub async fn save_network_token_in_locker( state: &SessionState, merchant_account: &domain::MerchantAccount, card_data: &domain::Card, payment_method_request: api::PaymentMethodCreate, ) -> RouterResult<( Option<api_models::payment_methods::PaymentMethodResponse>, Option<payment_methods::transformers::DataDuplicationCheck>, Option<String>, )> { let customer_id = payment_method_request .customer_id .clone() .get_required_value("customer_id")?; let network_tokenization_supported_card_networks = &state .conf .network_tokenization_supported_card_networks .card_networks; if card_data .card_network .as_ref() .filter(|cn| network_tokenization_supported_card_networks.contains(cn)) .is_some() { let optional_card_cvc = Some(card_data.card_cvc.clone()); match network_tokenization::make_card_network_tokenization_request( state, &domain::CardDetail::from(card_data), optional_card_cvc, &customer_id, ) .await { Ok((token_response, network_token_requestor_ref_id)) => { // Only proceed if the tokenization was successful let network_token_data = api::CardDetail { card_number: token_response.token.clone(), card_exp_month: token_response.token_expiry_month.clone(), card_exp_year: token_response.token_expiry_year.clone(), card_holder_name: None, nick_name: None, card_issuing_country: None, card_network: Some(token_response.card_brand.clone()), card_issuer: None, card_type: None, }; let (res, dc) = Box::pin(payment_methods::cards::add_card_to_locker( state, payment_method_request, &network_token_data, &customer_id, merchant_account, None, )) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Add Network Token Failed")?; Ok((Some(res), dc, network_token_requestor_ref_id)) } Err(err) => { logger::error!("Failed to tokenize card: {:?}", err); Ok((None, None, None)) //None will be returned in case of error when calling network tokenization service } } } else { Ok((None, None, None)) //None will be returned in case of unsupported card network. } } <file_sep path="hyperswitch/crates/router/src/connector/utils.rs" role="context" start="82" end="146"> pub trait RouterData { fn get_billing(&self) -> Result<&hyperswitch_domain_models::address::Address, Error>; fn get_billing_country(&self) -> Result<api_models::enums::CountryAlpha2, Error>; fn get_billing_phone(&self) -> Result<&hyperswitch_domain_models::address::PhoneDetails, Error>; fn get_description(&self) -> Result<String, Error>; fn get_billing_address( &self, ) -> Result<&hyperswitch_domain_models::address::AddressDetails, Error>; fn get_shipping_address( &self, ) -> Result<&hyperswitch_domain_models::address::AddressDetails, Error>; fn get_shipping_address_with_phone_number( &self, ) -> Result<&hyperswitch_domain_models::address::Address, Error>; fn get_connector_meta(&self) -> Result<pii::SecretSerdeValue, Error>; fn get_session_token(&self) -> Result<String, Error>; fn get_billing_first_name(&self) -> Result<Secret<String>, Error>; fn get_billing_full_name(&self) -> Result<Secret<String>, Error>; fn get_billing_last_name(&self) -> Result<Secret<String>, Error>; fn get_billing_line1(&self) -> Result<Secret<String>, Error>; fn get_billing_city(&self) -> Result<String, Error>; fn get_billing_email(&self) -> Result<Email, Error>; fn get_billing_phone_number(&self) -> Result<Secret<String>, Error>; fn to_connector_meta<T>(&self) -> Result<T, Error> where T: serde::de::DeserializeOwned; fn is_three_ds(&self) -> bool; fn get_payment_method_token(&self) -> Result<types::PaymentMethodToken, Error>; fn get_customer_id(&self) -> Result<id_type::CustomerId, Error>; fn get_connector_customer_id(&self) -> Result<String, Error>; fn get_preprocessing_id(&self) -> Result<String, Error>; fn get_recurring_mandate_payment_data( &self, ) -> Result<types::RecurringMandatePaymentData, Error>; #[cfg(feature = "payouts")] fn get_payout_method_data(&self) -> Result<api::PayoutMethodData, Error>; #[cfg(feature = "payouts")] fn get_quote_id(&self) -> Result<String, Error>; fn get_optional_billing(&self) -> Option<&hyperswitch_domain_models::address::Address>; fn get_optional_shipping(&self) -> Option<&hyperswitch_domain_models::address::Address>; fn get_optional_shipping_line1(&self) -> Option<Secret<String>>; fn get_optional_shipping_line2(&self) -> Option<Secret<String>>; fn get_optional_shipping_city(&self) -> Option<String>; fn get_optional_shipping_country(&self) -> Option<enums::CountryAlpha2>; fn get_optional_shipping_zip(&self) -> Option<Secret<String>>; fn get_optional_shipping_state(&self) -> Option<Secret<String>>; fn get_optional_shipping_first_name(&self) -> Option<Secret<String>>; fn get_optional_shipping_last_name(&self) -> Option<Secret<String>>; fn get_optional_shipping_phone_number(&self) -> Option<Secret<String>>; fn get_optional_shipping_email(&self) -> Option<Email>; fn get_optional_billing_full_name(&self) -> Option<Secret<String>>; fn get_optional_billing_line1(&self) -> Option<Secret<String>>; fn get_optional_billing_line2(&self) -> Option<Secret<String>>; fn get_optional_billing_city(&self) -> Option<String>; fn get_optional_billing_country(&self) -> Option<enums::CountryAlpha2>; fn get_optional_billing_zip(&self) -> Option<Secret<String>>; fn get_optional_billing_state(&self) -> Option<Secret<String>>; fn get_optional_billing_first_name(&self) -> Option<Secret<String>>; fn get_optional_billing_last_name(&self) -> Option<Secret<String>>; fn get_optional_billing_phone_number(&self) -> Option<Secret<String>>; fn get_optional_billing_email(&self) -> Option<Email>; } <file_sep path="hyperswitch/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/event.test.js" role="context" start="61" end="78"> "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.", ); } // Response body should have value "succeeded" for "status" if (jsonData?.status) { pm.test( "[POST]::/payments - Content check if value for 'status' matches 'succeeded'", function () { pm.expect(jsonData.status).to.eql("succeeded"); }, ); }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payments/flows/setup_mandate_flow.rs<|crate|> router anchor=create_connector_customer kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/core/payments/flows/setup_mandate_flow.rs" role="context" start="188" end="200"> async fn create_connector_customer<'a>( &self, state: &SessionState, connector: &api::ConnectorData, ) -> RouterResult<Option<String>> { customers::create_connector_customer( state, connector, self, types::ConnectorCustomerData::try_from(self.request.to_owned())?, ) .await } <file_sep path="hyperswitch/crates/router/src/core/payments/flows/setup_mandate_flow.rs" role="context" start="187" end="187"> use crate::{ core::{ errors::{ConnectorErrorExt, RouterResult}, mandate, payments::{ self, access_token, customers, helpers, tokenization, transformers, PaymentData, }, }, routes::SessionState, services, types::{self, api, domain}, }; <file_sep path="hyperswitch/crates/router/src/core/payments/flows/setup_mandate_flow.rs" role="context" start="229" end="231"> fn get_amount(&self) -> i64 { 0 } <file_sep path="hyperswitch/crates/router/src/core/payments/flows/setup_mandate_flow.rs" role="context" start="202" end="225"> async fn build_flow_specific_connector_request( &mut self, state: &SessionState, connector: &api::ConnectorData, call_connector_action: payments::CallConnectorAction, ) -> RouterResult<(Option<services::Request>, bool)> { match call_connector_action { payments::CallConnectorAction::Trigger => { let connector_integration: services::BoxedPaymentConnectorIntegrationInterface< api::SetupMandate, types::SetupMandateRequestData, types::PaymentsResponseData, > = connector.connector.get_connector_integration(); Ok(( connector_integration .build_request(self, &state.conf.connectors) .to_payment_failed_response()?, true, )) } _ => Ok((None, true)), } } <file_sep path="hyperswitch/crates/router/src/core/payments/flows/setup_mandate_flow.rs" role="context" start="169" end="186"> async fn add_payment_method_token<'a>( &mut self, state: &SessionState, connector: &api::ConnectorData, tokenization_action: &payments::TokenizationAction, should_continue_payment: bool, ) -> RouterResult<types::PaymentMethodTokenResult> { let request = self.request.clone(); tokenization::add_payment_method_token( state, connector, tokenization_action, self, types::PaymentMethodTokenizationData::try_from(request)?, should_continue_payment, ) .await } <file_sep path="hyperswitch/crates/router/src/core/payments/flows/setup_mandate_flow.rs" role="context" start="158" end="167"> async fn add_access_token<'a>( &self, state: &SessionState, connector: &api::ConnectorData, merchant_account: &domain::MerchantAccount, creds_identifier: Option<&str>, ) -> RouterResult<types::AddAccessTokenResult> { access_token::add_access_token(state, connector, merchant_account, self, creds_identifier) .await } <file_sep path="hyperswitch/crates/router/src/core/errors.rs" role="context" start="31" end="31"> pub type RouterResult<T> = CustomResult<T, ApiErrorResponse>; <file_sep path="hyperswitch/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/event.test.js" role="context" start="61" end="78"> "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.", ); } // Response body should have value "succeeded" for "status" if (jsonData?.status) { pm.test( "[POST]::/payments - Content check if value for 'status' matches 'succeeded'", function () { pm.expect(jsonData.status).to.eql("succeeded"); }, ); }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payments/flows/setup_mandate_flow.rs<|crate|> router anchor=create_connector_customer kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/core/payments/flows/setup_mandate_flow.rs" role="context" start="188" end="200"> async fn create_connector_customer<'a>( &self, state: &SessionState, connector: &api::ConnectorData, ) -> RouterResult<Option<String>> { customers::create_connector_customer( state, connector, self, types::ConnectorCustomerData::try_from(self.request.to_owned())?, ) .await } <file_sep path="hyperswitch/crates/router/src/core/payments/flows/setup_mandate_flow.rs" role="context" start="187" end="187"> use crate::{ core::{ errors::{ConnectorErrorExt, RouterResult}, mandate, payments::{ self, access_token, customers, helpers, tokenization, transformers, PaymentData, }, }, routes::SessionState, services, types::{self, api, domain}, }; <file_sep path="hyperswitch/crates/router/src/core/payments/flows/setup_mandate_flow.rs" role="context" start="229" end="231"> fn get_amount(&self) -> i64 { 0 } <file_sep path="hyperswitch/crates/router/src/core/payments/flows/setup_mandate_flow.rs" role="context" start="202" end="225"> async fn build_flow_specific_connector_request( &mut self, state: &SessionState, connector: &api::ConnectorData, call_connector_action: payments::CallConnectorAction, ) -> RouterResult<(Option<services::Request>, bool)> { match call_connector_action { payments::CallConnectorAction::Trigger => { let connector_integration: services::BoxedPaymentConnectorIntegrationInterface< api::SetupMandate, types::SetupMandateRequestData, types::PaymentsResponseData, > = connector.connector.get_connector_integration(); Ok(( connector_integration .build_request(self, &state.conf.connectors) .to_payment_failed_response()?, true, )) } _ => Ok((None, true)), } } <file_sep path="hyperswitch/crates/router/src/core/payments/flows/setup_mandate_flow.rs" role="context" start="169" end="186"> async fn add_payment_method_token<'a>( &mut self, state: &SessionState, connector: &api::ConnectorData, tokenization_action: &payments::TokenizationAction, should_continue_payment: bool, ) -> RouterResult<types::PaymentMethodTokenResult> { let request = self.request.clone(); tokenization::add_payment_method_token( state, connector, tokenization_action, self, types::PaymentMethodTokenizationData::try_from(request)?, should_continue_payment, ) .await } <file_sep path="hyperswitch/crates/router/src/core/payments/flows/setup_mandate_flow.rs" role="context" start="158" end="167"> async fn add_access_token<'a>( &self, state: &SessionState, connector: &api::ConnectorData, merchant_account: &domain::MerchantAccount, creds_identifier: Option<&str>, ) -> RouterResult<types::AddAccessTokenResult> { access_token::add_access_token(state, connector, merchant_account, self, creds_identifier) .await } <file_sep path="hyperswitch/crates/router/src/core/errors.rs" role="context" start="31" end="31"> pub type RouterResult<T> = CustomResult<T, ApiErrorResponse>;
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payment_link.rs<|crate|> router anchor=check_payment_link_status kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/src/core/payment_link.rs" role="context" start="525" end="535"> pub fn check_payment_link_status( payment_link_expiry: PrimitiveDateTime, ) -> api_models::payments::PaymentLinkStatus { let curr_time = common_utils::date_time::now(); if curr_time > payment_link_expiry { api_models::payments::PaymentLinkStatus::Expired } else { api_models::payments::PaymentLinkStatus::Active } } <file_sep path="hyperswitch/crates/router/src/core/payment_link.rs" role="context" start="524" end="524"> use api_models::{ admin::PaymentLinkConfig, payments::{PaymentLinkData, PaymentLinkStatusWrap}, }; use common_utils::{ consts::{DEFAULT_LOCALE, DEFAULT_SESSION_EXPIRY}, ext_traits::{OptionExt, ValueExt}, types::{AmountConvertor, StringMajorUnitForCore}, }; use time::PrimitiveDateTime; use super::{ errors::{self, RouterResult, StorageErrorExt}, payments::helpers, }; <file_sep path="hyperswitch/crates/router/src/core/payment_link.rs" role="context" start="593" end="601"> pub fn extract_payment_link_config( pl_config: serde_json::Value, ) -> Result<PaymentLinkConfig, error_stack::Report<errors::ApiErrorResponse>> { serde_json::from_value::<PaymentLinkConfig>(pl_config).change_context( errors::ApiErrorResponse::InvalidDataValue { field_name: "payment_link_config", }, ) } <file_sep path="hyperswitch/crates/router/src/core/payment_link.rs" role="context" start="537" end="591"> fn validate_order_details( order_details: Option<Vec<Secret<serde_json::Value>>>, currency: api_models::enums::Currency, ) -> Result< Option<Vec<api_models::payments::OrderDetailsWithStringAmount>>, error_stack::Report<errors::ApiErrorResponse>, > { let required_conversion_type = StringMajorUnitForCore; let order_details = order_details .map(|order_details| { order_details .iter() .map(|data| { data.to_owned() .parse_value("OrderDetailsWithAmount") .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "OrderDetailsWithAmount", }) .attach_printable("Unable to parse OrderDetailsWithAmount") }) .collect::<Result<Vec<api_models::payments::OrderDetailsWithAmount>, _>>() }) .transpose()?; let updated_order_details = match order_details { Some(mut order_details) => { let mut order_details_amount_string_array: Vec< api_models::payments::OrderDetailsWithStringAmount, > = Vec::new(); for order in order_details.iter_mut() { let mut order_details_amount_string : api_models::payments::OrderDetailsWithStringAmount = Default::default(); if order.product_img_link.is_none() { order_details_amount_string.product_img_link = Some(DEFAULT_PRODUCT_IMG.to_string()) } else { order_details_amount_string .product_img_link .clone_from(&order.product_img_link) }; order_details_amount_string.amount = required_conversion_type .convert(order.amount, currency) .change_context(errors::ApiErrorResponse::AmountConversionFailed { amount_type: "StringMajorUnit", })?; order_details_amount_string.product_name = capitalize_first_char(&order.product_name.clone()); order_details_amount_string.quantity = order.quantity; order_details_amount_string_array.push(order_details_amount_string) } Some(order_details_amount_string_array) } None => None, }; Ok(updated_order_details) } <file_sep path="hyperswitch/crates/router/src/core/payment_link.rs" role="context" start="507" end="523"> pub async fn list_payment_link( state: SessionState, merchant: domain::MerchantAccount, constraints: api_models::payments::PaymentLinkListConstraints, ) -> RouterResponse<Vec<api_models::payments::RetrievePaymentLinkResponse>> { let db = state.store.as_ref(); let payment_link = db .list_payment_link_by_merchant_id(merchant.get_id(), constraints) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to retrieve payment link")?; let payment_link_list = future::try_join_all(payment_link.into_iter().map(|payment_link| { api_models::payments::RetrievePaymentLinkResponse::from_db_payment_link(payment_link) })) .await?; Ok(services::ApplicationResponse::Json(payment_link_list)) } <file_sep path="hyperswitch/crates/router/src/core/payment_link.rs" role="context" start="493" end="505"> fn validate_sdk_requirements( currency: Option<api_models::enums::Currency>, client_secret: Option<String>, ) -> Result<(api_models::enums::Currency, String), errors::ApiErrorResponse> { let currency = currency.ok_or(errors::ApiErrorResponse::MissingRequiredField { field_name: "currency", })?; let client_secret = client_secret.ok_or(errors::ApiErrorResponse::MissingRequiredField { field_name: "client_secret", })?; Ok((currency, client_secret)) } <file_sep path="hyperswitch/crates/router/src/core/payment_link.rs" role="context" start="42" end="64"> pub async fn retrieve_payment_link( state: SessionState, payment_link_id: String, ) -> RouterResponse<api_models::payments::RetrievePaymentLinkResponse> { let db = &*state.store; let payment_link_config = db .find_payment_link_by_payment_link_id(&payment_link_id) .await .to_not_found_response(errors::ApiErrorResponse::PaymentLinkNotFound)?; let session_expiry = payment_link_config.fulfilment_time.unwrap_or_else(|| { common_utils::date_time::now() .saturating_add(time::Duration::seconds(DEFAULT_SESSION_EXPIRY)) }); let status = check_payment_link_status(session_expiry); let response = api_models::payments::RetrievePaymentLinkResponse::foreign_from(( payment_link_config, status, )); Ok(services::ApplicationResponse::Json(response)) } <file_sep path="hyperswitch/crates/router/src/core/payment_link.rs" role="context" start="78" end="306"> pub async fn form_payment_link_data( state: &SessionState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, merchant_id: common_utils::id_type::MerchantId, payment_id: common_utils::id_type::PaymentId, ) -> RouterResult<(PaymentLink, PaymentLinkData, PaymentLinkConfig)> { let db = &*state.store; let key_manager_state = &state.into(); let payment_intent = db .find_payment_intent_by_payment_id_merchant_id( &(state).into(), &payment_id, &merchant_id, &key_store, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let payment_link_id = payment_intent .payment_link_id .get_required_value("payment_link_id") .change_context(errors::ApiErrorResponse::PaymentLinkNotFound)?; let merchant_name_from_merchant_account = merchant_account .merchant_name .clone() .map(|merchant_name| merchant_name.into_inner().peek().to_owned()) .unwrap_or_default(); let payment_link = db .find_payment_link_by_payment_link_id(&payment_link_id) .await .to_not_found_response(errors::ApiErrorResponse::PaymentLinkNotFound)?; let payment_link_config = if let Some(pl_config_value) = payment_link.payment_link_config.clone() { extract_payment_link_config(pl_config_value)? } else { PaymentLinkConfig { theme: DEFAULT_BACKGROUND_COLOR.to_string(), logo: DEFAULT_MERCHANT_LOGO.to_string(), seller_name: merchant_name_from_merchant_account, sdk_layout: DEFAULT_SDK_LAYOUT.to_owned(), display_sdk_only: DEFAULT_DISPLAY_SDK_ONLY, enabled_saved_payment_method: DEFAULT_ENABLE_SAVED_PAYMENT_METHOD, hide_card_nickname_field: DEFAULT_HIDE_CARD_NICKNAME_FIELD, show_card_form_by_default: DEFAULT_SHOW_CARD_FORM, allowed_domains: DEFAULT_ALLOWED_DOMAINS, transaction_details: None, background_image: None, details_layout: None, branding_visibility: None, payment_button_text: None, custom_message_for_card_terms: None, payment_button_colour: None, skip_status_screen: None, background_colour: None, payment_button_text_colour: None, sdk_ui_rules: None, payment_link_ui_rules: None, enable_button_only_on_form_ready: DEFAULT_ENABLE_BUTTON_ONLY_ON_FORM_READY, } }; let profile_id = payment_link .profile_id .clone() .or(payment_intent.profile_id) .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("Profile id missing in payment link and payment intent")?; let business_profile = db .find_business_profile_by_profile_id(key_manager_state, &key_store, &profile_id) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; let return_url = if let Some(payment_create_return_url) = payment_intent.return_url.clone() { payment_create_return_url } else { business_profile .return_url .ok_or(errors::ApiErrorResponse::MissingRequiredField { field_name: "return_url", })? }; let (currency, client_secret) = validate_sdk_requirements( payment_intent.currency, payment_intent.client_secret.clone(), )?; let required_conversion_type = StringMajorUnitForCore; let amount = required_conversion_type .convert(payment_intent.amount, currency) .change_context(errors::ApiErrorResponse::AmountConversionFailed { amount_type: "StringMajorUnit", })?; let order_details = validate_order_details(payment_intent.order_details.clone(), currency)?; let session_expiry = payment_link.fulfilment_time.unwrap_or_else(|| { payment_intent .created_at .saturating_add(time::Duration::seconds(DEFAULT_SESSION_EXPIRY)) }); // converting first letter of merchant name to upperCase let merchant_name = capitalize_first_char(&payment_link_config.seller_name); let payment_link_status = check_payment_link_status(session_expiry); let is_payment_link_terminal_state = check_payment_link_invalid_conditions( payment_intent.status, &[ storage_enums::IntentStatus::Cancelled, storage_enums::IntentStatus::Failed, storage_enums::IntentStatus::Processing, storage_enums::IntentStatus::RequiresCapture, storage_enums::IntentStatus::RequiresMerchantAction, storage_enums::IntentStatus::Succeeded, storage_enums::IntentStatus::PartiallyCaptured, storage_enums::IntentStatus::RequiresCustomerAction, ], ); if is_payment_link_terminal_state || payment_link_status == api_models::payments::PaymentLinkStatus::Expired { let status = match payment_link_status { api_models::payments::PaymentLinkStatus::Active => { logger::info!("displaying status page as the requested payment link has reached terminal state with payment status as {:?}", payment_intent.status); PaymentLinkStatusWrap::IntentStatus(payment_intent.status) } api_models::payments::PaymentLinkStatus::Expired => { if is_payment_link_terminal_state { logger::info!("displaying status page as the requested payment link has reached terminal state with payment status as {:?}", payment_intent.status); PaymentLinkStatusWrap::IntentStatus(payment_intent.status) } else { logger::info!( "displaying status page as the requested payment link has expired" ); PaymentLinkStatusWrap::PaymentLinkStatus( api_models::payments::PaymentLinkStatus::Expired, ) } } }; let attempt_id = payment_intent.active_attempt.get_id().clone(); let payment_attempt = db .find_payment_attempt_by_payment_id_merchant_id_attempt_id( &payment_intent.payment_id, &merchant_id, &attempt_id.clone(), merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let payment_details = api_models::payments::PaymentLinkStatusDetails { amount, currency, payment_id: payment_intent.payment_id, merchant_name, merchant_logo: payment_link_config.logo.clone(), created: payment_link.created_at, status, error_code: payment_attempt.error_code, error_message: payment_attempt.error_message, redirect: false, theme: payment_link_config.theme.clone(), return_url: return_url.clone(), locale: Some(state.clone().locale), transaction_details: payment_link_config.transaction_details.clone(), unified_code: payment_attempt.unified_code, unified_message: payment_attempt.unified_message, }; return Ok(( payment_link, PaymentLinkData::PaymentLinkStatusDetails(Box::new(payment_details)), payment_link_config, )); }; let payment_link_details = api_models::payments::PaymentLinkDetails { amount, currency, payment_id: payment_intent.payment_id, merchant_name, order_details, return_url, session_expiry, pub_key: merchant_account.publishable_key, client_secret, merchant_logo: payment_link_config.logo.clone(), max_items_visible_after_collapse: 3, theme: payment_link_config.theme.clone(), merchant_description: payment_intent.description, sdk_layout: payment_link_config.sdk_layout.clone(), display_sdk_only: payment_link_config.display_sdk_only, hide_card_nickname_field: payment_link_config.hide_card_nickname_field, show_card_form_by_default: payment_link_config.show_card_form_by_default, locale: Some(state.clone().locale), transaction_details: payment_link_config.transaction_details.clone(), background_image: payment_link_config.background_image.clone(), details_layout: payment_link_config.details_layout, branding_visibility: payment_link_config.branding_visibility, payment_button_text: payment_link_config.payment_button_text.clone(), custom_message_for_card_terms: payment_link_config.custom_message_for_card_terms.clone(), payment_button_colour: payment_link_config.payment_button_colour.clone(), skip_status_screen: payment_link_config.skip_status_screen, background_colour: payment_link_config.background_colour.clone(), payment_button_text_colour: payment_link_config.payment_button_text_colour.clone(), sdk_ui_rules: payment_link_config.sdk_ui_rules.clone(), payment_link_ui_rules: payment_link_config.payment_link_ui_rules.clone(), status: payment_intent.status, enable_button_only_on_form_ready: payment_link_config.enable_button_only_on_form_ready, }; Ok(( payment_link, PaymentLinkData::PaymentLinkDetails(Box::new(payment_link_details)), payment_link_config, )) }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/core/fraud_check.rs<|crate|> router anchor=from kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/core/fraud_check.rs" role="context" start="770" end="778"> fn from(payment_data: PaymentToFrmData) -> Self { Self { amount: common_utils::types::MinorUnit::from(payment_data.amount).get_amount_as_i64(), currency: payment_data.payment_attempt.currency, payment_method: payment_data.payment_attempt.payment_method, payment_method_type: payment_data.payment_attempt.payment_method_type, refund_transaction_id: None, } } <file_sep path="hyperswitch/crates/router/src/core/fraud_check.rs" role="context" start="769" end="769"> use self::{ flows::{self as frm_flows, FeatureFrm}, types::{ self as frm_core_types, ConnectorDetailsCore, FrmConfigsObject, FrmData, FrmInfo, PaymentDetails, PaymentToFrmData, }, }; use crate::{ core::{ errors::{self, RouterResult}, payments::{self, flows::ConstructFlowSpecificData, operations::BoxedOperation}, }, db::StorageInterface, routes::{app::ReqState, SessionState}, services, types::{ self as oss_types, api::{ fraud_check as frm_api, routing::FrmRoutingAlgorithm, Connector, FraudCheckConnectorData, Fulfillment, }, domain, fraud_check as frm_types, storage::{ enums::{ AttemptStatus, FraudCheckLastStep, FraudCheckStatus, FraudCheckType, FrmSuggestion, IntentStatus, }, fraud_check::{FraudCheck, FraudCheckUpdate}, PaymentIntent, }, }, utils::ValueExt, }; <file_sep path="hyperswitch/crates/router/src/core/fraud_check.rs" role="context" start="845" end="913"> pub async fn make_fulfillment_api_call( db: &dyn StorageInterface, fraud_check: FraudCheck, payment_intent: PaymentIntent, state: SessionState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, req: frm_core_types::FrmFulfillmentRequest, ) -> RouterResponse<frm_types::FraudCheckResponseData> { let payment_attempt = db .find_payment_attempt_by_attempt_id_merchant_id( &payment_intent.active_attempt.get_id(), merchant_account.get_id(), merchant_account.storage_scheme, ) .await .change_context(errors::ApiErrorResponse::PaymentNotFound)?; let connector_data = FraudCheckConnectorData::get_connector_by_name(&fraud_check.frm_name)?; let connector_integration: services::BoxedFrmConnectorIntegrationInterface< Fulfillment, frm_types::FraudCheckFulfillmentData, frm_types::FraudCheckResponseData, > = connector_data.connector.get_connector_integration(); let router_data = frm_flows::fulfillment_flow::construct_fulfillment_router_data( &state, &payment_intent, &payment_attempt, &merchant_account, &key_store, fraud_check.frm_name.clone(), req, ) .await?; let response = services::execute_connector_processing_step( &state, connector_integration, &router_data, payments::CallConnectorAction::Trigger, None, ) .await .to_payment_failed_response()?; let fraud_check_copy = fraud_check.clone(); let fraud_check_update = FraudCheckUpdate::ResponseUpdate { frm_status: fraud_check.frm_status, frm_transaction_id: fraud_check.frm_transaction_id, frm_reason: fraud_check.frm_reason, frm_score: fraud_check.frm_score, metadata: fraud_check.metadata, modified_at: common_utils::date_time::now(), last_step: FraudCheckLastStep::Fulfillment, payment_capture_method: fraud_check.payment_capture_method, }; let _updated = db .update_fraud_check_response_with_attempt_id(fraud_check_copy, fraud_check_update) .await .map_err(|error| error.change_context(errors::ApiErrorResponse::PaymentNotFound))?; let fulfillment_response = response .response .map_err(|err| errors::ApiErrorResponse::ExternalConnectorError { code: err.code, message: err.message, connector: connector_data.connector_name.clone().to_string(), status_code: err.status_code, reason: err.reason, })?; Ok(services::ApplicationResponse::Json(fulfillment_response)) } <file_sep path="hyperswitch/crates/router/src/core/fraud_check.rs" role="context" start="783" end="841"> pub async fn frm_fulfillment_core( state: SessionState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, req: frm_core_types::FrmFulfillmentRequest, ) -> RouterResponse<frm_types::FraudCheckResponseData> { let db = &*state.clone().store; let payment_intent = db .find_payment_intent_by_payment_id_merchant_id( &(&state).into(), &req.payment_id.clone(), merchant_account.get_id(), &key_store, merchant_account.storage_scheme, ) .await .change_context(errors::ApiErrorResponse::PaymentNotFound)?; match payment_intent.status { IntentStatus::Succeeded => { let invalid_request_error = errors::ApiErrorResponse::InvalidRequestData { message: "no fraud check entry found for this payment_id".to_string(), }; let existing_fraud_check = db .find_fraud_check_by_payment_id_if_present( req.payment_id.clone(), merchant_account.get_id().clone(), ) .await .change_context(invalid_request_error.to_owned())?; match existing_fraud_check { Some(fraud_check) => { if (matches!(fraud_check.frm_transaction_type, FraudCheckType::PreFrm) && fraud_check.last_step == FraudCheckLastStep::TransactionOrRecordRefund) || (matches!(fraud_check.frm_transaction_type, FraudCheckType::PostFrm) && fraud_check.last_step == FraudCheckLastStep::CheckoutOrSale) { Box::pin(make_fulfillment_api_call( db, fraud_check, payment_intent, state, merchant_account, key_store, req, )) .await } else { Err(errors::ApiErrorResponse::PreconditionFailed {message:"Frm pre/post flow hasn't terminated yet, so fulfillment cannot be called".to_string(),}.into()) } } None => Err(invalid_request_error.into()), } } _ => Err(errors::ApiErrorResponse::PreconditionFailed { message: "Fulfillment can be performed only for succeeded payment".to_string(), } .into()), } } <file_sep path="hyperswitch/crates/router/src/core/fraud_check.rs" role="context" start="757" end="766"> pub fn is_operation_allowed<Op: Debug>(operation: &Op) -> bool { ![ "PaymentSession", "PaymentApprove", "PaymentReject", "PaymentCapture", "PaymentsCancel", ] .contains(&format!("{operation:?}").as_str()) } <file_sep path="hyperswitch/crates/router/src/core/fraud_check.rs" role="context" start="677" end="755"> pub async fn call_frm_before_connector_call<F, Req, D>( operation: &BoxedOperation<'_, F, Req, D>, merchant_account: &domain::MerchantAccount, payment_data: &mut D, state: &SessionState, frm_info: &mut Option<FrmInfo<F, D>>, customer: &Option<domain::Customer>, should_continue_transaction: &mut bool, should_continue_capture: &mut bool, key_store: domain::MerchantKeyStore, ) -> RouterResult<Option<FrmConfigsObject>> where F: Send + Clone, D: payments::OperationSessionGetters<F> + payments::OperationSessionSetters<F> + Send + Sync + Clone, { let (is_frm_enabled, frm_routing_algorithm, frm_connector_label, frm_configs) = should_call_frm(merchant_account, payment_data, state, key_store.clone()).await?; if let Some((frm_routing_algorithm_val, profile_id)) = frm_routing_algorithm.zip(frm_connector_label) { if let Some(frm_configs) = frm_configs.clone() { let mut updated_frm_info = Box::pin(make_frm_data_and_fraud_check_operation( &*state.store, state, merchant_account, payment_data.to_owned(), frm_routing_algorithm_val, profile_id, frm_configs.clone(), customer, )) .await?; if is_frm_enabled { pre_payment_frm_core( state, merchant_account, payment_data, &mut updated_frm_info, frm_configs, customer, should_continue_transaction, should_continue_capture, key_store, operation, ) .await?; } *frm_info = Some(updated_frm_info); } } let fraud_capture_method = frm_info.as_ref().and_then(|frm_info| { frm_info .frm_data .as_ref() .map(|frm_data| frm_data.fraud_check.payment_capture_method) }); if matches!(fraud_capture_method, Some(Some(CaptureMethod::Manual))) && matches!( payment_data.get_payment_attempt().status, AttemptStatus::Unresolved ) { if let Some(info) = frm_info { info.suggested_action = Some(FrmSuggestion::FrmAuthorizeTransaction) }; *should_continue_transaction = false; logger::debug!( "skipping connector call since payment_capture_method is already {:?}", fraud_capture_method ); }; logger::debug!("frm_configs: {:?} {:?}", frm_configs, is_frm_enabled); Ok(frm_configs) } <file_sep path="hyperswitch/crates/router/src/core/fraud_check/types.rs" role="context" start="78" end="87"> pub struct PaymentToFrmData { pub amount: Amount, pub payment_intent: PaymentIntent, pub payment_attempt: PaymentAttempt, pub merchant_account: MerchantAccount, pub address: PaymentAddress, pub connector_details: ConnectorDetailsCore, pub order_details: Option<Vec<OrderDetailsWithAmount>>, pub frm_metadata: Option<SecretSerdeValue>, }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payments/flows/complete_authorize_flow.rs<|crate|> router anchor=add_access_token kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/core/payments/flows/complete_authorize_flow.rs" role="context" start="150" end="159"> async fn add_access_token<'a>( &self, state: &SessionState, connector: &api::ConnectorData, merchant_account: &domain::MerchantAccount, creds_identifier: Option<&str>, ) -> RouterResult<types::AddAccessTokenResult> { access_token::add_access_token(state, connector, merchant_account, self, creds_identifier) .await } <file_sep path="hyperswitch/crates/router/src/core/payments/flows/complete_authorize_flow.rs" role="context" start="149" end="149"> use crate::{ core::{ errors::{ApiErrorResponse, ConnectorErrorExt, RouterResult}, payments::{self, access_token, helpers, transformers, PaymentData}, }, routes::{metrics, SessionState}, services, types::{self, api, domain, transformers::ForeignTryFrom}, }; <file_sep path="hyperswitch/crates/router/src/core/payments/flows/complete_authorize_flow.rs" role="context" start="189" end="211"> async fn build_flow_specific_connector_request( &mut self, state: &SessionState, connector: &api::ConnectorData, call_connector_action: payments::CallConnectorAction, ) -> RouterResult<(Option<services::Request>, bool)> { let request = match call_connector_action { payments::CallConnectorAction::Trigger => { let connector_integration: services::BoxedPaymentConnectorIntegrationInterface< api::CompleteAuthorize, types::CompleteAuthorizeData, types::PaymentsResponseData, > = connector.connector.get_connector_integration(); connector_integration .build_request(self, &state.conf.connectors) .to_payment_failed_response()? } _ => None, }; Ok((request, true)) } <file_sep path="hyperswitch/crates/router/src/core/payments/flows/complete_authorize_flow.rs" role="context" start="161" end="187"> async fn add_payment_method_token<'a>( &mut self, state: &SessionState, connector: &api::ConnectorData, _tokenization_action: &payments::TokenizationAction, should_continue_payment: bool, ) -> RouterResult<types::PaymentMethodTokenResult> { // TODO: remove this and handle it in core if matches!(connector.connector_name, types::Connector::Payme) { let request = self.request.clone(); payments::tokenization::add_payment_method_token( state, connector, &payments::TokenizationAction::TokenizeInConnector, self, types::PaymentMethodTokenizationData::try_from(request)?, should_continue_payment, ) .await } else { Ok(types::PaymentMethodTokenResult { payment_method_token_result: Ok(None), is_payment_method_tokenization_performed: false, connector_response: None, }) } } <file_sep path="hyperswitch/crates/router/src/core/payments/flows/complete_authorize_flow.rs" role="context" start="99" end="148"> async fn decide_flows<'a>( mut self, state: &SessionState, connector: &api::ConnectorData, call_connector_action: payments::CallConnectorAction, connector_request: Option<services::Request>, business_profile: &domain::Profile, header_payload: hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<Self> { let connector_integration: services::BoxedPaymentConnectorIntegrationInterface< api::CompleteAuthorize, types::CompleteAuthorizeData, types::PaymentsResponseData, > = connector.connector.get_connector_integration(); let mut complete_authorize_router_data = services::execute_connector_processing_step( state, connector_integration, &self, call_connector_action.clone(), connector_request, ) .await .to_payment_failed_response()?; match complete_authorize_router_data.response.clone() { Err(_) => Ok(complete_authorize_router_data), Ok(complete_authorize_response) => { // Check if the Capture API should be called based on the connector and other parameters if super::should_initiate_capture_flow( &connector.connector_name, self.request.customer_acceptance, self.request.capture_method, self.request.setup_future_usage, complete_authorize_router_data.status, ) { complete_authorize_router_data = Box::pin(process_capture_flow( complete_authorize_router_data, complete_authorize_response, state, connector, call_connector_action.clone(), business_profile, header_payload, )) .await?; } Ok(complete_authorize_router_data) } } } <file_sep path="hyperswitch/crates/router/src/core/payments/flows/complete_authorize_flow.rs" role="context" start="79" end="88"> async fn get_merchant_recipient_data<'a>( &self, _state: &SessionState, _merchant_account: &domain::MerchantAccount, _key_store: &domain::MerchantKeyStore, _merchant_connector_account: &helpers::MerchantConnectorAccountType, _connector: &api::ConnectorData, ) -> RouterResult<Option<types::MerchantRecipientData>> { Ok(None) } <file_sep path="hyperswitch/crates/router/src/core/errors.rs" role="context" start="31" end="31"> pub type RouterResult<T> = CustomResult<T, ApiErrorResponse>; <file_sep path="hyperswitch/v2_compatible_migrations/2024-08-28-081757_drop_not_null_constraints_on_v1_columns/up.sql" role="context" start="5" end="21"> ALTER COLUMN org_id DROP NOT NULL; -- Create index on org_id in organization table -- This is done to mullify the effects of droping primary key for v1 CREATE INDEX idx_organization_org_id ON organization (org_id); ------------------------ Merchant Account ------------------- -- Drop not null in merchant_account table for v1 columns that are dropped in v2 ALTER TABLE merchant_account DROP CONSTRAINT merchant_account_pkey, ALTER COLUMN merchant_id DROP NOT NULL, ALTER COLUMN primary_business_details DROP NOT NULL, ALTER COLUMN is_recon_enabled DROP NOT NULL; -- This is done to mullify the effects of droping primary key for v1 CREATE INDEX idx_merchant_account_merchant_id ON merchant_account (merchant_id); <file_sep path="hyperswitch/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/event.test.js" role="context" start="61" end="78"> "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.", ); } // Response body should have value "succeeded" for "status" if (jsonData?.status) { pm.test( "[POST]::/payments - Content check if value for 'status' matches 'succeeded'", function () { pm.expect(jsonData.status).to.eql("succeeded"); }, ); }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payments/flows/setup_mandate_flow.rs<|crate|> router anchor=add_access_token kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/core/payments/flows/setup_mandate_flow.rs" role="context" start="158" end="167"> async fn add_access_token<'a>( &self, state: &SessionState, connector: &api::ConnectorData, merchant_account: &domain::MerchantAccount, creds_identifier: Option<&str>, ) -> RouterResult<types::AddAccessTokenResult> { access_token::add_access_token(state, connector, merchant_account, self, creds_identifier) .await } <file_sep path="hyperswitch/crates/router/src/core/payments/flows/setup_mandate_flow.rs" role="context" start="157" end="157"> use crate::{ core::{ errors::{ConnectorErrorExt, RouterResult}, mandate, payments::{ self, access_token, customers, helpers, tokenization, transformers, PaymentData, }, }, routes::SessionState, services, types::{self, api, domain}, }; <file_sep path="hyperswitch/crates/router/src/core/payments/flows/setup_mandate_flow.rs" role="context" start="188" end="200"> async fn create_connector_customer<'a>( &self, state: &SessionState, connector: &api::ConnectorData, ) -> RouterResult<Option<String>> { customers::create_connector_customer( state, connector, self, types::ConnectorCustomerData::try_from(self.request.to_owned())?, ) .await } <file_sep path="hyperswitch/crates/router/src/core/payments/flows/setup_mandate_flow.rs" role="context" start="169" end="186"> async fn add_payment_method_token<'a>( &mut self, state: &SessionState, connector: &api::ConnectorData, tokenization_action: &payments::TokenizationAction, should_continue_payment: bool, ) -> RouterResult<types::PaymentMethodTokenResult> { let request = self.request.clone(); tokenization::add_payment_method_token( state, connector, tokenization_action, self, types::PaymentMethodTokenizationData::try_from(request)?, should_continue_payment, ) .await } <file_sep path="hyperswitch/crates/router/src/core/payments/flows/setup_mandate_flow.rs" role="context" start="117" end="156"> async fn decide_flows<'a>( mut self, state: &SessionState, connector: &api::ConnectorData, call_connector_action: payments::CallConnectorAction, connector_request: Option<services::Request>, _business_profile: &domain::Profile, _header_payload: hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<Self> { let connector_integration: services::BoxedPaymentConnectorIntegrationInterface< api::SetupMandate, types::SetupMandateRequestData, types::PaymentsResponseData, > = connector.connector.get_connector_integration(); // Change the authentication_type to ThreeDs, for google_pay wallet if card_holder_authenticated or account_verified in assurance_details is false if let hyperswitch_domain_models::payment_method_data::PaymentMethodData::Wallet( hyperswitch_domain_models::payment_method_data::WalletData::GooglePay(google_pay_data), ) = &self.request.payment_method_data { if let Some(assurance_details) = google_pay_data.info.assurance_details.as_ref() { // Step up the transaction to 3DS when either assurance_details.card_holder_authenticated or assurance_details.account_verified is false if !assurance_details.card_holder_authenticated || !assurance_details.account_verified { logger::info!("Googlepay transaction stepped up to 3DS"); self.auth_type = diesel_models::enums::AuthenticationType::ThreeDs; } } } let resp = services::execute_connector_processing_step( state, connector_integration, &self, call_connector_action.clone(), connector_request, ) .await .to_setup_mandate_failed_response()?; Ok(resp) } <file_sep path="hyperswitch/crates/router/src/core/payments/flows/setup_mandate_flow.rs" role="context" start="103" end="112"> async fn get_merchant_recipient_data<'a>( &self, _state: &SessionState, _merchant_account: &domain::MerchantAccount, _key_store: &domain::MerchantKeyStore, _merchant_connector_account: &helpers::MerchantConnectorAccountType, _connector: &api::ConnectorData, ) -> RouterResult<Option<types::MerchantRecipientData>> { Ok(None) } <file_sep path="hyperswitch/crates/router/src/core/errors.rs" role="context" start="31" end="31"> pub type RouterResult<T> = CustomResult<T, ApiErrorResponse>; <file_sep path="hyperswitch/v2_compatible_migrations/2024-08-28-081757_drop_not_null_constraints_on_v1_columns/up.sql" role="context" start="5" end="21"> ALTER COLUMN org_id DROP NOT NULL; -- Create index on org_id in organization table -- This is done to mullify the effects of droping primary key for v1 CREATE INDEX idx_organization_org_id ON organization (org_id); ------------------------ Merchant Account ------------------- -- Drop not null in merchant_account table for v1 columns that are dropped in v2 ALTER TABLE merchant_account DROP CONSTRAINT merchant_account_pkey, ALTER COLUMN merchant_id DROP NOT NULL, ALTER COLUMN primary_business_details DROP NOT NULL, ALTER COLUMN is_recon_enabled DROP NOT NULL; -- This is done to mullify the effects of droping primary key for v1 CREATE INDEX idx_merchant_account_merchant_id ON merchant_account (merchant_id);
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payments/flows/approve_flow.rs<|crate|> router anchor=add_access_token kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/core/payments/flows/approve_flow.rs" role="context" start="94" end="103"> async fn add_access_token<'a>( &self, state: &SessionState, connector: &api::ConnectorData, merchant_account: &domain::MerchantAccount, creds_identifier: Option<&str>, ) -> RouterResult<types::AddAccessTokenResult> { access_token::add_access_token(state, connector, merchant_account, self, creds_identifier) .await } <file_sep path="hyperswitch/crates/router/src/core/payments/flows/approve_flow.rs" role="context" start="93" end="93"> use crate::{ core::{ errors::{ApiErrorResponse, NotImplementedMessage, RouterResult}, payments::{self, access_token, helpers, transformers, PaymentData}, }, routes::SessionState, services, types::{self, api, domain}, }; <file_sep path="hyperswitch/crates/router/src/core/payments/flows/approve_flow.rs" role="context" start="105" end="115"> async fn build_flow_specific_connector_request( &mut self, _state: &SessionState, _connector: &api::ConnectorData, _call_connector_action: payments::CallConnectorAction, ) -> RouterResult<(Option<services::Request>, bool)> { Err(ApiErrorResponse::NotImplemented { message: NotImplementedMessage::Reason("Flow not supported".to_string()), } .into()) } <file_sep path="hyperswitch/crates/router/src/core/payments/flows/approve_flow.rs" role="context" start="79" end="92"> async fn decide_flows<'a>( self, _state: &SessionState, _connector: &api::ConnectorData, _call_connector_action: payments::CallConnectorAction, _connector_request: Option<services::Request>, _business_profile: &domain::Profile, _header_payload: hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<Self> { Err(ApiErrorResponse::NotImplemented { message: NotImplementedMessage::Reason("Flow not supported".to_string()), } .into()) } <file_sep path="hyperswitch/crates/router/src/core/payments/flows/approve_flow.rs" role="context" start="63" end="72"> async fn get_merchant_recipient_data<'a>( &self, _state: &SessionState, _merchant_account: &domain::MerchantAccount, _key_store: &domain::MerchantKeyStore, _merchant_connector_account: &helpers::MerchantConnectorAccountType, _connector: &api::ConnectorData, ) -> RouterResult<Option<types::MerchantRecipientData>> { Ok(None) } <file_sep path="hyperswitch/crates/router/src/core/errors.rs" role="context" start="31" end="31"> pub type RouterResult<T> = CustomResult<T, ApiErrorResponse>; <file_sep path="hyperswitch/v2_compatible_migrations/2024-08-28-081757_drop_not_null_constraints_on_v1_columns/up.sql" role="context" start="5" end="21"> ALTER COLUMN org_id DROP NOT NULL; -- Create index on org_id in organization table -- This is done to mullify the effects of droping primary key for v1 CREATE INDEX idx_organization_org_id ON organization (org_id); ------------------------ Merchant Account ------------------- -- Drop not null in merchant_account table for v1 columns that are dropped in v2 ALTER TABLE merchant_account DROP CONSTRAINT merchant_account_pkey, ALTER COLUMN merchant_id DROP NOT NULL, ALTER COLUMN primary_business_details DROP NOT NULL, ALTER COLUMN is_recon_enabled DROP NOT NULL; -- This is done to mullify the effects of droping primary key for v1 CREATE INDEX idx_merchant_account_merchant_id ON merchant_account (merchant_id);
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payments/flows/incremental_authorization_flow.rs<|crate|> router anchor=add_access_token kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/core/payments/flows/incremental_authorization_flow.rs" role="context" start="114" end="123"> async fn add_access_token<'a>( &self, state: &SessionState, connector: &api::ConnectorData, merchant_account: &domain::MerchantAccount, creds_identifier: Option<&str>, ) -> RouterResult<types::AddAccessTokenResult> { access_token::add_access_token(state, connector, merchant_account, self, creds_identifier) .await } <file_sep path="hyperswitch/crates/router/src/core/payments/flows/incremental_authorization_flow.rs" role="context" start="113" end="113"> use crate::{ core::{ errors::{ConnectorErrorExt, RouterResult}, payments::{self, access_token, helpers, transformers, Feature, PaymentData}, }, routes::SessionState, services, types::{self, api, domain}, }; <file_sep path="hyperswitch/crates/router/src/core/payments/flows/incremental_authorization_flow.rs" role="context" start="125" end="147"> async fn build_flow_specific_connector_request( &mut self, state: &SessionState, connector: &api::ConnectorData, call_connector_action: payments::CallConnectorAction, ) -> RouterResult<(Option<services::Request>, bool)> { let request = match call_connector_action { payments::CallConnectorAction::Trigger => { let connector_integration: services::BoxedPaymentConnectorIntegrationInterface< api::IncrementalAuthorization, types::PaymentsIncrementalAuthorizationData, types::PaymentsResponseData, > = connector.connector.get_connector_integration(); connector_integration .build_request(self, &state.conf.connectors) .to_payment_failed_response()? } _ => None, }; Ok((request, true)) } <file_sep path="hyperswitch/crates/router/src/core/payments/flows/incremental_authorization_flow.rs" role="context" start="86" end="112"> async fn decide_flows<'a>( self, state: &SessionState, connector: &api::ConnectorData, call_connector_action: payments::CallConnectorAction, connector_request: Option<services::Request>, _business_profile: &domain::Profile, _header_payload: hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<Self> { let connector_integration: services::BoxedPaymentConnectorIntegrationInterface< api::IncrementalAuthorization, types::PaymentsIncrementalAuthorizationData, types::PaymentsResponseData, > = connector.connector.get_connector_integration(); let resp = services::execute_connector_processing_step( state, connector_integration, &self, call_connector_action, connector_request, ) .await .to_payment_failed_response()?; Ok(resp) } <file_sep path="hyperswitch/crates/router/src/core/payments/flows/incremental_authorization_flow.rs" role="context" start="66" end="75"> async fn get_merchant_recipient_data<'a>( &self, _state: &SessionState, _merchant_account: &domain::MerchantAccount, _key_store: &domain::MerchantKeyStore, _merchant_connector_account: &helpers::MerchantConnectorAccountType, _connector: &api::ConnectorData, ) -> RouterResult<Option<types::MerchantRecipientData>> { Ok(None) } <file_sep path="hyperswitch/crates/router/src/core/errors.rs" role="context" start="31" end="31"> pub type RouterResult<T> = CustomResult<T, ApiErrorResponse>; <file_sep path="hyperswitch/v2_compatible_migrations/2024-08-28-081757_drop_not_null_constraints_on_v1_columns/up.sql" role="context" start="5" end="21"> ALTER COLUMN org_id DROP NOT NULL; -- Create index on org_id in organization table -- This is done to mullify the effects of droping primary key for v1 CREATE INDEX idx_organization_org_id ON organization (org_id); ------------------------ Merchant Account ------------------- -- Drop not null in merchant_account table for v1 columns that are dropped in v2 ALTER TABLE merchant_account DROP CONSTRAINT merchant_account_pkey, ALTER COLUMN merchant_id DROP NOT NULL, ALTER COLUMN primary_business_details DROP NOT NULL, ALTER COLUMN is_recon_enabled DROP NOT NULL; -- This is done to mullify the effects of droping primary key for v1 CREATE INDEX idx_merchant_account_merchant_id ON merchant_account (merchant_id); <file_sep path="hyperswitch/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/event.test.js" role="context" start="61" end="78"> "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.", ); } // Response body should have value "succeeded" for "status" if (jsonData?.status) { pm.test( "[POST]::/payments - Content check if value for 'status' matches 'succeeded'", function () { pm.expect(jsonData.status).to.eql("succeeded"); }, ); }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payments/flows/incremental_authorization_flow.rs<|crate|> router anchor=add_access_token kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/core/payments/flows/incremental_authorization_flow.rs" role="context" start="114" end="123"> async fn add_access_token<'a>( &self, state: &SessionState, connector: &api::ConnectorData, merchant_account: &domain::MerchantAccount, creds_identifier: Option<&str>, ) -> RouterResult<types::AddAccessTokenResult> { access_token::add_access_token(state, connector, merchant_account, self, creds_identifier) .await } <file_sep path="hyperswitch/crates/router/src/core/payments/flows/incremental_authorization_flow.rs" role="context" start="113" end="113"> use crate::{ core::{ errors::{ConnectorErrorExt, RouterResult}, payments::{self, access_token, helpers, transformers, Feature, PaymentData}, }, routes::SessionState, services, types::{self, api, domain}, }; <file_sep path="hyperswitch/crates/router/src/core/payments/flows/incremental_authorization_flow.rs" role="context" start="125" end="147"> async fn build_flow_specific_connector_request( &mut self, state: &SessionState, connector: &api::ConnectorData, call_connector_action: payments::CallConnectorAction, ) -> RouterResult<(Option<services::Request>, bool)> { let request = match call_connector_action { payments::CallConnectorAction::Trigger => { let connector_integration: services::BoxedPaymentConnectorIntegrationInterface< api::IncrementalAuthorization, types::PaymentsIncrementalAuthorizationData, types::PaymentsResponseData, > = connector.connector.get_connector_integration(); connector_integration .build_request(self, &state.conf.connectors) .to_payment_failed_response()? } _ => None, }; Ok((request, true)) } <file_sep path="hyperswitch/crates/router/src/core/payments/flows/incremental_authorization_flow.rs" role="context" start="86" end="112"> async fn decide_flows<'a>( self, state: &SessionState, connector: &api::ConnectorData, call_connector_action: payments::CallConnectorAction, connector_request: Option<services::Request>, _business_profile: &domain::Profile, _header_payload: hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<Self> { let connector_integration: services::BoxedPaymentConnectorIntegrationInterface< api::IncrementalAuthorization, types::PaymentsIncrementalAuthorizationData, types::PaymentsResponseData, > = connector.connector.get_connector_integration(); let resp = services::execute_connector_processing_step( state, connector_integration, &self, call_connector_action, connector_request, ) .await .to_payment_failed_response()?; Ok(resp) } <file_sep path="hyperswitch/crates/router/src/core/payments/flows/incremental_authorization_flow.rs" role="context" start="66" end="75"> async fn get_merchant_recipient_data<'a>( &self, _state: &SessionState, _merchant_account: &domain::MerchantAccount, _key_store: &domain::MerchantKeyStore, _merchant_connector_account: &helpers::MerchantConnectorAccountType, _connector: &api::ConnectorData, ) -> RouterResult<Option<types::MerchantRecipientData>> { Ok(None) } <file_sep path="hyperswitch/crates/router/src/core/errors.rs" role="context" start="31" end="31"> pub type RouterResult<T> = CustomResult<T, ApiErrorResponse>; <file_sep path="hyperswitch/v2_compatible_migrations/2024-08-28-081757_drop_not_null_constraints_on_v1_columns/up.sql" role="context" start="5" end="21"> ALTER COLUMN org_id DROP NOT NULL; -- Create index on org_id in organization table -- This is done to mullify the effects of droping primary key for v1 CREATE INDEX idx_organization_org_id ON organization (org_id); ------------------------ Merchant Account ------------------- -- Drop not null in merchant_account table for v1 columns that are dropped in v2 ALTER TABLE merchant_account DROP CONSTRAINT merchant_account_pkey, ALTER COLUMN merchant_id DROP NOT NULL, ALTER COLUMN primary_business_details DROP NOT NULL, ALTER COLUMN is_recon_enabled DROP NOT NULL; -- This is done to mullify the effects of droping primary key for v1 CREATE INDEX idx_merchant_account_merchant_id ON merchant_account (merchant_id);
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payments/flows/cancel_flow.rs<|crate|> router anchor=add_access_token kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/core/payments/flows/cancel_flow.rs" role="context" start="111" end="120"> async fn add_access_token<'a>( &self, state: &SessionState, connector: &api::ConnectorData, merchant_account: &domain::MerchantAccount, creds_identifier: Option<&str>, ) -> RouterResult<types::AddAccessTokenResult> { access_token::add_access_token(state, connector, merchant_account, self, creds_identifier) .await } <file_sep path="hyperswitch/crates/router/src/core/payments/flows/cancel_flow.rs" role="context" start="110" end="110"> use crate::{ core::{ errors::{ConnectorErrorExt, RouterResult}, payments::{self, access_token, helpers, transformers, PaymentData}, }, routes::{metrics, SessionState}, services, types::{self, api, domain}, }; <file_sep path="hyperswitch/crates/router/src/core/payments/flows/cancel_flow.rs" role="context" start="122" end="144"> async fn build_flow_specific_connector_request( &mut self, state: &SessionState, connector: &api::ConnectorData, call_connector_action: payments::CallConnectorAction, ) -> RouterResult<(Option<services::Request>, bool)> { let request = match call_connector_action { payments::CallConnectorAction::Trigger => { let connector_integration: services::BoxedPaymentConnectorIntegrationInterface< api::Void, types::PaymentsCancelData, types::PaymentsResponseData, > = connector.connector.get_connector_integration(); connector_integration .build_request(self, &state.conf.connectors) .to_payment_failed_response()? } _ => None, }; Ok((request, true)) } <file_sep path="hyperswitch/crates/router/src/core/payments/flows/cancel_flow.rs" role="context" start="78" end="109"> async fn decide_flows<'a>( self, state: &SessionState, connector: &api::ConnectorData, call_connector_action: payments::CallConnectorAction, connector_request: Option<services::Request>, _business_profile: &domain::Profile, _header_payload: hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<Self> { metrics::PAYMENT_CANCEL_COUNT.add( 1, router_env::metric_attributes!(("connector", connector.connector_name.to_string())), ); let connector_integration: services::BoxedPaymentConnectorIntegrationInterface< api::Void, types::PaymentsCancelData, types::PaymentsResponseData, > = connector.connector.get_connector_integration(); let resp = services::execute_connector_processing_step( state, connector_integration, &self, call_connector_action, connector_request, ) .await .to_payment_failed_response()?; Ok(resp) } <file_sep path="hyperswitch/crates/router/src/core/payments/flows/cancel_flow.rs" role="context" start="62" end="71"> async fn get_merchant_recipient_data<'a>( &self, _state: &SessionState, _merchant_account: &domain::MerchantAccount, _key_store: &domain::MerchantKeyStore, _merchant_connector_account: &helpers::MerchantConnectorAccountType, _connector: &api::ConnectorData, ) -> RouterResult<Option<types::MerchantRecipientData>> { Ok(None) } <file_sep path="hyperswitch/crates/router/src/core/errors.rs" role="context" start="31" end="31"> pub type RouterResult<T> = CustomResult<T, ApiErrorResponse>; <file_sep path="hyperswitch/v2_compatible_migrations/2024-08-28-081757_drop_not_null_constraints_on_v1_columns/up.sql" role="context" start="5" end="21"> ALTER COLUMN org_id DROP NOT NULL; -- Create index on org_id in organization table -- This is done to mullify the effects of droping primary key for v1 CREATE INDEX idx_organization_org_id ON organization (org_id); ------------------------ Merchant Account ------------------- -- Drop not null in merchant_account table for v1 columns that are dropped in v2 ALTER TABLE merchant_account DROP CONSTRAINT merchant_account_pkey, ALTER COLUMN merchant_id DROP NOT NULL, ALTER COLUMN primary_business_details DROP NOT NULL, ALTER COLUMN is_recon_enabled DROP NOT NULL; -- This is done to mullify the effects of droping primary key for v1 CREATE INDEX idx_merchant_account_merchant_id ON merchant_account (merchant_id);
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payments/flows/psync_flow.rs<|crate|> router anchor=add_access_token kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/core/payments/flows/psync_flow.rs" role="context" start="180" end="189"> async fn add_access_token<'a>( &self, state: &SessionState, connector: &api::ConnectorData, merchant_account: &domain::MerchantAccount, creds_identifier: Option<&str>, ) -> RouterResult<types::AddAccessTokenResult> { access_token::add_access_token(state, connector, merchant_account, self, creds_identifier) .await } <file_sep path="hyperswitch/crates/router/src/core/payments/flows/psync_flow.rs" role="context" start="179" end="179"> use crate::{ connector::utils::RouterData, core::{ errors::{ApiErrorResponse, ConnectorErrorExt, RouterResult}, payments::{self, access_token, helpers, transformers, PaymentData}, }, routes::SessionState, services::{self, api::ConnectorValidation, logger}, types::{self, api, domain}, }; <file_sep path="hyperswitch/crates/router/src/core/payments/flows/psync_flow.rs" role="context" start="254" end="318"> async fn execute_connector_processing_step_for_each_capture( &self, state: &SessionState, pending_connector_capture_id_list: Vec<String>, call_connector_action: payments::CallConnectorAction, connector_integration: services::BoxedPaymentConnectorIntegrationInterface< api::PSync, types::PaymentsSyncData, types::PaymentsResponseData, >, ) -> RouterResult<Self> { let mut capture_sync_response_map = HashMap::new(); if let payments::CallConnectorAction::HandleResponse(_) = call_connector_action { // webhook consume flow, only call connector once. Since there will only be a single event in every webhook let resp = services::execute_connector_processing_step( state, connector_integration, self, call_connector_action.clone(), None, ) .await .to_payment_failed_response()?; Ok(resp) } else { // in trigger, call connector for every capture_id for connector_capture_id in pending_connector_capture_id_list { // TEMPORARY FIX: remove the clone on router data after removing this function as an impl on trait RouterDataPSync // TRACKING ISSUE: https://github.com/juspay/hyperswitch/issues/4644 let mut cloned_router_data = self.clone(); cloned_router_data.request.connector_transaction_id = types::ResponseId::ConnectorTransactionId(connector_capture_id.clone()); let resp = services::execute_connector_processing_step( state, connector_integration.clone_box(), &cloned_router_data, call_connector_action.clone(), None, ) .await .to_payment_failed_response()?; match resp.response { Err(err) => { capture_sync_response_map.insert(connector_capture_id, types::CaptureSyncResponse::Error { code: err.code, message: err.message, reason: err.reason, status_code: err.status_code, amount: None, }); }, Ok(types::PaymentsResponseData::MultipleCaptureResponse { capture_sync_response_list })=> { capture_sync_response_map.extend(capture_sync_response_list.into_iter()); } _ => Err(ApiErrorResponse::PreconditionFailed { message: "Response type must be PaymentsResponseData::MultipleCaptureResponse for payment sync".into() })?, }; } let mut cloned_router_data = self.clone(); cloned_router_data.response = Ok(types::PaymentsResponseData::MultipleCaptureResponse { capture_sync_response_list: capture_sync_response_map, }); Ok(cloned_router_data) } } <file_sep path="hyperswitch/crates/router/src/core/payments/flows/psync_flow.rs" role="context" start="191" end="229"> async fn build_flow_specific_connector_request( &mut self, state: &SessionState, connector: &api::ConnectorData, call_connector_action: payments::CallConnectorAction, ) -> RouterResult<(Option<services::Request>, bool)> { let request = match call_connector_action { payments::CallConnectorAction::Trigger => { //validate_psync_reference_id if call_connector_action is trigger if connector .connector .validate_psync_reference_id( &self.request, self.is_three_ds(), self.status, self.connector_meta_data.clone(), ) .is_err() { logger::warn!( "validate_psync_reference_id failed, hence skipping call to connector" ); return Ok((None, false)); } let connector_integration: services::BoxedPaymentConnectorIntegrationInterface< api::PSync, types::PaymentsSyncData, types::PaymentsResponseData, > = connector.connector.get_connector_integration(); connector_integration .build_request(self, &state.conf.connectors) .to_payment_failed_response()? } _ => None, }; Ok((request, true)) } <file_sep path="hyperswitch/crates/router/src/core/payments/flows/psync_flow.rs" role="context" start="112" end="178"> async fn decide_flows<'a>( mut self, state: &SessionState, connector: &api::ConnectorData, call_connector_action: payments::CallConnectorAction, connector_request: Option<services::Request>, _business_profile: &domain::Profile, _header_payload: hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<Self> { let connector_integration: services::BoxedPaymentConnectorIntegrationInterface< api::PSync, types::PaymentsSyncData, types::PaymentsResponseData, > = connector.connector.get_connector_integration(); let capture_sync_method_result = connector_integration .get_multiple_capture_sync_method() .to_payment_failed_response(); match (self.request.sync_type.clone(), capture_sync_method_result) { ( types::SyncRequestType::MultipleCaptureSync(pending_connector_capture_id_list), Ok(services::CaptureSyncMethod::Individual), ) => { let mut new_router_data = self .execute_connector_processing_step_for_each_capture( state, pending_connector_capture_id_list, call_connector_action, connector_integration, ) .await?; // Initiating Integrity checks let integrity_result = helpers::check_integrity_based_on_flow( &new_router_data.request, &new_router_data.response, ); new_router_data.integrity_check = integrity_result; Ok(new_router_data) } (types::SyncRequestType::MultipleCaptureSync(_), Err(err)) => Err(err), _ => { // for bulk sync of captures, above logic needs to be handled at connector end let mut new_router_data = services::execute_connector_processing_step( state, connector_integration, &self, call_connector_action, connector_request, ) .await .to_payment_failed_response()?; // Initiating Integrity checks let integrity_result = helpers::check_integrity_based_on_flow( &new_router_data.request, &new_router_data.response, ); new_router_data.integrity_check = integrity_result; Ok(new_router_data) } } } <file_sep path="hyperswitch/crates/router/src/core/payments/flows/psync_flow.rs" role="context" start="96" end="105"> async fn get_merchant_recipient_data<'a>( &self, _state: &SessionState, _merchant_account: &domain::MerchantAccount, _key_store: &domain::MerchantKeyStore, _merchant_connector_account: &helpers::MerchantConnectorAccountType, _connector: &api::ConnectorData, ) -> RouterResult<Option<types::MerchantRecipientData>> { Ok(None) } <file_sep path="hyperswitch/crates/router/src/core/errors.rs" role="context" start="31" end="31"> pub type RouterResult<T> = CustomResult<T, ApiErrorResponse>; <file_sep path="hyperswitch/v2_compatible_migrations/2024-08-28-081757_drop_not_null_constraints_on_v1_columns/up.sql" role="context" start="5" end="21"> ALTER COLUMN org_id DROP NOT NULL; -- Create index on org_id in organization table -- This is done to mullify the effects of droping primary key for v1 CREATE INDEX idx_organization_org_id ON organization (org_id); ------------------------ Merchant Account ------------------- -- Drop not null in merchant_account table for v1 columns that are dropped in v2 ALTER TABLE merchant_account DROP CONSTRAINT merchant_account_pkey, ALTER COLUMN merchant_id DROP NOT NULL, ALTER COLUMN primary_business_details DROP NOT NULL, ALTER COLUMN is_recon_enabled DROP NOT NULL; -- This is done to mullify the effects of droping primary key for v1 CREATE INDEX idx_merchant_account_merchant_id ON merchant_account (merchant_id);
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payments/flows/authorize_flow.rs<|crate|> router anchor=add_access_token kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/core/payments/flows/authorize_flow.rs" role="context" start="239" end="248"> async fn add_access_token<'a>( &self, state: &SessionState, connector: &api::ConnectorData, merchant_account: &domain::MerchantAccount, creds_identifier: Option<&str>, ) -> RouterResult<types::AddAccessTokenResult> { access_token::add_access_token(state, connector, merchant_account, self, creds_identifier) .await } <file_sep path="hyperswitch/crates/router/src/core/payments/flows/authorize_flow.rs" role="context" start="238" end="238"> use crate::{ core::{ errors::{ConnectorErrorExt, RouterResult}, mandate, payments::{ self, access_token, customers, helpers, tokenization, transformers, PaymentData, }, }, logger, routes::{metrics, SessionState}, services::{self, api::ConnectorValidation}, types::{ self, api, domain, transformers::{ForeignFrom, ForeignTryFrom}, }, utils::OptionExt, }; <file_sep path="hyperswitch/crates/router/src/core/payments/flows/authorize_flow.rs" role="context" start="281" end="298"> async fn add_payment_method_token<'a>( &mut self, state: &SessionState, connector: &api::ConnectorData, tokenization_action: &payments::TokenizationAction, should_continue_payment: bool, ) -> RouterResult<types::PaymentMethodTokenResult> { let request = self.request.clone(); tokenization::add_payment_method_token( state, connector, tokenization_action, self, types::PaymentMethodTokenizationData::try_from(request)?, should_continue_payment, ) .await } <file_sep path="hyperswitch/crates/router/src/core/payments/flows/authorize_flow.rs" role="context" start="250" end="279"> async fn add_session_token<'a>( self, state: &SessionState, connector: &api::ConnectorData, ) -> RouterResult<Self> where Self: Sized, { let connector_integration: services::BoxedPaymentConnectorIntegrationInterface< api::AuthorizeSessionToken, types::AuthorizeSessionTokenData, types::PaymentsResponseData, > = connector.connector.get_connector_integration(); let authorize_data = &types::PaymentsAuthorizeSessionTokenRouterData::foreign_from(( &self, types::AuthorizeSessionTokenData::foreign_from(&self), )); let resp = services::execute_connector_processing_step( state, connector_integration, authorize_data, payments::CallConnectorAction::Trigger, None, ) .await .to_payment_failed_response()?; let mut router_data = self; router_data.session_token = resp.session_token; Ok(router_data) } <file_sep path="hyperswitch/crates/router/src/core/payments/flows/authorize_flow.rs" role="context" start="173" end="237"> async fn decide_flows<'a>( mut self, state: &SessionState, connector: &api::ConnectorData, call_connector_action: payments::CallConnectorAction, connector_request: Option<services::Request>, business_profile: &domain::Profile, header_payload: hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<Self> { let connector_integration: services::BoxedPaymentConnectorIntegrationInterface< api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData, > = connector.connector.get_connector_integration(); if self.should_proceed_with_authorize() { self.decide_authentication_type(); logger::debug!(auth_type=?self.auth_type); let mut auth_router_data = services::execute_connector_processing_step( state, connector_integration, &self, call_connector_action.clone(), connector_request, ) .await .to_payment_failed_response()?; // Initiating Integrity check let integrity_result = helpers::check_integrity_based_on_flow( &auth_router_data.request, &auth_router_data.response, ); auth_router_data.integrity_check = integrity_result; metrics::PAYMENT_COUNT.add(1, &[]); // Move outside of the if block match auth_router_data.response.clone() { Err(_) => Ok(auth_router_data), Ok(authorize_response) => { // Check if the Capture API should be called based on the connector and other parameters if super::should_initiate_capture_flow( &connector.connector_name, self.request.customer_acceptance, self.request.capture_method, self.request.setup_future_usage, auth_router_data.status, ) { auth_router_data = Box::pin(process_capture_flow( auth_router_data, authorize_response, state, connector, call_connector_action.clone(), business_profile, header_payload, )) .await?; } Ok(auth_router_data) } } } else { Ok(self.clone()) } } <file_sep path="hyperswitch/crates/router/src/core/payments/flows/authorize_flow.rs" role="context" start="141" end="168"> async fn get_merchant_recipient_data<'a>( &self, state: &SessionState, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, merchant_connector_account: &helpers::MerchantConnectorAccountType, connector: &api::ConnectorData, ) -> RouterResult<Option<types::MerchantRecipientData>> { let payment_method = &self .payment_attempt .get_payment_method() .get_required_value("PaymentMethod")?; let data = if *payment_method == enums::PaymentMethod::OpenBanking { payments::get_merchant_bank_data_for_open_banking_connectors( merchant_connector_account, key_store, connector, state, merchant_account, ) .await? } else { None }; Ok(data) } <file_sep path="hyperswitch/crates/router/src/core/errors.rs" role="context" start="31" end="31"> pub type RouterResult<T> = CustomResult<T, ApiErrorResponse>; <file_sep path="hyperswitch/v2_compatible_migrations/2024-08-28-081757_drop_not_null_constraints_on_v1_columns/up.sql" role="context" start="5" end="21"> ALTER COLUMN org_id DROP NOT NULL; -- Create index on org_id in organization table -- This is done to mullify the effects of droping primary key for v1 CREATE INDEX idx_organization_org_id ON organization (org_id); ------------------------ Merchant Account ------------------- -- Drop not null in merchant_account table for v1 columns that are dropped in v2 ALTER TABLE merchant_account DROP CONSTRAINT merchant_account_pkey, ALTER COLUMN merchant_id DROP NOT NULL, ALTER COLUMN primary_business_details DROP NOT NULL, ALTER COLUMN is_recon_enabled DROP NOT NULL; -- This is done to mullify the effects of droping primary key for v1 CREATE INDEX idx_merchant_account_merchant_id ON merchant_account (merchant_id);
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payments/flows/capture_flow.rs<|crate|> router anchor=add_access_token kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/core/payments/flows/capture_flow.rs" role="context" start="144" end="153"> async fn add_access_token<'a>( &self, state: &SessionState, connector: &api::ConnectorData, merchant_account: &domain::MerchantAccount, creds_identifier: Option<&str>, ) -> RouterResult<types::AddAccessTokenResult> { access_token::add_access_token(state, connector, merchant_account, self, creds_identifier) .await } <file_sep path="hyperswitch/crates/router/src/core/payments/flows/capture_flow.rs" role="context" start="143" end="143"> use crate::{ core::{ errors::{ConnectorErrorExt, RouterResult}, payments::{self, access_token, helpers, transformers, Feature, PaymentData}, }, routes::SessionState, services, types::{self, api, domain}, }; <file_sep path="hyperswitch/crates/router/src/core/payments/flows/capture_flow.rs" role="context" start="155" end="177"> async fn build_flow_specific_connector_request( &mut self, state: &SessionState, connector: &api::ConnectorData, call_connector_action: payments::CallConnectorAction, ) -> RouterResult<(Option<services::Request>, bool)> { let request = match call_connector_action { payments::CallConnectorAction::Trigger => { let connector_integration: services::BoxedPaymentConnectorIntegrationInterface< api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData, > = connector.connector.get_connector_integration(); connector_integration .build_request(self, &state.conf.connectors) .to_payment_failed_response()? } _ => None, }; Ok((request, true)) } <file_sep path="hyperswitch/crates/router/src/core/payments/flows/capture_flow.rs" role="context" start="109" end="142"> async fn decide_flows<'a>( self, state: &SessionState, connector: &api::ConnectorData, call_connector_action: payments::CallConnectorAction, connector_request: Option<services::Request>, _business_profile: &domain::Profile, _header_payload: hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<Self> { let connector_integration: services::BoxedPaymentConnectorIntegrationInterface< api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData, > = connector.connector.get_connector_integration(); let mut new_router_data = services::execute_connector_processing_step( state, connector_integration, &self, call_connector_action, connector_request, ) .await .to_payment_failed_response()?; // Initiating Integrity check let integrity_result = helpers::check_integrity_based_on_flow( &new_router_data.request, &new_router_data.response, ); new_router_data.integrity_check = integrity_result; Ok(new_router_data) } <file_sep path="hyperswitch/crates/router/src/core/payments/flows/capture_flow.rs" role="context" start="93" end="102"> async fn get_merchant_recipient_data<'a>( &self, _state: &SessionState, _merchant_account: &domain::MerchantAccount, _key_store: &domain::MerchantKeyStore, _merchant_connector_account: &helpers::MerchantConnectorAccountType, _connector: &api::ConnectorData, ) -> RouterResult<Option<types::MerchantRecipientData>> { Ok(None) } <file_sep path="hyperswitch/crates/router/src/core/errors.rs" role="context" start="31" end="31"> pub type RouterResult<T> = CustomResult<T, ApiErrorResponse>; <file_sep path="hyperswitch/v2_compatible_migrations/2024-08-28-081757_drop_not_null_constraints_on_v1_columns/up.sql" role="context" start="5" end="21"> ALTER COLUMN org_id DROP NOT NULL; -- Create index on org_id in organization table -- This is done to mullify the effects of droping primary key for v1 CREATE INDEX idx_organization_org_id ON organization (org_id); ------------------------ Merchant Account ------------------- -- Drop not null in merchant_account table for v1 columns that are dropped in v2 ALTER TABLE merchant_account DROP CONSTRAINT merchant_account_pkey, ALTER COLUMN merchant_id DROP NOT NULL, ALTER COLUMN primary_business_details DROP NOT NULL, ALTER COLUMN is_recon_enabled DROP NOT NULL; -- This is done to mullify the effects of droping primary key for v1 CREATE INDEX idx_merchant_account_merchant_id ON merchant_account (merchant_id);
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payments/flows/session_flow.rs<|crate|> router anchor=add_access_token kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/core/payments/flows/session_flow.rs" role="context" start="146" end="155"> async fn add_access_token<'a>( &self, state: &routes::SessionState, connector: &api::ConnectorData, merchant_account: &domain::MerchantAccount, creds_identifier: Option<&str>, ) -> RouterResult<types::AddAccessTokenResult> { access_token::add_access_token(state, connector, merchant_account, self, creds_identifier) .await } <file_sep path="hyperswitch/crates/router/src/core/payments/flows/session_flow.rs" role="context" start="145" end="145"> use common_utils::{ ext_traits::ByteSliceExt, request::RequestContent, types::{AmountConvertor, StringMajorUnitForConnector}, }; use crate::{ consts::PROTOCOL, core::{ errors::{self, ConnectorErrorExt, RouterResult}, payments::{self, access_token, helpers, transformers, PaymentData}, }, headers, logger, routes::{self, app::settings, metrics}, services, types::{ self, api::{self, enums}, domain, }, utils::OptionExt, }; <file_sep path="hyperswitch/crates/router/src/core/payments/flows/session_flow.rs" role="context" start="195" end="227"> fn is_dynamic_fields_required( required_fields: &settings::RequiredFields, payment_method: enums::PaymentMethod, payment_method_type: enums::PaymentMethodType, connector: types::Connector, required_field_type: Vec<enums::FieldType>, ) -> bool { required_fields .0 .get(&payment_method) .and_then(|pm_type| pm_type.0.get(&payment_method_type)) .and_then(|required_fields_for_connector| { required_fields_for_connector.fields.get(&connector) }) .map(|required_fields_final| { required_fields_final .non_mandate .iter() .flatten() .any(|field_info| required_field_type.contains(&field_info.field_type)) || required_fields_final .mandate .iter() .flatten() .any(|field_info| required_field_type.contains(&field_info.field_type)) || required_fields_final .common .iter() .flatten() .any(|field_info| required_field_type.contains(&field_info.field_type)) }) .unwrap_or(false) } <file_sep path="hyperswitch/crates/router/src/core/payments/flows/session_flow.rs" role="context" start="161" end="190"> fn is_dynamic_fields_required( required_fields: &settings::RequiredFields, payment_method: enums::PaymentMethod, payment_method_type: enums::PaymentMethodType, connector: types::Connector, required_field_type: Vec<enums::FieldType>, ) -> bool { required_fields .0 .get(&payment_method) .and_then(|pm_type| pm_type.0.get(&payment_method_type)) .and_then(|required_fields_for_connector| { required_fields_for_connector.fields.get(&connector) }) .map(|required_fields_final| { required_fields_final .non_mandate .iter() .any(|(_, val)| required_field_type.contains(&val.field_type)) || required_fields_final .mandate .iter() .any(|(_, val)| required_field_type.contains(&val.field_type)) || required_fields_final .common .iter() .any(|(_, val)| required_field_type.contains(&val.field_type)) }) .unwrap_or(false) } <file_sep path="hyperswitch/crates/router/src/core/payments/flows/session_flow.rs" role="context" start="122" end="144"> async fn decide_flows<'a>( self, state: &routes::SessionState, connector: &api::ConnectorData, call_connector_action: payments::CallConnectorAction, _connector_request: Option<services::Request>, business_profile: &domain::Profile, header_payload: hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<Self> { metrics::SESSION_TOKEN_CREATED.add( 1, router_env::metric_attributes!(("connector", connector.connector_name.to_string())), ); self.decide_flow( state, connector, Some(true), call_connector_action, business_profile, header_payload, ) .await } <file_sep path="hyperswitch/crates/router/src/core/payments/flows/session_flow.rs" role="context" start="108" end="117"> async fn get_merchant_recipient_data<'a>( &self, _state: &routes::SessionState, _merchant_account: &domain::MerchantAccount, _key_store: &domain::MerchantKeyStore, _merchant_connector_account: &helpers::MerchantConnectorAccountType, _connector: &api::ConnectorData, ) -> RouterResult<Option<types::MerchantRecipientData>> { Ok(None) } <file_sep path="hyperswitch/crates/router/src/core/errors.rs" role="context" start="31" end="31"> pub type RouterResult<T> = CustomResult<T, ApiErrorResponse>; <file_sep path="hyperswitch/v2_compatible_migrations/2024-08-28-081757_drop_not_null_constraints_on_v1_columns/up.sql" role="context" start="5" end="21"> ALTER COLUMN org_id DROP NOT NULL; -- Create index on org_id in organization table -- This is done to mullify the effects of droping primary key for v1 CREATE INDEX idx_organization_org_id ON organization (org_id); ------------------------ Merchant Account ------------------- -- Drop not null in merchant_account table for v1 columns that are dropped in v2 ALTER TABLE merchant_account DROP CONSTRAINT merchant_account_pkey, ALTER COLUMN merchant_id DROP NOT NULL, ALTER COLUMN primary_business_details DROP NOT NULL, ALTER COLUMN is_recon_enabled DROP NOT NULL; -- This is done to mullify the effects of droping primary key for v1 CREATE INDEX idx_merchant_account_merchant_id ON merchant_account (merchant_id);
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payment_methods/tokenize/card_executor.rs<|crate|> router anchor=new kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/src/core/payment_methods/tokenize/card_executor.rs" role="context" start="65" end="79"> pub fn new() -> Self { Self { state: std::marker::PhantomData, customer: None, card: None, card_cvc: None, network_token: None, stored_card: None, stored_token: None, payment_method_response: None, card_tokenized: false, error_code: None, error_message: None, } } <file_sep path="hyperswitch/crates/router/src/core/payment_methods/tokenize/card_executor.rs" role="context" start="64" end="64"> use std::str::FromStr; <file_sep path="hyperswitch/crates/router/src/core/payment_methods/tokenize/card_executor.rs" role="context" start="98" end="148"> pub fn set_card_details( self, card_req: &'a domain::TokenizeCardRequest, optional_card_info: Option<diesel_models::CardInfo>, ) -> NetworkTokenizationBuilder<'a, CardDetailsAssigned> { let card = domain::CardDetail { card_number: card_req.raw_card_number.clone(), card_exp_month: card_req.card_expiry_month.clone(), card_exp_year: card_req.card_expiry_year.clone(), bank_code: optional_card_info .as_ref() .and_then(|card_info| card_info.bank_code.clone()), nick_name: card_req.nick_name.clone(), card_holder_name: card_req.card_holder_name.clone(), card_issuer: optional_card_info .as_ref() .map_or(card_req.card_issuer.clone(), |card_info| { card_info.card_issuer.clone() }), card_network: optional_card_info .as_ref() .map_or(card_req.card_network.clone(), |card_info| { card_info.card_network.clone() }), card_type: optional_card_info.as_ref().map_or( card_req .card_type .as_ref() .map(|card_type| card_type.to_string()), |card_info| card_info.card_type.clone(), ), card_issuing_country: optional_card_info .as_ref() .map_or(card_req.card_issuing_country.clone(), |card_info| { card_info.card_issuing_country.clone() }), }; NetworkTokenizationBuilder { state: std::marker::PhantomData, card: Some(card), card_cvc: card_req.card_cvc.clone(), customer: self.customer, network_token: self.network_token, stored_card: self.stored_card, stored_token: self.stored_token, payment_method_response: self.payment_method_response, card_tokenized: self.card_tokenized, error_code: self.error_code, error_message: self.error_message, } } <file_sep path="hyperswitch/crates/router/src/core/payment_methods/tokenize/card_executor.rs" role="context" start="80" end="94"> pub fn set_validate_result(self) -> NetworkTokenizationBuilder<'a, CardRequestValidated> { NetworkTokenizationBuilder { state: std::marker::PhantomData, customer: self.customer, card: self.card, card_cvc: self.card_cvc, network_token: self.network_token, stored_card: self.stored_card, stored_token: self.stored_token, payment_method_response: self.payment_method_response, card_tokenized: self.card_tokenized, error_code: self.error_code, error_message: self.error_message, } } <file_sep path="hyperswitch/crates/router/src/core/payment_methods/tokenize/card_executor.rs" role="context" start="59" end="61"> fn default() -> Self { Self::new() } <file_sep path="hyperswitch/crates/router/src/core/payment_methods/tokenize/card_executor.rs" role="context" start="364" end="452"> pub async fn create_customer(&self) -> RouterResult<api::CustomerDetails> { let db = &*self.state.store; let customer_id = self .customer .customer_id .as_ref() .get_required_value("customer_id") .change_context(errors::ApiErrorResponse::MissingRequiredField { field_name: "customer_id", })?; let key_manager_state: &KeyManagerState = &self.state.into(); let encrypted_data = crypto_operation( key_manager_state, type_name!(domain::Customer), CryptoOperation::BatchEncrypt(domain::FromRequestEncryptableCustomer::to_encryptable( domain::FromRequestEncryptableCustomer { name: self.customer.name.clone(), email: self .customer .email .clone() .map(|email| email.expose().switch_strategy()), phone: self.customer.phone.clone(), }, )), Identifier::Merchant(self.merchant_account.get_id().clone()), self.key_store.key.get_inner().peek(), ) .await .inspect_err(|err| logger::info!("Error encrypting customer: {:?}", err)) .and_then(|val| val.try_into_batchoperation()) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to encrypt customer")?; let encryptable_customer = domain::FromRequestEncryptableCustomer::from_encryptable(encrypted_data) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to form EncryptableCustomer")?; let new_customer_id = generate_customer_id_of_default_length(); let domain_customer = domain::Customer { customer_id: new_customer_id.clone(), merchant_id: self.merchant_account.get_id().clone(), name: encryptable_customer.name, email: encryptable_customer.email.map(|email| { utils::Encryptable::new( email.clone().into_inner().switch_strategy(), email.into_encrypted(), ) }), phone: encryptable_customer.phone, description: None, phone_country_code: self.customer.phone_country_code.to_owned(), metadata: None, connector_customer: None, created_at: common_utils::date_time::now(), modified_at: common_utils::date_time::now(), address_id: None, default_payment_method_id: None, updated_by: None, version: common_types::consts::API_VERSION, }; db.insert_customer( domain_customer, key_manager_state, self.key_store, self.merchant_account.storage_scheme, ) .await .inspect_err(|err| logger::info!("Error creating a customer: {:?}", err)) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { format!( "Failed to insert customer [id - {:?}] for merchant [id - {:?}]", customer_id, self.merchant_account.get_id() ) })?; Ok(api::CustomerDetails { id: new_customer_id, name: self.customer.name.clone(), email: self.customer.email.clone(), phone: self.customer.phone.clone(), phone_country_code: self.customer.phone_country_code.clone(), }) }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payment_methods/tokenize/payment_method_executor.rs<|crate|> router anchor=new kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/src/core/payment_methods/tokenize/payment_method_executor.rs" role="context" start="51" end="65"> pub fn new() -> Self { Self { state: std::marker::PhantomData, customer: None, card: None, card_cvc: None, network_token: None, stored_card: None, stored_token: None, payment_method_response: None, card_tokenized: false, error_code: None, error_message: None, } } <file_sep path="hyperswitch/crates/router/src/core/payment_methods/tokenize/payment_method_executor.rs" role="context" start="103" end="120"> pub fn set_validate_result( self, customer: &'a api::CustomerDetails, ) -> NetworkTokenizationBuilder<'a, PmValidated> { NetworkTokenizationBuilder { state: std::marker::PhantomData, customer: Some(customer), card: self.card, card_cvc: self.card_cvc, network_token: self.network_token, stored_card: self.stored_card, stored_token: self.stored_token, payment_method_response: self.payment_method_response, card_tokenized: self.card_tokenized, error_code: self.error_code, error_message: self.error_message, } } <file_sep path="hyperswitch/crates/router/src/core/payment_methods/tokenize/payment_method_executor.rs" role="context" start="66" end="99"> pub fn set_payment_method( self, payment_method: &domain::PaymentMethod, ) -> NetworkTokenizationBuilder<'a, PmFetched> { let payment_method_response = api::PaymentMethodResponse { merchant_id: payment_method.merchant_id.clone(), customer_id: Some(payment_method.customer_id.clone()), payment_method_id: payment_method.payment_method_id.clone(), payment_method: payment_method.payment_method, payment_method_type: payment_method.payment_method_type, recurring_enabled: true, installment_payment_enabled: false, metadata: payment_method.metadata.clone(), created: Some(payment_method.created_at), last_used_at: Some(payment_method.last_used_at), client_secret: payment_method.client_secret.clone(), card: None, bank_transfer: None, payment_experience: None, }; NetworkTokenizationBuilder { state: std::marker::PhantomData, payment_method_response: Some(payment_method_response), customer: self.customer, card: self.card, card_cvc: self.card_cvc, network_token: self.network_token, stored_card: self.stored_card, stored_token: self.stored_token, card_tokenized: self.card_tokenized, error_code: self.error_code, error_message: self.error_message, } } <file_sep path="hyperswitch/crates/router/src/core/payment_methods/tokenize/payment_method_executor.rs" role="context" start="45" end="47"> fn default() -> Self { Self::new() } <file_sep path="hyperswitch/crates/router/src/core/payment_methods/tokenize/payment_method_executor.rs" role="context" start="124" end="168"> pub fn set_card_details( self, card_from_locker: &'a api_models::payment_methods::Card, optional_card_info: Option<diesel_models::CardInfo>, card_cvc: Option<Secret<String>>, ) -> NetworkTokenizationBuilder<'a, PmAssigned> { let card = domain::CardDetail { card_number: card_from_locker.card_number.clone(), card_exp_month: card_from_locker.card_exp_month.clone(), card_exp_year: card_from_locker.card_exp_year.clone(), bank_code: optional_card_info .as_ref() .and_then(|card_info| card_info.bank_code.clone()), nick_name: card_from_locker .nick_name .as_ref() .map(|nick_name| Secret::new(nick_name.clone())), card_holder_name: card_from_locker.name_on_card.clone(), card_issuer: optional_card_info .as_ref() .and_then(|card_info| card_info.card_issuer.clone()), card_network: optional_card_info .as_ref() .and_then(|card_info| card_info.card_network.clone()), card_type: optional_card_info .as_ref() .and_then(|card_info| card_info.card_type.clone()), card_issuing_country: optional_card_info .as_ref() .and_then(|card_info| card_info.card_issuing_country.clone()), }; NetworkTokenizationBuilder { state: std::marker::PhantomData, card: Some(card), card_cvc, customer: self.customer, network_token: self.network_token, stored_card: self.stored_card, stored_token: self.stored_token, payment_method_response: self.payment_method_response, card_tokenized: self.card_tokenized, error_code: self.error_code, error_message: self.error_message, } }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payment_link.rs<|crate|> router anchor=get_meta_tags_html kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/router/src/core/payment_link.rs" role="context" start="481" end="491"> fn get_meta_tags_html(payment_details: &api_models::payments::PaymentLinkDetails) -> String { format!( r#"<meta property="og:title" content="Payment request from {0}"/> <meta property="og:description" content="{1}"/>"#, payment_details.merchant_name.clone(), payment_details .merchant_description .clone() .unwrap_or_default() ) } <file_sep path="hyperswitch/crates/router/src/core/payment_link.rs" role="context" start="480" end="480"> use api_models::{ admin::PaymentLinkConfig, payments::{PaymentLinkData, PaymentLinkStatusWrap}, }; use super::{ errors::{self, RouterResult, StorageErrorExt}, payments::helpers, }; <file_sep path="hyperswitch/crates/router/src/core/payment_link.rs" role="context" start="507" end="523"> pub async fn list_payment_link( state: SessionState, merchant: domain::MerchantAccount, constraints: api_models::payments::PaymentLinkListConstraints, ) -> RouterResponse<Vec<api_models::payments::RetrievePaymentLinkResponse>> { let db = state.store.as_ref(); let payment_link = db .list_payment_link_by_merchant_id(merchant.get_id(), constraints) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to retrieve payment link")?; let payment_link_list = future::try_join_all(payment_link.into_iter().map(|payment_link| { api_models::payments::RetrievePaymentLinkResponse::from_db_payment_link(payment_link) })) .await?; Ok(services::ApplicationResponse::Json(payment_link_list)) } <file_sep path="hyperswitch/crates/router/src/core/payment_link.rs" role="context" start="493" end="505"> fn validate_sdk_requirements( currency: Option<api_models::enums::Currency>, client_secret: Option<String>, ) -> Result<(api_models::enums::Currency, String), errors::ApiErrorResponse> { let currency = currency.ok_or(errors::ApiErrorResponse::MissingRequiredField { field_name: "currency", })?; let client_secret = client_secret.ok_or(errors::ApiErrorResponse::MissingRequiredField { field_name: "client_secret", })?; Ok((currency, client_secret)) } <file_sep path="hyperswitch/crates/router/src/core/payment_link.rs" role="context" start="469" end="479"> fn get_color_scheme_css(payment_link_config: &PaymentLinkConfig) -> String { let background_primary_color = payment_link_config .background_colour .clone() .unwrap_or(payment_link_config.theme.clone()); format!( ":root {{ --primary-color: {background_primary_color}; }}" ) } <file_sep path="hyperswitch/crates/router/src/core/payment_link.rs" role="context" start="462" end="467"> fn get_js_script(payment_details: &PaymentLinkData) -> RouterResult<String> { let payment_details_str = serde_json::to_string(payment_details) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to serialize PaymentLinkData")?; Ok(format!("window.__PAYMENT_DETAILS = {payment_details_str};")) } <file_sep path="hyperswitch/crates/router/src/core/payment_link.rs" role="context" start="411" end="456"> pub async fn initiate_payment_link_flow( state: SessionState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, merchant_id: common_utils::id_type::MerchantId, payment_id: common_utils::id_type::PaymentId, ) -> RouterResponse<services::PaymentLinkFormData> { let (_, payment_details, payment_link_config) = form_payment_link_data(&state, merchant_account, key_store, merchant_id, payment_id) .await?; let css_script = get_color_scheme_css(&payment_link_config); let js_script = get_js_script(&payment_details)?; match payment_details { PaymentLinkData::PaymentLinkStatusDetails(status_details) => { let payment_link_error_data = services::PaymentLinkStatusData { js_script, css_script, }; logger::info!( "payment link data, for building payment link status page {:?}", status_details ); Ok(services::ApplicationResponse::PaymentLinkForm(Box::new( services::api::PaymentLinkAction::PaymentLinkStatus(payment_link_error_data), ))) } PaymentLinkData::PaymentLinkDetails(payment_details) => { let html_meta_tags = get_meta_tags_html(&payment_details); let payment_link_data = services::PaymentLinkFormData { js_script, sdk_url: state.conf.payment_link.sdk_url.clone(), css_script, html_meta_tags, }; logger::info!( "payment link data, for building open payment link {:?}", payment_link_data ); Ok(services::ApplicationResponse::PaymentLinkForm(Box::new( services::api::PaymentLinkAction::PaymentLinkFormData(payment_link_data), ))) } } } <file_sep path="hyperswitch/crates/router/src/core/payment_link.rs" role="context" start="308" end="409"> pub async fn initiate_secure_payment_link_flow( state: SessionState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, merchant_id: common_utils::id_type::MerchantId, payment_id: common_utils::id_type::PaymentId, request_headers: &header::HeaderMap, ) -> RouterResponse<services::PaymentLinkFormData> { let (payment_link, payment_link_details, payment_link_config) = form_payment_link_data(&state, merchant_account, key_store, merchant_id, payment_id) .await?; validator::validate_secure_payment_link_render_request( request_headers, &payment_link, &payment_link_config, )?; let css_script = get_color_scheme_css(&payment_link_config); match payment_link_details { PaymentLinkData::PaymentLinkStatusDetails(ref status_details) => { let js_script = get_js_script(&payment_link_details)?; let payment_link_error_data = services::PaymentLinkStatusData { js_script, css_script, }; logger::info!( "payment link data, for building payment link status page {:?}", status_details ); Ok(services::ApplicationResponse::PaymentLinkForm(Box::new( services::api::PaymentLinkAction::PaymentLinkStatus(payment_link_error_data), ))) } PaymentLinkData::PaymentLinkDetails(link_details) => { let secure_payment_link_details = api_models::payments::SecurePaymentLinkDetails { enabled_saved_payment_method: payment_link_config.enabled_saved_payment_method, hide_card_nickname_field: payment_link_config.hide_card_nickname_field, show_card_form_by_default: payment_link_config.show_card_form_by_default, payment_link_details: *link_details.to_owned(), payment_button_text: payment_link_config.payment_button_text, custom_message_for_card_terms: payment_link_config.custom_message_for_card_terms, payment_button_colour: payment_link_config.payment_button_colour, skip_status_screen: payment_link_config.skip_status_screen, background_colour: payment_link_config.background_colour, payment_button_text_colour: payment_link_config.payment_button_text_colour, sdk_ui_rules: payment_link_config.sdk_ui_rules, payment_link_ui_rules: payment_link_config.payment_link_ui_rules, enable_button_only_on_form_ready: payment_link_config .enable_button_only_on_form_ready, }; let js_script = format!( "window.__PAYMENT_DETAILS = {}", serde_json::to_string(&secure_payment_link_details) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to serialize PaymentLinkData")? ); let html_meta_tags = get_meta_tags_html(&link_details); let payment_link_data = services::PaymentLinkFormData { js_script, sdk_url: state.conf.payment_link.sdk_url.clone(), css_script, html_meta_tags, }; let allowed_domains = payment_link_config .allowed_domains .clone() .ok_or(report!(errors::ApiErrorResponse::InternalServerError)) .attach_printable_lazy(|| { format!( "Invalid list of allowed_domains found - {:?}", payment_link_config.allowed_domains.clone() ) })?; if allowed_domains.is_empty() { return Err(report!(errors::ApiErrorResponse::InternalServerError)) .attach_printable_lazy(|| { format!( "Invalid list of allowed_domains found - {:?}", payment_link_config.allowed_domains.clone() ) }); } let link_data = GenericLinks { allowed_domains, data: GenericLinksData::SecurePaymentLink(payment_link_data), locale: DEFAULT_LOCALE.to_string(), }; logger::info!( "payment link data, for building secure payment link {:?}", link_data ); Ok(services::ApplicationResponse::GenericLinkForm(Box::new( link_data, ))) } } }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/router/src/core/payment_link.rs<|crate|> router anchor=get_meta_tags_html kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/router/src/core/payment_link.rs" role="context" start="481" end="491"> fn get_meta_tags_html(payment_details: &api_models::payments::PaymentLinkDetails) -> String { format!( r#"<meta property="og:title" content="Payment request from {0}"/> <meta property="og:description" content="{1}"/>"#, payment_details.merchant_name.clone(), payment_details .merchant_description .clone() .unwrap_or_default() ) } <file_sep path="hyperswitch/crates/router/src/core/payment_link.rs" role="context" start="480" end="480"> use api_models::{ admin::PaymentLinkConfig, payments::{PaymentLinkData, PaymentLinkStatusWrap}, }; use super::{ errors::{self, RouterResult, StorageErrorExt}, payments::helpers, }; <file_sep path="hyperswitch/crates/router/src/core/payment_link.rs" role="context" start="507" end="523"> pub async fn list_payment_link( state: SessionState, merchant: domain::MerchantAccount, constraints: api_models::payments::PaymentLinkListConstraints, ) -> RouterResponse<Vec<api_models::payments::RetrievePaymentLinkResponse>> { let db = state.store.as_ref(); let payment_link = db .list_payment_link_by_merchant_id(merchant.get_id(), constraints) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to retrieve payment link")?; let payment_link_list = future::try_join_all(payment_link.into_iter().map(|payment_link| { api_models::payments::RetrievePaymentLinkResponse::from_db_payment_link(payment_link) })) .await?; Ok(services::ApplicationResponse::Json(payment_link_list)) } <file_sep path="hyperswitch/crates/router/src/core/payment_link.rs" role="context" start="493" end="505"> fn validate_sdk_requirements( currency: Option<api_models::enums::Currency>, client_secret: Option<String>, ) -> Result<(api_models::enums::Currency, String), errors::ApiErrorResponse> { let currency = currency.ok_or(errors::ApiErrorResponse::MissingRequiredField { field_name: "currency", })?; let client_secret = client_secret.ok_or(errors::ApiErrorResponse::MissingRequiredField { field_name: "client_secret", })?; Ok((currency, client_secret)) } <file_sep path="hyperswitch/crates/router/src/core/payment_link.rs" role="context" start="469" end="479"> fn get_color_scheme_css(payment_link_config: &PaymentLinkConfig) -> String { let background_primary_color = payment_link_config .background_colour .clone() .unwrap_or(payment_link_config.theme.clone()); format!( ":root {{ --primary-color: {background_primary_color}; }}" ) } <file_sep path="hyperswitch/crates/router/src/core/payment_link.rs" role="context" start="462" end="467"> fn get_js_script(payment_details: &PaymentLinkData) -> RouterResult<String> { let payment_details_str = serde_json::to_string(payment_details) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to serialize PaymentLinkData")?; Ok(format!("window.__PAYMENT_DETAILS = {payment_details_str};")) } <file_sep path="hyperswitch/crates/router/src/core/payment_link.rs" role="context" start="411" end="456"> pub async fn initiate_payment_link_flow( state: SessionState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, merchant_id: common_utils::id_type::MerchantId, payment_id: common_utils::id_type::PaymentId, ) -> RouterResponse<services::PaymentLinkFormData> { let (_, payment_details, payment_link_config) = form_payment_link_data(&state, merchant_account, key_store, merchant_id, payment_id) .await?; let css_script = get_color_scheme_css(&payment_link_config); let js_script = get_js_script(&payment_details)?; match payment_details { PaymentLinkData::PaymentLinkStatusDetails(status_details) => { let payment_link_error_data = services::PaymentLinkStatusData { js_script, css_script, }; logger::info!( "payment link data, for building payment link status page {:?}", status_details ); Ok(services::ApplicationResponse::PaymentLinkForm(Box::new( services::api::PaymentLinkAction::PaymentLinkStatus(payment_link_error_data), ))) } PaymentLinkData::PaymentLinkDetails(payment_details) => { let html_meta_tags = get_meta_tags_html(&payment_details); let payment_link_data = services::PaymentLinkFormData { js_script, sdk_url: state.conf.payment_link.sdk_url.clone(), css_script, html_meta_tags, }; logger::info!( "payment link data, for building open payment link {:?}", payment_link_data ); Ok(services::ApplicationResponse::PaymentLinkForm(Box::new( services::api::PaymentLinkAction::PaymentLinkFormData(payment_link_data), ))) } } } <file_sep path="hyperswitch/crates/router/src/core/payment_link.rs" role="context" start="308" end="409"> pub async fn initiate_secure_payment_link_flow( state: SessionState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, merchant_id: common_utils::id_type::MerchantId, payment_id: common_utils::id_type::PaymentId, request_headers: &header::HeaderMap, ) -> RouterResponse<services::PaymentLinkFormData> { let (payment_link, payment_link_details, payment_link_config) = form_payment_link_data(&state, merchant_account, key_store, merchant_id, payment_id) .await?; validator::validate_secure_payment_link_render_request( request_headers, &payment_link, &payment_link_config, )?; let css_script = get_color_scheme_css(&payment_link_config); match payment_link_details { PaymentLinkData::PaymentLinkStatusDetails(ref status_details) => { let js_script = get_js_script(&payment_link_details)?; let payment_link_error_data = services::PaymentLinkStatusData { js_script, css_script, }; logger::info!( "payment link data, for building payment link status page {:?}", status_details ); Ok(services::ApplicationResponse::PaymentLinkForm(Box::new( services::api::PaymentLinkAction::PaymentLinkStatus(payment_link_error_data), ))) } PaymentLinkData::PaymentLinkDetails(link_details) => { let secure_payment_link_details = api_models::payments::SecurePaymentLinkDetails { enabled_saved_payment_method: payment_link_config.enabled_saved_payment_method, hide_card_nickname_field: payment_link_config.hide_card_nickname_field, show_card_form_by_default: payment_link_config.show_card_form_by_default, payment_link_details: *link_details.to_owned(), payment_button_text: payment_link_config.payment_button_text, custom_message_for_card_terms: payment_link_config.custom_message_for_card_terms, payment_button_colour: payment_link_config.payment_button_colour, skip_status_screen: payment_link_config.skip_status_screen, background_colour: payment_link_config.background_colour, payment_button_text_colour: payment_link_config.payment_button_text_colour, sdk_ui_rules: payment_link_config.sdk_ui_rules, payment_link_ui_rules: payment_link_config.payment_link_ui_rules, enable_button_only_on_form_ready: payment_link_config .enable_button_only_on_form_ready, }; let js_script = format!( "window.__PAYMENT_DETAILS = {}", serde_json::to_string(&secure_payment_link_details) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to serialize PaymentLinkData")? ); let html_meta_tags = get_meta_tags_html(&link_details); let payment_link_data = services::PaymentLinkFormData { js_script, sdk_url: state.conf.payment_link.sdk_url.clone(), css_script, html_meta_tags, }; let allowed_domains = payment_link_config .allowed_domains .clone() .ok_or(report!(errors::ApiErrorResponse::InternalServerError)) .attach_printable_lazy(|| { format!( "Invalid list of allowed_domains found - {:?}", payment_link_config.allowed_domains.clone() ) })?; if allowed_domains.is_empty() { return Err(report!(errors::ApiErrorResponse::InternalServerError)) .attach_printable_lazy(|| { format!( "Invalid list of allowed_domains found - {:?}", payment_link_config.allowed_domains.clone() ) }); } let link_data = GenericLinks { allowed_domains, data: GenericLinksData::SecurePaymentLink(payment_link_data), locale: DEFAULT_LOCALE.to_string(), }; logger::info!( "payment link data, for building secure payment link {:?}", link_data ); Ok(services::ApplicationResponse::GenericLinkForm(Box::new( link_data, ))) } } } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="7992" end="8026"> pub struct PaymentLinkDetails { pub amount: StringMajorUnit, pub currency: api_enums::Currency, pub pub_key: String, pub client_secret: String, pub payment_id: id_type::PaymentId, #[serde(with = "common_utils::custom_serde::iso8601")] pub session_expiry: PrimitiveDateTime, pub merchant_logo: String, pub return_url: String, pub merchant_name: String, pub order_details: Option<Vec<OrderDetailsWithStringAmount>>, pub max_items_visible_after_collapse: i8, pub theme: String, pub merchant_description: Option<String>, pub sdk_layout: String, pub display_sdk_only: bool, pub hide_card_nickname_field: bool, pub show_card_form_by_default: bool, pub locale: Option<String>, pub transaction_details: Option<Vec<admin::PaymentLinkTransactionDetails>>, pub background_image: Option<admin::PaymentLinkBackgroundImageConfig>, pub details_layout: Option<api_enums::PaymentLinkDetailsLayout>, pub branding_visibility: Option<bool>, pub payment_button_text: Option<String>, pub skip_status_screen: Option<bool>, pub custom_message_for_card_terms: Option<String>, pub payment_button_colour: Option<String>, pub payment_button_text_colour: Option<String>, pub background_colour: Option<String>, pub sdk_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub payment_link_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub status: api_enums::IntentStatus, pub enable_button_only_on_form_ready: bool, }
symbol_neighborhood